LogQL Parser β Internal Design
The internal/logql package provides a typed LogQL parser that powers query validation, structural routing, and drop/keep extraction throughout the proxy. It replaced the previous regex-based approach with a proper recursive-descent parser that builds a typed AST, enabling accurate semantic validation and reliable query decomposition without false positives.
Why a Typed AST?β
The old approach used regular expressions layered on top of the raw query string. This worked for simple cases but broke on:
- Nested expressions (vector matching with
on()/group_left()) - Embedded regex inside label matchers (e.g.
{app=~"api|web"}) - Ambiguous operator sequences (
!=inside a string vs. between labels) rate_counterrequiring| unwrapβ impossible to validate structurally without an AST
The typed AST makes these cases explicit. Each node type is a Go struct with typed fields, so routing logic (is this a range aggregation? a binary expression?) becomes a type switch rather than a regex match.
Package Structureβ
| File | Purpose |
|---|---|
scanner.go | Lexer: converts raw query string to a token stream |
parser.go | Recursive-descent parser: builds typed AST from tokens |
ast.go | AST node types (LogQuery, RangeAggregation, VectorAggregation, BinOpExpr, β¦) |
semantic.go | Semantic validation pass: checks constraints that require AST understanding |
validate.go | Public API: ValidateLogQL(query) string β Loki-compatible error messages |
translate.go | Bridges AST to the translator package: normalises to canonical LogQL, then delegates |
Data Flowβ
Four consumers of the LogQL AST:
-
Validation (
ValidateLogQL) β called on every inbound query before any work is done. Returns a Loki-shaped error string ("parse error at line 1, col 1: ...") or""if valid. -
Routing (
proxy.go) β callslogql.Parse()on the validated query and type-switches to dispatch binary expressions and range aggregations to separate execution paths. -
Translation (
TranslateLogQLWithCapabilitiesandlogql.Translate) β two paths described in detail below. -
Drop/Keep extraction (
stream_processing.go) β reads the| drop/| keepstages of the query's memoised parse (the stages the plan'sLogSelectholds) and compiles their matchers intotranslate.DropConditions for post-processing VL response streams. The line-field exposure of the Loki-compatible profile (loki_profile.go) reads the same parse.
AST Node Hierarchyβ
Expr (interface)
βββ *StreamSelector {app="api", env=~"prod.*"}
βββ *LogQuery StreamSelector + []Stage pipeline
β βββ Stage (interface)
β βββ *LineFilterStage |= "text" / |~ "re" / |> "pattern"
β βββ *ParserStage | json / | logfmt / | regexp / | pattern / | unpack
β βββ *LabelFilterStage | level="error" (raw, opaque)
β βββ *LineFormatStage | line_format "{{.msg}}"
β βββ *LabelFormatStage | label_format dst=src, tmpl="{{.x}}" (parsed entries + raw)
β βββ *UnwrapStage | unwrap bytes(label)
β βββ *DropStage | drop a, b, c=~"re"
β βββ *KeepStage | keep a, b
β βββ *DecolorizeStage | decolorize
βββ *RangeAggregation rate({...}[5m]) β argument is always a log query (no subqueries)
βββ *VectorAggregation sum by (label) (rate(...)) / topk(5, ...)
βββ *BinOpExpr left op right, optional VectorMatching
βββ *LiteralExpr scalar 3.14
βββ *OpaqueMetricExpr label_replace(...), vector(...) β raw pass-through
Opaque pass-through nodesβ
Two node types capture content without parsing it:
-
LabelFilterStage/LabelFormatStageβ the inner expression grammar for| level > 1or| label_format dst=srcis complex and context-dependent. These stages capture the raw text after the keyword so the translator sees exactly what Loki would see. -
OpaqueMetricExprβ metric-level functions that aren't yet expressible in the AST (label_replace,vector,approx_topk; any other name is a Loki parse error). The parser captures the full raw text including balanced parentheses and returns it verbatim so VictoriaLogs receives the original expression unchanged.
Scannerβ
The scanner (scanner.go) is a hand-written lexer with no external dependencies. Key design choices:
- Single-pass, no backtracking. Each call to
scan()advances exactly one token. - Disambiguates
!=vs!~vs!>vs!=(label vs line filter). Context is resolved by the parser, not the scanner β the scanner emits separateTokBangEq,TokBangTilde,TokBangGttokens. - Range durations (
5m,1h30m) are emitted asTokDurationinside a[range], with the unit string preserved. Nothing is skipped inside the brackets, and the text up to the]is checked as Loki checks it (see Lexical rules). - Number, duration and bytes literals outside a range are read as Loki's lexer reads them (see Lexical rules):
TokNumber,TokDurationLit(offset 5m,-5m) andTokBytes(5KB). - Quoted strings are unescaped; raw backtick strings are returned verbatim.
- Lexer errors (a malformed number, NUL, an unclosed
[) are noted by the scanner as it reads the token, andParsereports the first one ahead of any parse error, as Loki does.
Parserβ
The parser (parser.go) is a recursive-descent parser with one-token lookahead. The top-level entry points are:
// Parse returns the typed AST or an error.
func Parse(input string) (Expr, error)
// ParseAndValidate parses and runs the semantic pass; returns the first error.
func ParseAndValidate(input string) error
Grammar summary (simplified)β
Expr := Primary (BinOp Primary)*
Primary := VectorAgg | RangeAgg | UnknownMetricFn | LogQuery | '(' Expr ')' | Literal
VectorAgg := VecOp [Grouping] '(' [Param ','] Expr ')'
RangeAgg := RangeOp '(' LogQuery '[' Range [':' Step] ']' [Offset] ')' [Grouping]
UnknownMetricFn:= Ident '(' ... ')' β OpaqueMetricExpr (raw text)
LogQuery := StreamSelector Pipeline*
Pipeline := '|=' | '!=' | '|~' | '!~' | '|>' | '!>' LineFilter
| '|' json | logfmt | regexp | pattern | unpack
| '|' LabelFilter (raw)
| '|' line_format | label_format (raw)
| '|' unwrap [Converter] Label (in a range aggregation only; label filters only after it)
| '|' drop DropList
| '|' keep DropList
| '|' decolorize
Unknown function handlingβ
When the parser encounters an identifier followed by ( that isn't a known range op or vector op, it captures the raw input text from the start of the identifier to the matching close paren (tracking nesting depth) and returns an OpaqueMetricExpr. This ensures label_replace(sum by (level)(rate(...)), ...) passes through to VictoriaLogs unchanged instead of causing a 503.
A label_replace or vector call is then typed with a quiet parser of its own over the call's text (typeOpaqueCall: the sample expression and the four strings, or the number). Nested calls are read once per level, whatever the depth: the first quiet parser of a nesting records where every parenthesis in it closes, and the parsers of the calls nested in it jump there instead of scanning the text again (internal/logql/quiet_calls.go); they note the log queries they read in one shared list, and the validation does not read a typed call again. The parse, the validation and the request rewrite cost about the same per level at every depth up to Loki's 128 KB input size limit (TestDeepCallsCostGrowsLinearly; TestDeepCallCostSweep writes the sweep). A query longer than the 4 KB the short memos keep is validated, respelled and parsed once per request and kept in a memo bounded by bytes (internal/proxy/long_query_memo.go).
Lexical rules of Loki's lexerβ
Loki lexes a query with Go's text/scanner, a duration and bytes attempt after every number, and a few lexer rules of its own. The proxy follows them, with Loki's error text and column, and every rule is held to the Loki parser by recorded answers (internal/logql TestLabelFilterNumberLiteralsMatchLoki, 53,000 queries; conformance case semantics/label-filter-number-literal-scan). The scan lives in internal/logql/label_filter_literal.go; the label filter lexer is lfParser in label_filter_expr.go, the query lexer is scanner.go.
| Rule | Behaviour |
|---|---|
| Number | Go's scanner: prefixes 0x 0o 0b and a leading 0 (octal), _ only between digits, decimal floats, hexadecimal floats that need a p exponent. Errors keep the scanner's text: hexadecimal literal has no digits, exponent has no digits, invalid digit '8' in octal literal, '_' must separate successive digits, 'p' exponent requires hexadecimal mantissa, and so on, at the start of the literal. |
| Duration | After a number, the run of digits, . and n u Β΅ s m h d w y is a DURATION when the whole text is Go's duration syntax or whole y w d h m s ms units, each once, largest first (1d12h; not 1h1d, 1.5d). Otherwise the number stands alone and the rest is the next token (1h30 is 1 then the name h30). |
| Bytes | After a number, the run of digits, . and B i k K M G T P is a BYTES size when Humanize's size parser reads it in any case (5kB, 5Ki, 5k; 5kb is 5k then the name b; 5gb is a number then a name), and the size fits 64 bits. |
| Sign | -5m (a minus right before a duration Go reads) is one DURATION token. A sign otherwise belongs to a NUMBER: +5m and -5B are unexpected DURATION/BYTES, expecting NUMBER. |
0b after white space | A 0b or 0B literal that follows white space is decimal literal has no digits, whatever follows the prefix. Right after an operator (a<0b1) it is scanned normally. A comment takes the line break that ends it, so what follows is not after white space. |
| White space | Only space, tab, CR and LF. \v, \f, U+0085, a non-breaking space, U+2003 and the like are tokens of their own (names), so between two tokens they are Loki's syntax error (sum\u00a0by (a) (...) is unexpected IDENTIFIER, expecting ( or by or without); in a list of names (by (a,\u00a0)) one is the name of a label no stream has and is left out. The query is parsed with the white space around it: a trailing control character is a token and the end-of-input column counts the trailing white space. A double-quoted string ends at a line break (literal not terminated). Held by TestWhitespaceMatchesLoki (16,356 recorded queries). |
| Range | The text between [ and ] is one token, read with Prometheus' duration rules: whole numbers with the units y w d h m s ms, each at most once and largest first, a sum of at most about 292 years. Errors in Loki's order, at the column of the [: a part without digits or unit, or a number above 64 bits, is not a valid duration string ([5m5], [ 5m]); then an unknown unit ([1Β΅s], [1us], [1.5m] names .); then a repeated or out-of-order unit ([5m5m], [30s5m]); then duration out of range. An offset reads Go's durations, so offset 1us and offset 5m5m are accepted. Held by TestRangeAndUnwrapGrammarMatchLoki. |
| Names and other characters | A name is letters, digits and _ (dots stay inside a name: the proxy's dotted names, DottedNameError for the Loki profile). Any other character is a token of its own: + - * / % ^ . { } ] are named by themselves in errors, the rest are identifiers, 'x' is a one-character literal (invalid char literal, literal not terminated), and [ starts a range that needs its ] (missing closing ']' in duration, line 0). Only an ASCII digit starts a number: another decimal digit (U+0663, U+0966, U+FF13), a superscript, a fraction and a Roman numeral start no token and are identifiers of their own, so {app="a"} | x Ω£ and | x Β² are unexpected IDENTIFIER. The scanner must move on every character: a scan that reads nothing once made the parser loop without end (FuzzParseTerminates holds every entry point to 200 ms and a mebibyte per input byte). |
| Keywords | by without bool offset on ignoring group_left group_right unless unwrap json regexp logfmt unpack pattern label_format line_format decolorize drop keep variants of (any case) are keyword tokens wherever they stand, so a label filter cannot name a label by. ip, label_replace, vector, the range and vector aggregation names and the unwrap conversions (bytes, duration, duration_seconds) are keywords only before a ( or a by (/without (, and print in upper case in errors (unexpected RATE, BYTES_CONV). "Any case" is Go's lower casing, as in Loki's lexer: the Kelvin sign (U+212A) is a k and U+0130 an i (topβͺ(, avg_over_tΔ°me(, wΔ°thout), while U+017F (ΕΏ), which only case-folds to s, is a letter of a name. The request path writes every keyword in lower case (LowercaseKeywords) before the handlers, the cache keys and the translation read the query; a word right after a digit, a letter or a dot, inside a range or not valid UTF-8 keeps its spelling. |
| NUL | invalid character NUL, at the start of the token before it: its line when the NUL follows the token, line 0 when white space or a comment lies between. Inside a quoted or backquoted string it is the error of the string, at its opening quote; the string's errors come in the order of the text, so a bad escape, a line break or a missing closing quote before the NUL is reported instead. Inside a comment it is the error of the comment, on line 0. A query with a NUL keeps its comments, so the validation sees the byte. |
| Order of errors | A lexer error is reported ahead of the parse error it may cause, and for a query that parses, but only for tokens Loki has read when it stops: a parse error at a token hides the lexer error of a later one. |
| Binary operator after a label filter | + - * / % ^ == > >= < <= unless after a complete filter belong to the query, whose left operand is the pipeline: the query goes on from there and a log query operand is unexpected type for left leg of binary operation (+): *syntax.PipelineExpr (MatchersExpr for a bare selector, right leg for the right operand; the left operand first). Inside parentheses the operator is a syntax error. |
| Float conversions | A number Go's ParseFloat cannot read (0x1, 0b1, 1e999) is unable to parse literal as a float: strconv.ParseFloat: parsing ... for an operand, unable to parse vectorExpr as a float in vector(), invalid parameter for operation quantile_over_time: ... and invalid parameter topk(0x1, for a parameter; Loki raises it after the left leg type check. |
Not covered: a range of a bare 0, which Loki reads as a duration of nothing and the proxy rejects, a range that holds a Grafana variable ([$__auto]) keeps the parser's own error, a byte order mark at the start of a query is a name to the proxy where Loki drops it, a stage that is a bare name alone (| x) passes through to the backend as an unknown stage (a name followed by more of the stage, | x+y=1, | a, b or | a .5, is Loki's syntax error at the token after the name), the content of a stream selector that is not closed ({app="a"} + {) keeps the generic error, approx_topk is read as an opaque call, so a character after it that is no parenthesis or a grouping gets the call's errors instead of Loki's expecting ( or by or without and grouping not allowed for approx_topk aggregation, and in the parenthesized range form an unwrap followed by another token ((... | unwrap x(a))[1m], (... | unwrap x y)[1m]) gets Loki's status, position and unexpected token with expecting RANGE or | where Loki also lists ).
The query the handlers readβ
Before any handler, the response cache or the translation reads a query, the request rewrite writes it in one spelling that Loki reads as the query sent (lowercaseQueryKeywords in internal/proxy/http_utils.go):
#comments are removed (logql.StripComments), and the logfmt flags (logql.StripParserFlags);- keywords are written in lower case (
logql.LowercaseKeywords); - for a query the validation accepts, the metric calls and parentheses are written in one spelling (
logql.CanonicalSpelling): no blank between a metric call's name and its parenthesis (rate ({a="x"}[5m]),vector (1),sum (rate(...))), no blank right inside its parentheses (vector( 1 ),sum by (a) ( rate(...) )), no parentheses around a call or around parentheses ((rate(...)),sum((rate(...)))), and none around a binary operation that no operator reads (the whole query, or the whole argument of a call); parentheses right after a vector matching clause (x / on(a) (sum(...))) keep their spelling. The metric calls are the range functions, the vector aggregations and rankings,label_replace(whose first argument is respelled as the whole argument of a call, read where it stands),vectorandapprox_topk. Log queries, pipelines, ranges,by/without/on/ignoringclauses, numbers and the blanks around binary operators keep their bytes.
The spellings the rewrite keeps are read from the parsed tree by the query plan, which serves them: quoted text (a parenthesis, bool or a run of blanks in a line filter under a binary operation), the blanks around a binary operator (x/2, x -2, a tab), a number written otherwise than its shortest form (* 1e3, / 2.50), a vector matching modifier spelled otherwise than on(a, b), a quantile written .5, 0.50 or 5e-1, and an unwrap conversion with a blank before or inside its parenthesis (| unwrap bytes (n)). The lowering has no text screen that copies the string translator's reading of them; the bytes of the binary text's own markers in an operand's quoted text (|||, @@@, __binary__:, __lvp_lr:) are left to the translator, decided from the lowered operands. The proxy's answers for these spellings are Loki's (TestPlanSpellingsMatchLoki: recorded Loki engine answers, VictoriaLogs v1.49.0 and v1.54.0). An unwrap of a name that is no conversion followed by a parenthesis (| unwrap x(a)) is Loki's syntax error at the parenthesis (TestUnwrapNameBeforeParenthesisMatchesLoki).
A query the validation rejects keeps its spelling, so its error names Loki's line and column. The rewrite is memoised by the query as sent (up to 1,024 queries of up to 4 KiB): a repeated query costs one lookup; a new one a scan of its bytes, and only a query the scan names a validation (memoised for the validation that follows) and a parse. Loki's parser reads every respelled query as the query sent (TestCanonicalSpellingMatchesLoki, recorded Loki parser answers over the plan-corpus rows the rewrite changes and a grid of spellings), and a respelled query gets the answer, the VictoriaLogs requests and the response cache entry of its canonical spelling (TestCanonicalSpelling_AnswersMatchLokiEngine, TestCanonicalSpelling_SameVictoriaLogsRequests).
Semantic Validationβ
After parsing, validateSemantics walks the AST and enforces constraints:
| Check | Error message |
|---|---|
Empty stream selector {} | parse error at line 1, col 2: queries require at least one matcher that is not a wildcard |
rate_counter without | unwrap | parse error : rate_counter requires | unwrap expression |
| unwrap outside a range aggregation | parse error at line 1, col N: syntax error: unexpected unwrap, at the unwrap, ahead of every other check of the query (the parser keeps such a log query, so the handlers can drop Grafana's | unwrap [1s] stubs first) |
A stage after | unwrap that is no label filter | parse error at line 1, col N: syntax error: unexpected drop, expecting IDENTIFIER or ( (a line filter: unexpected |=, expecting RANGE or |, line 0), raised by the parser; the error of a stage before it that Loki builds while it parses (a regexp or pattern parser, a regex) comes first |
rate() / bytes_rate() referencing __error__ | parse error : __error__ and __error_details__ are not allowed inside rate() range vectors |
quantile_over_time with a sign or a string before the parameter | parse error at line 1, col N: syntax error: unexpected -, expecting NUMBER or { or ( at the parameter, as Loki reads the parameter as a number token |
| A vector operation other than topk and bottomk with a number before its expression | parse error : unsupported parameter for operation sum(1,, a check over the parsed tree |
| line_format with unclosed {{ }} | parse error : stage 'β¦' : invalid line template: β¦ |
| Binary op with log stream on either side | parse error at line 1, col 1: unexpected expression for binary operation |
topk/bottomk whose first argument is not a number followed by a comma | The argument is read as the expression the operation aggregates, as Loki does: a comma after it is syntax error: unexpected , at the comma (topk(-1, β¦), topk(1 + 2, β¦), topk(rate(β¦), 2)), a ) after a metric expression is parse error : parameter required for operation topk (topk(-1)), a ) after a log query is syntax error: unexpected ) |
All error strings are formatted to match Loki 3.x responses so Grafana datasource clients receive the error shape they expect.
Order of the checksβ
A query with more than one error answers the error Loki answers. Loki runs its checks in phases, and the first phase that fails answers (recorded with the Loki oracle over a grid of 1628 queries, internal/logql/testdata/error-order-loki.jsonl.gz):
- Actions while parsing. A pattern or regexp parser that does not build, and a regex in a selector, label filter, drop or keep that does not parse. The parser keeps the matchers and stages it has read (
actionErrorSoFar). The first failing one answers ahead of a later syntax error and of a lexer error the parse goes on after, also inside label_replace. A syntax error or an invalid string before it ends the parse first. - Lexer errors, then the syntax error. A label_replace or vector call that is not Loki's grammar (three or five strings, a number for a string,
vector(x)) is its syntax error ahead of every check over the tree, with the line and column of the whole query; a call a#comment leaves open isunexpected $endat the end of the query with what Loki expects there (internal/logql/testdata/call_errors_loki.jsonl). - Checks over the parsed tree, in the order Loki's walk meets them, a node before its operands and the left operand first: a vector operation's parameter (
topk(0,sum(1,), approx_topk with a grouping, a range aggregation's grouping and unwrap, a log query or a literal as a binary operand, label_replace's regex (ahead of the tree inside the call, an outer call's first), the empty-compatible selector, then the query plan's checks (sort with a grouping, quantile_over_time without a parameter). - The pipeline build (
semanticPasswith build): line filter regexes and patterns, templates, json and logfmt expressions,ip(). On query and query_range it comes after the request's limits. On the instant route, a log query answers its query type error first.
ip() filter validationβ
The ip("value") line filter extension (parsed in internal/logql/parser.go, matched in internal/logql/ip_filter.go) validates the inner value at parse time with net/netip, following Loki's matcher rules: a single address (netip.ParseAddr), a prefix (netip.ParsePrefix), or an ordered same-family range (a.b.c.d-e.f.g.h, zones stripped). Validation is eager: the query is rejected with HTTP 400 even when the time range contains no data.
| Input | Parse error contains |
|---|---|
Invalid address, prefix or range, e.g. |= ip("999.999.999.999") | ip: invalid pattern: "999.999.999.999" |
ip() with a line filter operator other than |= or !=, e.g. |~ ip("10.0.0.1") | ip: invalid operation |
A label filter stage that is one ip() comparison (| addr=ip("zzz")) is validated the same way and answers Loki's parse error : stage '| addr=ip("zzz")' : ip: invalid pattern: "zzz"; a stage that joins several filters is not, as in Loki. Matching is exact for IPv4 line filters and approximate for IPv6 (see translation reference).
Line filter runsβ
Loki builds the line filters of a pipeline as runs: a label filter, line_format, unpack and unwrap end a run, while json, logfmt, regexp, pattern, label_format, drop, keep and decolorize do not, so |~ "(" | json |~ "[" is one run. An invalid line filter's error quotes the whole run (stage '|= "x" |~ "("'), names the run's last invalid filter, and comes in Loki's order next to the errors of other stages, as recorded with the Loki oracle.
Pattern line filter validationβ
The pattern of a |> or !> filter may not hold two captures in a row (found consecutive capture '<_><_>': invalid expression) and its only capture is <_> (named captures are not allowed: found '<foo>'), as Loki builds it. Within one pattern, captures in a row are reported first; a |> chain is read in order and a !> chain, which Loki builds as one !> per alternative, from its last alternative. The | pattern parser keeps its named captures.
ValidateLogQL APIβ
// ValidateLogQL returns a Loki-compatible error string, or "" if valid.
func ValidateLogQL(query string) string
Fast-path cases handled before parsing:
- Empty string β
parse error : syntax error: unexpected $end - Bare
*β valid (Grafana sends this as a wildcard) - Starts with
|βparse error at line 1, col 1: syntax error: unexpected | - Contains
<>β parse error at the>position
Everything else goes through the full parse + semantic pass.
Translationβ
Query plan lowering (which translator answers)β
A query is translated by one of two paths, and the client cannot tell which: the same VictoriaLogs query comes out of both, byte for byte, but for a label that LogsQL reads as a keyword (not, in, options, and, or, contains_all, contains_any, contains_common_case, equals_common_case, in any case): Loki accepts such a label, VictoriaLogs rejects it written bare, and the plan quotes it ("not":="a") where the string translator does not.
- Served from the plan: log queries made of a stream selector, line filters (
|=,!=,|~,!~), pattern filters (|>,!>) and label filters (includingip()and repeated filters), with no parser stage, and the log queries whose other stages are all in a flipped stage family (proxy.QueryPlanFlippedLogStages: adetected_levelfilter with no parser or formatting stage before it;jsonandlogfmtparsers, with or without an extraction list (logfmtwith its flags), and the label filters after them;regexpandpatternparsers and the label filters after them;dropandkeepstages;label_formatstages whose values are text and{{.name}}fields or renames;line_formatstages with such a template, the stored line kept aside where the Loki-compatible profile keeps it; and aregexporpatternparser written with no blank before its expression,|pattern"<_> <m>", which Loki reads as the spaced parser and the string translator copied into a pipe VictoriaLogs rejects: the plan writes the spaced spelling'sextracttext, for metric queries too; the allocation-free text screenlower.ScreenLogStagesnames the families before any parse, then the typed gateservesLogStagesand the lowering decide). The request's validation keeps its parse in the plan memo for a query the plan serves, so the translation does not parse it again, and the log query lowering parses a query no handler parsed with itsline_formattemplates untyped (it reads them as text).lower.Planbuilds the filters with the shared builders ininternal/translateandphysical.Encodewrites the text. Metric queries too: range and vector aggregations, binary operations andlabel_replacecalls whose plan writes the string translator's text byte for byte (lowerMetric: the allocation-free text screenlower.ScreenMetricInnames the construct before any parse, then the typed gatewritesTranslatorTextand the lowering decide), a range function whose series akeepbefore the unwrap decides, and the spellings the string translator reads otherwise than the tree (see The query the handlers read). Three of the plan's own readings are served where the string translator writes another text, each held to Loki by recorded answers: an equality on a number, a duration or a byte size in a label filter after ajsonorlogfmtparser (| json | status = 200), in log and metric queries, compared as a number (a VictoriaLogs range pair; the translator matched the literal's text;TestNumericEqualityAfterParserMatchesLoki, with the values VictoriaLogs still reads otherwise listed there), a label filter value that holds a\x00,\x01or\x02byte in a log query with stages (the translator cut it at its stage markers;TestMarkerBytesInLabelValueMeanWhatLokiMeans), and a metric query's matcher or label filter on_time,_stream,_stream_idor_msgbefore any parser (the stream tag;TestReservedFieldLabelsMatchLoki, the metric Loki differential).-query-plan-lowering=falsereturns every query to the string translator. - Still on the string translator: a log query with
unpackordecolorize, a query that holds a comparison with a signed number, akeepof names and matchers together, aline_formatorlabel_formattemplate that is more than text and{{.name}}fields, aline_formatwritten with no blank before its template, a spacedregexporpatternexpression the plan would spell another way (an escape in a double-quoted one, a control byte), aservice_namefilter, adetected_levelfilter after a parser or formatting stage, the metric queries the proxy evaluates itself or the plan writes another way (rankings,stddevandstdvarat any level, a binary with awithoutclause or avector()operand,vector(), an emptywithout (), anunpack, the recorded differences), and any query the lowering answers with an error. That includes a regexp line filter (|~,!~) or an exact matcher on a stream field whose value is written with an escape (\x41, an octal escape), a raw control character or backquotes: the string translator sends the client's spelling of those two, and the lowering holds only the value, so it leaves them (LogSelect escaped spelling, counted as not lowered). Every other position, and a plain spelling of the same value, is still served from the plan. - Labels named after VictoriaLogs' own fields: a label called
_time,_stream,_stream_idor_msgreaches VictoriaLogs only as a tag of the stream, and a filter naming the field is VictoriaLogs' time, stream, stream id or line filter; the plan filters the tag ({app="a"} | _time="x"isapp:="a" {_time="x"}, a comparison reads the tag's value out of_stream), and writes_TIME,_Streamor_STREAM_IDas the stream filter in a selector and, in a label filter, copies the field into a scratch field the filter reads (| copy _TIME as __lxrf_TIME | filter __lxrf_TIME:="x"): VictoriaLogs reads such a name bare as its own filter, and prints a quoted one bare when it clones the query, so only these forms read back as written. The string translator writes the field filter, which VictoriaLogs rejects or reads as its own filter (_time:>=5sis a time range). The proxy serves the plan's form for log queries with only filters and for metric queries whose matcher or label filter on such a name comes before any parser; a log query with such a filter and a stage, and a grouping, drop, keep or unwrap of the name, still get the string translator's text. - Labels that are keywords: a label Loki's lexer reads as a keyword token (
of,bool,offset,unwrap,json,regexp,logfmt,unpack,pattern,label_format,line_format,decolorize,drop,keep,variants, in any case) is no label name: a stream selector, grouping list, drop or keep list, json or logfmt extraction,label_formatorunwrapthat names one is Loki's 400 with Loki's text.Ip,IPandLabel_replaceare labels (ipandlabel_replaceare keywords only before a parenthesis) and keep their case. - Why it is safe to switch: the corpus shadow (
TestPlanShadow, see testing) asserts, for every native corpus row under each of the 12 translator profiles, thatphysical.Encode(lower.Plan(...))equals the translator's text byte for byte (with the keyword label names above quoted:lower.QuoteKeywordFieldText); the route-parity test sends the same queries through a fake VictoriaLogs with the flag on and off and compares the answers and every upstream request.
LogQL stage β LogsQL pipe mappingβ
The AST-to-AST translator (logql.Translate) maps LogQL pipeline stages to logsql typed pipe nodes:
| LogQL stage | Condition | LogsQL output | Notes |
|---|---|---|---|
*StreamSelectorExpr | always | logsql.FilterExpr | Label matchers =, !=, =~, !~ |
*LineFilterStage | |= / != / |~ / !~ / |> / !> | logsql.PipeFilter | Pattern filter |> mapped to VL seq() or regexp |
*LabelFilterStage | bare label condition | logsql.PipeFilter | Raw expression preserved; complex filters fall through |
*ParserStage β json | always | logsql.PipeUnpackJSON | |
*ParserStage β logfmt | always | logsql.PipeUnpackLogfmt | |
*ParserStage β regexp | always | logsql.PipeExtractRegexp | |
*ParserStage β unpack | always | logsql.PipeUnpackJSON | |
*DropStage | bare labels only | logsql.PipeDelete | Matcher-based drop β errFallthrough |
*KeepStage | bare labels only | logsql.PipeKeep | Matcher-based keep β errFallthrough |
*LineFormatStage | simple templates | logsql.PipeFormat | Complex {{ templates β errFallthrough |
*LabelFormatStage | any | errFallthrough | No LogsQL equivalent yet |
*UnwrapStage | any | errFallthrough | Handled by metric translator |
*DecolorizeStage | any | errFallthrough | No LogsQL equivalent |
*RangeAggregation | any | errFallthrough | Metric path via string translator |
*VectorAggregation | any | errFallthrough | Metric path via string translator |
*BinOpExpr | any | errFallthrough | Binary metric path |
*OpaqueMetricExpr | any | raw pass-through | label_replace, vector, approx_topk |
errFallthrough is a package-private sentinel β callers route to TranslateLogQLWithCapabilities unchanged.
Edge casesβ
| Situation | Behaviour |
|---|---|
Empty stream selector {} | Semantic validation rejects before translation: "queries require at least one matcher that is not a wildcard" |
*= / !*= matchers | Converted to =~.* / !=.* (LogsQL has no native glob) |
Label names with dots (service.name) | LabelFn rewrites to underscores if OTel mode enabled; otherwise passed through |
|~ ".+" β always-true regex | Optimised away (no LogsQL equivalent needed) |
rate() / bytes_rate() over __error__ | Rejected at semantic pass: 400 |
quantile_over_time Ο < 0 | Rejected at semantic pass: 400 |
Unknown function (label_replace, custom) | OpaqueMetricExpr: raw text forwarded to VL unchanged |
| VL version < required capability | Capabilities gating downgrades construct (e.g. BestIPv4Range β regexp fallback) |
| No LogsQL equivalent for valid LogQL | UnsupportedError β the query handler returns HTTP 400 with the translator message as the text/plain body (for example the message for a range aggregation such as avg_over_time written without an unwrap stage) |
| ` | line_format` unclosed template |
| ` | pattern` parser stage |
Parser Stages and Series Identityβ
ParserCaptureLabels (internal/logql/parser_captures.go) reads the capture names of | regexp and | pattern stages from the parsed pipeline: the named groups of the Go regexp, and the <name> placeholders of a pattern (<_> skips). Metric routing adds them to the series identity, because Loki names a metric series with the stream labels plus every label the pipeline extracted.
The key set of | json and | logfmt is known only once a line is read, so it cannot come from the AST and the proxy keeps the stream identity unless -exact-parser-series-identity is set. KNOWN_ISSUES.md records the measured difference.
How Routing Uses the ASTβ
proxy.go calls logql.Parse() on the already-validated query (error cannot occur at this point) and type-switches to dispatch:
This is more reliable than the previous approach of injecting routing markers into the translated LogsQL string and re-detecting them downstream.
Testingβ
The package has five test files:
| File | What it covers |
|---|---|
scanner_test.go | Token-level scanning: identifiers, strings, operators, ranges |
parser_test.go | Round-trip parse β String() for representative expressions |
ast_test.go | AST node String() methods and edge cases |
semantic.go tests (in edge_cases_test.go) | All semantic validation constraints |
edge_cases_test.go | 116 exhaustive parity cases against Loki's behaviour |
bench_test.go | Allocation and throughput benchmarks |
fuzz_test.go | Corpus-based fuzzing: go test -fuzz=FuzzParse |
The 116 edge-case parity tests are driven by query-semantics-matrix.json and cover: invalid selectors, missing unwrap, quantile bounds, rate/bytes_rate with __error__, line format template validation, binary op constraints, and exhaustive LogQL syntax acceptance/rejection matching Loki's exact error strings.