Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
e1708ea
refactor(traceql): build the parser once and pin the grammar with AST…
44YHC Oct 12, 2026
f5ea8c4
feat(sql_select): render WITH RECURSIVE CTEs and comma-separated SETT…
44YHC Oct 12, 2026
a48324e
refactor(traceql): take search, autocomplete and metrics time bounds …
44YHC Oct 12, 2026
00130d2
feat(dbversion): add the 24.9 structural-queries capability
44YHC Oct 12, 2026
70ebff5
refactor(traceql): resolve version info for search, tags v2, values v…
44YHC Oct 12, 2026
9c831f9
refactor(traceql): name the closed span-start bound and resolve metri…
44YHC Oct 12, 2026
98f0b85
fix(traceql): require an operator between chained spanset operands
44YHC Oct 12, 2026
23587d5
refactor(traceql): plan search, autocomplete and metrics from a lower…
44YHC Oct 12, 2026
20b543c
refactor(traceql): lower spanset operators with Tempo precedence and …
44YHC Oct 12, 2026
4807b0f
fix(traceql): evaluate search over uncapped span sets and cap spanset…
44YHC Oct 12, 2026
f8e16c3
build(e2e): pin the gigapipe-tests ref and parametrise the ClickHouse…
44YHC Oct 12, 2026
df97b8b
fix(traceql): order the attribute-less trace pre-pick like the search…
44YHC Oct 12, 2026
32303c2
fix(traceql): evaluate && and || across selectors per trace
44YHC Oct 12, 2026
5bfce0a
refactor(traceql): fold the spanset operator tree in one place
44YHC Oct 12, 2026
2584057
feat(traceql): evaluate one-hop structural operators on the span tree
44YHC Oct 12, 2026
de7c4c3
refactor(traceql): name misspelt operators, key one-hop spans by type…
44YHC Oct 12, 2026
39a5657
feat(traceql): evaluate transitive structural operators by pointer ju…
44YHC Oct 12, 2026
5ef4922
refactor(traceql): share the pointer-jump step and the result conditi…
44YHC Oct 12, 2026
e03fad4
feat(traceql): count metrics over the search result spans
44YHC Oct 12, 2026
e298de2
refactor(traceql): read exemplars from one span and keep metrics plan…
44YHC Oct 12, 2026
33ac741
feat(traceql): suggest autocomplete tags and values from the search r…
44YHC Oct 12, 2026
523dfa7
refactor(traceql): share autocomplete planning between tags and values
44YHC Oct 12, 2026
8d01aac
feat(traceql): parse Tempo pipelines and filter spansets by script-le…
44YHC Oct 12, 2026
a166a4d
refactor(traceql): name spanset attribute types and read unscoped agg…
44YHC Oct 12, 2026
1b576e0
feat(traceql): evaluate Tempo field expressions in spanset filters an…
44YHC Oct 12, 2026
c19cb29
refactor(traceql): type negations and attribute arithmetic statically…
44YHC Oct 12, 2026
e5c5209
refactor(traceql): name the arithmetic result type helper
44YHC Oct 12, 2026
aba8a2d
feat(traceql): narrow later pipeline stages to the spans of the stage…
44YHC Oct 13, 2026
7ab38ad
refactor(traceql): name the narrowed stage's own attributes and share…
44YHC Oct 13, 2026
c566d5c
feat(traceql): group pipeline spansets with by() and merge them with …
44YHC Oct 13, 2026
34a1ecd
refactor(traceql): compute by() pivot keys once and semi-join the piv…
44YHC Oct 13, 2026
0696d34
feat(traceql): add select() stages and the sample and exemplars hints
44YHC Oct 13, 2026
d4abd43
refactor(traceql): build the selected-value columns up front and reje…
44YHC Oct 13, 2026
c85816a
docs(traceql): document structural operators, pipelines and the relea…
44YHC Oct 13, 2026
52c8468
docs(traceql): cover trailing-operator errors, nil in && and ||, sum …
44YHC Oct 13, 2026
a3a6b1b
docs(traceql): scope the autocomplete time range and tighten Tempo-di…
44YHC Oct 13, 2026
8ba62d4
Merge remote-tracking branch 'upstream/master' into feat/traceql-stru…
44YHC Nov 5, 2026
ceb2cb1
test(traceql): replace TestStringDanglingAndOr with TestParseRejectsD…
44YHC Nov 6, 2026
3795840
test(traceql): replace #1040's metrics join tests with a planner inva…
44YHC Nov 6, 2026
03708ca
test(traceql): add ClickHouse behaviour-test harness
44YHC Nov 6, 2026
ecfae8f
fix(traceql): query the requested range in every complexity portion
44YHC Nov 6, 2026
80180f0
fix(traceql): skip unresolved traces instead of failing the query
44YHC Nov 6, 2026
16e9402
docs(traceql): move TraceQL docs into configuration and README
44YHC Nov 6, 2026
5cb301a
feat(traceql): warn about unresolved traces after the response
44YHC Nov 6, 2026
23d18db
fix(traceql): run the unresolved-trace probe for readonly=1 readers
44YHC Nov 6, 2026
873ec89
fix(reader): pass the health check for readonly=1 readers over HTTP
44YHC Nov 6, 2026
657f58d
feat(traceql): add a date bound on a span's stored date in any time zone
44YHC Nov 7, 2026
7f385c8
fix(traceql): bound search and autocomplete dates in UTC, a day eithe…
44YHC Nov 7, 2026
1c9a120
fix(tempo): bound by-label, compare() and tag search dates in UTC, a …
44YHC Nov 7, 2026
0e42e5d
test(traceql): pin traces reads against a reader zone and another zon…
44YHC Nov 7, 2026
57d4a1f
Merge upstream/master into feat/traceql-structural-ops
44YHC Nov 9, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .github/workflows/node-clickhouse-cluster.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,17 @@ jobs:
- name: Rollback Deployment
if: failure() && steps.execution.outcome == 'failure'
run: npm test -- -u

