Skip to content

Fix alias error in distributed calls, simplification for nanoseconds in Iceberg - #2749

Merged
mkmkme merged 23 commits into
antalya-26.6from
bugfix/antalya-26.6/remote-initiator-join-alias
Nov 3, 2026
Merged

mkmkme merged 23 commits into
antalya-26.6from
bugfix/antalya-26.6/remote-initiator-join-alias

Conversation

@ianton-ru

Copy link
Copy Markdown

Solved #2748
Solved #2747

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix alias error in distributed calls, simplification for nanoseconds in Iceberg

Documentation entry for user-facing changes

Solved #2748 - restore alias in distributed query (changes in src/Storages/IStorageCluster.cpp)
Solved #2747 - changes in #2239 for nanoseconds were overcomplicated, and broke work for microseconds. Partially reverted.

CI/CD Options

Exclude tests:

  • Fast test
  • Integration Tests
  • Stateless tests
  • Stateful tests
  • Unit tests
  • Performance tests
  • Aarch64 tests
  • All with ASAN
  • All with TSAN
  • All with MSAN
  • All with UBSAN
  • All with Coverage
  • All Regression
  • Disable CI Cache

Regression jobs to run:

  • Fast suites (mostly <1h)
  • Aggregate Functions (2h)
  • Alter (1.5h)
  • Benchmark (30m)
  • CAS (content-addressed storage; Antalya only)
  • ClickHouse Keeper (1h)
  • Iceberg (2h)
  • LDAP (1h)
  • OAuth (5m)
  • Parquet (1.5h)
  • RBAC (1.5h)
  • SSL Server (1h)
  • S3 (2h)
  • S3 Export (2h)
  • Swarms (30m)
  • Tiered Storage (2h)

ianton-ru and others added 4 commits October 30, 2026 16:13
`JoinedTables` only reads the outer table function, so an old-analyzer global JOIN failed with "No alias for subquery or table function in JOIN". The inner alias stays for the query sent to the remote initiator.

https: //github.com//issues/2748
Co-authored-by: Cursor <[email protected]>
…conds

Scale-6 bounds in the normal range were dropped, so min/max pruning skipped every `timestamp` file. Values above `1e18` are still converted from nanoseconds, and `(1e16, 1e18]` still fails open.

https: //github.com//issues/2747
Co-authored-by: Cursor <[email protected]>
Appendix D already sets the unit from the field type. `DateTime64(6)` stays microseconds and `DateTime64(9)` stays nanoseconds.

https: //github.com//issues/2747
Co-authored-by: Cursor <[email protected]>
The decoder reads bounds at the type scale. A `timestamp` column whose bounds are nanoseconds is corrupt data, so those tests are not required.

Co-authored-by: Cursor <[email protected]>
@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Workflow [PR], commit [7b40736]

@ianton-ru
ianton-ru marked this pull request as ready for review October 30, 2026 18:37
@mkmkme

mkmkme commented Oct 31, 2026

Copy link
Copy Markdown
Collaborator

@blau-ai

@blau-ai

blau-ai commented Oct 31, 2026

Copy link
Copy Markdown
Collaborator

CI triage for a24fa31

4 red checks. None look caused by this PR: 1 pre-existing test failure, 2 known upstream crashes in aggregation code, 1 stress-harness timeout.

Everything that touches this PR passed: builds, unit tests (including the rewritten gtest_iceberg_field_parse_helpers), all integration shards, and the Iceberg and Swarms regression suites.

Check Failure Verdict
Stateless (amd_asan_ubsan, distributed plan, parallel, 2/2) 05387_s3_cluster_remote_initiator_keeps_stripped_join Pre-existing on antalya-26.6
Stateless (amd_binary, cas s3 storage, parallel) Server died: GroupingAggregatedTransform pushed bucket 4 twice Known upstream crash, not related to this PR
Stateless (amd_asan_ubsan, cas s3 storage, parallel, 1/2) Server died: GroupingAggregatedTransform pushed bucket 3 twice Same as above
Stress test (amd_debug, cas s3 storage) Test script failed, script exit code: 1 Infra: the stress harness timed out

1. 05387_s3_cluster_remote_initiator_keeps_stripped_join (pre-existing)

The CI report's randomized-settings diagnosis:

Runs: 25, Failed: 25 (same randomized settings)
Runs: 34, Failed: 0  (without randomization)
Culprit settings: --prefer_localhost_replica 0

The old (old analyzer) half passes. The analyzer half (query 7) fails on the remote initiator:

Code: 499. DB::Exception: Received from localhost:9000. ... Failed to get object info: No response body.. HTTP response code: 403.
Please check your AWS credentials and permissions: while reading '05387_test_xafu307b.tsv' in bucket 'test' on disk 'StorageS3': While executing Remote. (S3_ERROR)
  ... StorageObjectStorageStableTaskDistributor::getMatchingFileFromIterator <- TaskDistributor <- RemoteQueryExecutor::processReadTaskRequest

Why it's not this PR: #2713 is an unrelated backport (Nullable ALTER) at 5284d10. The same test fails there in the same suite, with the same 403 and the same culprit setting (Runs: 26, Failed: 26 → Culprit settings: --prefer_localhost_replica 0). This PR doesn't touch the test.

What to do: this PR works on the remote-initiator path, so you may want to deal with it here, though it doesn't block the PR. The 403 comes from the read-task callback on the remote initiator, so with prefer_localhost_replica = 0 the S3 credentials apparently don't reach the key iterator there. I haven't confirmed that. Options:

  • Real fix: find out why the credentials are lost on the analyzer path when the hop goes over TCP rather than local, probably a separate issue.
  • Stop-gap: pin prefer_localhost_replica = 1 in the test's SETTINGS, with a comment linking the issue, so the suite stops failing on every PR.

