Skip to content

Fix time series table accessors on parallel replicas - #118518

Closed
vitlibar wants to merge 9 commits into
ClickHouse:masterfrom
vitlibar:fix-time-series-table-accessors
Closed

vitlibar wants to merge 9 commits into
ClickHouse:masterfrom
vitlibar:fix-time-series-table-accessors

Conversation

@vitlibar

@vitlibar vitlibar commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Experimental Feature

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

Fix time series table accessors: SELECT * FROM timeSeriesSamples(ts) now works on parallel replicas.

Fixes #118130


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

@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d75feb2]

Summary: ✅


AI Review

Summary

This PR fixes the analyzer and serialized-plan path for timeSeries* accessors by qualifying table-function arguments with the database name and by propagating the coordinated parallel-replica flag through ReadFromTableFunctionStep. The direction is correct, but I do not think the change is merge-ready yet: the legacy enable_analyzer = 0 execution path is still broken, and even on the analyzer path the replica liveness probe still uses the initiator's resolved hidden inner-table name.

Findings

❌ Blockers

  • [src/Planner/PlannerJoinTree.cpp:2695-2703, src/Processors/QueryPlan/ReadFromRemote.cpp:1202-1203, src/Client/ConnectionEstablisher.cpp:108-119] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/118518#discussion_r3948372858] The shipped query text is now qualified correctly, but the parallel-replica coordinator still identifies the remote read by storage->getStorageID(). For timeSeriesTags / timeSeriesSamples / timeSeriesMetrics that is the initiator's resolved hidden target table, and hidden inner-table names are still derived from the outer table UUID (src/Storages/TimeSeries/createTimeSeriesInnerTable.cpp:72-77) filled from the local catalog (src/Interpreters/Context.cpp:8194-8208). On Atomic replicas created separately, valid replicas will still be dropped during TablesStatusRequest with UNKNOWN_TABLE before the qualified accessor call has a chance to resolve locally. The fix needs to stop probing replicas by the initiator's hidden target name and instead track the outer TimeSeries table or otherwise resolve the target per replica.
  • [src/Storages/StorageMergeTree.cpp:355-359, src/Storages/StorageReplicatedMergeTree.cpp:6280-6283, src/Interpreters/ClusterProxy/executeQuery.cpp:1277-1282, src/Interpreters/ClusterProxy/SelectStreamFactory.cpp:77-82] The PR still does not fix the legacy enable_analyzer = 0 path that the title/body claim to fix. When the analyzer is off, MergeTree and ReplicatedMergeTree still enter the old executeQueryWithParallelReplicas(query_info.query, ...) overload, which rewrites the query as a plain remote_database.remote_table and never rebuilds a qualified timeSeries* / timeSeriesSelector / prometheusQuery* table-function call. SELECT ... FROM timeSeriesSamples(ts) still resolves against the wrong current database on replicas, and the JOIN-right-side cases from the new test stay broken there. Either reject these accessors when enable_analyzer = 0 or implement the equivalent rewrite in the legacy text path.
Tests
  • ⚠️ tests/queries/0_stateless/05104_time_series_table_functions_parallel_replicas.sql:10-13 pins enable_analyzer = 1 and never enables serialize_query_plan, while this PR also changes createRemotePlanForParallelReplicas, ReadFromTableFunctionStep, resolveStorages, and the query-plan serialization version. serialize_query_plan still defaults to false (src/Core/Settings.cpp:6981-6983), so please add one focused serialize_query_plan = 1 subcase that proves timeSeriesTags / timeSeriesSamples still return each row once, and once the legacy path is fixed add one enable_analyzer = 0 case so this regression does not come back.
Final Verdict

Changes requested. The analyzer-side fix looks directionally right, but the PR still leaves one real deployment topology broken and one still-supported execution path unfixed.

LLVM Coverage Report

