Repository navigation
Conversation
Search runs up to the per-trace spansets and returns them to Go with the listed span ids. Data reads spans, summaries and selected values for the ids shipped as the external table _search_result (trace_id, span_id[]), with plain IN on clusters too, so spansets never reach ClickHouse twice.
Structural and plain searches over fixed traces compare with golden results captured from the single-statement search; the cluster runs spread the traces over both shards.
…ments Statement 1 lists the result span ids by trace into the external table _search_result (compare()'s selection into _selection_result); statement 2 reads the spans of those ids with plain IN, on clusters too. The ids statement keeps the sample and the analyzer setting; statement 2 always runs, also over empty ids.
…ements Statement 1 lists the result span ids of the query by trace into the external table _search_result; statement 2 reads the attribute keys or values of those spans from the attrs table with plain IN, on clusters too. The ids statement keeps the analyzer setting and is uncapped; statement 2 carries the suggestion limit and does not run over empty ids. Each complexity portion runs both statements once. A query that selects every span still reads every key or value in one statement.
The golden pins tag keys and values of name and a for plain, structural, deep, unresolved, limited and portioned queries, captured on 143cc1b, the single-statement plan, with single node and two shards agreeing. A recorder test checks that each portion lists its ids once and reads them once, and skips the attributes read without ids.
…trace Every structural operator reads its operand sides, the traces they share and their parent ids into one _nodes group and resolves ancestry in a single pointer jump with a per-trace round count. One-hop operators recurse only for traces with a root and a missing parent. The _edges/_spans/_links/_flags chain and its reach and resolved CTEs are removed.
On a cluster, the ids statement of a structural search runs whole on every
shard inside cluster('<name>', view(...)) over the local tables, with a
per-shard LIMIT and each trace's newest span as trace_newest; the
coordinator keeps the newest traces of the merged rows. Single-node SQL is
unchanged. The plan context carries the cluster name.
This requires a trace's spans to live on one shard, which writers get by
inserting through the _dist tables; docs/traceql.md states it. The two-shard
search fixtures are seeded by trace instead of by span-id parity.
A `||` whose other side repeats an operand of its structural side plans the structural operator alone, keeping every row of that operand. The pivot's trace-id set reads its source rows directly instead of the grouped pivot.
Run ClickHouse with MALLOC_CONF=background_thread:true,dirty_decay_ms:1000, muzzy_decay_ms:0 and set it on the e2e compose ClickHouse services. Measured on two shards at 7 GiB per node (aarch64, ClickHouse 25.3), 24h Drilldown, warm-up plus five back-to-back runs: - defaults: 1/6 pass; jemalloc keeps the previous run's freed pages, RSS starts at 2-4.8 GiB instead of ~0.9 and the 0.9 x 7 GiB cap trips (241) at ~3 GB tracked. - with the env: 6/6 pass, median 7.8 s (default warm-up 9.7 s), RSS peak <= 5.04 GiB, tracked unchanged (~3-3.8 GB per node). `>>`, `~` and broad queries at 24h stay within +-2.5 % wall, RSS peak 0.5-1.3 GiB lower. - dirty_decay_ms:1000,muzzy_decay_ms:0 alone passes (median 8.6 s); background_thread:true alone does not (2/6). - memory_worker_correct_memory_tracker: 3/6 (the tracker follows RSS). Query-level max_bytes_before_external_group_by/_sort=1e9: 6/6 but +33 % wall on every large query.
Metrics, compare() and autocomplete run their structural ids statement whole on each shard through cluster(view()), with prefer_localhost_replica=0; the coordinator passes on (trace_id, span_ids) only. The metrics behaviour fixtures seed by trace through the Distributed tables.
compare() reads the attributes of the baseline traces only and counts them with IN sets over the baseline and selection spans. On a cluster the counts run whole on each shard through cluster(view()) with prefer_localhost_replica=0 over local tables; the coordinator sums the per-shard counts, then keeps the top values per attribute as before.
rita7lopes
left a comment
There was a problem hiding this comment.
Four things before I approve. Line numbers are from 13257f5.
1. Warn when a cross-cluster reader has no CLICKHOUSE_READ_CLUSTER
Shard-local statements run on ctx.ClusterName through cluster(...) (shard_local.go:63). That only follows the read cluster when CLICKHOUSE_READ_CLUSTER is set (tables.go:114). An existing reader with CLICKHOUSE_READ_DIST_SUFFIX=_dist_cross_cluster and no CLICKHOUSE_READ_CLUSTER reads remote regions today, but after upgrading its structural queries and compare() read only the local cluster, with no error.
Please log a warning at startup when the read suffix isn't _dist and CLICKHOUSE_READ_CLUSTER is unset. It should say that structural queries and compare() will read only the local cluster, and name the setting to fix it. Don't block startup, and don't add a fallback path.
2. Document memory in the reader, no code change
readIds holds every returned ID in reader memory, with no limit in that function (ids_query.go:88). Sizing memory is the operator's call, so I'm not asking for a cap or a second path. Please add the reader to the "ClickHouse memory" section of docs/configuration.md, explaining that span IDs are held there during metrics and compare().
If max_result_rows on the reader's ClickHouse user does cap the IDs statement, please confirm that and mention it too.
Also document that compare() on a cluster now goes through cluster(...) and sets prefer_localhost_replica (metrics.go:223, shard_local.go:82), and what access the reader's ClickHouse user needs for that, including in readonly mode.
3. Benchmark the top of the stack too
This PR replaces the metrics path that the benchmark I asked for on #1034 measures, so a #1034 number alone won't show what users get. Please run the same comparison against master on this branch: 24h {} | rate(), {...} | rate() by (...) and quantile_over_time(duration, 0.95), with time and peak memory for both ClickHouse and the reader.
The two-shard numbers in the description used the tuned MALLOC_CONF. Please also post them without it, so operators can see whether it's required.
4. Rebase, and run the full suites
The description says the full e2e suite and the grid didn't run on this branch, and CI here only ran Socket and CLA. Please run both once this is rebased.
The #1034 fixes need to carry through, since this PR rewrites much of structural.go: skipping and logging unresolved traces, and keeping from fixed in complexity portions. Please also recheck the garbled round-limit error over HTTP noted in the description, which that fix may remove.
Accepted, no change needed
- The one-shard-per-trace requirement: stating it in
docs/traceql.mdis enough. repeatedOperandonly handlingX || A: it has a measured benefit for Drilldown, and we can generalise it later.- The
TracesDataPlugincolumn change, since nobody uses these hooks.
Remove ancestryGuard and unresolvedAncestryError. An unresolved row is unreachable under >>, !>> and the one-hop operators; <<, !<<, &>> and &<< return nothing from a trace with an unresolved row. Each unresolved-trace probe runs on each shard over local tables, one row per shard, and the warning deduplicates the ids across shards.
A custom CLICKHOUSE_READ_DIST_SUFFIX without CLICKHOUSE_READ_CLUSTER leaves TraceQL structural queries and compare() on the local cluster. The reader logs that once at start-up, names the setting, and carries on.
Structural queries count spans in range on each shard through onEachShard, so one row per shard reaches the evaluator and its largest-row rule picks the fullest shard. A single node counts as one shard; span-only estimates keep their operand count against the same setting. The estimate goes through the structural gate, which skips unavailable shards like the read tables and reports an unsupported server before counting.
The docs state that the default assumes MALLOC_CONF.
A shard failing after another shard returned its row would otherwise leave a smaller estimate and too few portions.
…quirements Move what shard-local reads need of a trace's shard into Requirements, with the analyzer a cluster needs, and link CLICKHOUSE_READ_CLUSTER to it. Restore the round count under Depth limit and the one-shard reason in the numberer's cap. Add what readIds holds, what max_result_rows counts and why not break, the grants with the <secret> rule, and what a readonly=1 user must set. Drop the measured sizing from ClickHouse memory.
A user with the documented grants and settings in its profile matches the admin over native and HTTP, for readonly=1 with the settings, with CHANGEABLE_IN_READONLY and for readonly=2. A user without them gets code 164 naming the setting, the probe still finds cycles, and the connected node gets the shard statement as a remote query.
Each autocomplete portion is a trace_id range, so tempo_traces reads narrow by its sort key. The ranges split the ids with a nonzero high half by that half and the ids with a zero high half (64-bit ids) by the low half, so the portions partition every stored id and stay balanced. Every table read of a portioned statement keeps the portion: operands, the ancestry tree read, root and nested-set reads, pipeline pivots and the tags/values data stage.
Seeds trace ids spread over both halves of the id space and checks that portioned tags and values equal the unportioned ones, single node and on two shards, with every portion's ids and data statements reading a trace_id range.
The tree read of tempo_traces reads every partition. Its spans are ancestors of operands in range, so an upper bound of the query end plus one hour keeps them, and a parent starting later than that counts as missing.
A filter that compares only duration or span:duration is decided on each attribute row, since every row carries the span's duration. Tags and tag values for such a filter read tempo_traces_attrs_gin directly, with no ids stage, estimate or portions. A span re-sent with differing durations and not yet merged suggests only the attributes of the copies that pass.
# Conflicts: # reader/tempo/metrics_query.go # reader/tempo/metrics_query_test.go # reader/traceql/timerange/timerange.go # reader/traceql/traceql_transpiler/clickhouse_transpiler/select_tags_planner.go
Stacked on #1035; merge that first. It merges into #1035 as a merge commit, once the top PRs (#1091, #1092) have merged into it.
Breaking changes
Queries that now fail
readonly=1ClickHouse users on a cluster. Structural TraceQL metrics, autocomplete andcompare()fail with code 164 (Cannot modify 'prefer_localhost_replica' setting in readonly mode), and where the read tables skip unavailable shards, so do structural searches and everycompare().Without
prefer_localhost_replica=0, a structural search that succeeds logs no unresolved-trace warning: the warning's probe changes that setting. Each refused probe prints the code 164 error to stdout and resets the reader's connection pool, at most once a minute.Set
prefer_localhost_replica=0, andskip_unavailable_shards=1if the read tables skip unavailable shards, in the user's settings, or allow them withCHANGEABLE_IN_READONLY, or usereadonly=2. Setting them on the user applies to all of that user's Distributed reads. Over HTTP, also setcancel_http_readonly_queries_on_client_close=1on the user, so the server stops a read when the reader stops waiting. See ClickHouse access.Results that change
CLICKHOUSE_READ_CLUSTER. Structural queries andcompare()run on each shard ofctx.ClusterNamethroughcluster(...). With a read suffix other than_distandCLICKHOUSE_READ_CLUSTERunset, they read only the local cluster, with no error, where they used to read every cluster of the read table. The reader logs a warning at start-up naming the setting. With the one-pass metrics PR on top, TraceQL metrics with no spanset operator (&&,||, structural), scalar filter orby()stage join this list, except that a lone{}still reads all the clusters of the read table for itshistogram_over_time()exemplars and, with no custombylabel, for its other exemplars and formin_over_time()andmax_over_time(). With the lone{}follow-up (perf(traceql): read a lone {} metric's rows as master does #1093) on top, a lone{}reads all the clusters of the read table under a custombylabel too:avg,sum,min,max,quantile_over_timeandhistogram_over_time()read every cluster. The exceptions, which read only the local cluster, arerate(),count_over_time()and exemplars other thanhistogram_over_time()'s under a custombylabel, and the range series of aquantile_over_time()of several levels. SetCLICKHOUSE_READ_CLUSTERon readers. See Requirements.Upgrade notes
CLICKHOUSE_READ_CLUSTERon cross-cluster readers. See Results that change.MALLOC_CONF=background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:0(an environment variable of the server, not a config key). It is required at the default portion budget on 7 GiB nodes for 24h structural metrics, tag values andcompare(); without it they can fail with code 241. See ClickHouse memory.GIGAPIPE_TRACEQL_PORTION_SPANScounts per shard. Structural queries count spans in range on each shard and portion by the fullest one; a single node counts as one shard. Its default is5000000.enable_analyzerat its default of 1 for the reader's user, including throughcompatibility.SELECTon the database, including the local tables, plusREMOTE ON *.*. Without<secret>inremote_servers, shards run as the cluster's<user>; with it, the initial user must exist on every shard withSELECT.compare()or filtered tag autocomplete request:24 + 8 x spansbytes per trace, uncapped, for the whole request;compare()holds both tables at once.max_result_rowson the reader's user caps the IDs statement and counts traces. Withresult_overflow_mode=throwa request over it gets a 500; don't usebreak, which silently returns wrongcompare()counts and metrics.TracesDataPluginmust providetrace_newestas the last column of its final select on the shard-local path too.Summary
Structural TraceQL queries (
>>,<<,~,&>>, …) read far fewer table parts and fit in memory at 24h on single node and two shards, including Grafana Traces Drilldown's "Service structure" query(ROOT &>> {kind = server}) || ROOT.compare()and tag autocomplete first select the matching ids, then read data for those ids only (ids_query.go, one runner for all of them).compare()'s counts run on each shard over local tables; the coordinator only merges. Non-structural ids statements stay as they were. The portion budget is counted on each shard, and the shard-local path carries thetrace_newestrank, so portion merging stays exact.X || AwhereXalready readsA(the Drilldown query),Ais planned once and its rows are kept by widening the final filter._distand has noCLICKHOUSE_READ_CLUSTER(or noCLUSTER_NAME) logs which queries read only the local cluster and names the setting. It doesn't block start-up, and there is no fallback path. Writer-only instances don't warn.docs/configuration.mdgains Requirements (one shard per trace, the analyzer), ClickHouse memory (MALLOC_CONF, reader IDs,max_result_rows) and ClickHouse access (grants,<secret>,readonly=1), andCLICKHOUSE_READ_CLUSTERlinks Requirements.Evidence
compare()and tag golden responses are unchanged by the two-statement plans, single node and two shards. After the merge from feat(traceql): nested-set intrinsics, numbered at write time #1035 the goldens were re-recorded and checked key by key: only thesample=keys (scaled by1/f) and onepkey change, and the skip commit turns error results into results or[].go test ./reader/...withGIGAPIPE_TEST_CLICKHOUSE(and_CLUSTER,_HTTP) passes on 24.9 and 25.3, single node and two shards, native and HTTP, includingreadonly=1reader users on search, autocomplete, metrics andcompare(). Unresolved traces return results over HTTP (testSearchOverHTTP); the garbled round-limit error no longer arises, because no query raises it.grid.traceqlon two shards with 24.9, pass on the full stack tip.MALLOC_CONFon and off: the queries in the review, the Drilldown query,>>,~, structuralrate(), tag values andcompare(), and plaincompare(). The results stay out of this description and go to the reviewer directly.Known limits
!one.&&over terms met by different copies, a span can suggest none of its attributes.max_memory_usage.trace_idranges that assume uniform ids. Ids with a time prefix concentrate in few portions: results stay exact, but memory per portion isn't bounded by the budget.&>>with a root operand reads that operand and its root read twice in a statement.masterbut takes longer and uses more memory; for duration-only tag valuesmasterreturned no values on the same query, so there is no like-for-like cost.>>walk at the default budget. A slice statement can log code 241 while the request still returns its full result.Merge Danger
Door: two-way. No schema change; reverting the code restores the old statements.
Blast Radius: traces
Every TraceQL search, metrics,
compare()and tag autocomplete request runs two statements. On clusters, structural queries assume one shard per trace (see Requirements) and read only the cluster named byCLICKHOUSE_READ_CLUSTERorCLUSTER_NAME.