# The TraceQL grid suite on ClickHouse 24.9, the oldest version structural queries support.
traceql-clickhouse-24-9:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Check out the e2e test suite
run: make e2e-deps
- name: Install Compose
uses: ndeloof/install-compose-action@v0.0.1
with:
version: v2.1.0
legacy: true
- run: make e2e-ci E2E_CLICKHOUSE_IMAGE=clickhouse/clickhouse-server:24.9 E2E_TEST_ARGS=--testNamePattern=grid.traceql
12 changes: 9 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ docker-compose ?= docker-compose
# rather than duplicating the checkout.
E2E_TESTS_REPO ?= https://github.com/metrico/gigapipe-tests.git
E2E_TESTS_DIR ?= ./deps/gigapipe-tests
# Branch, tag or commit of the suite to run; a PR may pin its own tests branch.
E2E_TESTS_REF ?= traceql-structural-ops
# ClickHouse image of the e2e stack; the TraceQL suite also runs on the 24.9 floor.
export E2E_CLICKHOUSE_IMAGE ?= clickhouse/clickhouse-server:25.3
# Extra jest arguments, e.g. --testNamePattern=grid.traceql to run one suite.
E2E_TEST_ARGS ?=

# Enable the recording-rules ruler for e2e: exported so both the gigapipe
# server (via compose interpolation) and the test runner see the same value.
Expand Down Expand Up @@ -59,7 +65,7 @@ fuzz:

e2e-deps:
if [ ! -d $(E2E_TESTS_DIR) ]; then git clone $(E2E_TESTS_REPO) $(E2E_TESTS_DIR); fi
cd $(E2E_TESTS_DIR) && git pull && git checkout main && git pull;
cd $(E2E_TESTS_DIR) && git fetch origin $(E2E_TESTS_REF) && git checkout --detach FETCH_HEAD