Measured on commit d75feb2.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 129/146 (88.36%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Sep 7, 2026
@vitlibar vitlibar added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Sep 7, 2026
@vitlibar
vitlibar force-pushed the fix-time-series-table-accessors branch from 90ee134 to f197d8a Compare September 7, 2026 09:01
@vitlibar vitlibar changed the title Fix time series table accessors Fix time series table accessors on parallel replicas Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d75feb214 with master fe1a91eac (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 129e4b59b; 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.

Object file sizes

62 object files changed (+107.75 KiB total), 0 added.

Object file Master PR Δ
src/TableFunctions/CMakeFiles/clickhouse_table_functions.dir/TableFunctionPrometheusQuery.cpp.o 71.09 KiB 87.57 KiB +16.48 KiB (+23.18%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@vitlibar
vitlibar force-pushed the fix-time-series-table-accessors branch from f197d8a to 6465f7b Compare September 7, 2026 11:57
@vitlibar
vitlibar force-pushed the fix-time-series-table-accessors branch from 983a9c8 to 2546e64 Compare September 7, 2026 16:06
-- See https://github.com/ClickHouse/ClickHouse/issues/118130

SET allow_experimental_time_series_table = 1;
SET enable_analyzer = 1;

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.

This regression test still leaves the new serialize_query_plan = 1 path uncovered. serialize_query_plan defaults to false (src/Core/Settings.cpp:6977), so the assertions here only exercise the text-query path, while this PR also changes createRemotePlanForParallelReplicas / ReadFromTableFunctionStep / resolveStorages and bumps the query-plan serialization version for the coordinated table-function read.

Please add one focused subcase with serialize_query_plan = 1 (and force a remote replica if needed) that checks timeSeriesTags / timeSeriesSamples still return each row once; otherwise the newly added shipped-plan path can regress without this test noticing.

@vitlibar
vitlibar force-pushed the fix-time-series-table-accessors branch from e0ef726 to 0bac2b2 Compare September 7, 2026 22:19
/// database on a receiving server, so a resolved table function qualifies its arguments with the database name
/// (like `TableNode` always qualifies the table name with the database name).
if (table_function)
table_function->qualifyArgumentsWithDatabase(arguments_ast->children);

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.

This only fixes the analyzer QueryTree -> AST path. The legacy enable_analyzer = 0 parallel-replica path that these TimeSeries accessors still support remains broken, so the PR does not actually close issue #118130 for old-analyzer sessions.

StorageMergeTree::read / StorageReplicatedMergeTree::readParallelReplicasImpl still pass query_info.query into executeQueryWithParallelReplicas when the analyzer is off (src/Storages/StorageMergeTree.cpp:355-359, src/Storages/StorageReplicatedMergeTree.cpp:6360-6368). That overload goes through rewriteSelectQuery(..., nullptr) (src/Interpreters/ClusterProxy/executeQuery.cpp:1277-1278), and the legacy branch there does not rebuild a qualified table-function call: it just replaces the first table expression with remote_database.remote_table (src/Interpreters/ClusterProxy/SelectStreamFactory.cpp:77-82, src/Parsers/ASTSelectQuery.cpp:485-503). So timeSeriesTags / timeSeriesSamples / timeSeriesMetrics, and the right-hand timeSeriesSelector / prometheusQuery* JOIN cases, are still wrong unless enable_analyzer = 1.

Please either mirror the qualification/rewrite in the non-analyzer path or reject these table functions there, and add a regression case without forcing enable_analyzer = 1.


SELECT '-- one-argument form';
SELECT metric_name FROM timeSeriesTags(ts) ORDER BY metric_name;
SELECT value FROM timeSeriesSamples(ts) ORDER BY value;

@vitlibar vitlibar Sep 8, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This test shows the two issues this PR solves:

  • SELECT value FROM timeSeriesSamples(ts) didn't work on parallel replica because timeSeriesSamples(ts) means resolving table ts in the current database and parallel replica didn't know what the current database is and used the "default" database. This issue was solved by adding a new function ITableFunction::qualifyArgumentsWithDatabase and overriding it for classes TableFunctionTimeSeriesTarget, TableFunctionTimeSeriesSelector, TableFunctionTimeSeriesPrometheusQuery.


SELECT '-- every row is returned once';
SELECT count() FROM (SELECT * FROM timeSeriesTags(currentDatabase(), ts)) SETTINGS optimize_trivial_count_query = 0;
SELECT count() FROM (SELECT * FROM timeSeriesSamples(currentDatabase(), ts)) SETTINGS optimize_trivial_count_query = 0;

@vitlibar vitlibar Sep 8, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The second issue was here:

  • even with explicit database with parallel replicas timeSeriesSamples(currentDatabase(), ts) didn't work well because it could return each row twice. This was fixed by changing the Planner - since function timeSeriesSamples(ts) just returns a storage of another table, now the Planner considers TableFunctionNode in addition to TableNode (see buildQueryPlanForParallelReplicas for example)

@vitlibar

vitlibar commented Sep 8, 2026 •

Copy link
Copy Markdown
Member Author

The code was written mostly by Claude, I read it, but it's not a part of our code base which I know really well, so @nickitat please take a look carefully

@vitlibar
vitlibar force-pushed the fix-time-series-table-accessors branch from 0bac2b2 to d75feb2 Compare September 9, 2026 07:55
@nickitat

Copy link
Copy Markdown
Member

I'm trying a bit different implementation locally. Will keep you updated.

@vitlibar
vitlibar marked this pull request as draft September 16, 2026 14:08
Bartok9 pushed a commit to Bartok9/ClickHouse that referenced this pull request Oct 4, 2026
`Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel)` runs on every PR since
ClickHouse#122853, and five TimeSeries tests fail there on unrelated PRs (CIDB, that job, since 2026-09-29,
147 runs): 05213 51, 05218 26, 05237 10, 05059 6, 04838 4.

Both failure classes are the open defects of the TimeSeries table functions on parallel replicas:
- the argument of `timeSeriesSamples` / `timeSeriesMetricFamilies` is sent to the replicas as it was
  written, and a parallel-replica connection carries no default database, so a replica looks the
  table up in `default` (`UNKNOWN_TABLE`; 05213, 05218, 05237). With the default
  `parallel_replicas_local_plan = 1` this is a race, which is why it is intermittent;
- no replica announces its parts to the coordinator, so every replica reads the whole inner table
  and each row of `timeSeriesTags` comes back once per replica (05059, 04838, which already pass
  the database explicitly).

Same change as 0bc5beb made for 05057: the `no-parallel-replicas` tag plus one line naming
the defect. The engine fix is ClickHouse#118518, which should
drop these tags when it lands.

Related: ClickHouse#118130

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot closed this Oct 8, 2026
syoshida20 pushed a commit to syoshida20/ClickHouse that referenced this pull request Nov 1, 2026
`SELECT * FROM timeSeriesSamples(ts)` was wrong with parallel replicas in two
independent ways, and this fixes both without adding anything specific to the
`TimeSeries` engine beyond one small interface.

The name did not resolve. The `QueryTree -> AST` conversion qualifies a table
name with its database, so a forwarded query is self-contained - but the
arguments of a table function are shipped as written, so the replicas resolved
`ts` against their own current database. Rather than teach each table function
to qualify its own arguments, the initiator now sends its current database to
the replicas as the `database` setting. It was previously stripped by
`stripInitiatorOnlySettings`, for a reason that belongs to the `Distributed`
fan-out: `rewriteSelectQuery` can leave the remote table unqualified there, so a
shard must use its own default database. Parallel replicas have no such
remapping - every replica holds the same tables - so the setting is put back
after the strip. This covers every table function that takes an unqualified
table name, not just the `TimeSeries` accessors, and it works whichever analyzer
plans the query.

Every row came back once per replica. The parallel-replicas planner recognises
only a `TableNode` as the table a distributed read is anchored to, so a read
through a table function left the followers with no chosen table: each disabled
parallel replicas for its own read and scanned everything. A table function that
is nothing but a stable reference to an existing table can anchor the read just
like the table itself, because every replica resolves the call locally - so
`ITableFunction::getReferencedTableID` names that property, `TableFunctionTimeSeriesTarget`
implements it, and the planner is widened from `TableNode` to `ITableExpressionNode`.
Gating on the property rather than on "the resolved storage looks like a
`MergeTree`" keeps a table function that builds a storage of its own from ever
becoming an anchor.

The id it returns is the outer `db.ts`, not the hidden inner table the call
resolves to. That matters for `RemoteQueryExecutor::main_table`, which every
replica is asked about before it joins the read: an inner table is named after a
UUID the initiator assigned, so it is not a name another replica can be asked
about, while `db.ts` is.

`serialize_query_plan = 1` ships no plan for such a read.
`createRemotePlanForParallelReplicas` can only mark a `ReadFromTableStep` as the
coordinated read, and marking a `ReadFromTableFunctionStep` instead would need a
new query-plan serialization version, which excludes every older replica from
plan-based parallel replicas. It now returns null when it cannot mark the read,
and the caller sends the query text, which the replicas plan themselves. This is
also safer than before for the pre-existing view-over-`UNION` case, which used to
ship a plan with no read marked at all.

Thirteen tests gain an `is_initial_query` guard on their `system.query_log`
filter. They used `current_database = currentDatabase()` to mean "my query",
which only worked because a secondary query was attributed to `default`; now
that a replica runs it in the database the query was written against, the filter
has to say so.

Closes: ClickHouse#118130
Related: ClickHouse#118518

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01HqTzo2T96TYt2BUpK1mHuK
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TimeSeries table functions are broken with parallel replicas: UNKNOWN_TABLE on the replicas and duplicated rows

3 participants