Skip to content

M1: tooling groundwork + PromQL transpile-determinism fix - #925

Closed
tsouza wants to merge 16 commits into
metrico:masterfrom
tsouza:m1-groundwork-golden-sql-corpus
Closed

tsouza wants to merge 16 commits into
metrico:masterfrom
tsouza:m1-groundwork-golden-sql-corpus

Conversation

@tsouza

@tsouza tsouza commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Closes #918

Summary

Lands the M1 tooling floor: golangci-lint, -race on the unit-test lane, the
Makefile as the single entry point for build/test/lint/fuzz, go-arch-lint in
report-only mode — plus the one bug fix that's a hard prerequisite for anything
that pins transpiler behavior later.

  • Groundwork: golangci-lint (scoped to what's actually idiomatic here — see
    the config's comments for why errcheck/structtag/composites are excluded),
    -race on the CI unit-test lane, Makefile targets (build/test-unit/
    lint/arch-lint/fuzz) as the single entry point for these lanes,
    go-arch-lint wired in report-only mode.
  • Determinism fix: TranspileExpressionV2's pushdown-substitute naming used
    rand.Int63(), so the same query could emit different (but equivalent) SQL
    across runs. Replaced with a per-transpile counter on promql_parser.Expr,
    now covered by a direct determinism test (transpile the same expression twice
    via the real engine path, assert byte-identical output).
  • Parser AST-shape pins per query head (PromQL/LogQL/TraceQL): table-driven
    tests pinning that a representative valid query parses to the expected
    root/field shapes the planners consume, and that a representative invalid
    query fails with the documented error class — cheap insurance against
    upstream parser-dependency bumps changing shapes underneath the transpilers.
    Lives in its own reader/internal/parserpin package.
  • Parser fuzz targets: one native Go FuzzParse target per query head,
    wired as make fuzz HEAD=<head> [DURATION=<duration>]. Local and
    manual-dispatch only — never a CI gate.

What's not in this PR

The original scope included a golden-SQL corpus (153 fixtures pinning the
literal ClickHouse SQL text each PromQL/LogQL/TraceQL query lowers to). That's
been dropped: a static SQL-text contract bakes in today's emitted shape,
including shapes that may themselves be bugs, so every fix becomes two edits
(code + golden) instead of one. Query-behavior pinning now lands at two other
layers instead — decision pins for internal routing/pushdown choices, and
response-level goldens for the Loki/Prometheus/Tempo JSON contracts Grafana
actually depends on. Neither is part of this PR; both land in later milestones
of the testing epic (#917, resequenced accordingly — see the epic for the
updated milestone order).

Test plan

  • go build ./...
  • go test ./... -race -count=1 (whole module, clean)
  • make lint → 0 issues
  • make arch-lint → no warnings
  • make fuzz HEAD=promql DURATION=2s (and logql/traceql) → no crashes
  • New determinism test (TestTranspileIsDeterministic) run with
    -race -count=2, green
  • Manually swept the full diff for any reference to a prior/internal
    source project name and any AI-generated attribution text — none found

@CLAassistant

CLAassistant commented Aug 21, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

tsouza added 7 commits August 21, 2026 18:56
Local Claude Code project settings (hooks, permissions) are
machine-specific and should not be tracked in the repo.
TranspileExpressionV2's substitute walker named pushdown placeholders
via rand.Int63(), so the emitted SQL for a given query was not
reproducible across runs. Substitute names only need to be unique
within one transpile, so a counter on the per-call Expr struct gives
the same guarantee deterministically. This is a hard prerequisite for
golden-SQL corpus pinning: two runs of the same (query, step, range)
must now emit byte-identical SQL.
Adds the tooling floor for the golden-SQL corpus work: a golangci-lint
config scoped to what's actually idiomatic in this codebase (participle
grammar struct tags aren't real struct tags, errcheck flags this
repo's existing Close()-in-defer style, etc.), -race added to the CI
unit-test lane, a Justfile as the single entry point for build/test/
lint/corpus/fuzz recipes, and go-arch-lint wired in report-only mode to
baseline current package coupling without gating on it yet.
Introduces reader/internal/goldentest: a TXTAR-based fixture
format/loader/writer with a -update regeneration flag, a recording
fake implementing the reader's DB session interfaces (IDBRegistry/
ISqlxDB) for driving the real PromQL engine without a live ClickHouse,
and a generic parser-pin table-driven test helper. This is the shared
harness the three query-head golden corpora build on.
50 fixtures capturing the real PromQL engine's emitted SQL for
(query, step, range) tuples, driven end-to-end through the actual
engine and a recording DB-session fake so both the pushdown
substitution decision and the raw-vs-downsampled table routing are
genuinely exercised, not hand-built. Also adds parser AST-shape pins
and a native FuzzParse target seeded from representative queries.
64 fixtures pinning the SQL clickhouse_planner.Plan renders for a
LogQL query: stream selectors, line/label filters, parsers
(json/logfmt/regexp), line_format/label_format, unwrap, range
aggregations with by/without grouping, and binary expressions (each
side's SQL pinned separately, since the merge itself happens
in-process). Also adds parser AST-shape pins and a native FuzzParse
target.
39 fixtures pinning both the simple-vs-complex routing decision and
the resulting SQL statement(s) for TraceQL queries: attribute/
resource/span selectors, intrinsics, conjunctions, structural
operators, pipeline aggregates, and tag/value lookups, with a mix of
simple- and complex-routed queries. Also adds parser AST-shape pins
and a native FuzzParse target.
@tsouza
tsouza force-pushed the m1-groundwork-golden-sql-corpus branch from 525a2df to 57f0df8 Compare August 21, 2026 18:56
@rita7lopes
rita7lopes self-requested a review August 21, 2026 19:30
tsouza added 5 commits August 24, 2026 17:31
The repo already has a Makefile for e2e/docker workflows; introducing a
second build-tool entry point (Justfile) split tooling across two
files for no reason. Move build/test-unit/lint/arch-lint/update-golden/
fuzz into Makefile targets (HEAD/DURATION passed as make variables) and
drop the Justfile, updating the doc/comment references that pointed at it.
Comments in the fuzz/golden test files and docs/contributing.md's code
block alignment still pointed at \`just\` commands after the Justfile was
folded into the Makefile.
Resolves the go.mod conflict from upstream's dependency bumps (grpc,
go 1.27.0, otel/prometheus deps) against this branch's addition of
golang.org/x/tools as a direct dependency: keep the x/tools promotion,
take upstream's bumped versions, then `go mod tidy` to reconcile go.sum.

Upstream also landed a promql fill-gap fix (include the last step in
the grid) that changes generated SQL, so the promql golden corpus is
regenerated to match (`make update-golden HEAD=promql`); re-run with
-count=2 confirms byte-identical, deterministic output. Full `go test
-race ./...` is green post-merge.
golangci-lint refuses to run when its own build's Go toolchain is
older than the module's `go` directive. v2.12.2 (this job's pin) was
built with go1.26.2, so once master's go.mod bump to 1.27.0 landed
here via merge, the lint check started hard-failing with "can't load
config" before running a single linter. v2.13.1 is built with go1.27.0
and lints clean locally (0 issues). Also switch the job's Go setup to
go-version-file: go.mod so it doesn't drift from the module version
again.
@akvlad

akvlad commented Aug 27, 2026

Copy link
Copy Markdown
Collaborator

Hello @tsouza .
This is a PR for unit testing. We thank you for that.
Although I don't see a lot of sense in this kind of unit tests, it can improve our codebase.
Please use a 3rd party test library like go-snaps, autogold, gotest.tools/v3/golden instead of the self-written internal/goldentest one.

Thanks.

@tsouza

tsouza commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi, thanks for the notes.

Please use a 3rd party test library like go-snaps, autogold, gotest.tools/v3/golden instead of the self-written internal/goldentest one.

The reason for writing it standalone is really to simplify things. I will evaluate those tools to see if any can be used without increasing complexity.

Although I don't see a lot of sense in this kind of unit tests, it can improve our codebase.

This is part of a larger plan. Indeed this code change alone does not makes sense, but since it's part of a much larger change, I decided to split. See #917 for more context

Static SQL-text goldens pin today's ClickHouse-specific output shape as a
contract, including shapes that may themselves be bugs -- every fix then
requires updating both the code and the golden file. Query-behavior pinning
now belongs at two other layers instead: decision pins for internal
routing/pushdown choices, and response-level goldens for the Loki/
Prometheus/Tempo JSON contracts Grafana actually depends on. Neither is
part of this PR; both land in later milestones of the testing epic (metrico#917).

What stays: golangci-lint, -race, the Makefile entrypoints, go-arch-lint
(report-only), and the rand.Int63() -> per-transpile-counter fix for
pushdown-substitute naming, now covered by a direct determinism test
(transpile the same expression twice, assert byte-identical output) instead
of only being inferred from golden re-runs.

What's removed: reader/internal/goldentest (996 lines), the three
golden_test.go files, all 153 testdata/golden/*.txtar fixtures, the three
corpus-* CI jobs, the update-golden Makefile target and its docs, and
.gitattributes (its only content was golden-fixture -merge entries). The
parser AST-shape pins and fuzz targets are unaffected and stay -- they're
not goldens, and relocate cleanly: parserpin.go moves to its own
reader/internal/parserpin package since it has no goldentest dependency.

go.mod: golang.org/x/tools reverts from a direct to an indirect
dependency now that goldentest.go (its only direct importer) is gone.
@tsouza tsouza changed the title M1: groundwork + golden-SQL corpus for PromQL/LogQL/TraceQL M1: tooling groundwork + PromQL transpile-determinism fix Sep 4, 2026
@tsouza

tsouza commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Rescoped this PR after further discussion. Dropped the golden-SQL corpus (153 SQL-text fixtures + the goldentest infra) — a static SQL-text contract pins today's emitted shape, including shapes that may themselves be bugs, so every fix meant two edits (code + golden) instead of one. Query-behavior pinning now lands at two other layers in later milestones instead: decision pins for internal routing/pushdown choices, and response-level goldens for the actual Loki/Prometheus/Tempo JSON contracts. See #917 for the updated milestone order.

What's left in this PR: tooling groundwork (golangci-lint, -race, Makefile entrypoints, go-arch-lint) and the rand.Int63() → per-transpile-counter determinism fix, now backed by a direct test instead of only being inferred from golden re-runs. Parser AST-shape pins and fuzz targets are unaffected.

Resolves the two real conflicts by hand: master's math/rand/v2 modernization
(metrico#954) touched the same rand.Int64() lines this branch's determinism fix
replaces with NextSubstituteName() -- kept this branch's fix, which fully
supersedes the modernization (no rand import needed once the counter replaces
random naming entirely). go.yml auto-merged cleanly, keeping both master's
gofmt step and this branch's lint/-race/arch-lint additions.
The pins/seeds landed with the M1 groundwork PR were thin (14-17 parser
pins, 10-14 fuzz seeds per head). Query strings for this expansion are
drawn from two permissively-licensed, cerberus-free upstream sources
already vendored for reference elsewhere:

- PromQL: prometheus/compliance's promql-test-queries.yml (MIT-derived),
  template placeholders resolved via its own testVariantArgs table.
- LogQL: grafana/loki's pkg/logql/bench query registry.
- TraceQL: no equivalent clean vendored corpus existed, so only bare
  query strings (no fixture names, comments, or expected-result
  metadata) were extracted from a local compatibility smoke corpus and
  validated independently against this repo's own parser -- one line
  mentioning a source project name was excluded outright, consistent
  with this project's no-reference-project-mentions policy.

Every candidate was run through this repo's actual Parse() (not assumed
from the source project's behavor) to classify it as a valid-shape pin,
an invalid-syntax pin, or fuzz-only seed material; several negative pins
document real, current parser gaps (unwrap's conversion-function syntax,
empty by()/without() on LRAOrUnwrap, TraceQL's ">"/"<"/"!(" forms) rather
than assuming upstream behavior transfers unchanged.

Also fixes two dangling "golden corpus"/"golden-SQL pinning" comment
references left over from the previous commit's corpus removal.
@tsouza

tsouza commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Pushed a follow-up commit enriching the parser AST-shape pins and fuzz seed corpus for all three heads (they were thin: 14-17 pins / 10-14 seeds each). New material is validated against this repo's actual parser (not assumed) and drawn from permissively-licensed upstream sources already vendored for reference elsewhere — prometheus/compliance's query set for PromQL, grafana/loki's pkg/logql/bench registry for LogQL. Several new pins are negative cases documenting real current parser gaps (unwrap conversion-function syntax, empty by()/without() on range aggregations, TraceQL's bare ">"/"<"/"!(" forms) rather than assuming upstream grammar support carries over.

@rita7lopes

rita7lopes commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the rescope — dropping the SQL-text corpus was the right call, and the PR is much closer to landable.

Three more things needed before merging the PR.

1. Remove the parser AST-shape pins

reader/promql/promql_parser/parserpin_test.go      (425)
reader/traceql/traceql_parser/parserpin_test.go    (320)
reader/logql/logql_parser/parserpin_test.go        (271)
reader/internal/parserpin/parserpin.go             (70)

The four come out cleanly as a unit — the fuzz targets don't import the helper, and nothing else consumes it.

The reasoning is the one that retired the SQL corpus, one layer up. These pin the shape of a parsed AST rather than a behaviour, and the coverage already exists at the behaviour level: reader/promql/promql_transpiler/transpiler_test.go:17-22 parses and transpiles sum by (a) (rate(http_requests_total{...}[5m])) and asserts on the emitted result, so an upstream AST change breaks that first and with a clearer message. There are ~2,370 lines of transpiler tests on master already doing this.

Two categories are worth calling out specifically:

  • The 37 LogQL/TraceQL Check pins assert our own participle struct shapes (StrSelCmds, Pipelines[0].LineFilter.Fn, ByOrWithoutSuffix). There is no upstream parser behind those two heads, so they don't protect against a dependency bump — they fire when we refactor our own AST.
  • Five of the WantErr pins assert that we reject queries which are valid in the real languages, which pins the gap open: a contributor who implements the feature gets a red test telling them not to.

That last point is the most valuable thing in this PR. Those five are real compatibility bugs, now filed with the upstream grammar citations: #986, #987, #988, #989, #990. Checking them turned up more than the pins covered — 11 of TraceQL's 14 structural operators are unsupported, and all three LogQL unwrap conversion functions, not just duration(). Without this work none of that would have surfaced.

2. Match the Go toolchain to go.mod

The arch-lint job pins go-version: '1.26', but master is on 1.27.1 (#969) and #933 moved CI to go-version-file: go.mod.

3. Confirm the golangci-lint pin still builds

v2.13.1 was pinned when go.mod was on an older Go; worth re-checking against 1.27.1.


Keeping: the determinism fix and its direct test — "same input produces the same output" is exactly the kind of invariant that earns a permanent test — plus the three FuzzParse targets, golangci-lint, -race, go-arch-lint, and the Makefile entrypoints.

Context for the wider plan is in #917 and the per-milestone comments.


Sorry for the delay in replying. Between the work on #972 and the other PRs from @janeblower, we needed to agree on the path forward first so the tests would match the plan rather than the other way round.

Let us know whether you'd like to make the three changes, or if you'd rather I do it.

@rita7lopes rita7lopes left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check my comment above

Guess-Who-sec added a commit to Guess-Who-sec/gigapipe that referenced this pull request Nov 9, 2026
…names (metrico#918)

Takes over metrico#925, keeping the scope agreed in its review, and completes
the rest of metrico#918.

Fix: PromQL pushdown substitutes were named with rand.Int64(), so the same
query transpiled to a different residual expression on every run. Each
parsed Expr now hands out names from its own counter
(Expr.NextSubstituteName). Names stay unique within a query, which is the
only scope prom_queryable looks them up in. TestTranspileIsDeterministic
transpiles twice and requires a byte-identical residual expression and
byte-identical SQL for every substitute.

Makefile as the single entry point; CI runs only recipes:
- fmt-check, build, test-unit (go test -race ./...), lint, arch-lint,
  fuzz HEAD=<head> [DURATION=60s]
- lint builds golangci-lint v2.14.0 from source and reports only issues
  new since LINT_NEW_FROM_REV (CI passes the PR base commit). v2.13.x
  cannot read the export data go1.27.3 writes (format V5 needs
  golang.org/x/tools >= v0.50.0)
- arch-lint runs go-arch-lint v1.19.0 from tools/archlint, which raises
  golang.org/x/tools to v0.50.0 for the same reason; no go-arch-lint
  release does yet. Report-only in CI (continue-on-error)

Parser fuzzing:
- FuzzParse for LogQL, PromQL and TraceQL asserts no panic and that any
  accepted query round-trips (render, parse, render gives the same text)
- "Parser fuzz" workflow, manually dispatched only, uploads crashers
- the LogQL crasher it found (dangling and/or in a label filter) is
  committed as a regression seed

Review changes on top of metrico#925:
- drop the parser AST-shape pins and the reader/internal/parserpin helper
- arch-lint reads the Go version from go.mod instead of pinning 1.26
- bump golangci-lint v2.13.1 -> v2.14.0 (see above)

Co-authored-by: Thiago Souza <122435+tsouza@users.noreply.github.com>
rita7lopes added a commit that referenced this pull request Nov 9, 2026
…names (#918) (#1059)

* chore(ci): M1 tooling groundwork and deterministic PromQL substitute names (#918)

Takes over #925, keeping the scope agreed in its review, and completes
the rest of #918.

Fix: PromQL pushdown substitutes were named with rand.Int64(), so the same
query transpiled to a different residual expression on every run. Each
parsed Expr now hands out names from its own counter
(Expr.NextSubstituteName). Names stay unique within a query, which is the
only scope prom_queryable looks them up in. TestTranspileIsDeterministic
transpiles twice and requires a byte-identical residual expression and
byte-identical SQL for every substitute.

Makefile as the single entry point; CI runs only recipes:
- fmt-check, build, test-unit (go test -race ./...), lint, arch-lint,
  fuzz HEAD=<head> [DURATION=60s]
- lint builds golangci-lint v2.14.0 from source and reports only issues
  new since LINT_NEW_FROM_REV (CI passes the PR base commit). v2.13.x
  cannot read the export data go1.27.3 writes (format V5 needs
  golang.org/x/tools >= v0.50.0)
- arch-lint runs go-arch-lint v1.19.0 from tools/archlint, which raises
  golang.org/x/tools to v0.50.0 for the same reason; no go-arch-lint
  release does yet. Report-only in CI (continue-on-error)

Parser fuzzing:
- FuzzParse for LogQL, PromQL and TraceQL asserts no panic and that any
  accepted query round-trips (render, parse, render gives the same text)
- "Parser fuzz" workflow, manually dispatched only, uploads crashers
- the LogQL crasher it found (dangling and/or in a label filter) is
  committed as a regression seed

Review changes on top of #925:
- drop the parser AST-shape pins and the reader/internal/parserpin helper
- arch-lint reads the Go version from go.mod instead of pinning 1.26
- bump golangci-lint v2.13.1 -> v2.14.0 (see above)

Co-authored-by: Thiago Souza <122435+tsouza@users.noreply.github.com>

* fix(ci): give lint a base commit on pushes

github.event.pull_request.base.sha is empty on a push, so once go.yml runs
on pushes to master, `make lint` gets no --new-from-rev and fails on every
pre-existing issue. Fall back to github.event.before, the commit before the
push, so a push is held to the same "new issues only" rule as a pull request.

* chore(ci): drop arch-lint, pin golangci-lint in a tools module

Review follow-up for #1059.

- Remove go-arch-lint (.go-arch-lint.yml, tools/archlint, the make target
  and CI job): with every component allowed every dependency and the job
  set to continue-on-error, it could not report anything.
- golangci-lint v2.14.0 is now a tool of a tools/ module, kept current by
  a Dependabot entry for /tools. make lint runs it from the repo root with
  go tool -modfile=tools/go.mod, so it lints gigapipe's packages.
- .golangci.yml header: CI runs make lint with --new-from-rev; drop the
  stale golangci-lint-action and corpus references.
- Fuzz targets: state that the seed corpus runs under go test ./....

* chore(ci): run golangci-lint@latest instead of a tools module

The tools/ module added a second go.mod with a hand-maintained go version
that go-version-sync does not update, plus a second Dependabot stream.
Run the latest golangci-lint release instead: nothing to bump, and it keeps
up with new Go releases. .golangci.yml lists the linters explicitly and
--new-from-rev only fails on new issues.

* chore(ci): point make lint, CI and docs at golangci-lint@latest

Completes the previous commit, which removed tools/ but left make lint,
the CI cache paths, the /tools Dependabot entry and the docs pointing at it.

---------

Co-authored-by: Thiago Souza <122435+tsouza@users.noreply.github.com>
Co-authored-by: rita7lopes <ritamlopes@live.com.pt>
@rita7lopes

Copy link
Copy Markdown
Contributor

Hi @tsouza
I'm closing this one, as superseded by #1059
Thank you so much for your work and all the issues!

@rita7lopes rita7lopes closed this Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

M1 — Tooling groundwork + PromQL transpile-determinism fix

4 participants