e2e-build:
docker build -f scripts/deploy/docker/Dockerfile -t gigapipe .
Expand All @@ -69,7 +75,7 @@ e2e-test:
docker rm -f qryn-go-test && \
sleep 60 && \
docker run \
-v `pwd`/$(E2E_TESTS_DIR):/deps/e2e \
-v $(abspath $(E2E_TESTS_DIR)):/deps/e2e \
--network=e2e_common \
--name=qryn-go-test \
-e INTEGRATION_E2E=1\
Expand All @@ -79,7 +85,7 @@ e2e-test:
-e QRYN_RULER_ENABLED \
-e OTEL_COLL_URL="http://a:b@e2e.aio:9080" \
node:18-alpine \
sh -c 'cd /deps/e2e && npm install && npm test -- --forceExit'
sh -c 'cd /deps/e2e && npm install && npm test -- --forceExit $(E2E_TEST_ARGS)'

e2e-cleanup:
$(docker-compose) -f ./scripts/test/e2e/docker-compose.yml down
Expand Down
134 changes: 134 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,140 @@ GET /api/metrics/query_range?q={span.http.status_code=200}&since=1h&step=1m

This query calculates span counts for successful HTTP requests over the last hour with 1-minute resolution.

#### Time range

A span is in range when it **starts** in `(from, to]`: a span starting exactly
at `from` is excluded, and one starting exactly at `to` is included. The same
rule applies to search, metrics and autocomplete with a filtering query, so
adjacent windows never count a span twice. Autocomplete without a query, or
with `{}`, reads whole days.

Only spans in range can be operands or results. The structural context of a
span (its parent, ancestors, siblings and roots) is read from the whole
trace, whenever those spans started. A long-running root that started before
`from` still links its descendants inside the range.

#### Search results

- `GET /api/search` - TraceQL search (`q`, `start`, `end`, `limit`, `spss`)
- `GET /api/v2/search/tags`, `GET /api/v2/search/tag/{tag}/values` - autocomplete (`q`)

Search and metrics are also served under the `/tempo` prefix.

- `spss` (spans per spanset) is the number of spans listed per spanset,
newest first. It defaults to 3. A value that isn't a positive integer is
rejected with `invalid spss: must be a positive number`.
- `matched` is the number of spans the spanset matched, even when `spss`
lists fewer.
- `limit` counts traces that satisfy the whole query.
- No cap applies to the spans a query evaluates. ClickHouse memory limits
apply.

#### Known issues

- `nestedSetParent < 0` applies to every span the query returns, not only to
the selector it is written in:
- As the left operand of a structural operator the selector matches every
span, and only root spans of the result are kept.
`{nestedSetParent < 0} >> {.a = 1}`, and the same with `>`, return nothing.
The other operators return only root spans: `{nestedSetParent < 0} << {.a = 1}`
returns the `.a = 1` roots that have any descendant.
- `{nestedSetParent < 0} && {.a = 1}` and `{nestedSetParent < 0} || {.a = 1}`
return only the root spans.
- `{nestedSetParent < 0 || .a = 1}` returns only root spans.

`{nestedSetParent < 0 && .a = 1}` in a single selector, and a pipeline stage
`{…} | {nestedSetParent < 0}`, are correct.
- Only `nestedSetParent < 0` is supported. Other comparisons of
`nestedSetParent`, `nestedSetLeft` or `nestedSetRight` with a number or
duration on the right hold for every span. A string or boolean on the right
fails with `binary operations must operate on the same type`.
- Any comparison of these fields, `nestedSetParent < 0` included, fails with
`unsupported attribute <name>` when:
- it is negated: `{!(nestedSetParent < 0)}`
- its other side is not a literal, or the literal is on the left:
`{nestedSetLeft > .a}`, `{0 > nestedSetParent}`
- the selector has another term such as `.a = .b`, `.a != nil`, `.a = true` or
`.a > 1ms`: `{nestedSetParent < 0 && .a = .b}`

#### Differences from Tempo

gigapipe returns the spans Tempo returns, except in the cases listed here.

<details>
<summary>Full list</summary>

**Time range and trace data**

- Operands must start in the query range. Tempo draws operands from every
span of a trace that overlaps the range.
- Tempo's rule that returns nothing for a trace in which three or more spans
share a span ID is not reproduced. Such traces are evaluated as stored.
- Traces that are too deep or cyclic are handled as described in
[Depth limit](docs/configuration.md#depth-limit).

**Grouping**

- The grouped-spanset error is raised before the query runs. So it also
fires on queries Tempo would run because every trace has a single group,
and on spanset operators after `by()` (`{A} | by(.x) | {B} > {C}`), which
Tempo evaluates per group.
- Groups are ordered by key. Tempo's order is random.
- Attribute group keys are returned as strings, since attributes are stored
untyped. Tempo returns typed values. `status` and `kind` read the stored
attribute, so spans without one form the nil group, where Tempo reports
`unset`.

**Field expressions and filters**

- `!` works inside spanset filters. Tempo returns nothing for such filters.
- `!x` on a non-boolean is false, where Tempo can fail.
- `span.a = nil`, `resource.a = nil` and `.a = nil` all test `a` whatever its
scope, and match only spans without `a`. In Tempo the scope matters, and
unscoped `.a = nil` also matches spans that have `.a`.
- Int, float and duration values aren't distinguished in storage, so
`.a = "200"` and `.a = 200` both match a stored `200`.
- `int ^ int` is evaluated as written. Tempo swaps base and exponent.
- Integer division and modulo by zero give nil, not an error.
- `&&` and `||` treat a nil operand as false and evaluate the other side.
Tempo usually makes the whole operation false.
- Typing is stricter. A filter that can't be boolean, or an aggregate
argument that can't be numeric, built only from attributes (`{ -.a }`,
`{ .a * .b }`, `{ !.a = 1 }`, `{ .a + .b = "x" }`, `avg(!.a)`), is
rejected before the query runs. Tempo accepts these and matches nothing or
fails per span.

**Scalar filters**

- In aggregate arguments, a span where the expression is nil (`.a + nil`) is
skipped. Tempo counts it.
- `sum()` over a mix of ints and floats adds every value as a float. Tempo
drops values whose type differs from the first value's.
- Literal arithmetic isn't folded, so `count() > 1 + 2` is rejected.
- `count() > count()` is rejected with Tempo's right-hand-side error text.
- `(count() > 2) && {B}` is a parse error. Tempo accepts it.
- A bare word as an aggregate argument (`avg(spanN)`) reads the attribute of
that name. Tempo rejects it.

**`select()`**

- Selected values are returned as strings. Tempo returns typed values.
- An attribute named like an intrinsic shares its storage key: a span
attribute `name`, `status` or `kind` is reported as the span's name,
status or kind.

**Metrics hints**

- `sample=f` keeps a deterministic hash sample. Queries that relate spans
across a trace sample whole traces by trace ID, and other queries sample
spans by span ID. Tempo keeps one item in N with a counter.
- Sampled metrics values are returned unscaled. Tempo scales them up by the
observed sampling ratio, except `min_over_time` and `max_over_time`.
- `exemplars=N` caps exemplars per series, spread over the buckets that have
one. Tempo applies the cap per query evaluator, not per series.

</details>

<br>

