Skip to content

Capture the tags collector when creating timeSeriesStoreTags and timeSeriesTagsToGroup - #126492

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-time-series-tags-expired-context
Nov 7, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-time-series-tags-expired-context

Conversation

@groeneai

@groeneai groeneai commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #104948

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Not required.

Description

Stress test (amd_msan) aborted with Logical error: 'Context has expired' in FunctionTimeSeriesStoreTags::executeImpl on a PromQL query from 05271_promql_label_matcher_pushdown (report, STID 1805-578d). It is a master-only regression from #104948, which made timeSeriesStoreTags and timeSeriesTagsToGroup hold their creation context weakly and look up the tags collector in executeImpl.

The creation context is the scope context of the analyzer query node. With parallel replicas and a local plan, createLocalPlanForParallelReplicas clones the query tree with fresh context copies, but the cloned function nodes share the original function objects. If the table of the parallel-replicas node is empty (here the samples table, after an injected memory error failed the test's INSERT), the local plan is returned alone, the original contexts are released, and the function finds its context gone when the pipeline runs.

The change captures the collector in the constructor again, as before #104948 and as the other timeSeries* tag functions do. A plain-SQL query (an IN subquery with a JOIN, over an empty table) reaches both functions the same way, so both are changed. Without a query context the function can still be created to read its signature; executing such an instance throws THERE_IS_NO_QUERY. Both files are removed from the WithContext exception list of the style check.

The new test (a TimeSeries table with tags and time ranges but an empty samples table, parallel replicas with a local plan) makes the debug server abort on master and passes with the change, 50/50 with randomized settings and in the DBReplicated, parallel-replicas and distributed-plan flavours.


Workflow [PR]
Sync PR [sync-upstream/pr/126492]

Version info

  • Merged into: 26.11.1.1611-master (included in 26.11 and later)

groeneai and others added 2 commits October 17, 2026 13:57
…SeriesTagsToGroup

ClickHouse#104948 changed both functions to hold their creation context weakly and to look up
the query's tags collector in executeImpl. The creation context is the scope context of
the analyzer query node, and it does not always live as long as the pipeline. With
parallel replicas and a local plan, createLocalPlanForParallelReplicas clones the query
tree and gives every query node a fresh context copy, while the cloned function nodes
share the original function objects. When the table of the parallel-replicas node is
empty, the local plan is returned alone and the original contexts are released before
the pipeline runs. A PromQL query over a TimeSeries table whose data table is empty then
throws LOGICAL_ERROR `Context has expired` from timeSeriesStoreTags (seen in the
Stress test (amd_msan) job, STID 1805-578d).

Capture the collector in the constructor again, as before ClickHouse#104948 and as the other
timeSeries tag functions do. The collector is created once per query context, so the
captured object is the one the deferred lookup returned. Without a query context the
function can still be created to read its signature (what ClickHouse#104948 wanted for
system.functions); executing such an instance throws THERE_IS_NO_QUERY.

Both files no longer use WithContext, so they are removed from the exception list of
the style check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merge the two-line constructor comments in timeSeriesStoreTags and timeSeriesTagsToGroup into one invariant line each.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 rounds: 2, 3 and 0 findings) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The empty-data queries return no rows with or without parallel replicas, so a run that silently drops parallel replicas would pass AGREE Fixed: the test asserts ParallelReplicasQueryCount for the five empty-data queries (5 5; 0 5 with parallel replicas off)
2 ⚠️ ParallelReplicasQueryCount does not distinguish the local plan from a remote-only one AGREE Fixed: parallel_replicas_prefer_local_replica = 1 and max_execution_time_leaf = 0 pinned, the remaining local-plan gates
3 ⚠️ No test fails when only the timeSeriesTagsToGroup half is reverted AGREE Fixed: a plain-SQL IN subquery with a JOIN for each function; a build with only the timeSeriesStoreTags half fails the test in timeSeriesTagsToGroup
4 ⚠️ Construction without a query context (the hasQueryContext() branch) has no test DISAGREE No in-tree caller builds these functions without a query context: system.functions resolves them with the SELECT's context, as for the 13 sibling tag functions that capture unguarded. Executing such an instance throws THERE_IS_NO_QUERY, like getQueryContext() did.
5 💡 The system.query_log check itself runs with parallel replicas AGREE Fixed: enable_parallel_replicas = 0 on that read
6 💡 The test's header comment names only timeSeriesStoreTags AGREE Noted, not blocking

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261017-135900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. TimeSeries table with explicit targets, TRUNCATE of the data table, then prometheusQueryRange(...) with enable_parallel_replicas = 1, parallel_replicas_local_plan = 1, cluster test_cluster_one_shard_three_replicas_localhost: the debug server aborts with Context has expired at timeSeriesStoreTags.cpp:117 (the CI frame) 3/3 for the CI query, and for req, sum(req), count_values(...). Same data present, parallel_replicas_local_plan = 0, or parallel replicas off: OK. A plain-SQL query, id IN (SELECT <function>(...) FROM t_tags ALL LEFT JOIN (...) USING (id) ...) inside two derived tables over an empty MergeTree table, aborts the same way in timeSeriesStoreTags and in timeSeriesTagsToGroup.
b Root cause explained? #104948 made both functions keep their creation context weakly and read the tags collector in executeImpl. The local parallel-replicas plan is built from a cloned query tree with fresh context copies that shares the original function objects; with an empty table it is returned alone and the original contexts are released before execution.
c Fix matches root cause? Yes. The functions no longer use their creation context at execution time (the style-check rule against WithContext in functions); the collector is captured at construction, as before #104948.
d Test intent preserved / new tests added? New 05410_time_series_tags_functions_parallel_replicas_expired_context.sql: server dies on master, passes with the fix; includes the plain-SQL query for each function; asserts through ParallelReplicasQueryCount in system.query_log that the five empty-data queries ran with parallel replicas (reads 0 5 with them off); also checks results with data under the same settings and system.functions introspection.
e Both directions demonstrated? Yes. Unfixed build: test FAIL (server died), also under --replicated-database; with only the timeSeriesStoreTags half applied it still fails, in timeSeriesTagsToGroup. Fixed build: 50/50 randomized, 10/10 in the parallel-replicas flavour at local_plan 1 and 0, 10/10 DBReplicated, 10/10 with serialize_query_plan = 1.
f Fix is general across code paths? Both functions changed this way by #104948 are fixed; the other timeSeries* tag functions already capture the collector in the constructor. timeSeriesTagsToGroup fails the same way (plain-SQL IN subquery with a JOIN), and the test covers each function separately.
g Fix generalizes across inputs (params/datatypes/wrappers)? The change is in construction, independent of argument types. Tested with selector, matcher, binary operator, aggregation and count_values queries, with and without data.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; inside a query the function uses the same per-query collector. Created without a query context it still constructs, and executing it throws THERE_IS_NO_QUERY as before.
i Invariants and contracts preserved? Producer and consumers share one collector per query (checked in the test). Dry runs touch no collector, unchanged. Construction never throws, so system.functions still lists the signatures.

