Documentation
¶
Index ¶
- Constants
- Variables
- func ApplyJQ(filter string, input interface{}) (interface{}, error)
- func ApplySeriesMode(records []map[string]interface{}, mode SeriesMode, digits int, tabular bool) []map[string]interface{}
- func ApplyTrueTypes(records []map[string]interface{}, types []ColumnTypeMapping)
- func AutoDefaultSuggestion(format string) string
- func ClassifyHTTPError(statusCode int) string
- func ClipRecordValues(records []map[string]interface{}, max int) (out []map[string]interface{}, fields []string)
- func ClipValue(v interface{}, max int) (out interface{}, fields []string)
- func ColorCode(code string) string
- func ColorEnabled() bool
- func Colorize(color, text string) string
- func DecodeSnapshotRecords(records []map[string]interface{}, simplify bool) []map[string]interface{}
- func DescribeKV(label string, width int, format string, args ...interface{})
- func DescribeSection(header string)
- func DoctorFail() string
- func DoctorOK() string
- func DoctorWarn() string
- func DrawBox(title string, content string, width int) string
- func DrawHeader(title string, width int) string
- func DrawSeparator(width int) string
- func EncodeEnvelope(w io.Writer, resp Response) error
- func EnvelopeIndented(w io.Writer) bool
- func EnvelopeSize(w io.Writer, resp Response) (int64, error)
- func ExpandMetadataFields(meta *QueryMetadata, fields []string, defaultWindow bool) []string
- func ExtForFormat(format string) string
- func FormatForExt(path string) string
- func FormatMetadataCSVComments(m *QueryMetadata, fields []string) string
- func FormatMetadataFooter(m *QueryMetadata, fields []string) string
- func FprintAutoChoice(w io.Writer, choice AutoChoice)
- func FprintDescribeKV(w io.Writer, label string, width int, format string, args ...interface{})
- func FprintDescribeSection(w io.Writer, header string)
- func FprintHint(w io.Writer, format string, args ...interface{})
- func FprintHumanError(w io.Writer, format string, args ...interface{})
- func FprintInfo(w io.Writer, format string, args ...interface{})
- func FprintSuccess(w io.Writer, format string, args ...interface{})
- func FprintWarning(w io.Writer, format string, args ...interface{})
- func GetFullscreenDimensions() (width, height int)
- func GetTerminalSize() (width, height int)
- func IsAllFields(fields []string) bool
- func IsAutoFormat(format string) bool
- func IsMinimalFields(fields []string) bool
- func IsStructuredOutputFormat(format string) bool
- func IsTabularFormat(format string, plain bool) bool
- func ManagedContextFor(path string) (contextName string, ok bool)
- func MarshalTOON(v interface{}) (string, error)
- func MeasureSerializedBytes(records interface{}, format string, layout JSONLayout) (int64, string)
- func MetadataOmitsFields(meta *QueryMetadata, fields []string) bool
- func MetadataToMap(meta *QueryMetadata, fields []string) interface{}
- func MiniGraph(values []float64, width int) string
- func MiniGraphColored(values []float64, width int) string
- func NormalizeJQOutputFormat(format string) string
- func NormalizeMeasureEncoding(format string) string
- func ParseFields(s string) []string
- func ParseMetadataFields(val string) ([]string, error)
- func PinColorOff()
- func PrintError(writer io.Writer, detail *ErrorDetail) error
- func PrintHint(format string, args ...interface{})
- func PrintHumanError(format string, args ...interface{})
- func PrintInfo(format string, args ...interface{})
- func PrintSuccess(format string, args ...interface{})
- func PrintWarning(format string, args ...interface{})
- func ProbeWritable(dir string) bool
- func PruneOldSpills(baseDir string, ttl time.Duration)
- func RenderColoredSparkline(values []float64, width int) string
- func RenderGradientBar(value, maxValue float64, width int) string
- func RenderGradientBarWithScheme(value, maxValue float64, width int, schemeIndex int) string
- func RenderProgressBar(value, maxValue float64, width int, showPercent bool) string
- func ResetColorCache()
- func RoundNumbers(records []map[string]interface{}, digits int) []map[string]interface{}
- func SampleRows(records []map[string]interface{}, n int) []map[string]interface{}
- func SanitizeContextName(name string) string
- func SetPlainMode(plain bool)
- func SidecarPathFor(dataPath string) string
- func SimplifySnapshotValues(value interface{}) interface{}
- func SpillBaseDir(preferred string) (dir string, managed bool, err error)
- func SpillHash(parts ...string) string
- func StatsDisplay(label string, value float64, unit string, labelWidth int) string
- func SummarizeSnapshotForTable(records []map[string]interface{}) []map[string]interface{}
- func SupportsFieldProjection(format string) bool
- func ValidMetadataFieldNames() []string
- func WriteSidecar(dataPath string, sc *SidecarManifest) error
- func WriteSpillFile(targetPath string, write func(io.Writer) error) (int64, error)
- type AgentPrinter
- func (p *AgentPrinter) Context() *ResponseContext
- func (p *AgentPrinter) Print(data interface{}) error
- func (p *AgentPrinter) PrintList(data interface{}) error
- func (p *AgentPrinter) SetDuration(duration string)
- func (p *AgentPrinter) SetHasMore(hasMore bool)
- func (p *AgentPrinter) SetJQFilter(filter string)
- func (p *AgentPrinter) SetLinks(links map[string]string)
- func (p *AgentPrinter) SetMaxFieldChars(n int)
- func (p *AgentPrinter) SetMetadata(meta interface{})
- func (p *AgentPrinter) SetResource(resource string)
- func (p *AgentPrinter) SetResultFormat(format string)
- func (p *AgentPrinter) SetSuggestions(suggestions []string)
- func (p *AgentPrinter) SetTotal(total int)
- func (p *AgentPrinter) SetWarnings(warnings []string)
- func (p *AgentPrinter) UseAutoByDefault()
- type AutoChoice
- type AutoPrinter
- type BarChartPrinter
- type BrailleChartPrinter
- type BrailleGraph
- type CSVPrinter
- type Change
- type ChangeType
- type ChartPrinter
- type ColumnStats
- type ColumnTypeMapping
- type Compaction
- func (c Compaction) Changed(encoding string) bool
- func (c Compaction) EnvelopeConstant() map[string]interface{}
- func (c Compaction) FilterColumns(cols []ColumnStats) []ColumnStats
- func (c Compaction) Sparse(records []map[string]interface{}) []map[string]interface{}
- func (c Compaction) Tabular(records []map[string]interface{}) []map[string]interface{}
- type CompactionAccumulator
- type CompiledJQ
- type DataFetcher
- type EmptyReason
- type ErrorDetail
- type ErrorPosition
- type FlatRows
- type InlineRecords
- type InlineRecordsEncoded
- type JQError
- type JSONLPrinter
- type JSONLayout
- type JSONPrinter
- type LivePrinter
- type MetadataBucket
- type MetadataContribs
- type MetadataNotice
- type MetadataTimeframe
- type MetricInfo
- type ParquetPrinter
- type Printer
- func NewPrinter(format string) Printer
- func NewPrinterWithOptions(format string, writer io.Writer, plainMode bool) Printer
- func NewPrinterWithOpts(opts PrinterOptions) Printer
- func NewPrinterWithWriter(format string, writer io.Writer) Printer
- func NewShapingPrinter(inner Printer, opts ShapeOptions) Printer
- type PrinterOptions
- type ProgressReporter
- type ProgressState
- type QueryMetadata
- type Response
- type ResponseContext
- type ResultFileManifest
- type SampleStats
- type Series
- type SeriesEffect
- type SeriesKind
- type SeriesMode
- type ShapeOptions
- type ShapingPrinter
- type SidecarManifest
- type SparklinePrinter
- type SpecFileManifest
- type SpillFileEntry
- type SpillList
- type SpillWriter
- type StatsAccumulator
- type TablePrinter
- type TimeWindow
- type TimeseriesData
- type ToonPrinter
- type TopValue
- type WatchPrinter
- type WatchPrinterInterface
- type YAMLPrinter
Constants ¶
const ( AutoReasonEmpty = "empty result" AutoReasonScalar = "scalar value" AutoReasonSingleObject = "single object" AutoReasonSingleRow = "single row" AutoReasonFlatRows = "uniform flat rows" AutoReasonSparseRows = "sparse rows" AutoReasonNested = "nested values" AutoReasonNotRows = "list of non-object values" AutoReasonUnencodable = "not JSON-encodable" )
Reasons ChooseAutoFormat gives for its choice. They are part of the stderr notice a human sees, so keep them short.
const ( // MaxSeriesCount is the maximum number of series to display in a chart MaxSeriesCount = 10 // DefaultChartHeight is the default height of the chart DefaultChartHeight = 15 // DefaultChartWidth is the default width for all chart visualizations DefaultChartWidth = 100 )
const ( // DefaultLiveInterval is the default refresh interval for live mode DefaultLiveInterval = 60 * time.Second // MinLiveInterval is the minimum allowed refresh interval MinLiveInterval = 1 * time.Second )
const ( // KindRecords is today's inline behaviour: the rows are returned directly. KindRecords = "records" // KindResultFile means the result was spilled to disk; the payload is a // manifest (stats + sample + a file handle). KindResultFile = "result-file" // KindSummaryOnly means the result was large but there was no writable // filesystem; the manifest is returned without a path (stats + sample only). KindSummaryOnly = "summary-only" // KindFileSummary is emitted by Layer 2 `dtctl inspect` for the re-derived // manifest primitives (--schema/--stats/--sample): the on-disk re-derivation // of the schema/stats/sample shape from a spilled file (INSPECT IN5). It is a // new kind, so a pre-inspect consumer treats it as opaque and falls back to // context — non-breaking by construction (D31). KindFileSummary = "file-summary" // KindDocumentFile means an opaque document — not a row set — was written to // disk and the payload is a handle to it. It is emitted by // `dtctl describe api --raw`, whose payload is one published OpenAPI document // rather than records, so none of the row/column primitives apply. Another new // kind, opaque to older consumers (D31). KindDocumentFile = "document-file" // KindFileList is emitted by `dtctl inspect --list`: an enumeration of the // spilled files visible in the active context's partition, each with its // sidecar provenance. It lets an agent recover a file handle that has aged out // of its context (the original spill envelope was trimmed/summarised) from disk // rather than re-querying Grail. Another new kind, opaque to older consumers // (D31). KindFileList = "file-list" )
result.kind discriminator values (D2). A consumer branches once on this.
const ( ErrCodeSpillFileNotFound = "spill_file_not_found" ErrCodeSpillFileUnreadable = "spill_file_unreadable" ErrCodeSpillFileWrongContext = "spill_file_wrong_context" )
Stable spill-file error codes (D32). These are part of the versioned envelope contract and are consumed by Layer 2 (`dtctl inspect`) when it acts on a handed-out path that has since become mortal (TTL prune / overwrite / delete).
const ( // DefaultStatsTopK is how many top values are reported for low-cardinality // string columns. Kept small (top-3) so a wide result's summary stays compact // in an agent's context: the long tail of a distribution is rarely load-bearing // for a next-step decision, and the full data is on disk for follow-up. DefaultStatsTopK = 3 // DefaultStatsMaxDistinct bounds exact distinct tracking per column. Above // this a column is flagged high-cardinality and exact distinct/top are // dropped (the buffered Layer-1 path stays O(distinct) per column, which is // bounded by this constant). DefaultStatsMaxDistinct = 1000 // DefaultSampleRows is how many leading rows are embedded in the manifest. DefaultSampleRows = 3 // DefaultMaxSummaryColumns bounds how many per-column profiles are embedded in // the in-context envelope (D14). A wide telemetry result can carry hundreds of // columns, most of them sparse; emitting a full profile for every one defeats // the point of the summary. Above this count the envelope keeps the profiles // for the most-populated columns and lists the rest by name; the on-disk // sidecar always carries the full set, so nothing is lost. DefaultMaxSummaryColumns = 50 )
Default knobs for the lean Layer-1 stats (D14). Kept small and Go-computed; richer profiling (quantiles, wide top-K) is deferred to the Layer 2 `inspect --stats` primitive.
const ( Reset = "\033[0m" Bold = "\033[1m" Dim = "\033[2m" Italic = "\033[3m" Underline = "\033[4m" // Foreground colors Black = "\033[30m" Red = "\033[31m" Green = "\033[32m" Yellow = "\033[33m" Blue = "\033[34m" Magenta = "\033[35m" Cyan = "\033[36m" White = "\033[37m" // Bright foreground colors BrightBlack = "\033[90m" BrightRed = "\033[91m" BrightGreen = "\033[92m" BrightYellow = "\033[93m" BrightBlue = "\033[94m" BrightMagenta = "\033[95m" BrightCyan = "\033[96m" BrightWhite = "\033[97m" )
ANSI color codes inspired by btop's color scheme
const ( BoxHorizontal = "─" BoxVertical = "│" BoxTopLeft = "┌" BoxTopRight = "┐" BoxBottomLeft = "└" BoxBottomRight = "┘" BoxVerticalRight = "├" BoxVerticalLeft = "┤" BoxHorizontalDown = "┬" BoxHorizontalUp = "┴" BoxCross = "┼" )
Box-drawing characters (single line - btop style)
const ( BoxDoubleHorizontal = "═" BoxDoubleVertical = "║" BoxDoubleTopLeft = "╔" BoxDoubleTopRight = "╗" BoxDoubleBottomLeft = "╚" BoxDoubleBottomRight = "╝" )
Double-line box characters for emphasis
const DefaultAgentMaxFieldChars = 500
DefaultAgentMaxFieldChars is the per-value cap agent mode applies to string values in an inline query result (--max-field-chars). A single log `content`, stack trace or serialised object can run to many KB, and `| limit N` bounds rows, not bytes; 500 runes keeps the head of such a value — usually the part that identifies it — while a clipped value still says how much it lost.
const DefaultSpillTTL = 24 * time.Hour
DefaultSpillTTL bounds how long spilled telemetry sits on disk (D11). It doubles as a privacy exposure-window bound.
const EnvelopeVersion = 1
EnvelopeVersion is the current agent-envelope contract version (D31). It is introduced at 1 with the spill feature and must be incremented on any future backward-incompatible shape change. Consumers MUST treat an unrecognised result.kind as opaque and fall back to context (the forward-compat rule).
const FormatAuto = "auto"
FormatAuto is the `-o auto` output format: instead of a fixed encoding, dtctl picks the most token-efficient lossless one for the shape of the result (ChooseAutoFormat) and reports what it picked.
const JQShapeMismatchCode = "jq_shape_mismatch"
JQShapeMismatchCode is the envelope error code for a well-formed --jq filter that addressed a key its input does not have. It is stable so an agent can branch on it rather than pattern-matching the message.
const MetadataMinimal = "minimal"
MetadataMinimal is the --metadata selector for the lean metadata set an agent acts on (#577): what the query cost, and whether the result is approximate. Everything the caller already knows — the query text it typed (twice, as query and canonicalQuery), locale, timezone, DQL version, query id — is left out. It combines with explicit field names: --metadata=minimal,metrics.
Variables ¶
var ( SparkCharsBlock = []rune{'▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'} SparkCharsDots = []rune{'⣀', '⣤', '⣶', '⣿'} SparkCharsSmooth = []rune{'▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'} )
Sparkline characters with different styles
var JSONLinesLayout = JSONLayout{Lines: true}
JSONLinesLayout is the layout of rows printed with -o jsonl.
Functions ¶
func ApplyJQ ¶
ApplyJQ transforms input using the provided jq filter. If filter is empty, input is returned unchanged.
Two outcomes have to stay distinguishable to a machine consumer, because jq spells both of them `null` and a caller that cannot tell them apart reads a wrong filter as a verified negative:
- The filter selected nothing — `empty`, or a `select(...)` no element satisfies. That is a genuine empty selection, and it returns an empty list: the natural zero of the multi-output case.
- The filter addressed a key the input does not have. That is a shape mismatch, and it returns an error naming the keys the input actually carries, so the mistake is self-correcting without a second round trip.
func ApplySeriesMode ¶
func ApplySeriesMode(records []map[string]interface{}, mode SeriesMode, digits int, tabular bool) []map[string]interface{}
ApplySeriesMode compacts the numeric series of DQL timeseries records (those carrying `timeframe` and `interval`) according to mode, and rounds every float in the result — timeseries or not — to `digits` significant digits (0 = no rounding; summary statistics default to 3). With tabular set, a summary is rendered as one human-readable cell instead of an object, for table and CSV output.
Records without timeframe/interval, and arrays that are not purely numeric (nulls allowed), pass through unchanged. The input is never mutated.
func ApplyTrueTypes ¶
func ApplyTrueTypes(records []map[string]interface{}, types []ColumnTypeMapping)
ApplyTrueTypes rewrites scalar record cells from their wire form into native Go scalar types, driven by the DQL column type metadata. It exists because the Grail query API deliberately serialises integer-valued columns (`long`, `duration`) as JSON strings to preserve int64 precision for JavaScript/ TypeScript consumers (see GRAIL-545). dtctl's JSON/YAML output faithfully passes those strings through, which is honest to the wire but surprises jq/pandas/DuckDB users, for whom a `count()` reading `"42"` is a string.
This transform is opt-in (the `--typed` flag). It is precision-safe on the dtctl side: a DQL `long` is an int64, and both encoding/json and yaml.v3 marshal a Go int64 as its full decimal digits, unquoted and lossless — never via a lossy float64. The only precision risk lives in a downstream consumer that parses JSON numbers as 64-bit floats (browser JSON.parse, old jq), which is exactly why the default output stays string-faithful and this is opt-in.
The rewrite is in place: cells are terminal at the point this is called, so no second copy of the (potentially large) result set is held. Columns not present in types, non-scalar values, nulls, and any value that does not cleanly parse to its declared type are left untouched — the transform never fails an export and never fabricates a value.
func AutoDefaultSuggestion ¶
AutoDefaultSuggestion is the context.suggestions entry added when the agent-mode default (-o auto, no -o given) returned a non-JSON encoding. It names the opt-out that restores the native JSON result.
func ClassifyHTTPError ¶
ClassifyHTTPError maps an HTTP status code to a machine-readable error code.
func ClipRecordValues ¶
func ClipRecordValues(records []map[string]interface{}, max int) (out []map[string]interface{}, fields []string)
ClipRecordValues returns a copy of records in which every string value longer than max runes, at any nesting depth, is cut to max runes and ends in the same "…(+N chars)" marker the spill summary uses, so a consumer can tell a clipped value from a short one and how much is missing. fields names the keys whose values were clipped (the nearest enclosing key for a nested value), sorted, so the caller can say which columns to re-fetch in full.
The input is never modified: the caller's rows still back a spill file, which keeps every value in full. Rows with nothing to clip are shared, not copied. max <= 0 disables clipping and returns records as-is.
func ClipValue ¶
ClipValue is ClipRecordValues for a value of arbitrary shape — the output of a --jq filter, which need not be a list of records.
func ColorCode ¶
ColorCode returns the color code if color is enabled, empty string otherwise. Useful for cases where Colorize() doesn't fit (e.g., multi-part color sequences).
func ColorEnabled ¶
func ColorEnabled() bool
ColorEnabled returns whether color output should be used. Respects NO_COLOR env var (https://no-color.org/), FORCE_COLOR env var, and auto-detects non-TTY output.
func Colorize ¶
Colorize wraps text in ANSI color codes if color is enabled. If color is disabled, returns the text unmodified.
func DecodeSnapshotRecords ¶
func DecodeSnapshotRecords(records []map[string]interface{}, simplify bool) []map[string]interface{}
DecodeSnapshotRecords decodes snapshot.data protobuf payloads in query records, adding a "parsed_snapshot" field to each record that contains snapshot data. The decoded tree uses normalized field names (type/value instead of @OT/@value). If simplify is true, variant wrappers are flattened to plain values (e.g., {"type": "Integer", "value": 42} becomes just 42).
func DescribeKV ¶
DescribeKV prints a key-value line with a bold label, right-padded to width. width is the total width of the label column (including the colon and padding). The value is formatted with the given format string and args.
Example: DescribeKV("ID:", 13, "%s", "abc-123") Output: ID: abc-123 (where "ID:" is bold)
func DescribeSection ¶
func DescribeSection(header string)
DescribeSection prints a bold section header (e.g., "Tasks:", "Criteria:"). The header is printed on its own line with no trailing content.
func DoctorFail ¶
func DoctorFail() string
DoctorFail returns a styled "[FAIL]" tag for doctor check output, padded to doctorTagWidth.
func DoctorOK ¶
func DoctorOK() string
DoctorOK returns a styled "[OK]" tag for doctor check output, padded to doctorTagWidth.
func DoctorWarn ¶
func DoctorWarn() string
DoctorWarn returns a styled "[WARN]" tag for doctor check output, padded to doctorTagWidth.
func DrawHeader ¶
DrawHeader renders a styled header line
func DrawSeparator ¶
DrawSeparator renders a horizontal separator
func EncodeEnvelope ¶
EncodeEnvelope writes the agent Response to w as JSON. It pretty-prints (2-space indent) only when w is an interactive terminal — a human running --agent by hand — and emits compact JSON otherwise (piped to a tool or AI agent, redirected to a file, or a test buffer). The compact form is what machine consumers get and drops the ~⅓ of bytes that indentation would otherwise add; the envelope shape is identical either way, only whitespace differs.
func EnvelopeIndented ¶
EnvelopeIndented reports whether EncodeEnvelope pretty-prints for w. It is the one place that decision is made: anything that has to predict the bytes an envelope written to w will take (EnvelopeSize, the spill measurement via EnvelopeRecordsLayout) asks it rather than repeating the test, so the prediction cannot drift from what is actually written.
func EnvelopeSize ¶
EnvelopeSize returns the number of bytes EncodeEnvelope would write for resp to w — the same indentation decision, so the count is what the reader of w actually receives. Nothing is written to w. An output budget (--max-output-bytes) is measured with it rather than with a separate serialisation of the rows, so the envelope, the context and the encoding the caller chose are all inside the budget.
func ExpandMetadataFields ¶
func ExpandMetadataFields(meta *QueryMetadata, fields []string, defaultWindow bool) []string
ExpandMetadataFields resolves the minimal selector against one response's metadata into concrete field names, so every renderer (envelope, JSON/YAML, CSV comment header, table footer) applies the same selection. A field is kept only when it is remarkable for this response:
- executionTimeMilliseconds: always
- scannedBytes, scannedDataPoints: when non-zero (the cost of the scan)
- sampled: only when true (the result is approximate)
- approximations: only when non-empty (the result is approximate)
- analysisTimeframe: only when defaultWindow — the query named no window, so the agent cannot know which one the server picked
- contributions: when present (the caller asked for them explicitly)
Explicit field names next to the selector are appended, deduplicated. A selection without the selector, or nil metadata, is returned unchanged.
func ExtForFormat ¶
ExtForFormat maps a spill format to the file extension used on disk. It is the inverse of FormatForExt and the single source of truth for the format→extension mapping (shared by query and inspect re-spill); an unknown format defaults to the jsonl extension to match the default spill format.
func FormatForExt ¶
FormatForExt maps a spilled-file extension to its spill format, or "" for a missing/unrecognised extension. It is the single source of truth for the extension→format mapping shared by the query spill path, `inspect`'s readers, and the re-spill path (so the supported-format set cannot drift between them).
func FormatMetadataCSVComments ¶
func FormatMetadataCSVComments(m *QueryMetadata, fields []string) string
FormatMetadataCSVComments formats query metadata as #-prefixed comment lines for prepending to CSV output. The fields parameter controls which fields are shown; nil or ["all"] means all fields.
func FormatMetadataFooter ¶
func FormatMetadataFooter(m *QueryMetadata, fields []string) string
FormatMetadataFooter formats query metadata as a human-readable footer for table and wide output. The fields parameter controls which fields are shown; nil or ["all"] means all fields.
func FprintAutoChoice ¶
func FprintAutoChoice(w io.Writer, choice AutoChoice)
FprintAutoChoice writes the one-line notice that tells a human which format `-o auto` picked. It goes to stderr so stdout stays exactly the chosen format.
func FprintDescribeKV ¶
FprintDescribeKV prints a key-value line with a bold label to the given writer.
func FprintDescribeSection ¶
FprintDescribeSection prints a bold section header to the given writer.
func FprintHint ¶
FprintHint prints a hint message to the given writer.
func FprintHumanError ¶
FprintHumanError prints a human-readable error message to the given writer.
func FprintInfo ¶
FprintInfo prints an informational message to the given writer.
func FprintSuccess ¶
FprintSuccess prints a success message to the given writer.
func FprintWarning ¶
FprintWarning prints a warning message to the given writer.
func GetFullscreenDimensions ¶
func GetFullscreenDimensions() (width, height int)
GetFullscreenDimensions returns chart dimensions suitable for fullscreen display It leaves some margin for headers and borders
func GetTerminalSize ¶
func GetTerminalSize() (width, height int)
GetTerminalSize returns the current terminal width and height Returns default values if terminal size cannot be determined
func IsAllFields ¶
IsAllFields returns true if the field list means "show all fields".
func IsAutoFormat ¶
IsAutoFormat reports whether format selects `-o auto`.
func IsMinimalFields ¶
IsMinimalFields reports whether the selection contains the minimal selector.
func IsStructuredOutputFormat ¶
IsStructuredOutputFormat reports whether a format can represent arbitrary JSON values emitted by jq. auto counts: it chooses its encoding after the filter has run.
func IsTabularFormat ¶
IsTabularFormat reports whether format renders rows and columns (and so wants the flat --fields representation). plain mirrors NewPrinterWithOpts, which turns table/wide into JSON in plain mode.
func ManagedContextFor ¶
ManagedContextFor reports whether path lies inside a managed spill cache tree (D7) and, if so, the context-partition segment it sits under (D9). It does not touch the filesystem or require the location to be writable — it is a pure path comparison used by Layer 2 to refuse cross-context reads structurally, before opening the file. ok is false for user-chosen paths (--spill-to / DTCTL_SPILL_DIR), which opt out of partitioning (D25) and so carry no structural context guarantee.
func MarshalTOON ¶
MarshalTOON encodes v as a TOON string using the same options as the TOON printer and the agent envelope's `-o toon` path, so every TOON payload dtctl emits comes out of one encoder. Exported for callers outside this package that embed a TOON-encoded payload inside the agent envelope (pkg/exec).
func MeasureSerializedBytes ¶
func MeasureSerializedBytes(records interface{}, format string, layout JSONLayout) (int64, string)
MeasureSerializedBytes serialises records in the chosen display encoding and returns the byte count plus the normalised encoding name used (D24). The threshold is measured against the actual encoding the invocation will emit so the byte count is a faithful proxy for the tokens the agent would otherwise receive (50 KB of JSON ≠ 50 KB of toon). table/wide/chart-style formats are measured as json because that is what agent mode actually emits.
layout is the JSON layout the rows are printed in, which the caller knows: compact in an agent envelope piped to a tool or a model, indented at the rows' depth on a terminal (EnvelopeRecordsLayout). Measured with the printer's root-level indentation instead, a piped agent result was overstated by up to 2.5x for narrow rows, so --spill=auto spilled results under --spill-threshold (#570). For json the count is then exactly the bytes the value occupies in the printed document, plus one for the newline that ends a top-level encoding; with JSONLinesLayout it is exactly what JSONLPrinter writes (-o jsonl outside agent mode). layout does not affect csv, yaml and toon; inside an agent envelope those are carried as a JSON string, and the count is the text before string escaping.
Nothing is kept: bytes go to io.Discard and only the count is returned. The JSON measurement — the one every agent-mode query pays, since json is the agent display encoding — streams element by element (streamJSONArray) rather than handing the whole slice to json.Encoder, whose indenting buffers the entire serialised result twice over. That transient buffer, not the column statistics or the row sample, was what made a spilling query peak higher than a non-spilling one (#467).
For -o auto the encoding is the one ChooseAutoFormat picks for records.
func MetadataOmitsFields ¶
func MetadataOmitsFields(meta *QueryMetadata, fields []string) bool
MetadataOmitsFields reports whether rendering meta with the given concrete field selection leaves out a field the full block would have shown.
func MetadataToMap ¶
func MetadataToMap(meta *QueryMetadata, fields []string) interface{}
MetadataToMap converts QueryMetadata to a map for JSON/YAML serialization. When specific fields are selected, the map includes only those fields, preserving zero values (unlike omitempty on the struct which suppresses them). When fields is nil/empty or contains "all", the original struct is returned so that omitempty can suppress genuine zeros for cleaner output.
func MiniGraphColored ¶
MiniGraphColored renders a colored mini graph
func NormalizeJQOutputFormat ¶
NormalizeJQOutputFormat promotes non-structured formats to json when --jq is used.
func NormalizeMeasureEncoding ¶
NormalizeMeasureEncoding maps a display format to the encoding the bytes are actually measured (and emitted) as in agent mode. Human-readable layouts that agent mode never emits collapse to json.
func ParseFields ¶
ParseFields splits a --fields value into trimmed, de-duplicated paths.
func ParseMetadataFields ¶
ParseMetadataFields parses the --metadata flag value into a field list. "all" (the NoOptDefVal) returns ["all"]. A comma-separated string like "executionTimeMilliseconds,scannedRecords" returns individual field names; the "minimal" selector may appear among them (see ExpandMetadataFields). Returns an error if any field name is not recognized.
func PinColorOff ¶
func PinColorOff()
PinColorOff turns colour off for the whole process, ahead of the cached detection, until ResetColorCache. The detection reads the process: NO_COLOR and FORCE_COLOR from its environment, and whether its stdout is a terminal. An invocation that prints to a writer of its own, as a concurrent embedded invocation does, is never a terminal and must not inherit the host's answer. Safe to call from several goroutines.
func PrintError ¶
func PrintError(writer io.Writer, detail *ErrorDetail) error
PrintError writes an error response to the given writer in agent envelope format. This is a package-level function because errors are handled centrally in cmd/root.go, not through the printer instance.
func PrintHint ¶
func PrintHint(format string, args ...interface{})
PrintHint prints a hint message to stderr, indented with a cyan label. Use this for actionable suggestions that follow an error or warning.
func PrintHumanError ¶
func PrintHumanError(format string, args ...interface{})
PrintHumanError prints a human-readable error message to stderr. Uses bold red for the "Error:" prefix. For agent/plain mode, use PrintError instead.
func PrintInfo ¶
func PrintInfo(format string, args ...interface{})
PrintInfo prints an informational message to stderr. No prefix or color is applied — use this for supplementary detail lines (e.g., IDs, URLs) that accompany a PrintSuccess message. Output goes to stderr so it doesn't interfere with structured stdout.
func PrintSuccess ¶
func PrintSuccess(format string, args ...interface{})
PrintSuccess prints a success message with a green "OK" prefix. Output goes to stderr so it doesn't interfere with structured stdout.
func PrintWarning ¶
func PrintWarning(format string, args ...interface{})
PrintWarning prints a warning message with a yellow prefix. Output goes to stderr so it doesn't interfere with structured stdout.
func ProbeWritable ¶
ProbeWritable reports whether dir can be created and written to. It does not trust config; it probes (D8) by ensuring the dir exists and creating then removing a marker file.
func PruneOldSpills ¶
PruneOldSpills opportunistically deletes spilled files (and stray .tmp files, D22) older than ttl, throttled to ~hourly via a marker so we never stat-storm (D11). Errors are swallowed: pruning is best-effort and must never fail a query.
func RenderColoredSparkline ¶
RenderColoredSparkline renders a simple white sparkline
func RenderGradientBar ¶
RenderGradientBar renders a simple horizontal bar (white filled, dim empty)
func RenderGradientBarWithScheme ¶
RenderGradientBarWithScheme renders a simple bar (schemeIndex ignored for simplicity)
func RenderProgressBar ¶
RenderProgressBar renders a progress bar with percentage
func ResetColorCache ¶
func ResetColorCache()
ResetColorCache resets the cached color detection result. NOT safe for concurrent use — intended for testing only.
func RoundNumbers ¶
RoundNumbers returns a copy of records with every float64 (recursively, through maps and slices) rounded to `digits` significant digits. digits <= 0 returns records unchanged. Strings — including DQL longs, which the API encodes as strings — are never touched.
func SampleRows ¶
SampleRows returns up to n leading records as the manifest's sample_rows, prepared for embedding in the envelope: non-finite floats are dropped and long string leaves are clipped (see prepareSampleValue). The originals are never mutated (the file writer serialises the full untouched rows).
func SanitizeContextName ¶
SanitizeContextName makes a context name safe to use as a single path segment (D9). Empty/degenerate names collapse to "default".
func SetPlainMode ¶
func SetPlainMode(plain bool)
SetPlainMode disables color output when --plain is used. Must be called before the first call to ColorEnabled() (e.g., during command initialization) so the cached result reflects the flag.
func SidecarPathFor ¶
SidecarPathFor returns the sidecar manifest path for a spilled data file.
func SimplifySnapshotValues ¶
func SimplifySnapshotValues(value interface{}) interface{}
SimplifySnapshotValues flattens variant type wrappers to plain values. The input should be a normalized decoded snapshot tree (after normalizeSnapshotFieldNames).
Simplification rules:
- Primitives: {"type": "Integer", "value": 42} → 42
- Strings: {"type": "String", "value": "hello"} → "hello"
- Objects: {"type": "MyClass", "@attributes": {field: ...}} → {field: ...} (recurse)
- Lists/Sets: {"type": "ArrayList", "value": [...]} → [...] (recurse into elements)
- Maps: {"type": "HashMap", "value": [[k,v],...]} → {k: v, ...} (convert pairs to map)
- Namespaces (plain maps without type wrappers): recurse into each value
func SpillBaseDir ¶
SpillBaseDir resolves the base directory for managed spills (D7). Resolution: an explicit preferred dir (config spill.dir / DTCTL_SPILL_DIR) if writable → the OS user cache dir → $TMPDIR. Returns an error only if none are usable, in which case the caller degrades to summary-only (D8). The returned bool reports whether the location is the managed cache (false ⇒ a user-chosen dir that opts out of the managed privacy guarantees, D25).
func SpillHash ¶
SpillHash returns the short stable digest used in the spill filename q-<hash>.<ext> (D10). It is computed over the canonical query + timeframe + segments + sampling so re-running the same query overwrites in place rather than accumulating. It is deliberately NOT a cache key — re-runs always re-query Grail and overwrite (D10 Non-Goal).
func StatsDisplay ¶
StatsDisplay formats statistics in btop style
func SummarizeSnapshotForTable ¶
SummarizeSnapshotForTable replaces the parsed_snapshot map in each record with a human-readable summary string, and filters to only the most relevant columns for readable table/CSV output. Example summary: "send() at PpxSessionSender.java:62 | 4 locals, 30 frames"
func SupportsFieldProjection ¶
SupportsFieldProjection reports whether format can render a --fields projection. Charts need the full typed records they were built for.
func ValidMetadataFieldNames ¶
func ValidMetadataFieldNames() []string
ValidMetadataFieldNames returns the sorted list of valid metadata field names for help text and validation messages.
func WriteSidecar ¶
func WriteSidecar(dataPath string, sc *SidecarManifest) error
WriteSidecar writes the on-disk sidecar manifest next to a spilled data file (D34). For data file q-<hash>.<ext> the sidecar is q-<hash>.manifest.json. It uses the same atomic temp+rename and 0600 perms, and is intended to be written LAST so its presence implies a complete data file.
func WriteSpillFile ¶
WriteSpillFile writes data atomically to targetPath: it writes to a unique temp file in the same directory and rename(2)s it onto the final name on success (D22). A crashed/partial spill leaves only a .tmp that the TTL prune sweeps; readers never observe a half-written file. Returns the number of bytes written. The parent directory is created with 0700 and the file ends up 0600.
Types ¶
type AgentPrinter ¶
type AgentPrinter struct {
// contains filtered or unexported fields
}
AgentPrinter wraps CLI output in a Response envelope for machine consumers. It implements the Printer interface.
By default, the result field inside the JSON envelope is encoded as native JSON. Callers can switch to TOON via SetResultFormat("toon") for token efficiency.
func AsAgentPrinter ¶
func AsAgentPrinter(pr Printer) *AgentPrinter
AsAgentPrinter returns the agent envelope printer behind pr — pr itself or the printer a wrapper such as ShapingPrinter delegates to — or nil.
func NewAgentPrinter ¶
func NewAgentPrinter(writer io.Writer, ctx *ResponseContext) *AgentPrinter
NewAgentPrinter creates an AgentPrinter that writes envelope-wrapped JSON to writer. The result field defaults to JSON encoding. Use SetResultFormat("toon") to enable TOON encoding for token efficiency.
func (*AgentPrinter) Context ¶
func (p *AgentPrinter) Context() *ResponseContext
Context returns the response context for direct manipulation.
func (*AgentPrinter) Print ¶
func (p *AgentPrinter) Print(data interface{}) error
Print writes a single result wrapped in the agent envelope.
func (*AgentPrinter) PrintList ¶
func (p *AgentPrinter) PrintList(data interface{}) error
PrintList writes a list result wrapped in the agent envelope. If Total has been set via SetTotal, it is included in the context.
func (*AgentPrinter) SetDuration ¶
func (p *AgentPrinter) SetDuration(duration string)
SetDuration sets the operation duration in the response context. Only use for commands where timing is meaningful (wait, query, exec).
func (*AgentPrinter) SetHasMore ¶
func (p *AgentPrinter) SetHasMore(hasMore bool)
SetHasMore indicates whether more results exist beyond the current page.
func (*AgentPrinter) SetJQFilter ¶
func (p *AgentPrinter) SetJQFilter(filter string)
SetJQFilter applies a jq transform to the result before envelope encoding.
func (*AgentPrinter) SetLinks ¶
func (p *AgentPrinter) SetLinks(links map[string]string)
SetLinks sets deep links to the Dynatrace UI in the response context.
func (*AgentPrinter) SetMaxFieldChars ¶
func (p *AgentPrinter) SetMaxFieldChars(n int)
SetMaxFieldChars clips every string value in the result longer than n runes (0 = off, the default), marking the clip on the context. It runs after the jq filter, so a filter still sees — and can match on — the full values.
func (*AgentPrinter) SetMetadata ¶
func (p *AgentPrinter) SetMetadata(meta interface{})
SetMetadata sets the envelope's metadata sibling (Grail query metadata). It keeps metadata reachable next to `result` even when a --jq filter narrowed the payload down to the rows, which is how the unfiltered query envelope presents it. Nil (the default) omits the field.
func (*AgentPrinter) SetResource ¶
func (p *AgentPrinter) SetResource(resource string)
SetResource sets the resource type in the response context.
func (*AgentPrinter) SetResultFormat ¶
func (p *AgentPrinter) SetResultFormat(format string)
SetResultFormat controls how the result field is encoded inside the agent envelope. Supported values are "toon", "auto" (chosen per result, reported in context.format) and "json" (default). Any other value falls back to "json" — the result must be a valid native JSON value inside the envelope — and records a warning on the response context, so an agent that passed `-o csv` learns its format was not honoured instead of silently receiving JSON that looks like it was what it asked for.
func (*AgentPrinter) SetSuggestions ¶
func (p *AgentPrinter) SetSuggestions(suggestions []string)
SetSuggestions sets the follow-up suggestions in the response context.
func (*AgentPrinter) SetTotal ¶
func (p *AgentPrinter) SetTotal(total int)
SetTotal sets the total item count in the response context.
func (*AgentPrinter) SetWarnings ¶
func (p *AgentPrinter) SetWarnings(warnings []string)
SetWarnings sets non-fatal warnings in the response context.
func (*AgentPrinter) UseAutoByDefault ¶
func (p *AgentPrinter) UseAutoByDefault()
UseAutoByDefault selects -o auto as the agent-mode default, used when the caller gave no -o. It differs from SetResultFormat("auto") only in that a csv/yaml choice adds AutoDefaultSuggestion, since the caller did not ask for a non-JSON result and may not expect one.
type AutoChoice ¶
type AutoChoice struct {
Format string // "csv", "yaml" or "json"
Reason string // one of the AutoReason* constants
}
AutoChoice is the format `-o auto` settled on and why.
func ChooseAutoFormat ¶
func ChooseAutoFormat(data interface{}) AutoChoice
ChooseAutoFormat picks an output format from the shape of data. Only lossless encodings are candidates (a table truncates and TOON is never the smallest here), and the rules are, in order:
- nil, an empty list, or a scalar → json. There is nothing to compress, and in agent mode the result then stays a native JSON value.
- a single object, or a list with one object → yaml (key: value lines).
- a list of objects whose values are all scalars and whose cells are at least half filled → csv. This is the typical `summarize`/`fields` result, where CSV states every column name once.
- anything else (nested values, sparse rows, lists of non-objects) → yaml, which stays readable for nested data and needs no quoting or braces.
Structs are judged by their JSON form, so field names match `-o json`.
func MarshalAuto ¶
func MarshalAuto(data interface{}) (choice AutoChoice, encoded string, err error)
MarshalAuto chooses a format for data and encodes it. For a json choice the value is returned unchanged (encoded stays empty) so callers can embed it natively; for csv/yaml encoded holds the text.
type AutoPrinter ¶
type AutoPrinter struct {
// contains filtered or unexported fields
}
AutoPrinter implements `-o auto` outside agent mode: it chooses the format from the (jq-filtered) data, prints it in that format, and names the choice on stderr. In agent mode the choice is reported in context.format instead (see AgentPrinter).
func (*AutoPrinter) Print ¶
func (p *AutoPrinter) Print(obj interface{}) error
Print prints obj in the format ChooseAutoFormat picks for it.
func (*AutoPrinter) PrintList ¶
func (p *AutoPrinter) PrintList(obj interface{}) error
PrintList prints a list in the format ChooseAutoFormat picks for it.
type BarChartPrinter ¶
type BarChartPrinter struct {
// contains filtered or unexported fields
}
BarChartPrinter prints timeseries data as horizontal bar charts (aggregated)
func NewBarChartPrinter ¶
func NewBarChartPrinter(writer io.Writer) *BarChartPrinter
NewBarChartPrinter creates a new bar chart printer
func NewBarChartPrinterWithSize ¶
func NewBarChartPrinterWithSize(writer io.Writer, width int) *BarChartPrinter
NewBarChartPrinterWithSize creates a new bar chart printer with custom width
func (*BarChartPrinter) Print ¶
func (p *BarChartPrinter) Print(obj interface{}) error
Print prints the data as bar charts if it contains timeseries, otherwise falls back to JSON
func (*BarChartPrinter) PrintList ¶
func (p *BarChartPrinter) PrintList(obj interface{}) error
PrintList prints a list of records as bar charts
type BrailleChartPrinter ¶
type BrailleChartPrinter struct {
// contains filtered or unexported fields
}
BrailleChartPrinter prints timeseries data as high-resolution braille graphs
func NewBrailleChartPrinter ¶
func NewBrailleChartPrinter(writer io.Writer) *BrailleChartPrinter
NewBrailleChartPrinter creates a new braille chart printer
func NewBrailleChartPrinterWithSize ¶
func NewBrailleChartPrinterWithSize(writer io.Writer, width, height int) *BrailleChartPrinter
NewBrailleChartPrinterWithSize creates a new braille chart printer with custom dimensions
func (*BrailleChartPrinter) Print ¶
func (p *BrailleChartPrinter) Print(obj interface{}) error
Print prints the data as braille charts if it contains timeseries
func (*BrailleChartPrinter) PrintList ¶
func (p *BrailleChartPrinter) PrintList(obj interface{}) error
PrintList prints a list of records as braille charts
type BrailleGraph ¶
type BrailleGraph struct {
// contains filtered or unexported fields
}
BrailleGraph renders a high-resolution graph using braille characters
func NewBrailleGraph ¶
func NewBrailleGraph(width, heightRows int) *BrailleGraph
NewBrailleGraph creates a new braille graph canvas
func (*BrailleGraph) PlotFilled ¶
func (bg *BrailleGraph) PlotFilled(values []float64, minVal, maxVal float64)
PlotFilled plots values as a filled area graph
func (*BrailleGraph) PlotLine ¶
func (bg *BrailleGraph) PlotLine(values []float64, minVal, maxVal float64)
PlotLine plots a series of values as a line graph
func (*BrailleGraph) Render ¶
func (bg *BrailleGraph) Render() string
Render converts the canvas to a string of braille characters
func (*BrailleGraph) RenderColored ¶
func (bg *BrailleGraph) RenderColored() string
RenderColored renders with color gradient based on row position
func (*BrailleGraph) SetPixel ¶
func (bg *BrailleGraph) SetPixel(x, y int)
SetPixel sets a pixel in the braille canvas
type CSVPrinter ¶
type CSVPrinter struct {
// contains filtered or unexported fields
}
CSVPrinter prints output as CSV
func (*CSVPrinter) Print ¶
func (p *CSVPrinter) Print(obj interface{}) error
Print prints a single object as CSV
func (*CSVPrinter) PrintList ¶
func (p *CSVPrinter) PrintList(obj interface{}) error
PrintList prints a list of objects as CSV
type Change ¶
type Change struct {
Type ChangeType
Resource interface{}
Field string
OldValue interface{}
NewValue interface{}
}
Change represents a detected change in watch mode
type ChangeType ¶
type ChangeType string
ChangeType represents the type of change detected in watch mode
const ( ChangeTypeAdded ChangeType = "ADDED" ChangeTypeModified ChangeType = "MODIFIED" ChangeTypeDeleted ChangeType = "DELETED" )
type ChartPrinter ¶
type ChartPrinter struct {
// contains filtered or unexported fields
}
ChartPrinter prints timeseries data as ASCII charts
func NewChartPrinter ¶
func NewChartPrinter(writer io.Writer) *ChartPrinter
NewChartPrinter creates a new chart printer
func NewChartPrinterWithSize ¶
func NewChartPrinterWithSize(writer io.Writer, width, height int) *ChartPrinter
NewChartPrinterWithSize creates a new chart printer with custom dimensions
func (*ChartPrinter) Print ¶
func (p *ChartPrinter) Print(obj interface{}) error
Print prints the data as a chart if it contains timeseries, otherwise falls back to JSON
func (*ChartPrinter) PrintList ¶
func (p *ChartPrinter) PrintList(obj interface{}) error
PrintList prints a list of records as charts
type ColumnStats ¶
type ColumnStats struct {
Name string `json:"name"`
Type string `json:"type"`
Nulls int `json:"nulls"`
Distinct *int `json:"distinct,omitempty"`
HighCardinality bool `json:"high_cardinality,omitempty"`
Min interface{} `json:"min,omitempty"`
Max interface{} `json:"max,omitempty"`
Mean *float64 `json:"mean,omitempty"`
Top []TopValue `json:"top,omitempty"`
// Basis is set to "sample" when the underlying result was sampled by Grail
// (D23) so an agent reading a column figure cannot miss that it is a
// sample-based estimate, not a population truth.
Basis string `json:"basis,omitempty"`
}
ColumnStats is the lean per-column profile embedded in a spill manifest. Optional numeric fields are pointers/interfaces so they are omitted (rather than emitted as a misleading zero) for columns where they don't apply.
func CapColumnsForEnvelope ¶
func CapColumnsForEnvelope(cols []ColumnStats, max int) (kept []ColumnStats, omitted []string)
CapColumnsForEnvelope returns a size-bounded view of column stats for the in-context envelope (C/D): when there are more than max columns it keeps the profiles of the most-populated columns (fewest nulls first; ties broken by name) and returns the names of the rest in `omitted`, so the agent still knows the full schema exists without paying to profile every sparse column. The kept columns are returned in the input's (alphabetical) order; omitted names are sorted. The input slice — used for the on-disk sidecar — is never mutated. max <= 0 or a column count within the cap returns the input unchanged.
func ComputeColumnStats ¶
func ComputeColumnStats(records []map[string]interface{}, sampled bool, topK, maxDistinct int) []ColumnStats
ComputeColumnStats computes the lean Layer-1 column profile over the buffered records in a single pass (PR2 is buffered; the same accumulator powers the streaming Layer 2 `inspect --stats` path). Columns are reported in deterministic (alphabetical) order. When sampled is true every column carries basis:"sample" per D23.
type ColumnTypeMapping ¶
type ColumnTypeMapping struct {
Name string
Type string // DQL type name, e.g. "long", "string", "timestamp"
}
ColumnTypeMapping is the output-layer view of a DQL column's type. It mirrors the SDK's per-column type info without importing the SDK into the dispatch path, keeping the dependency direction one-way.
type Compaction ¶
type Compaction struct {
// Constant holds every column that is present, non-null and equal in every
// row. Nil when there are fewer than two rows (a single row is trivially
// constant, and hoisting it would only move it) or nothing is shared.
Constant map[string]interface{}
// Records are copies of the input rows without the Constant columns and
// without null values. Never nil, so an empty result still encodes as [].
Records []map[string]interface{}
// NullColumns names, sorted, the columns that are null or absent in every
// row. They vanish from Records entirely; a summary that describes the
// schema can still list them.
NullColumns []string
// DroppedNulls counts the null values omitted from Records.
DroppedNulls int
}
Compaction is a token-lean view of a row set (#578). Telemetry rows are dominated by resource attributes that are identical across a result (k8s.*, host.*, service.name, ...) and by explicit nulls from mixed sources; repeating them on every row is most of what an agent pays for.
The original rows are recovered exactly as `row = Constant ∪ record`, with a key absent from both meaning null.
func CompactRecords ¶
func CompactRecords(records []map[string]interface{}) Compaction
CompactRecords computes the Compaction of records. The input is not mutated.
func (Compaction) Changed ¶
func (c Compaction) Changed(encoding string) bool
Changed reports whether the compaction altered what the given encoding emits: something was hoisted, or a null was dropped. Under the tabular encodings (TOON, CSV) only all-null columns drop (see Tabular), so a partial null does not count there.
func (Compaction) EnvelopeConstant ¶
func (c Compaction) EnvelopeConstant() map[string]interface{}
EnvelopeConstant returns Constant prepared for a summary envelope the way sample rows are (see prepareSampleValue): long strings clipped, non-finite floats dropped. The full values are in the rows on disk. Nil when there is nothing constant.
func (Compaction) FilterColumns ¶
func (c Compaction) FilterColumns(cols []ColumnStats) []ColumnStats
FilterColumns returns cols without the columns this compaction collapsed (constant and all-null ones), whose per-column profile carries nothing the Constant map or NullColumns list does not already say. cols is not mutated.
func (Compaction) Sparse ¶
func (c Compaction) Sparse(records []map[string]interface{}) []map[string]interface{}
Sparse returns copies of records without the constant columns and without any null value — the shape CompactRecords gives Records. A streamed result uses it for the few rows it keeps (the sample), since its Compaction carries no Records.
func (Compaction) Tabular ¶
func (c Compaction) Tabular(records []map[string]interface{}) []map[string]interface{}
Tabular returns copies of records (the rows this compaction was computed from) without the constant and all-null columns, but keeping the nulls of every other column. A tabular encoding (TOON, CSV) needs uniform rows to print one table; dropping a partial null there makes the rows ragged, and TOON's per-row key/value fallback costs more than the nulls it saved.
type CompactionAccumulator ¶
type CompactionAccumulator struct {
// contains filtered or unexported fields
}
CompactionAccumulator folds rows one at a time into the column-level half of a Compaction — the constant and all-null columns — so a streamed result can be compacted without being held. The per-row Records a buffered Compaction also carries have no place here; a streamed row is written to its destination and released.
Memory is O(columns), independent of the row count.
func NewCompactionAccumulator ¶
func NewCompactionAccumulator() *CompactionAccumulator
NewCompactionAccumulator creates an accumulator. Reuse one per result; it is not safe for concurrent use.
func (*CompactionAccumulator) Finalize ¶
func (a *CompactionAccumulator) Finalize() Compaction
Finalize produces the compaction the observed rows imply. It matches what CompactRecords would have computed over the same rows, minus Records: a single row yields no Constant (hoisting it would only move it), and columns that were null or absent everywhere are named rather than profiled.
func (*CompactionAccumulator) Observe ¶
func (a *CompactionAccumulator) Observe(rec map[string]interface{})
Observe folds a single row in.
type CompiledJQ ¶
type CompiledJQ struct {
// contains filtered or unexported fields
}
CompiledJQ is a jq program parsed and compiled once for repeated, per-record execution in a streaming filter (e.g. `dtctl inspect --jq` over a whole spilled file). ApplyJQ re-parses and re-compiles on every call, which is fine for a one-shot post-filter but quadratic when run over millions of records; CompiledJQ pays that cost once.
func CompileJQ ¶
func CompileJQ(filter string) (*CompiledJQ, error)
CompileJQ parses and compiles a jq program for streaming, per-record use. The returned *CompiledJQ is safe to reuse across records (gojq does not mutate the compiled code). A parse/compile failure is reported as an invalid-filter error.
func (*CompiledJQ) RunRecord ¶
func (c *CompiledJQ) RunRecord(rec map[string]interface{}) ([]interface{}, error)
RunRecord runs the compiled program over a single record and returns every value it emits, in order. A record that yields no output — a `select(...)` that does not match, or `empty` — returns an empty slice: that is exactly how filtering drops a row. A runtime error from the program (e.g. a type error) is returned so the caller can surface it rather than silently skipping rows.
The record is normalised through encoding/json first so values produced by any reader (Parquet/CSV typed columns, time values) run cleanly through gojq, which only accepts nil/bool/int/float64/string/[]any/map[string]any inputs.
type DataFetcher ¶
DataFetcher is a function that fetches fresh data for live updates
type EmptyReason ¶
type EmptyReason struct {
// Code is "field_not_in_sample" or "metric_not_in_window".
Code string `json:"code"`
Field string `json:"field,omitempty"`
Metric string `json:"metric,omitempty"`
DataObject string `json:"data_object,omitempty"`
DidYouMean []string `json:"did_you_mean,omitempty"`
SampleSize int `json:"sample_size,omitempty"`
Evidence string `json:"evidence"`
}
EmptyReason is a diagnosed cause of an empty query result. Each finding names its basis in Evidence (a sample, or the window that was checked), so a consumer never mistakes a sampled observation for a catalog fact.
type ErrorDetail ¶
type ErrorDetail struct {
Code string `json:"code"`
Message string `json:"message"`
Operation string `json:"operation,omitempty"`
StatusCode int `json:"status_code,omitempty"`
RequestID string `json:"request_id,omitempty"`
// Scope-check fields, populated for code == "insufficient_scope".
RequiredScopes []string `json:"required_scopes,omitempty"`
GrantedScopes []string `json:"granted_scopes,omitempty"`
MissingScopes []string `json:"missing_scopes,omitempty"`
// AlternativeScopes are scope sets the endpoint accepts in place of
// RequiredScopes; granting any one set in full would also suffice.
AlternativeScopes [][]string `json:"alternative_scopes,omitempty"`
// Query-error fields, populated when the DQL API reports where in the
// query the error is: the span, and the offending line with a caret line
// marking it.
Position *ErrorPosition `json:"position,omitempty"`
Snippet string `json:"snippet,omitempty"`
Suggestions []string `json:"suggestions,omitempty"`
}
ErrorDetail is a structured error for machine consumption. It lives in the Response envelope when ok=false.
type ErrorPosition ¶
type ErrorPosition struct {
Line int `json:"line"`
Column int `json:"column"`
EndLine int `json:"end_line,omitempty"`
EndColumn int `json:"end_column,omitempty"`
}
ErrorPosition locates an error in a query: 1-based line and column, in characters, with the end inclusive. The end is omitted when unknown.
type FlatRows ¶
type FlatRows struct {
Columns []string
Rows [][]interface{}
// contains filtered or unexported fields
}
FlatRows is the tabular form of a --fields projection: named columns in a fixed order, one row per item. The table, CSV and TOON printers render it with its column order intact; any other encoder sees an array of flat objects keyed by column name.
func (*FlatRows) MarshalJSON ¶
MarshalJSON encodes the rows as flat objects (a single object when the projection was of one item).
type InlineRecords ¶
type InlineRecords struct {
Kind string `json:"kind"`
Constant map[string]interface{} `json:"constant,omitempty"`
Records []map[string]interface{} `json:"records"`
Types interface{} `json:"types,omitempty"`
}
InlineRecords is the result payload for the KindRecords envelope (D2): the result was small enough to return inline, so the rows are carried directly, still behind the same self-describing discriminator so an agent branches on result.kind uniformly across inline and spilled results (D2/D31). Emitted only in agent mode on the spill-aware path; the non-spill output path is unchanged. Query metadata rides on the envelope's top-level `metadata` key (Response.Metadata), not inside the result payload, so it is placed identically for inline and spilled results.
When the result was compacted (--compact, the agent-mode default), Constant carries the columns that hold the same value in every row and Records omits them along with every null value; a row is `constant ∪ record`, an absent key meaning null (see CompactRecords). Constant precedes Records so a reader sees it first, and it is omitted when nothing was hoisted.
Types is the DQL per-column type block (indexRange + mappings), set only when the caller explicitly asked for it (--include-types) and the API returned it. It describes the full result, so it is the same whether the rows were compacted, clipped or cut by an output budget.
type InlineRecordsEncoded ¶
type InlineRecordsEncoded struct {
Kind string `json:"kind"`
Encoding string `json:"encoding"`
Constant map[string]interface{} `json:"constant,omitempty"`
Records string `json:"records"`
Types interface{} `json:"types,omitempty"`
}
InlineRecordsEncoded is the KindRecords payload when the agent asked for a dense row encoding (`-o toon`). It carries the same `kind` discriminator as InlineRecords so a consumer branches identically, but `records` is an encoded string rather than native JSON, and `encoding` names the codec so the string is self-describing. Keeping the envelope here is what makes `-o toon` behave the same way either side of the spill threshold: below it the rows come back encoded under this shape, above it as a `result-file` manifest — never as a bare TOON document with no `ok`/`context`. Constant is the compaction's hoisted columns, as on InlineRecords; it stays native JSON rather than joining the encoded string, and so does Types.
type JQError ¶
JQError is a --jq failure that carries a stable envelope code and self-correcting suggestions, so agent mode can surface both verbatim instead of classifying a bare message.
type JSONLPrinter ¶
type JSONLPrinter struct {
// contains filtered or unexported fields
}
JSONLPrinter prints output as JSON Lines (JSONL / newline-delimited JSON): one compact JSON value per line. It is well suited to large query results — each record is encoded and written as it is visited rather than marshalling the whole slice into one buffer, and the result is read natively by common local data tooling.
Note: this printer takes a materialised slice. The query path reaches the same line format without one — see pkg/exec/dql_stream.go.
func (*JSONLPrinter) Print ¶
func (p *JSONLPrinter) Print(obj interface{}) error
Print writes a single object as one JSON line.
func (*JSONLPrinter) PrintList ¶
func (p *JSONLPrinter) PrintList(obj interface{}) error
PrintList writes each element of a slice as its own JSON line. Non-slice input is written as a single line (mirroring the single-object case).
type JSONLayout ¶
type JSONLayout struct {
Prefix string
Indent string
// Lines is JSON Lines, as JSONLPrinter prints a slice: each element compact
// on a line of its own, with no array framing, and nothing at all for an
// empty slice. Prefix and Indent do not apply.
Lines bool
}
JSONLayout is how a JSON value is laid out where it is printed: compact (the zero value), or indented by Indent per level with every line after the first carrying Prefix, the indentation of the depth the value sits at inside its document. Measuring a value with the layout it is printed in counts exactly the bytes it takes there.
func EnvelopeRecordsLayout ¶
func EnvelopeRecordsLayout(w io.Writer) JSONLayout
EnvelopeRecordsLayout is the JSON layout of the rows of a kind:"records" result (InlineRecords: result.records, and result.constant and result.types beside them) in an envelope EncodeEnvelope writes to w, for the spill measurement (MeasureSerializedBytes): compact unless w is a terminal, and indented two levels deep, {"result": {"records": ...}}, when it is.
func IndentedJSONLayout ¶
func IndentedJSONLayout(depth int) JSONLayout
IndentedJSONLayout is the layout of a value depth levels deep in a document printed with the JSON printer's 2-space indentation; depth 0 is the root.
type JSONPrinter ¶
type JSONPrinter struct {
// contains filtered or unexported fields
}
JSONPrinter prints output as JSON
func (*JSONPrinter) Print ¶
func (p *JSONPrinter) Print(obj interface{}) error
Print prints a single object as JSON
func (*JSONPrinter) PrintList ¶
func (p *JSONPrinter) PrintList(obj interface{}) error
PrintList prints a list of objects as JSON
type LivePrinter ¶
type LivePrinter struct {
// contains filtered or unexported fields
}
LivePrinter wraps a Printer and provides live update functionality
func NewLivePrinter ¶
NewLivePrinter creates a new live printer that wraps an existing printer
func NewLivePrinterWithOpts ¶
func NewLivePrinterWithOpts(printer Printer, interval time.Duration, writer io.Writer, opts PrinterOptions) *LivePrinter
NewLivePrinterWithOpts creates a new live printer with options for resize support
func (*LivePrinter) RunLive ¶
func (p *LivePrinter) RunLive(ctx context.Context, fetcher DataFetcher) error
RunLive starts the live update loop, calling fetcher periodically It handles Ctrl+C gracefully and clears the screen between updates
type MetadataBucket ¶
type MetadataBucket struct {
Name string `json:"name" yaml:"name"`
Table string `json:"table" yaml:"table"`
ScannedBytes int64 `json:"scannedBytes" yaml:"scannedBytes"`
MatchedRecordsRatio float64 `json:"matchedRecordsRatio" yaml:"matchedRecordsRatio"`
}
MetadataBucket represents a single bucket's contribution.
type MetadataContribs ¶
type MetadataContribs struct {
Buckets []MetadataBucket `json:"buckets,omitempty" yaml:"buckets,omitempty"`
}
MetadataContribs represents bucket contributions.
type MetadataNotice ¶
type MetadataNotice struct {
Severity string `json:"severity,omitempty" yaml:"severity,omitempty"`
NotificationType string `json:"notificationType,omitempty" yaml:"notificationType,omitempty"`
Message string `json:"message,omitempty" yaml:"message,omitempty"`
MessageFormat string `json:"messageFormat,omitempty" yaml:"messageFormat,omitempty"`
Arguments []string `json:"arguments,omitempty" yaml:"arguments,omitempty"`
}
MetadataNotice is one of Grail's notifications on a query result, of any severity. The WARNING and ERROR ones are also printed to stderr (or carried in the agent envelope's warnings); this is the full, unfiltered list.
type MetadataTimeframe ¶
type MetadataTimeframe struct {
Start string `json:"start,omitempty" yaml:"start,omitempty"`
End string `json:"end,omitempty" yaml:"end,omitempty"`
}
MetadataTimeframe represents the analysis timeframe for a query.
type MetricInfo ¶
type MetricInfo struct {
MetricKey string `json:"metric.key,omitempty" yaml:"metric.key,omitempty"`
FieldName string `json:"fieldName,omitempty" yaml:"fieldName,omitempty"`
Aggregation string `json:"aggregation,omitempty" yaml:"aggregation,omitempty"`
DisplayName string `json:"displayName,omitempty" yaml:"displayName,omitempty"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
Unit string `json:"unit,omitempty" yaml:"unit,omitempty"`
}
MetricInfo describes a single metric referenced in a timeseries query result. It maps the DQL column name (FieldName) to the underlying metric descriptor. DisplayName, Description, and Unit are present only when the API returns metric catalogue data.
type ParquetPrinter ¶
type ParquetPrinter struct {
// contains filtered or unexported fields
}
ParquetPrinter writes query results as an Apache Parquet file.
Parquet is columnar, pure-Go (no CGO), and read natively by common local analytics tooling, which makes it a good target for large exported results. In this iteration the writer is buffered — it builds the schema from the full set of records held in memory before writing — matching how the rest of the query path already buffers results. (A streaming, row-group-flushed writer is a later optimisation.)
DQL → Parquet type mapping ¶
The column schema is derived from the DQL column types returned by the query API (populated when --include-types is set), falling back to value-inference for any column missing from the type mappings. Each column is OPTIONAL (nullable) so sparse rows and explicit nulls are tolerated.
DQL type Parquet column Notes
------------------------ ------------------ ---------------------------------
boolean BOOLEAN
long INT64
double DOUBLE
string STRING
timestamp INT64 (TIMESTAMP) nanosecond precision, UTC-adjusted;
unparseable values written as null
duration INT64 nanoseconds; math-ready, no CAST
needed; unparseable values → null
timeframe / ip STRING rendered as their string form
(anything else, nested STRING (complex) JSON-encoded — never crash, never
record/array, mixed) silently drop a column
Cells that cannot be coerced to their column's physical type are written as null rather than failing the whole export.
DQL types in the footer ¶
The full DQL type block is also persisted in the file footer under dqlTypesMetadataKey, so a reader can recover the declared Grail type of every column — including the disambiguation the physical schema loses (long vs string, both numeric on the wire) and columns that were null in every row (and so absent from the physical schema entirely). See dqlTypesMetadata.
func (*ParquetPrinter) Print ¶
func (p *ParquetPrinter) Print(obj interface{}) error
Print writes a single object as a one-row Parquet file.
func (*ParquetPrinter) PrintList ¶
func (p *ParquetPrinter) PrintList(obj interface{}) error
PrintList writes a slice of records as a Parquet file.
A Parquet file is always emitted, even for an empty result: a zero-byte file is not valid Parquet and would be rejected by downstream tooling, so an empty result yields a valid file with zero rows. When the DQL types are known the file carries that schema; when they are not (the API returns no types for an empty result) it carries a single placeholder column so it stays readable by mainstream tooling. (This differs from the CSV/JSONL printers, where an empty file is itself valid output.)
type Printer ¶
Printer interface for output formatting
func NewPrinter ¶
NewPrinter creates a new printer based on the format
func NewPrinterWithOptions ¶
NewPrinterWithOptions creates a new printer with specific options
func NewPrinterWithOpts ¶
func NewPrinterWithOpts(opts PrinterOptions) Printer
NewPrinterWithOpts creates a new printer with full options
func NewPrinterWithWriter ¶
NewPrinterWithWriter creates a new printer with a specific writer
func NewShapingPrinter ¶
func NewShapingPrinter(inner Printer, opts ShapeOptions) Printer
NewShapingPrinter wraps inner with the list shaping described by opts.
type PrinterOptions ¶
type PrinterOptions struct {
Format string
Writer io.Writer
PlainMode bool
JQFilter string
Width int // Chart width (0 = default)
Height int // Chart height (0 = default)
Fullscreen bool // Use terminal dimensions
// Types carries DQL column type info used by the Parquet printer to build a
// faithful schema. Ignored by other formats; nil falls back to inference.
Types []ColumnTypeMapping
// Notice receives the one-line format notice of the auto printer. nil means
// the process's stderr.
Notice io.Writer
}
PrinterOptions configures printer behavior
type ProgressReporter ¶
type ProgressReporter struct {
// contains filtered or unexported fields
}
ProgressReporter renders an in-place progress line to stderr while a query runs. It is drawn only for an interactive terminal; when disabled (non-TTY stderr, --plain, agent mode, or the user opted out) every method is a no-op, so callers can wire it unconditionally without disturbing piped or structured output. Color is emitted only when ColorEnabled() is true, so NO_COLOR still yields a plain (monochrome) bar.
A background goroutine redraws the line on a fixed interval (so the spinner and elapsed timer stay smooth between the far slower query polls), while Update — called from the poll loop — only refreshes the shared state. The mutex guards that state and serializes writes between the two.
func NewProgressReporter ¶
func NewProgressReporter(enabled, agentMode bool) *ProgressReporter
NewProgressReporter returns a reporter. When enabled is false (the user opted out), or in agent mode, or under --plain, or when stderr is not an interactive terminal, the reporter is a silent no-op. NO_COLOR is respected for color only — the bar is still drawn, just without color.
func NewProgressReporterTo ¶
func NewProgressReporterTo(enabled, agentMode bool, w io.Writer) *ProgressReporter
NewProgressReporterTo is NewProgressReporter drawing on w instead of the process's stderr, for a caller that owns the invocation's streams.
func (*ProgressReporter) Complete ¶
func (p *ProgressReporter) Complete(final ProgressState)
Complete halts the animator and, when a bar was actually shown, replaces it with a one-line completion summary (a green check, the final scan totals, and elapsed time). For a query too fast to have animated it just clears, adding no noise. It is idempotent with Stop; whichever runs first wins.
func (*ProgressReporter) Drawing ¶
func (p *ProgressReporter) Drawing() bool
Drawing reports whether the reporter is actively drawing to the terminal (enabled and stderr is a TTY). Callers use it to decide whether Stop() will have cleared the line for them, or whether they must emit their own leading newline to avoid gluing output to a partially printed line (e.g. a shell's "^C" echo).
func (*ProgressReporter) Stop ¶
func (p *ProgressReporter) Stop()
Stop halts the background animator and erases the progress line so the real result renders on a clean row. Use it on error or cancellation; use Complete on success to leave a summary. It is safe to call multiple times and when disabled.
func (*ProgressReporter) Update ¶
func (p *ProgressReporter) Update(s ProgressState)
Update refreshes the progress state. In animated mode it also starts the background redraw loop on first call and repaints immediately so new poll data (progress, scan totals) appears without waiting for the next tick. It is a no-op when the reporter is disabled.
type ProgressState ¶
type ProgressState struct {
// Progress is the completion percentage (0-100).
Progress int
// ScannedBytes / ScannedRecords are the running scan totals reported by the
// backend. When non-zero they are shown in preference to the preview count,
// since they reflect the actual work (and cost) done so far.
ScannedBytes int64
ScannedRecords int64
// PreviewRows is the number of rows in the latest preview snapshot, shown
// only when no scan totals are available (e.g. non-Grail-scan queries).
PreviewRows int
}
ProgressState is a snapshot of a running query's progress passed to ProgressReporter.Update. All fields are optional; zero values are omitted from the rendered line.
type QueryMetadata ¶
type QueryMetadata struct {
ExecutionTimeMilliseconds int64 `json:"executionTimeMilliseconds,omitempty" yaml:"executionTimeMilliseconds,omitempty"`
ScannedRecords int64 `json:"scannedRecords,omitempty" yaml:"scannedRecords,omitempty"`
ScannedBytes int64 `json:"scannedBytes,omitempty" yaml:"scannedBytes,omitempty"`
ScannedDataPoints int64 `json:"scannedDataPoints,omitempty" yaml:"scannedDataPoints,omitempty"`
Sampled bool `json:"sampled,omitempty" yaml:"sampled,omitempty"`
Approximations []string `json:"approximations,omitempty" yaml:"approximations,omitempty"`
Notifications []MetadataNotice `json:"notifications,omitempty" yaml:"notifications,omitempty"`
QueryID string `json:"queryId,omitempty" yaml:"queryId,omitempty"`
DQLVersion string `json:"dqlVersion,omitempty" yaml:"dqlVersion,omitempty"`
Query string `json:"query,omitempty" yaml:"query,omitempty"`
CanonicalQuery string `json:"canonicalQuery,omitempty" yaml:"canonicalQuery,omitempty"`
Timezone string `json:"timezone,omitempty" yaml:"timezone,omitempty"`
Locale string `json:"locale,omitempty" yaml:"locale,omitempty"`
AnalysisTimeframe *MetadataTimeframe `json:"analysisTimeframe,omitempty" yaml:"analysisTimeframe,omitempty"`
Contributions *MetadataContribs `json:"contributions,omitempty" yaml:"contributions,omitempty"`
Metrics []MetricInfo `json:"metrics,omitempty" yaml:"metrics,omitempty"`
}
QueryMetadata holds DQL query execution metadata for output formatting. This is a format-neutral representation used by the output layer.
type Response ¶
type Response struct {
OK bool `json:"ok"`
// EnvelopeVersion is the contract version (D31). It is set on envelopes that
// participate in the versioned spill contract (result.kind ∈ result-file /
// summary-only) so a consumer can detect "this dtctl is newer than I was
// written for". Omitted (0) on legacy envelopes to keep existing output
// byte-for-byte unchanged.
EnvelopeVersion int `json:"envelope_version,omitempty"`
Result interface{} `json:"result"`
Error *ErrorDetail `json:"error,omitempty"`
Context *ResponseContext `json:"context,omitempty"`
// Metadata carries the Grail query metadata (execution time, scanned
// records/bytes, sampled, queryId, ...) alongside the result, mirroring the
// non-agent `-o json --metadata` shape. Populated on the query envelope when
// --metadata is requested and the response carried metadata; omitted
// otherwise so other envelopes stay byte-for-byte unchanged.
Metadata interface{} `json:"metadata,omitempty"`
}
Response is the agent mode envelope that wraps all CLI output. Success responses have OK=true with Result populated. Error responses have OK=false with Error populated.
type ResponseContext ¶
type ResponseContext struct {
Total *int `json:"total,omitempty"`
HasMore bool `json:"has_more,omitempty"`
Verb string `json:"verb,omitempty"`
Resource string `json:"resource,omitempty"`
Suggestions []string `json:"suggestions,omitempty"`
Warnings []string `json:"warnings,omitempty"`
Duration string `json:"duration,omitempty"`
Links map[string]string `json:"links,omitempty"`
// Format names the encoding `-o auto` chose for result ("csv", "yaml" or
// "json"), so a consumer can branch on it before parsing. For csv and yaml
// the result is a string in that format; for json it is a native value.
// Omitted for every explicitly requested format.
Format string `json:"format,omitempty"`
// Spill decision provenance (D2/D24). Populated only on the spill path so
// both agents and humans can see *why* they got the shape they got.
// Decided is one of "inline", "spilled", "summary-only". MeasuredBytes is
// the size of the rows as they would be printed inline, in MeasuredEncoding
// and in the JSON layout of the output (compact unless stdout is a terminal,
// see EnvelopeRecordsLayout); --spill=auto compares it with ThresholdBytes.
Decided string `json:"decided,omitempty"`
ThresholdBytes int64 `json:"threshold_bytes,omitempty"`
MeasuredBytes int64 `json:"measured_bytes,omitempty"`
MeasuredEncoding string `json:"measured_encoding,omitempty"`
// Streamed marks a result written to disk row by row as it arrived, without
// ever being held whole. The spill decision was then settled by row count
// alone, so measured_bytes/measured_encoding are absent: nothing was
// serialised for inline emission to measure.
Streamed bool `json:"streamed,omitempty"`
// EmptyReason explains an empty query result when a cheap follow-up
// probe found a likely cause. Omitted when the result is not empty or the
// probes found nothing conclusive.
EmptyReason *EmptyReason `json:"empty_reason,omitempty"`
// Truncation markers. Truncated is true whenever the result is not the
// complete answer because dtctl bounded it: rows were dropped to fit an
// output budget (Returned < Total, see NextOffset/Next), or string values
// were clipped to MaxFieldChars (each clipped value ends in "…(+N chars)"
// and its field is named in TruncatedFields). Both can apply at once.
Truncated bool `json:"truncated,omitempty"`
// Returned is the number of rows in the result when an output budget
// dropped some; Total still counts every row the query returned.
Returned *int `json:"returned,omitempty"`
// NextOffset is the zero-based index of the first row the budget dropped.
NextOffset *int `json:"next_offset,omitempty"`
// Next is a ready-to-run command that continues at NextOffset without
// re-querying, when the full result was written to disk. Empty when it was
// not (spilling disabled); context.suggestions then says how to get the rest.
Next string `json:"next,omitempty"`
// BudgetBytes is the output budget that dropped rows, in bytes of the
// encoded envelope (--max-output-bytes, or --max-output-tokens × 4).
BudgetBytes int64 `json:"budget_bytes,omitempty"`
// MaxFieldChars is the per-value cap in runes, set only when it clipped at
// least one value.
MaxFieldChars int `json:"max_field_chars,omitempty"`
// TruncatedFields names the fields with at least one clipped value.
TruncatedFields []string `json:"truncated_fields,omitempty"`
// Window is the window `dtctl query` searched, as the response's own
// metadata states it.
Window *TimeWindow `json:"window,omitempty"`
}
ResponseContext provides operational metadata alongside the result.
func (*ResponseContext) MarkFieldsClipped ¶
func (c *ResponseContext) MarkFieldsClipped(max int, fields []string)
MarkFieldsClipped records on the context that values in fields were clipped to max runes. A no-op when nothing was clipped, so an unclipped result keeps a clean context.
type ResultFileManifest ¶
type ResultFileManifest struct {
Kind string `json:"kind"`
// Path is the on-disk location of the spilled file. Omitted for
// summary-only (no writable filesystem).
Path string `json:"path,omitempty"`
// Query is the original DQL text, recorded so a stale-file recovery can
// suggest a concrete re-query (D32).
Query string `json:"query,omitempty"`
Format string `json:"format"`
Rows int `json:"rows"`
// Bytes is the size of the spilled data file. Omitted for summary-only.
Bytes int64 `json:"bytes,omitempty"`
ContextName string `json:"context_name,omitempty"`
// TenantID is provenance kept in the manifest, not the path (D9).
TenantID string `json:"tenant_id,omitempty"`
Sampled bool `json:"sampled,omitempty"`
SamplingRatio float64 `json:"sampling_ratio,omitempty"`
// Constant and NullColumns are set when the result was compacted
// (--compact, the agent-mode default): the columns holding one value in
// every row are collapsed into Constant, the all-null ones are listed by
// name, and neither appears again in Columns / SampleStats or SampleRows.
// The on-disk sidecar keeps the full per-column profile.
Constant map[string]interface{} `json:"constant,omitempty"`
NullColumns []string `json:"null_columns,omitempty"`
// Exactly one of Columns / SampleStats is populated: Columns when the
// result was not sampled, SampleStats (with per-column basis) when it was.
Columns []ColumnStats `json:"columns,omitempty"`
SampleStats *SampleStats `json:"sample_stats,omitempty"`
// ColumnsOmitted lists, by name, the columns whose per-column profile was
// dropped from this envelope to keep it compact for a wide result (the
// least-populated columns; see CapColumnsForEnvelope). Full stats for every
// column — including these — are in the on-disk sidecar manifest. Empty when
// no columns were omitted.
ColumnsOmitted []string `json:"columns_omitted,omitempty"`
SampleRows []map[string]interface{} `json:"sample_rows,omitempty"`
// Types is the DQL per-column type block, as on InlineRecords: set only for
// an explicit --include-types, and describing the full spilled result.
Types interface{} `json:"types,omitempty"`
}
ResultFileManifest is the result payload for the KindResultFile / KindSummaryOnly envelope shapes. It is the in-session contract; the on-disk SidecarManifest (D34) carries the same provenance for cross-session use.
func (*ResultFileManifest) SetStats ¶
func (m *ResultFileManifest) SetStats(cols []ColumnStats, sampled bool)
SetStats places the computed column stats in the correct location depending on whether the result was sampled (D23): population stats go under `columns`, sampled stats go under `sample_stats` with basis:"sample".
type SampleStats ¶
type SampleStats struct {
Basis string `json:"basis"` // always "sample"
Columns []ColumnStats `json:"columns"`
}
SampleStats wraps per-column stats computed on a sampled result (D23). When a result is sampled the stats move out of the manifest's top-level `columns` into this block, each column additionally carrying basis:"sample", so an agent cannot read a sample-based figure as population truth.
type SeriesEffect ¶
type SeriesEffect struct {
Summarized bool // at least one series was replaced by a summary
Rounded bool // at least one float value changed through rounding
}
SeriesEffect reports what ApplySeriesModeWithEffect actually changed, so a caller that applied a lossy default can tell the user only when it mattered.
func ApplySeriesModeWithEffect ¶
func ApplySeriesModeWithEffect(records []map[string]interface{}, mode SeriesMode, digits int, tabular bool) ([]map[string]interface{}, SeriesEffect)
ApplySeriesModeWithEffect is ApplySeriesMode that also reports its effect.
type SeriesKind ¶
type SeriesKind int
SeriesKind selects how `query --series` renders the numeric arrays of a DQL timeseries result.
const ( // SeriesFull emits every datapoint unchanged (default). SeriesFull SeriesKind = iota // SeriesSummary replaces each series with per-series statistics and a sparkline. SeriesSummary // SeriesDownsample reduces each series to at most N points, keeping extremes. SeriesDownsample )
type SeriesMode ¶
type SeriesMode struct {
Kind SeriesKind
Points int // target point budget for SeriesDownsample
}
SeriesMode is a parsed --series value.
func ParseSeriesMode ¶
func ParseSeriesMode(s string) (SeriesMode, error)
ParseSeriesMode parses a --series value: "full", "summary" or "downsample:N" with N >= 2. The empty string means full.
type ShapeOptions ¶
type ShapeOptions struct {
// Limit keeps only the first Limit items of a list (0 = all).
Limit int
// Fields projects every item onto these paths, in this order. A path is a
// top-level key or a dotted path into nested objects
// ("modificationInfo.lastModifiedTime").
Fields []string
// Tabular selects the flat representation for table/wide/csv/toon: each
// field becomes one column named by its dotted path, and a field that
// resolves to an object is expanded into one column per leaf. Structured
// formats (json/yaml) keep the projected fields nested instead, so a path
// that works on the full object works on the projection.
Tabular bool
// Format is the output format being rendered; --fields is rejected for
// formats that cannot render a projection (see SupportsFieldProjection).
Format string
// Notices receives the truncation notice and unknown-field warnings when
// the wrapped printer is not an agent envelope (typically stderr). Nil
// discards them.
Notices io.Writer
}
ShapeOptions configures the list shaping applied by NewShapingPrinter: the `--limit` and `--fields` flags of the list verbs.
type ShapingPrinter ¶
type ShapingPrinter struct {
// contains filtered or unexported fields
}
ShapingPrinter applies ShapeOptions to whatever it prints, then delegates to the wrapped printer. Agent-mode notices go into the envelope context instead of Notices.
func (*ShapingPrinter) Print ¶
func (p *ShapingPrinter) Print(obj interface{}) error
Print shapes obj and prints it through the wrapped printer's Print.
func (*ShapingPrinter) PrintList ¶
func (p *ShapingPrinter) PrintList(obj interface{}) error
PrintList shapes obj and prints it through the wrapped printer's PrintList.
func (*ShapingPrinter) Unwrap ¶
func (p *ShapingPrinter) Unwrap() Printer
Unwrap returns the wrapped printer, so callers that need the concrete printer (e.g. the agent envelope) can still reach it.
type SidecarManifest ¶
type SidecarManifest struct {
EnvelopeVersion int `json:"envelope_version"`
Format string `json:"format"`
Sampled bool `json:"sampled"`
SamplingRatio float64 `json:"sampling_ratio,omitempty"`
TenantID string `json:"tenant_id,omitempty"`
ContextName string `json:"context_name,omitempty"`
Query string `json:"query,omitempty"`
Rows int `json:"rows"`
Bytes int64 `json:"bytes"`
Created time.Time `json:"created"`
Columns []ColumnStats `json:"columns,omitempty"`
}
SidecarManifest is the tiny on-disk JSON written next to the spilled data file (D34): q-<hash>.manifest.json. A spilled file can outlive its session, and sampled/sampling_ratio/tenant_id/query cannot be re-derived from raw rows, so they are persisted here for Layer 2's inspect to (a) present sampled stats honestly, (b) refuse cross-context reads, and (c) suggest a concrete re-query when the file is gone.
func ReadSidecar ¶
func ReadSidecar(dataPath string) (*SidecarManifest, error)
ReadSidecar reads and decodes the sidecar manifest next to a spilled data file (D34). It returns (nil, nil) when no sidecar exists — an older spill or a hand-copied bare file — so a caller can degrade gracefully (Layer 2 still does row access and schema re-derivation without it, only losing provenance). A present-but-corrupt sidecar returns an error.
type SparklinePrinter ¶
type SparklinePrinter struct {
// contains filtered or unexported fields
}
SparklinePrinter prints timeseries data as compact sparklines
func NewSparklinePrinter ¶
func NewSparklinePrinter(writer io.Writer) *SparklinePrinter
NewSparklinePrinter creates a new sparkline printer
func NewSparklinePrinterWithSize ¶
func NewSparklinePrinterWithSize(writer io.Writer, width int) *SparklinePrinter
NewSparklinePrinterWithSize creates a new sparkline printer with custom width
func (*SparklinePrinter) Print ¶
func (p *SparklinePrinter) Print(obj interface{}) error
Print prints the data as sparklines if it contains timeseries, otherwise falls back to JSON
func (*SparklinePrinter) PrintList ¶
func (p *SparklinePrinter) PrintList(obj interface{}) error
PrintList prints a list of records as sparklines
type SpecFileManifest ¶
type SpecFileManifest struct {
Kind string `json:"kind"`
Path string `json:"path"`
Format string `json:"format"`
Bytes int64 `json:"bytes"`
// API is the API the document describes, as the environment's index names it.
API string `json:"api,omitempty"`
// Document is the environment-relative path the document was fetched from.
Document string `json:"document,omitempty"`
}
SpecFileManifest is the result payload for the KindDocumentFile envelope: a handle to a written document plus enough provenance to know what it is. It is deliberately not ResultFileManifest — that shape promises rows, columns and a row sample, and every one of those would be a lie about an API specification.
type SpillFileEntry ¶
type SpillFileEntry struct {
Path string `json:"path"`
Format string `json:"format"`
Bytes int64 `json:"bytes"`
Created time.Time `json:"created"`
// Sidecar-derived provenance — empty/zero when the file has no manifest.
Query string `json:"query,omitempty"`
Rows int `json:"rows,omitempty"`
Sampled bool `json:"sampled,omitempty"`
SamplingRatio float64 `json:"sampling_ratio,omitempty"`
ContextName string `json:"context_name,omitempty"`
TenantID string `json:"tenant_id,omitempty"`
// SidecarMissing flags a bare data file with no manifest next to it: its
// provenance (query, sampling) is unknown, so a consumer must not trust the
// absence of `sampled` as proof the data is a full population.
SidecarMissing bool `json:"sidecar_missing,omitempty"`
}
SpillFileEntry describes one spilled result data file discovered in a spill directory, enriched with its sidecar provenance (D34) when present. It is the per-file element of a KindFileList listing — enough for an agent to recognise a lost handle (the original query, row count, when it was spilled, whether it was sampled) and inspect it by path, without re-querying Grail.
func ListSpillFiles ¶
func ListSpillFiles(dir string) ([]SpillFileEntry, error)
ListSpillFiles enumerates spilled result data files directly in dir (it does not recurse — a managed listing is scoped to a single context partition by the caller, D9), pairing each with its sidecar manifest when one is present. It skips sidecar, temp, probe and prune-marker files. A non-existent dir is not an error: it yields an empty list (nothing has been spilled in this context yet). Entries are sorted most-recent-first — the order most useful for recovering a handle that just aged out of context.
type SpillList ¶
type SpillList struct {
Kind string `json:"kind"`
Dir string `json:"dir"`
Managed bool `json:"managed"`
Files []SpillFileEntry `json:"files"`
}
SpillList is the result payload for the KindFileList envelope (D2): the spilled files visible in the directory that was listed. It carries the directory and whether it is the managed cache (vs. a user-chosen --spill-dir that opts out of the managed privacy guarantees, D25) so the listing is self-describing.
type SpillWriter ¶
type SpillWriter struct {
// contains filtered or unexported fields
}
SpillWriter is WriteSpillFile with the write spread over time: rows go to a temp file in dir as they arrive and are committed onto the final name by Commit. A streamed result only learns that name once the response metadata has arrived — after the rows — so the destination cannot be chosen upfront.
The same atomicity holds as for WriteSpillFile: readers never observe a half-written file, and an abandoned stream leaves only a .tmp for the TTL prune to sweep.
func NewSpillWriter ¶
func NewSpillWriter(dir string) (*SpillWriter, error)
NewSpillWriter creates the temp file that rows are streamed into. dir is created with 0700 if missing; Commit must name a path inside it.
func (*SpillWriter) Abort ¶
func (w *SpillWriter) Abort()
Abort discards an uncommitted stream. It is safe to call after Commit, and safe to call twice, so it works as a defer.
func (*SpillWriter) Bytes ¶
func (w *SpillWriter) Bytes() int64
Bytes reports how much has been written so far.
func (*SpillWriter) Commit ¶
func (w *SpillWriter) Commit(targetPath string) (int64, error)
Commit closes the temp file and renames it onto targetPath, which must live in the directory the writer was created with (rename(2) is only atomic within one filesystem). It returns the number of bytes written.
func (*SpillWriter) Writer ¶
func (w *SpillWriter) Writer() io.Writer
Writer returns the sink rows are written to.
type StatsAccumulator ¶
type StatsAccumulator struct {
// contains filtered or unexported fields
}
StatsAccumulator folds records one at a time into per-column sketches and finalises them to the lean Layer-1 column profile (D14/D20). Memory is O(columns × distinct-bound), independent of the row count, so it profiles a streamed file (Layer 2 `inspect --stats`) in a single bounded-memory pass as well as the buffered query slice (via ComputeColumnStats). Reuse one accumulator per file; it is not safe for concurrent use.
func NewStatsAccumulator ¶
func NewStatsAccumulator(topK, maxDistinct int) *StatsAccumulator
NewStatsAccumulator creates an accumulator with the given knobs; non-positive values fall back to the package defaults (DefaultStatsTopK / DefaultStatsMaxDistinct).
func (*StatsAccumulator) Finalize ¶
func (s *StatsAccumulator) Finalize(sampled bool) []ColumnStats
Finalize produces the per-column profiles in deterministic (alphabetical) order. When sampled is true every column carries basis:"sample" (D23). It is idempotent: the null back-fill mutates accumulator state, so it runs only once even if Finalize is called more than once (a second call returns the same profile rather than double-counting back-filled nulls).
func (*StatsAccumulator) Observe ¶
func (s *StatsAccumulator) Observe(rec map[string]interface{})
Observe folds a single record into the per-column sketches. A column absent from a record is treated as null for that record (back-filled in Finalize from the observed row count).
func (*StatsAccumulator) Rows ¶
func (s *StatsAccumulator) Rows() int
Rows reports how many records have been observed.
type TablePrinter ¶
type TablePrinter struct {
// contains filtered or unexported fields
}
TablePrinter prints output as a table
func (*TablePrinter) Print ¶
func (p *TablePrinter) Print(obj interface{}) error
Print prints a single object as a table
func (*TablePrinter) PrintList ¶
func (p *TablePrinter) PrintList(obj interface{}) error
PrintList prints a list of objects as a table
type TimeWindow ¶
type TimeWindow struct {
From string `json:"from"`
To string `json:"to"`
// Span is the window's length (2h, 24h, 7d), so a reader can hold it
// against the question without subtracting timestamps.
Span string `json:"span,omitempty"`
// Note says the window is the default one: the query named none.
Note string `json:"note,omitempty"`
}
TimeWindow is a query window as absolute RFC3339 instants.
type TimeseriesData ¶
TimeseriesData represents extracted timeseries data
type ToonPrinter ¶
type ToonPrinter struct {
// contains filtered or unexported fields
}
ToonPrinter prints output as TOON (Token-Oriented Object Notation). TOON is a compact, human-readable format optimised for LLM token efficiency.
Because dtctl resource structs use `json` tags (not `toon` tags), the printer round-trips through encoding/json to obtain a map[string]any representation that preserves the json field names, then passes it to toon.Marshal.
func (*ToonPrinter) Print ¶
func (p *ToonPrinter) Print(obj interface{}) error
Print prints a single object as TOON.
func (*ToonPrinter) PrintList ¶
func (p *ToonPrinter) PrintList(obj interface{}) error
PrintList prints a list of objects as TOON.
type TopValue ¶
type TopValue struct {
V interface{} `json:"v"`
N int `json:"n"`
}
TopValue is one entry of a low-cardinality column's top-K list.
type WatchPrinter ¶
type WatchPrinter struct {
// contains filtered or unexported fields
}
func NewWatchPrinter ¶
func NewWatchPrinter(basePrinter Printer) *WatchPrinter
func NewWatchPrinterWithWriter ¶
func NewWatchPrinterWithWriter(basePrinter Printer, writer io.Writer, colorize bool) *WatchPrinter
func (*WatchPrinter) Print ¶
func (p *WatchPrinter) Print(data interface{}) error
func (*WatchPrinter) PrintChanges ¶
func (p *WatchPrinter) PrintChanges(changes []Change) error
func (*WatchPrinter) PrintList ¶
func (p *WatchPrinter) PrintList(data interface{}) error
type WatchPrinterInterface ¶
WatchPrinterInterface is implemented by printers that support watch mode
type YAMLPrinter ¶
type YAMLPrinter struct {
// contains filtered or unexported fields
}
YAMLPrinter prints output as YAML
func (*YAMLPrinter) Print ¶
func (p *YAMLPrinter) Print(obj interface{}) error
Print prints a single object as YAML
func (*YAMLPrinter) PrintList ¶
func (p *YAMLPrinter) PrintList(obj interface{}) error
PrintList prints a list of objects as YAML
Source Files
¶
- agent.go
- auto.go
- barchart.go
- braille.go
- chart.go
- compact.go
- console_other.go
- csv.go
- fieldcap.go
- jq.go
- json_stream.go
- jsonl.go
- live.go
- live_unix.go
- manifest.go
- messages.go
- metadata.go
- metadata_minimal.go
- parquet.go
- printer.go
- progress.go
- series.go
- shape.go
- snapshot.go
- sparkline.go
- spill.go
- spill_list.go
- spill_stream.go
- stats.go
- styles.go
- table.go
- toon.go
- typed.go
- watch.go