### 🔥 Pyroscope + Phlare
Expand Down
4 changes: 4 additions & 0 deletions cmd/gigapipe/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"github.com/metrico/cloki-config/config"
"github.com/metrico/qryn/v5/ctrl"
"github.com/metrico/qryn/v5/reader"
"github.com/metrico/qryn/v5/reader/traceql/traceqlconfig"
"github.com/metrico/qryn/v5/reader/utils/logger"
"github.com/metrico/qryn/v5/reader/utils/middleware"
"github.com/metrico/qryn/v5/reader/utils/tables"
Expand Down Expand Up @@ -292,6 +293,9 @@ func main() {

func start() {
distconfig.Init()
if err := traceqlconfig.Init(); err != nil {
panic(err)
}
tables.InitDistTableNames()
var configPaths []string
if _, err := os.Stat(*appFlags.ConfigPath); err == nil {
Expand Down
71 changes: 71 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,77 @@ Variables that are not Gigapipe-specific — `CLICKHOUSE_*`, `PORT`, `HOST`,
- **`LOG_PATTERN_SIMILARITY`** - Similarity threshold for pattern grouping, range 0-1 (default: `0.7`). Higher values require more similarity.
- **`LOG_PATTERN_READ_LIMIT`** - Maximum number of log patterns to read per request (default: `300`)

## TraceQL

- **`GIGAPIPE_TRACEQL_ANCESTRY_ROUNDS`** - Number of rounds used to resolve span ancestry for TraceQL structural operators, an integer from `1` to `32` (default: `20`). With `R` rounds, traces up to `2^R` spans deep resolve. Spans of deeper traces, and of traces whose parent links form a cycle, are treated as unreachable, and a warning names those traces. Each round adds work to every query using `>>` or `<<`. An invalid value stops Gigapipe at start-up. See [Depth limit](#depth-limit).

Structural TraceQL queries need ClickHouse 24.9 or newer; see [Requirements](#requirements).

### Requirements

Queries that use a structural operator (`>`, `>>`, `<`, `<<`, `~` and their
`!`/`&` variants) need **ClickHouse 24.9 or newer**. On an older server they
fail with `TraceQL structural operators need ClickHouse 24.9 or newer`. All
other TraceQL queries keep working on older servers.

Structural queries need no schema migration, writer change or backfill: the
span tree is resolved at query time from the `parent_id` of the stored spans.
Clustered (Distributed) deployments return the same results as single-node
ones, provided **a trace's spans and attribute rows live on one shard**.
Writers inserting through the `_dist` tables place them so: the sharding key is
`sipHash64(oid, trace_id)`, and a trace has one `oid`.

### Depth limit

The span tree is built at query time from stored `parent_id`s:

- A span takes part in a structural relation only when its parent chain
reaches a root span (a span without a parent).
- A span that can't reach a root, such as one in an orphan subtree whose
parent was never ingested or in a trace with no root, never matches a
positive or `&` operator, and always matches a `!` operator.
- A span whose ancestor hasn't been ingested yet starts matching once that
ancestor arrives.
- When a trace has several roots, they are all siblings under `~`.

Ancestry is resolved in a fixed number of rounds, set by
`GIGAPIPE_TRACEQL_ANCESTRY_ROUNDS`. With `R` rounds, traces up to `2^R` spans
deep resolve. The default of 20 covers traces about a million spans deep.

A span whose ancestry is still unresolved after the last round is either in
a trace deeper than the limit or has parent links that form a cycle. The
query doesn't fail. Instead:

- Under `>>`, `!>>` and the one-hop operators (`>`, `<`, `~` and their
variants), unresolved spans are treated like orphans. The rest of the trace
is evaluated normally.
- Under `<<`, `!<<`, `&>>` and `&<<`, the whole trace is skipped and returns
no spans from that operator, including under `!`.

Only traces that are candidates for the operator are affected: traces with
spans on both sides of a `>>`/`<<` operator or its variants, and, for the
one-hop operators, traces that have a root and also a span whose parent is
missing.

At most once a minute, gigapipe logs a warning that names the affected
traces:

```
TraceQL structural query: N trace(s) have unresolved ancestry (deeper than 2^R spans at GIGAPIPE_TRACEQL_ANCESTRY_ROUNDS=R, or parent links form a cycle); their unresolved spans are treated as unreachable; trace_ids=[…]
```

The line lists up to 20 trace IDs. Raising the round limit helps only with
deep traces, not cycles.

The warning comes from a background probe with a time limit. The probe reads the
reader's `readonly` setting each time it runs. When that read returns 0, the
server stops any probe statement started with more than a second of the limit
left, shortly after the limit. In every other case the reader stops waiting at
the limit. Over the native protocol that also stops the query on the server.
Over HTTP the server stops it only if `readonly` is not 0 and the reader's
profile holds `cancel_http_readonly_queries_on_client_close=1`; otherwise it
runs on to its end.

## Recording Rules (Ruler)

The ruler evaluates LogQL and PromQL recording rules on a schedule and writes
Expand Down
9 changes: 8 additions & 1 deletion reader/controller/tempo.go
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ func (t *TempoController) Search(w http.ResponseWriter, r *http.Request) {
params.Limit = 20
}
ch, err := t.Service.SearchTraceQL(internalCtx,
params.Q, params.Limit, params.Start, params.End)
params.Q, params.Limit, params.Spss, params.Start, params.End)
if err != nil {
PromError(500, err.Error(), w)
return
Expand Down Expand Up @@ -451,6 +451,7 @@ type traceSearchParams struct {
MinDuration time.Duration
MaxDuration time.Duration
Limit int
Spss int // spans per spanset; 0 means the default
Start time.Time
End time.Time
}
Expand All @@ -473,6 +474,12 @@ func parseTraceSearchParams(r *http.Request) (*traceSearchParams, error) {
if err != nil {
return nil, fmt.Errorf("limit: %v", err)
}
if spss := r.URL.Query().Get("spss"); spss != "" {
res.Spss, err = strconv.Atoi(spss)
if err != nil || res.Spss <= 0 {
return nil, fmt.Errorf("invalid spss: must be a positive number")
}
}
startS, err := strconv.ParseInt(orDefault(r.URL.Query().Get("start"), "0"), 10, 64)
if err != nil {
return nil, fmt.Errorf("start: %v", err)
Expand Down
29 changes: 29 additions & 0 deletions reader/controller/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,3 +209,32 @@ func TestTamePanic_FlushThenPanicAborts(t *testing.T) {
t.Fatal("client read a complete-looking response from an aborted handler")
}
}

func TestParseTraceSearchParamsSpss(t *testing.T) {
for _, c := range []struct {
query string
want int
wantErr bool
}{
{"", 0, false},
{"spss=7", 7, false},
{"spss=0", 0, true},
{"spss=-1", 0, true},
{"spss=x", 0, true},
} {
r := httptest.NewRequest(http.MethodGet, "/api/search?q=%7B%7D&"+c.query, nil)
got, err := parseTraceSearchParams(r)
if c.wantErr {
if err == nil {
t.Errorf("%q: no error", c.query)
}
continue
}
if err != nil {
t.Fatalf("%q: %v", c.query, err)
}
if got.Spss != c.want {
t.Errorf("%q: spss %d, want %d", c.query, got.Spss, c.want)
}
}
}
19 changes: 18 additions & 1 deletion reader/logql/logql_transpiler/shared/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ type PlannerContext struct {
OrderASC bool
Limit int64
Offset time.Duration
// SpansPerSpanSet caps the spans listed per TraceQL search spanset; 0 means the default.
SpansPerSpanSet int64
// AncestryRounds is the pointer-jumping rounds of TraceQL structural
// operators; 0 means the default.
AncestryRounds int

TimeSeriesGinTableName string
TimeSeriesGinDistTableName string
Expand Down Expand Up @@ -83,11 +88,23 @@ type PlannerContext struct {

RandomFilter RandomFilter
CachedTraceIds []string
VersionInfo dbversion.VersionInfo
// Portions is the number of complexity portions the request was read in,
// or 0 when it was read at once.
Portions int64
VersionInfo dbversion.VersionInfo

// TracesIntrinsicWhere holds extra WHERE conditions for the tempo_traces table
// (e.g., nestedSetParent < 0 → parent_id = '').
TracesIntrinsicWhere []sql.SQLCondition

// TracesOperandSpans, when set, holds the previous pipeline stage's span
// rows: the only ones TraceQL selectors may match, and the input of a
// nested pipeline.
TracesOperandSpans *sql.With

// TracesSample, when set, keeps the sampled rows of every TraceQL
// operand read.
TracesSample sql.SQLCondition
}

func (p *PlannerContext) Id() int {
Expand Down
Loading
Loading