Session id: cron:clickhouse-impl-slot-4:20261017-122100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vitlibar @nikitamikhaylov, could you review this? Since #104948 timeSeriesStoreTags and timeSeriesTagsToGroup read the tags collector through their weakly held creation context in executeImpl, and with a parallel-replicas local plan over an empty table that context is already released (logical error Context has expired); this captures the collector at construction again, like the other tag functions.

@clickhouse-gh

clickhouse-gh Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bc48c1b]

Summary: ✅


AI Review

Summary

The PR makes timeSeriesStoreTags and timeSeriesTagsToGroup retain the per-query ContextTimeSeriesTagsCollector, avoiding an expired creation-context lookup after parallel-replica local-plan cloning. The regression test covers both functions and checks execution through parallel replicas. No actionable findings.

Missing context / blind spots
  • ⚠️ Tests were not run locally. The debug flaky check at 37bb4d014930 passed the regression test 50/50, but current-head CI has not yet reported the test result after the latest fixture update. A passing current-head run would close this runtime-validation gap.
Final Verdict

Status: ✅ Approve. No code changes requested; current-head test execution remains pending in CI.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... labels Oct 17, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - bb36b12

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, sequential, 2/2) / 03821_drop_workload_during_query_race flaky, not from this PR (it changes only the two TimeSeries tag functions): the test prints the stack trace of an expected INVALID_SCHEDULER_NODE error from a query racing DROP WORKLOAD; the same failure is on 65 other PRs and twice on master since 2026-10-16 #126345 (mine, open)
Performance Comparison (arm_release, master_head, 5/6) / new_json_type #1 performance, not from this PR (it cannot reach the JSON type): all three new_json_type queries are slower on the PR server (#1: 413 vs 314 ms); new_json_type #1 was also reported slower on master and on 8 other PRs since 2026-10-15 a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the rows above #126345 and the fix task above (the owners of the rows above)