2. GroupingAggregatedTransform pushed bucket N twice (known upstream crash)

The server aborted on a logical error in both CAS-S3 stateless jobs:

Logical error: 'GroupingAggregatedTransform pushed bucket 4 twice'.
src/Processors/Transforms/MergingAggregatedMemoryEfficientTransform.cpp:63:15: DB::GroupingAggregatedTransform::pushData(...)
src/Processors/Transforms/MergingAggregatedMemoryEfficientTransform.cpp:123:9: DB::GroupingAggregatedTransform::tryPushTwoLevelData()

What to do: safe to re-run.

3. Stress test (amd_debug, cas s3 storage) (infra/harness)

Every server-health result was OK (Server successfully started, No lost s3 keys, No SharedMergeTree lost forever), and fatal.log is empty. The only failure is the pre-stress sanity run of 00001_select_1 and 00234_… in --replicated-database mode. Both tests passed in about 18s, but the whole clickhouse-test call overran its 180s wrapper timeout:

[2 / 2] 00001_select_1: [ OK ] 1.76 sec.   2 tests passed ... 17.98 s elapsed
subprocess.TimeoutExpired: Command '/usr/bin/clickhouse-test --stress-tests --cas-s3-storage ... --replicated-database --database test_5 ...' timed out after 180 seconds

That's slow setup or teardown of the replicated database on CAS S3, not a server problem.

What to do: safe to re-run.


Sources: the CI report (result_pr.json) for a24fa31, plus those of #2713 (5284d10) and #2644 (97ac101) for comparison. No local build or test run; this is from CI evidence only.

…ry plan

With `serialize_query_plan=1` and `prefer_localhost_replica=0`, `ClusterProxy::SelectStreamFactory`
builds a local `QueryPlan` for each shard and sends it over the native protocol via
`ReadFromTableFunctionStep`. The table function AST was formatted with secrets hidden
(`show_secrets_=false`), so a function like `s3`/`s3Cluster` arrived on the executing
shard with its access key or secret replaced by the `[HIDDEN]` literal, which the shard
then used to sign requests, failing with `403 Forbidden`.

This AST only travels inside the cluster and is never shown to the user, so format it
with `formatWithSecretsOneLine` instead, matching the plain-SQL distributed query path
(`IStorageCluster::readFromRemoteInitiator`, `ClusterProxy::rewriteSelectQuery`).

Co-authored-by: Cursor <[email protected]>
@ianton-ru

Copy link
Copy Markdown
Author

Add potential fix for 05387_s3_cluster_remote_initiator_keeps_stripped_join

@ianton-ru

ianton-ru commented Nov 2, 2026 •

Copy link
Copy Markdown
Author

GroupingAggregatedTransform pushed bucket N twice - fix is in ClickHouse#116446, backport ClickHouse#120637 in 26.6.9, but antalya-26.6 is rebased only on 26.6.8 in #2481.

@alsugiliazova

alsugiliazova commented Nov 2, 2026 •

Copy link
Copy Markdown
Member

PR #2749 Audit Review

AI audit note: This review was generated by AI (Grok 4.7).

Verdict

One High, one Medium. No Low.

The alias is copied onto remote(), and the inner table function keeps it. JoinedTables reads the outer name, so the old-analyzer error in #2748 is gone. The query that #2748 actually runs still sends a plain INNER JOIN to a random replica. On cluster_simple that replica often does not have the right-hand table.

Iceberg timestamp (DateTime64(6)) and timestamp_ns (DateTime64(9)) are decoded at the type's own scale again. Spec-correct microsecond bounds prune. The same decoder treats nanosecond statistics on a timestamp column as microseconds, so #2240's count() goes back to 0. Commit e6200be still converted values above 1e18. Commit 7994754 removed that conversion, and the tests that locked the layout were deleted.

A serialized query plan now sends the table function with its credentials. The shard can sign an s3 request. EXPLAIN and formatForLogging still hide the key.

What the change does

Three independent edits.

Remote initiator alias. convertToRemote used to produce remote('host', icebergS3(...) AS t1). DatabaseAndTableWithAlias reads only the outer function (DatabaseAndTableWithAlias.cpp, the table_function arm), so JoinedTables::resolveTables threw No alias for subquery or table function in JOIN under joined_subquery_requires_alias. The outer remote() now gets the same alias. The inner function keeps it because ASTSelectQuery::addTableFunction copies an alias only when that alias is empty (ASTSelectQuery.cpp 501–502), so the node sent to the replica is icebergS3(...) AS t1.

Iceberg bounds. deserializeDateTime64FromBinaryRepr again returns the 8-byte little-endian integer at getDecimalScale(type). Scale 6 stays microseconds. Scale 9 stays nanoseconds. The magnitude test, the nanosecond-to-microsecond conversion, and the fail-open nullopt are gone.

Plan text for a table function. When serialize_query_plan is on, buildQueryPlanForTableExpression puts the table function into a ReadFromTableFunctionStep as one line of SQL. The shard parses that string in resolveStorages and builds the storage again. The formatter used to set show_secrets = false, so s3(...) arrived with the key replaced by [HIDDEN] and S3 answered 403. It now calls formatWithSecretsOneLine(), the same quoting (WhenNecessary, backticks, one line) with secrets left in. wipeSensitiveDataAndCutToLength runs with wiping off, and max_length = 0 does not truncate.

Findings

Silent wrong pruning

High: nanosecond min/max on an Iceberg timestamp column prunes every file, and the query returns no rows.

  • Impact. Partition pruning works incorrectly #2240 is ice.otel.logs.time_unix_nano DateTime64(6) with IcebergMinMaxIndexPrunedFiles = 28 and count() = 0. Turning use_iceberg_partition_pruning off returns 10837020. A 2026 nanosecond bound is about 1.76e18. Read as microseconds that is roughly year 58000, which sits entirely after <= 2026-08-11, so every data file is excluded. The parquet values are microseconds of 2026. The result is missing rows, with no error.
  • Anchor. deserializeDateTime64FromBinaryRepr (IcebergFieldParseHelpers.cpp 32–41). IcebergSchemaProcessor::getSimpleType maps timestamp to DateTime64(6) (SchemaProcessor.cpp 434–435). ManifestFileIterator builds the hyperrectangle from those fields and prunes when both bounds decode (ManifestFileIterator.cpp 528–541). After the mis-read, lower is still less than or equal to upper, so the mixed-scale skip on the next line does not fire.
  • Trigger. A manifest whose schema says timestamp and whose lower/upper bound bytes are nanoseconds. That is the layout the deleted helper patch_iceberg_timestamp_bounds_us_to_ns built, and the layout Fix iceberg partition pruning by nanoseconds #2239 was fixing. No clock skew and no mixed version required.
  • Why defect. On the base, |ticks| > 1e18 on scale 6 was divided by 1000 and the 2026 bound survived. This head keeps the raw integer. timestamp_ns is a different type and still works, because it is DateTime64(9). Deleting test_minmax_pruning_ns_bounds_on_timestamp_schema and check_minmax_ns_bounds_on_timestamp_schema removes the only lock on this layout. The new gtest NanosecondDateTime64BoundsAreKept uses scale 9.
  • Fix direction. For scale 6, divide by 1000 only when |ticks| > 1e18. Otherwise keep the integer. That is what commit e6200be did, before 7994754 replaced it with scale-only decoding. Put the deleted integration tests back.
  • Regression test direction. The deleted no-spark and spark tests that rewrite a timestamp manifest's bounds from microseconds to nanoseconds and expect the 2026 filter to keep the file.

Join is not global on the fallback path

Medium: old-analyzer object_storage_cluster_join_mode = 'global' still ships a plain INNER JOIN to a random replica.

  • Impact. The query in Remote initiator global JOIN without analyzer fails with 'No alias for subquery or table function in JOIN' after #2228 #2748 no longer dies on the alias check. convertToRemote then picks one replica of cluster_simple (getClusterImpl expands replicas to shards, then rng() % shard_count). The integration cluster is node1, node2, and node3 (tests/integration/test_storage_iceberg_with_spark/configs/config.d/cluster.xml). The Memory table is created only on node1. node2 and node3 answer that the table does not exist. A one-replica cluster succeeds.
  • Anchor. updateQueryWithJoinToSendIfNeeded, the GLOBAL arm (IStorageCluster.cpp 456–468): with no query tree it returns and leaves INNER/LEFT/CROSS in query_to_send. The fallback path (object_storage_remote_initiator_cluster set, no object_storage_cluster) never analyzes that AST on the Iceberg storage. rewriteASTForGlobalJoin runs only when the interpreter's storage is an IStorageCluster (InterpreterSelectQuery.cpp 795–801). On this path the left storage is remote() → StorageDistributed, so the locality stays local. ClusterProxy::rewriteSelectQuery replaces remote() with icebergS3(...) AS t1 and keeps the JOIN.
  • Trigger. The Remote initiator global JOIN without analyzer fails with 'No alias for subquery or table function in JOIN' after #2228 #2748 statement: old analyzer, object_storage_remote_initiator = 1, object_storage_cluster_join_mode = 'global', right-hand table local to one replica, initiator cluster with more than one replica.
  • Why defect. The new-analyzer arm rewrites the join to global and ships the right side. This arm does not. The comment above the return says the left scan is what gets shipped. The JOIN is still in the AST. The alias fix is what lets execution reach this send.
  • Fix direction. On the old-analyzer global path, run rewriteASTJoinsToGlobal before convertToRemote, including the fallback path. RIGHT/FULL can stay on the initiator, as they do today.
  • Regression test direction. Run test_remote_initiator_global_join_without_analyzer in a loop against cluster_simple. It should return 1, 1, 2 for every chosen replica, not only when the draw is node1.

What was checked and found clean

The alias reaches both places that read it. JoinedTables sees remote(...) AS t1. addTableFunction then clones the inner function, which still has alias t1, and the empty-alias branch does not clear it. QueryAliasesNoSubqueries does not walk into ASTTableExpression, so the two copies of t1 do not raise MULTIPLE_EXPRESSIONS_FOR_ALIAS. A query with no alias is unchanged. remoteSecure and the user/password constructor both set the alias after the remote() node is built.

Spec-correct bounds match Appendix D. timestamp / timestamptz are scale 6. timestamp_ns / timestamptz_ns are scale 9. A value of the wrong width still returns nullopt, and that column is left out of the hyperrectangle. The Spark 9999-12-31 sentinel (253402300799999999) is kept as microseconds. The remaining test test_minmax_pruning_far_future_us_upper_bound_on_timestamp_schema covers that. Negative microseconds are kept. The new gtests match those three cases.

The plan string uses the same quoting as the SQL path. ReadFromCluster already sends formatWithSecretsOneLine() (IStorageCluster.cpp 954), and executeQuery does the same when it builds the query text for a shard. FunctionSecretArgumentsFinder masks s3 keys again whenever the re-parsed AST is formatted for a log or an error. EXPLAIN does not print the string: ReadFromTableFunctionStep has no describeActions. The only reader of getSerializedAST() is resolveStorages. The comment in PlannerJoinTree.cpp names ClusterProxy::rewriteSelectQuery as a formatter. That function returns an AST. The SQL string is formatted at the two sites above.

05387_s3_cluster_remote_initiator_keeps_stripped_join uses object_storage_cluster_join_mode = 'allow', which strips the join before the wrap. With serialize_query_plan on, the shard now receives the real key instead of [HIDDEN].

Coverage

Area Result
Outer alias read by JoinedTables Reviewed. The #2748 error is fixed
Alias on the replica query Reviewed. It comes from the inner function, which this PR leaves in place
New-analyzer remote initiator Reviewed. The alias is taken from the query tree in buildQueryTreeDistributed, not from this setAlias
allow / local join mode Reviewed. The join is stripped before the wrap
Old-analyzer global on the fallback path Reviewed. Medium finding
Spec-correct timestamp and timestamp_ns bounds Reviewed. Pruning works again for #2747
Nanosecond bounds on timestamp Reviewed. High finding. #2240 returns
Plan text keeps S3 credentials Reviewed. The shard can sign the request. Logs and EXPLAIN still hide the key
Partition values Reviewed. reinterpretPartitionDateTime64 already uses the key scale. This PR does not change it
CI Not triaged

Deferred. The integration join test was not re-run here, so the 2-out-of-3 replica failure is from the code path. No test in the diff forces serialize_query_plan on an s3 function. The distributed-plan stateless job is the run that exercises that path.

Operational readiness

Persona. Operator querying Iceberg, and anyone running an old-analyzer global join through object_storage_remote_initiator.

1. A 2026 filter on time_unix_nano returns 0 rows

  • Symptom. count() is 0, IcebergMinMaxIndexPrunedFiles equals the file count, and the same query with use_iceberg_partition_pruning = 0 returns the rows (IcebergFieldParseHelpers.cpp:32, Partition pruning works incorrectly #2240).
  • Trigger. Iceberg type timestamp (DateTime64(6)) whose manifest bounds are nanoseconds.
  • Signal quality. Silent.
  • Severity. High.
  • Recovery. Turn pruning off for that query. The rows are still in the files.

2. Global join without the analyzer fails on some replicas

  • Symptom. UNKNOWN_TABLE for the right-hand table, from the replica named in remote('…').
  • Trigger. allow_experimental_analyzer = 0, object_storage_cluster_join_mode = 'global', object_storage_remote_initiator = 1, and more than one replica in the initiator cluster.
  • Signal quality. Clear on the replica that fails. Easy to misread as a missing table rather than a routing choice.
  • Severity. Medium.
  • Recovery. Use one replica in the initiator cluster, or create the right-hand table on every replica. The new analyzer global path already ships the right side.

Readiness verdict

Ordinary microsecond timestamp pruning is ready. Sending table-function credentials inside a serialized plan is ready. The #2240 layout is not, because of finding 1. The #2748 join is ready only when the initiator cluster has a single replica. On the three-replica integration cluster it is not ready, because of finding 2.

Do not merge this as the fix for both issues. #2747 is fixed. #2240 is reopened, and the tests that would catch it are gone.

Operator guidance

  • For OTEL-style DateTime64(6) columns whose stats are nanoseconds, set use_iceberg_partition_pruning = 0 until the conversion is restored. Check IcebergMinMaxIndexPrunedFiles before trusting a count() of 0.
  • For the old-analyzer global join, point object_storage_remote_initiator_cluster at a one-replica cluster, or create the right-hand table on every replica.

Recommended fixes

  1. For scale 6, keep the integer, and divide by 1000 only when |ticks| > 1e18. Restore the deleted nanosecond-bounds tests (finding 1).
  2. Call rewriteASTJoinsToGlobal on the old-analyzer global path before the remote wrap, and loop the Remote initiator global JOIN without analyzer fails with 'No alias for subquery or table function in JOIN' after #2228 #2748 test across every replica (finding 2).

`convertToRemote` sent the local table name to one replica, so a replica without that table returned `UNKNOWN_TABLE`. `RIGHT`, `FULL`, and `PASTE` still stay on the initiator.

Co-authored-by: Cursor <[email protected]>
@ianton-ru

Copy link
Copy Markdown
Author

Shit.
Back to #2240.
In that sample column time_unix_nano has lower and upper bounds in nanoseconds.
But Iceberg column has a type timestamp, converted to DateTime64(6), not timestamp_ns, which should be converted in DateTime64(9).
It means, that information about precision was lost in source Iceberg table. Only one hint about precision is a column name time_unix_nano.
So I tried to write some heuristic to interpret bounds as microseconds or as nanoseconds by value, 1e18 and greater is a nanosecond, less is a microsecond.
But it's a problem.
1e17 can be 1973 yeas in nanoseconds and 4870 yeas in microseconds, which is still valid data.
It can't be solved.

ianton-ru and others added 5 commits November 2, 2026 16:38
Bounds at or below `1e18` stay microseconds, so ordinary `timestamp` pruning still runs. The previous threshold dropped those bounds and skipped the column.

Co-authored-by: Cursor <[email protected]>
…1e18`

Bounds below `1e16` stay microseconds and bounds at or above `1e18` are nanoseconds. A file in the middle band is pruned only when the predicate misses both readings.

Co-authored-by: Cursor <[email protected]>
Optional fields are `Nullable(DateTime64)`, so the outer type check skipped both units between `1e16` and `1e18`.

Co-authored-by: Cursor <[email protected]>
…nd `1e18`

That band can be either unit, so the shortcut must read the file. Pruning and the shortcut share the same two thresholds.

Co-authored-by: Cursor <[email protected]>
The reader already loads these bounds as little-endian `long`s. `test_minmax_pruning` now checks Spark-written `timestamp` values with `unix_micros`.

Co-authored-by: Cursor <[email protected]>
@ianton-ru

Copy link
Copy Markdown
Author

Some compromise.
Bounds with values less than 1e16 are interpreted as microseconds.
Bound with values 1e18 and greater are interpreted as nanoseconds.
Values between are interpreted as both, file is not pruned when one of ranges is passed.

Size effect - cons column optimization does not work anymore for timestamp type in range 1e16-1e18, because it is not clean what precision is used for bounds.

@ianton-ru

Copy link
Copy Markdown
Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-02T18:18:44.398476Z 237fb0b Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 12930fc83b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines 63 to +66
if (scale == 6)
{
if (!magnitudeExceeds(unscaled, nanoseconds_lower_threshold))
return std::nullopt;

unscaled = nanosecondsToMicrosecondsForBound(unscaled, lower_bound);
if (!icebergTimestampMagnitudeBelow(unscaled, iceberg_timestamp_nanoseconds_lower_threshold))
unscaled = nanosecondsToMicrosecondsForBound(unscaled, lower_bound);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep near-epoch nanosecond bounds from becoming constants

When an Iceberg timestamp manifest contains the nanosecond statistics this compatibility code is intended to handle, dates close to the epoch have |ticks| < 1e18, so this branch now returns the raw nanosecond count as a microsecond value. For a file whose timestamp is constant, DataFileMetaInfo accepts that point range and StorageObjectStorageSource substitutes it without reading the Parquet column; for example, 86400000000000 ns (1970-01-02) is returned as a timestamp in 1972. These ambiguous bounds need to fail open rather than becoming a constant.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

86400000000000 is less than 1e16, must be interpreted as microsoconds only.
Test is fixed to avoid misunderstanding.

Comment on lines +246 to +249
const bool allow_microseconds = icebergTimestampMagnitudeBelow(*lower_ticks, iceberg_timestamp_nanoseconds_lower_threshold)
&& icebergTimestampMagnitudeBelow(*upper_ticks, iceberg_timestamp_nanoseconds_lower_threshold);
const bool allow_nanoseconds = !icebergTimestampMagnitudeBelow(*lower_ticks, iceberg_timestamp_microseconds_only_threshold)
&& !icebergTimestampMagnitudeBelow(*upper_ticks, iceberg_timestamp_microseconds_only_threshold);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve the nanosecond interpretation below 1e16

For timestamp-schema manifests carrying nanosecond statistics, valid near-epoch values can have both bounds below 1e16 (for example, 1970-01-02 is 8.64e13 ns). Here such a pair enables only the microsecond range, so the manifest pruner compares the predicate against a date years later and can discard a file containing matching rows. The removed near-epoch regression cases exercised exactly this scenario; pruning must fail open or retain the nanosecond interpretation for this band.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

It's an heuristic for already incorrectly written tables, where bounds in nanoseconds, when columns in microseconds.
For this tables pruning and constant column optimization must be turned off. ClickHouse can't detect and recognize this cases in 100%. If we though that any time less 1e16 can be nanoseconds, all normal tables with microseconds can't be pruned correctly.

`86400000000000` is `1972-09-27` as microseconds. The test locks that single range so it is not read as `1970-01-02` nanoseconds.

Co-authored-by: Cursor <[email protected]>
@ianton-ru

Copy link
Copy Markdown
Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 237fb0baaa

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@alsugiliazova

Copy link
Copy Markdown
Member

PR #2749 Audit Review

AI audit note: This review was generated by AI (Grok 4.7).

Field Value
PR Altinity/ClickHouse#2749 — Fix alias error in distributed calls, simplification for nanoseconds in Iceberg
Author ianton-ru
Base antalya-26.6
Head 237fb0baaaf7fcaf80d342b4efdc16e2e0e9257d
State at review Open
Scope reviewed Full diff at that head: old-analyzer global join broadcast (IStorageCluster), remote() alias copy, query-plan table-function serialization, Iceberg timestamp min/max decode and pruning, DateTime64 bound endianness
Method audit-review, static review at head. Nothing was built or run

Verdict

Three Medium findings, one Low. No High.

The remote() alias copy matches what JoinedTables reads. Sending the table-function AST with secrets matches the plain SQL distributed path. Spec-correct timestamp microseconds below 1e16, nanoseconds at or above 1e18, and the open band between them follow the rules in deserializeDateTime64MinMaxRanges. The broadcast path is the part that still returns the wrong rows or fails on inputs the new code accepts.

Confirmed defects

Old-analyzer global join

Medium: a join alias that matches a temporary table joins that table instead of the broadcast rows.

  • Impact: JOIN some_table AS t2 returns rows from the session temporary table t2. The join key still matches, so the query succeeds with the wrong right-hand side.
  • Anchor: broadcastOldAnalyzerGlobalJoin (src/Storages/IStorageCluster.cpp). The name comes from GlobalSubqueriesMatcher::Data::addExternalStorage (src/Interpreters/GlobalSubqueriesVisitor.cpp).
  • Trigger: Old analyzer, object_storage_cluster_join_mode = 'global', and a right-hand table whose alias is already a temporary or external table in the session. AS t2 is enough when CREATE TEMPORARY TABLE t2 ran earlier in the session.
  • Why defect: addExternalStorage uses the alias as the external table name and rewrites the AST to that identifier. The register loop then skips addExternalTable when tryResolveStorageID(..., ResolveExternal) finds the alias, and that lookup walks the session context. The holder just built is destroyed with the local map. The rewritten JOIN t2 reads the table that was already there.
if (!mutable_context->tryResolveStorageID(StorageID{"", name}, Context::ResolveExternal))
    mutable_context->addExternalTable(name, std::move(*holder));
  • Fix direction: Register the broadcast under _data_{hash} when the alias is already taken, and keep the alias only as the SQL alias of that new name.
  • Regression test direction: CREATE TEMPORARY TABLE t2 (...) with one row, then the old-analyzer global join AS t2 against a Memory table with a different row. The result must be the Memory row.

Medium: a table function on the right side fails with WRONG_GLOBAL_SUBQUERY.

  • Impact: The query errors. The previous global path sent that table function to the chosen replica, where s3() / iceberg() can run.

  • Anchor: broadcastOldAnalyzerGlobalJoin → GlobalSubqueriesMatcher::visit(ASTTablesInSelectQueryElement) → addExternalStorage (GlobalSubqueriesVisitor.cpp).

  • Trigger: Old analyzer, object_storage_cluster_join_mode = 'global', INNER / LEFT / CROSS, right side is a table function (JOIN s3(...) AS t2). A subquery right side (JOIN (SELECT * FROM s3(...))) still works.

  • Why defect: rewriteASTJoinsToGlobal marks the join GLOBAL, then the visitor calls addExternalStorage on the table expression. That function only accepts a table identifier or a subquery. A table function hits throw ... WRONG_GLOBAL_SUBQUERY, "Global subquery requires subquery or table name".

  • Fix direction: Leave a table-function right side in query_to_send, or wrap it in a subquery before addExternalStorage.

  • Regression test direction: Old analyzer, global mode, remote initiator, icebergS3(...) AS t1 JOIN s3(...) AS t2. The query should return the joined rows.

Medium: global join mode rewrites every local IN and runs it on the initiator.

  • Impact: WHERE col IN (SELECT ...) or IN some_table is evaluated on the node the client connected to, then broadcast. A table that exists only on the chosen replica now raises UNKNOWN_TABLE. A table that exists on both nodes contributes the initiator's rows.

  • Anchor: broadcastOldAnalyzerGlobalJoin calls rewriteASTForGlobalJoin → rewriteASTJoinsToGlobal → rewriteASTInFunctionsToGlobalIn (IStorageCluster.cpp). The visitor then calls addExternalStorage for the renamed globalIn.

  • Trigger: Old analyzer and object_storage_cluster_join_mode = 'global', including a query with no JOIN. Default mode is allow, so this is the global setting only. IN (subquery), IN table, and the same forms of notIn / nullIn / notNullIn are renamed. Nested selects are not walked into; the outer predicate still becomes GLOBAL.

  • Why defect: The call is unconditional on the old-analyzer global path. The new-analyzer branch rewrites IN only when has_local_columns_in_where. A local IN that the replica used to execute is now interpretSubquery on the initiator.

  • Fix direction: Rewrite IN only when its right side must be read on the initiator, the same gate the new-analyzer branch uses.

  • Regression test direction: Old analyzer, global mode, no join, WHERE id IN (SELECT id FROM memory_only_on_initiator) and a second case whose subquery table exists only on the other replica. The first returns the initiator's ids. The second should keep today's replica-side behavior, or fail with an error that names the table and the node.

Iceberg timestamp bounds

Low: min/max bounds that differ by exactly 1000 collapse into one constant timestamp.

  • Impact: With allow_experimental_iceberg_read_optimization left at its default (true), every row in the file gets one DateTime64 value and the Parquet column is not read. A file whose nanosecond bounds are 1e15 and 1e18 (1970-01-12 through 2001-09-09) is returned as the single microsecond instant 1e15.

  • Anchor: DataFileMetaInfo::DataFileMetaInfo (src/Storages/ObjectStorage/DataLakes/IDataLakeMetadata.cpp), using deserializeDateTime64FromBinaryRepr (IcebergFieldParseHelpers.cpp). The constant is applied in StorageObjectStorageSource when the hyperrectangle isPoint().

  • Trigger: Iceberg timestamp (DateTime64(6)) whose lower bound is in [1e15, 1e16) and whose upper bound is that lower bound times 1000 (so the upper bound is at or above 1e18). A remainder on the upper bound still collapses when rounding lands on the lower bound. isAmbiguousIcebergTimestampBound is false for both ends: the lower bound is below 1e16, and 1e18 is outside the half-open middle band.

  • Why defect: The two bounds are decoded independently. The lower bound stays a microsecond count. The upper bound is divided by 1000. Those results can be equal, so the shortcut stores a point. deserializeDateTime64MinMaxRanges refuses this pair (neither unit fits both ends) and does not prune the file, but the shortcut still replaces the column. Equal bounds in one unit stay a genuine point and are fine.

  • Fix direction: Build the constant from deserializeDateTime64MinMaxRanges. Substitute only when that function returns one point range.

  • Regression test direction: A one-file table with lower ticks 10^15 and upper ticks 10^18, Parquet values at both ends. SELECT DISTINCT ts must return both instants. The existing BoundsBelow1e16StayMicroseconds case stays a single microsecond point.

Coverage summary

Scope reviewed: the PR diff at 237fb0ba plus the callees it depends on (GlobalSubqueriesVisitor, StorageObjectStorageSource constant-column substitution, ReadFromTableFunctionStep, SelectStreamFactory::rewriteSelectQuery / ASTSelectQuery::addTableFunction).

Categories failed:

  • External-table registration when the join alias is already a temporary table
  • Table-function right side under old-analyzer global mode
  • Unconditional IN → GLOBAL IN on that same path
  • Constant-column shortcut for mixed bounds that meet after dividing by 1000

Categories passed:

  • remote() carries the inner table-function alias, and the inner alias stays so addTableFunction still sends it. That function copies an alias only when the existing alias is empty; leaving the alias on the inner node covers that.
  • formatWithSecretsOneLine on ReadFromTableFunctionStep matches IStorageCluster / ClusterProxy::rewriteSelectQuery. The step has no describe() override, so EXPLAIN does not print the AST. The bytes go to cluster peers over the native protocol.
  • RIGHT / FULL / PASTE still return through rewriteQueryForInitiatorLocalJoin and do not broadcast.
  • DateTime64(6) below 1e16 stays microseconds, including the constant shortcut. The new unit test locks 86400000000000 as 1972-09-27. Nanosecond stats in that band are read as microseconds. That is the rule this head encodes, not a second defect.
  • |ticks| >= 1e18 converts with nanosecondsToMicrosecondsForBound, which widens a bound instead of truncating it inward. INT64_MIN / INT64_MAX do not overflow that adjustment.
  • The middle band [1e16, 1e18) returns both ranges, and pruning drops the file only when every range misses. A pair that fits neither unit produces no range, and the column is not pruned.
  • Optional timestamp columns go through removeNullable before the scale check.
  • Little-endian DateTime64 bounds match unalignedLoadLittleEndian on the reader. On little-endian hosts this is the same byte pattern memcpy already wrote.
  • No new lock, shared container, or cross-thread lifetime. addExternalTable uses the existing context mutex on the query thread during planning.

Categories N/A:

  • Parallel-replica early return inside GlobalSubqueriesVisitor. parallel_replicas_only_with_analyzer defaults to true, so with the analyzer off canUseParallelReplicasOnInitiator() is false and that return does not run.
  • Version skew and auth changes, other than the secret-bearing plan payload above.

Assumptions/limits: static only. The integration test in test_remote_initiator.py was not run. GlobalSubqueriesVisitor.cpp is unchanged by the diff and was read at this head. The null prepared_sets fallback inside broadcastOldAnalyzerGlobalJoin builds a set that dies with the function; InterpreterSelectQuery::getSampleBlockImpl assigns query_info.prepared_sets before IStorageCluster::read, so the live path uses the interpreter's set.

ianton-ru and others added 4 commits November 2, 2026 21:35
A table function on the right is read through `interpretSubquery`. `IN some_table` runs on the initiator, and `IN (SELECT 1)` stays on the replica.

Co-authored-by: Cursor <[email protected]>
If either bound is below `1e16`, both stay microseconds. Otherwise a bound at or above `1e18` makes both nanoseconds.

Co-authored-by: Cursor <[email protected]>
The interpreter rewrites the same tree that is sent, so it must not turn every subquery into `globalIn`.

Co-authored-by: Cursor <[email protected]>
`deserializeDateTime64MinMaxRanges` already returns two ranges for the middle band.

Co-authored-by: Cursor <[email protected]>
@alsugiliazova

Copy link
Copy Markdown
Member

PR #2749 Audit Review

AI audit note: This review was generated by AI (Grok 4.7).

Field Value
PR Altinity/ClickHouse#2749 — Fix alias error in distributed calls, simplification for nanoseconds in Iceberg
Author ianton-ru
Base antalya-26.6
Head 31cd84fede27bef770c83c9d60c1a37c21563829
State at review Open
Scope reviewed Full diff at that head. The four commits after 237fb0ba are included: broadcast naming, one precision for a timestamp bound pair, IN rewritten only when its right side names a table, and removal of isAmbiguousIcebergTimestampBound
Method audit-review, static review at head. Nothing was built or run

Verdict

No confirmed defects in reviewed scope.

Confirmed defects

No confirmed defects in reviewed scope.

Coverage summary

Scope reviewed: the PR diff at 31cd84fe, plus interpretSubquery (table-function branch), GlobalSubqueriesMatcher::visit for IN, and the constant-column use of hyperrectangle in StorageObjectStorageSource.

Assumptions/limits: static only. The new cases in test_remote_initiator.py and gtest_iceberg_field_parse_helpers.cpp were not run. GlobalSubqueriesVisitor.cpp is now part of the diff and was read at this head.

@alsugiliazova

Copy link
Copy Markdown
Member

PR #2749 CI Verification

AI audit note: This review was generated by AI (Grok 4.7).

Field Value
PR Altinity/ClickHouse#2749 — Fix alias error in distributed calls, simplification for nanoseconds in Iceberg
Base antalya-26.6
Head 31cd84fede27bef770c83c9d60c1a37c21563829
Run 41526497806 attempt 1
Method pr-ci-failure-triage. Job logs and the CI report for this attempt. No gh-data.checks query: the database password was not available. In-job reruns, the stack, and the diff placed every failure.

Verdict

One failure is from this pull request. The other red jobs are not.

test_remote_initiator_global_join_without_analyzer[s3] dies before the new SQL runs. The nine joins just above it passed. The check shells clickhouse-client inside a container that only has /usr/bin/clickhouse.

Iceberg, Parquet, Swarms, OAuth, and S3 export regression jobs passed. A second attempt of this workflow was already in progress when this report was written. The verdict below is attempt 1 only.

Category Count Where
regression 1 test_storage_iceberg_with_spark/test_remote_initiator.py::test_remote_initiator_global_join_without_analyzer[s3]
pre-existing-flaky 2 02477_single_value_data_string_regression; GroupingAggregatedTransform pushed bucket 4 twice
infrastructure 1 Integration shard 1/8, session timeout 10800s
cascade 1 Server died in the CAS S3 stateless job, after the aggregation abort
unknown 0 —

How the list was reduced

Four GitHub jobs failed. The report lists five rows because the CAS job records both the logical error and Server died.

  1. Cascade. Server died is the harness reaction to the abort in GroupingAggregatedTransform::pushData. One row removed.
  2. No bulk rate query. The remaining rows were placed from the log, the in-job rerun, and whether the diff touches the failing code.
  3. Infrastructure. Integration shard 1/8 prints xdist.dsession.Interrupted: session-timeout: 10800.0 sec exceeded. That is pytest's clock, not a server abort. Exit code 2 here is that interrupt.
  4. Investigated. The remote-initiator test, 02477, and the aggregation abort.

regression

test_remote_initiator_global_join_without_analyzer[s3] in Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/8).

The nine instance.query() joins in the same test passed. The temporary-table check then ran clickhouse-client via exec_in_container and returned in 46ms:

exec: "clickhouse-client": executable file not found in $PATH (exit 126).

The SQL that check was written to run never reached the server. The test file is in this pull request. Change that call to the same client the passing queries use (instance.query(), or /usr/bin/clickhouse client).

pre-existing-flaky

02477_single_value_data_string_regression in Stateless tests (amd_asan_ubsan, distributed plan, parallel, 2/2).

The test expects server error 33 (CANNOT_READ_ALL_DATA) and got 241 (MEMORY_LIMIT_EXCEEDED). The same job reran it 16 times. All 16 passed. The diff does not touch aggregate-state parsing. The report marks the row flaky and also "new" against base 6b543544, which only means that one base run passed.

GroupingAggregatedTransform pushed bucket 4 twice in Stateless tests (amd_binary, cas s3 storage, parallel).

Release binary aborted with signal 6 in MergingAggregatedMemoryEfficientTransform.cpp:63 (GroupingAggregatedTransform::pushData). The query was INSERT INTO res SELECT x, sum(y) FROM d GROUP BY x with distributed_aggregation_memory_efficient = 1, group_by_two_level_threshold = 1, max_threads = 8. The harness then sent SIGTERM. Passed tests in the job: 3624. Failed tests: 0. This pull request does not change that file. The same abort is the upstream CI crash ClickHouse/ClickHouse#115986.

No 60-day fail rate was queried for either row.

infrastructure

Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/8) stopped at session-timeout: 10800.0 sec exceeded. The summary was 1 failed, 646 passed, 16 skipped, and the session was still running (3:02:14).

The one failure inside that session was test_filesystem_cache/test.py::test_concurrent_eviction[lru]: clickhouse benchmark hit SOCKET_TIMEOUT (code 209, 10s) under asan. The automatic retry passed in 35s. The job stays red because of the session timeout, not because that test stayed failed.

cascade

Server died in Stateless tests (amd_binary, cas s3 storage, parallel) is the same abort as the GroupingAggregatedTransform row. Classify that abort, not this label.

What passed that this pull request cares about

Regression jobs that were selected on the PR all passed: Iceberg (1) and (2), Parquet, Parquet S3 (minio and aws_s3), Swarms, OAuth, S3 export (partition and part). The other seven shards of Integration tests (amd_asan_ubsan, db disk, old analyzer) passed, including the shard that did not contain this test.

The integration container has no `clickhouse-client` on `PATH`.

Co-authored-by: Cursor <[email protected]>
@ianton-ru

ianton-ru commented Nov 3, 2026 •

Copy link
Copy Markdown
Author

@alsugiliazova
test_remote_initiator_global_join_without_analyzer[s3] it's a test issue, not a code issue.
Fix pushed, code does not required new audit, only test was changed.

ianton-ru and others added 4 commits November 3, 2026 14:59
`numbers(2).number + 1` is `UInt64`, while the Iceberg column is `Nullable(Int32)`. Compare `tag` so the old analyzer accepts the key.

Co-authored-by: Cursor <[email protected]>
… is chosen.

A choice of node1 executes in-process and writes no non-initial `query_log` row.

Co-authored-by: Cursor <[email protected]>
The replica receives `IN ((SELECT 1) AS _subqueryN)`, so the check looks for `(SELECT 1)`.

Co-authored-by: Cursor <[email protected]>
`QueryFinish` can still be queued when the first `SYSTEM FLUSH LOGS` returns.

Co-authored-by: Cursor <[email protected]>
@ianton-ru

Copy link
Copy Markdown
Author

Test issue again, fix in progress

`is_initial_query = 0` only sees the replica `DESCRIBE`. The `SELECT` is a different `query_id` and still contains `(SELECT 1)`.

Co-authored-by: Cursor <[email protected]>
@ianton-ru

Copy link
Copy Markdown
Author

Testa are passed

@mkmkme
mkmkme merged commit 2a8bb67 into antalya-26.6 Nov 3, 2026
278 of 281 checks passed
@mkmkme mkmkme added the verified Approved for release label Nov 3, 2026
@zvonand

zvonand commented Nov 4, 2026

Copy link
Copy Markdown
Member

@ianton-ru pls don't forget to add port-antalya label

@zvonand zvonand added the port-antalya PRs to be ported to all new Antalya releases label Nov 4, 2026
@ianton-ru

Copy link
Copy Markdown
Author

@zvonand port for 26.8 is on the way

@zvonand

zvonand commented Nov 4, 2026

Copy link
Copy Markdown
Member

@ianton-ru you will do the port manually?

@ianton-ru

Copy link
Copy Markdown
Author

@zvonand Yes, I will.

@ianton-ru

Copy link
Copy Markdown
Author

Port is in #2749

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

antalya antalya-26.6 antalya-26.6.8.20003 port-antalya PRs to be ported to all new Antalya releases verified Approved for release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants