Skip to content

Fix icebergBucket for timestamp_ns values before 1970 - #125351

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-125330-iceberg-bucket-timestamp-ns-floor
Oct 16, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-125330-iceberg-bucket-timestamp-ns-floor

Conversation

@groeneai

@groeneai groeneai commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

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 into CHANGELOG.md):

Fixed icebergBucket and icebergHash for DateTime64(9) values (Iceberg timestamp_ns and timestamptz_ns) before 1970 that have a sub-microsecond part: nanoseconds are now floored to microseconds as the Iceberg spec requires, so partition pruning no longer skips the files that hold such rows, and INSERT writes them into the same bucket as other engines. Closes #125330.

Description

On 26.8.18.2 (and 26.3.42.3), icebergBucket(16, toDateTime64('1969-12-31 23:59:59.999999999', 9, 'UTC')) returns 12 instead of the spec's 8, so on a timestamp_ns Iceberg table partitioned by bucket[N] and written by another engine, WHERE ts = <such a value> returns no rows with the default use_iceberg_partition_pruning = 1.

Root cause: icebergHash converted nanoseconds to microseconds with value / 1000, which rounds toward zero. The spec hashes microsecsFromUnixEpoch(v), and Java Iceberg computes it with Math.floorDiv(nanos, 1000) (DateTimeUtil.nanosToMicros). For a value before 1970 with a sub-microsecond part the two differ by one microsecond, so the hash and the bucket differ. Manifest pruning, the INSERT partitioner and DROP PARTITION all call the function, so the conversion is floored at that one site, with the floorDivide helper the temporal transforms already use (#119579), now shared in src/Functions/icebergCommon.h.

Validation: the new test pins the values Java Iceberg 1.10 returns (cross-checked with an independent Murmur3 implementation) and fails on master. On the Java-written table from #125329, an equality filter on each row now returns the same rows with pruning on and off (4 of 9 rows were lost on master), and an INSERT of 1969-12-31 23:59:59.999999999 writes bucket 8 instead of 12.

#125329 skips bucket pruning for 1969 values in 05369 because of this issue; the skip can be dropped once both are merged.

Data that ClickHouse already keyed by the old value stays there: an equality filter on exactly such a value now skips Iceberg rows that a ClickHouse INSERT put in the old bucket (other engines already did), and likewise MergeTree parts whose PARTITION BY or ORDER BY applies icebergBucket or icebergHash to such values.


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

Version info

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

icebergHash converted a DateTime64(9) value to microseconds with integer
division, which rounds toward zero. The Iceberg spec hashes
microsecsFromUnixEpoch, and Java Iceberg computes it with
DateTimeUtil.nanosToMicros = Math.floorDiv(nanos, 1000). For a value before
1970 with a sub-microsecond part the two differ by one microsecond, so
icebergBucket returned a different bucket than other engines: Iceberg
partition pruning skipped the data file that holds the row (the query
returned no rows), and INSERT wrote such rows into a non-spec bucket.

All bucket consumers (manifest pruning, ChunkPartitioner, DROP PARTITION)
call the function, so the conversion is fixed at that single site. The
temporal transforms already floor (b79c31a).

ClickHouse#125330

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 12, 2026
@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; 0 findings) plus my own cold review (3 nits).

# Sev Finding Verdict Evidence / action
1 💡 The scale-9 floor division duplicates floorDivide from icebergDateTransforms.cpp AGREE, not blocking one expression in two files; I can move it to a shared header if preferred
2 💡 The compatibility note omitted MergeTree keys built on icebergBucket/icebergHash AGREE, fixed description now names them (KeyCondition pushes the constant through deterministic key functions)
3 💡 No pruning on/off equivalence line in the committed test DISAGREE a ClickHouse-written table buckets with the same function before and after the fix, so that line passes on master; the spec-written fixture is in #125329

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

Session id: cron:clickhouse-review-slot-8:20261012-083800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. icebergBucket(16, toDateTime64('1969-12-31 23:59:59.999999999', 9, 'UTC')) returns 12 on master (and on 26.3.42.3, 26.8.18.2); the spec and Java Iceberg 1.10 give 8.
b Root cause explained? icebergHash converted ns to us with truncating division; the spec floors (Math.floorDiv(nanos, 1000)). For a pre-1970 value with a sub-microsecond part the hashed long is one microsecond too large, so pruning, the partitioner and DROP PARTITION all disagree with spec writers.
c Fix matches root cause? Yes. The conversion is floored where the wrong value is made; no consumer-side adjustment.
d Test intent preserved / new tests added? New SQL test: Java/oracle-pinned bucket values plus a 10000-value sweep over both signs and every sub-microsecond remainder. No existing test changed.
e Both directions demonstrated? Yes. Master prints 12 8 8 12 0 4995, the fix prints the reference 8 5 8 8 1 0; 50 randomized + 50 non-randomized runs pass. On #125329's Java-written table, pruning on/off now agrees for every row (4 of 9 rows were lost on master).
f Fix is general across code paths? Yes. This is the only ns-to-us conversion in the hash; every bucket consumer calls the function; the temporal transforms already floor (#119579).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Const, materialized, Nullable, NULL, timestamptz_ns time zones and the Int64 minimum and maximum checked against the oracle; scale 6 and non-negative values unchanged. LowCardinality(DateTime64) cannot be created.
h Backward compatible? (maintainer-approved exception only) The output changes only for pre-1970 DateTime64(9) values with sub-microsecond digits, where the old value disagreed with every other engine. Such rows already written by a ClickHouse INSERT stay in the old bucket (noted in the description).
i Invariants and contracts preserved? Yes. Same result type and size, still deterministic, no new error path.

Session id: cron:clickhouse-impl-slot-4:20261012-081900

@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [314d186]

Summary: ✅


AI Review

Summary

The PR fixes icebergHash and icebergBucket for negative nanosecond timestamps by flooring to microseconds, consistent with Java Iceberg, and shares floorDivide with the temporal transforms. The correction is sound, but the previously reported wrong-answer risk for existing persisted keys remains unresolved at 314d1868c93dbfdacc6412556c45509f7f716966.

Findings

❌ Blockers

  • src/Functions/icebergBucketTransform.cpp:160: Changing the hash must preserve access to data keyed by the old result. For 1969-12-31 23:59:59.999999999, the previous implementation hashes microsecond 0 and selects bucket 12 with 16 buckets; this implementation hashes -1 and selects bucket 8. Files previously written by ClickHouse remain in bucket 12, while ManifestFilesPruner constructs its KeyCondition using bucket 8 and rejects those files under the default partition pruning. Persisted MergeTree partition/primary keys using either function have the same mismatch. There is no hash version, migration, or compatibility control. Preserve legacy semantics for existing stored SQL keys and provide an explicit migration path; Iceberg pruning must conservatively include affected legacy buckets. This is the existing unresolved finding; no duplicate inline comment was posted.
Tests
  • ⚠️ The scalar regression 05370_iceberg_bucket_timestamp_ns_before_1970 passes in head CI, but does not exercise existing persisted keys. Add focused upgrade coverage using data keyed by the previous hash: an equality predicate must retain the row with Iceberg pruning enabled, and with a MergeTree key containing the transform, before and after migration.
Final Verdict

❌ Block. Provide compatibility/migration handling for previously stored hash values and regression coverage proving existing rows remain queryable.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 12, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Oct 12, 2026
{
value_int = value_int / 1000;
}
value_int = value_int / 1000 - (value_int % 1000 < 0 ? 1 : 0);

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 fixes future timestamp_ns hashing, but it also changes the partition/key value that ClickHouse computes for already-written pre-1970 DateTime64(9) values with sub-microsecond digits. The PR description already calls out the consequence: after upgrade, exact predicates on those values prune to the new spec bucket and silently miss rows that older ClickHouse builds wrote into the old bucket with the default use_iceberg_partition_pruning = 1; the same compatibility break applies to MergeTree keys built on icebergBucket / icebergHash.

That is a wrong-answer risk on existing data, not just a forward fix. Please add a migration/compatibility path before flipping the default semantics here — for example by probing both the old and corrected bucket for the affected domain, or by gating the new hash behind a setting plus a documented rewrite procedure for existing data.

@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 314d1868c93dbfdacc6412556c45509f7f716966 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception; stopped retrying after the 1250 s read budget).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f668011

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_binary, ParallelReplicas, s3 storage, parallel) / 05210_lightweight_update_materialized_cte_in_ignore flaky, not from this PR (it only changes the Iceberg bucket hash of DateTime64(9)): Code: 60 ... Unknown table expression identifier '_materialized_cte_c_...' with parallel replicas, 1 of 128 reruns failed; it failed on 155 other PRs and 27 master commits in the last 7 days #123121 (mine, open)
Performance Comparison (arm_release, master_head, 6/6) / join_nullable_keys_small_table #4, #8 not from this PR (no JOIN executes the changed function): the candidate was about 27% and 23% slower, with the same slow timings on 2 other unrelated PRs within 27 minutes against the same reference build a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the rows above #123121 (mine, open); a fix task is created for the performance row

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261012-180013

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison (arm_release, master_head, 6/6) join_nullable_keys_small_table row: #125542

@PedroTadim PedroTadim self-assigned this Oct 15, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai 🕵️ src/Functions/icebergDateTransforms.cpp already has floorDivide(Int64, Int64), added in #119579 for the temporal transforms, in an anonymous namespace. Could it move to a small shared header next to these functions, so that this line becomes value_int = floorDivide(value_int, 1000);? Then every Iceberg transform that turns nanoseconds into a coarser unit uses one floor rule. A future fix of that rule, or a new transform, can't miss one of the copies, and the expression no longer needs a comment.

Move floorDivide from the anonymous namespace of icebergDateTransforms.cpp
to src/Functions/icebergCommon.h and use it for the nanoseconds to
microseconds conversion in icebergHash, so every Iceberg transform that
converts to a coarser time unit uses the same floor rule.

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

Copy link
Copy Markdown
Collaborator Author

Done in 314d186: floorDivide now lives in src/Functions/icebergCommon.h, icebergDateTransforms.cpp includes it instead of its local copy, and the timestamp_ns line is value_int = floorDivide(value_int, 1000); without the comment. icebergYear/Month/Day/Hour return the same values as master on pre-1970 inputs, and 05370 passes, as does 05369 from #125329 with its bucket skip removed.

@PedroTadim
PedroTadim added this pull request to the merge queue Oct 16, 2026
Merged via the queue into ClickHouse:master with commit 3db971e Oct 16, 2026
178 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 16, 2026
@clickhouse-gh clickhouse-gh Bot added comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... and removed comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default 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.

Iceberg bucket transform truncates timestamp_ns toward zero: partition pruning silently drops pre-1970 rows

3 participants