The only other FAIL rows on this head are the Config Workflow / Pre Hooks rows of the two earlier attempts, which stopped on the missing can be tested label.

Session id: cron:our-pr-ci-monitor:20261018-073006

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison (arm_release) new_json_type #1 slowdown: #125949, together with #124676. The slow mode follows the server's load address on arm, not this PR; measurement: #125949 (comment)

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Oct 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bc48c1b0c with master ab83663d4 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of e720b7367; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

8 translation units recompiled, 10 s compile time in total, 8 of them have a recent master baseline.

Job report

groeneai and others added 2 commits October 23, 2026 00:26
…pped

ClickHouse#126742 made TimeSeries version 10 (inner targets only) the default, so
`CREATE TABLE ts ENGINE = TimeSeries DATA ts_data ...` now fails with
INCORRECT_QUERY and the test fails before reaching the query it guards.

The test needs time series whose tags and time ranges exist while the
samples table has no parts. It used to get that by truncating an external
data table. Inner tables have generated names, so now the tags are inserted
with empty sample arrays and the time ranges are written through
`timeSeriesTimeRanges`; the samples for the "with data" part are added
through `timeSeriesSamples`. Inserting tags with empty samples alone is not
enough: without time ranges no series matches and the query never reaches
the parallel replicas local plan.

Measured on a debug build: the snapshot master binary (31d10e5, no fix)
dies on the test at timeSeriesStoreTags.cpp:117 'Context has expired'; the
PR head passes it 50/50 with random settings, 10/10 with
serialize_query_plan = 1 and 10/10 with a Replicated database. The
reference is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With parallel replicas the `SELECT ... FROM timeSeriesTags(ts)` of the two
fixture inserts is also sent to the remote replicas, which look up the bare
`ts` in their default database and fail with UNKNOWN_TABLE. The test passed
only when the local replica finished first: it failed 3/150 in the PR flaky
checks (query 23, the samples insert), 1/50 locally in flaky-check mode, and
2/5 with parallel replicas enabled for the whole run (the ParallelReplicas
job), there at the time ranges insert.

Pin both fixture inserts to `enable_parallel_replicas = 0`. The empty-data
queries keep running through parallel replicas, and the unfixed server still
dies on the test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ClickHouse#117344 switched the samples inner table to the bucketed schema of version 11
(id, samples, bucket, min_time, max_time), so the fixture's
`INSERT INTO FUNCTION timeSeriesSamples(ts) SELECT id, timestamp, value ...`
fails on current master with NUMBER_OF_COLUMNS_DOESNT_MATCH (source: 3 and
result: 5). Insert the samples through the TimeSeries table instead, which
works with every samples layout. The reference is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master e720b7367

Suite Baseline Current Delta
Prometheus compliance 100.00% 100.00% +0.00%
Extended support (upstream engine tests) 93.17% 93.17% +0.00%
Suite Passed Failed Unsupported
Prometheus compliance 539 -> 539 (+0) 0 -> 0 (+0) 0 -> 0 (+0)
Extended support (upstream engine tests) 682 -> 682 (+0) 16 -> 16 (+0) 34 -> 34 (+0)

Extended support (upstream engine tests): native-histogram exclusions: 149; excluded assertions: 248; upstream 3da2514eff5c.

Note: Prometheus compliance score is unchanged vs baseline.

Uploaded compliance JSON for this PR commit

@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Nov 7, 2026
@alexey-milovidov alexey-milovidov self-assigned this Nov 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 7, 2026
Merged via the queue into ClickHouse:master with commit 326029b Nov 7, 2026
182 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... manual approve Manual approve required to run CI pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants