Repository navigation
Fix DeltaLake partitioned writes corrupting path-like partition values and rejecting NULL - #111793
Conversation
…s and rejecting NULL Partition values containing path characters were corrupted on partitioned INSERT (allow_experimental_delta_lake_writes=1): 'a/b' was committed and read back as 'a', '%' produced a data file that could not be read back, and NULL failed with NOT_IMPLEMENTED. DeltaLakePartitionedSink built the Hive directory from raw partition values (so '/' became a path separator and '%' was written literally) and recovered partitionValues by parsing that directory back, which cannot round-trip a value containing '/' or '='. The committed add.path was the raw relative path, but the reader resolves it through a single unescapeForFileName, so a literal '%' decoded to a different, non-existent path. Now each partition value is serialized with toString (nulls preserved), percent-encoded into a single Hive path segment using the Delta/Hive escape set (so '-', space and non-ASCII stay unescaped, matching other Delta engines), and stored in partitionValues as its true value. A null or empty-string value is written as __HIVE_DEFAULT_PARTITION__ with a JSON null partitionValues entry, and a real NULL is kept distinct from the literal string __HIVE_DEFAULT_PARTITION__. add.path is URI-encoded (Hadoop/Delta encode set) so it is a valid URI whose single unescapeForFileName recovers the on-disk path. A null-equivalent value for a non-nullable partition column (per the authoritative Delta write schema) is rejected up front. The partitionValues map value type is now Nullable(String). Closes: ClickHouse#111758 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-5:20260724-110900 |
Internal second-model review (click to expand)An independent model reviewed this change across several rounds. All actionable findings were fixed; the one remaining item is a verification-ask that a stateless test cannot structurally satisfy. ❌ Blockers
💡 Nits
|
|
cc @PedroTadim (you asked me to fix this) @hanfei1991 — this fixes the partitioned DeltaLake write corruption from #111758: partition values are Hive/URI-encoded into a single path segment, the true value is committed in partitionValues (not reverse-parsed from the path), and NULL/empty become HIVE_DEFAULT_PARTITION with a JSON null. Verified round-trip in ClickHouse and cross-read by delta-rs. |
|
Workflow [PR], commit [5ff40d9] Summary: ✅
AI ReviewSummaryThis PR fixes Final VerdictStatus: ✅ Approve |
|
@hanfei1991 @kssenii this ended up being too large for me to review |
There was a problem hiding this comment.
@groeneai, what about Unicode characters and non-UTF-8 ones? Is that going to work?
There was a problem hiding this comment.
Unicode (valid UTF-8) works and round-trips both ways. escapeForFileName / the Hive escape set only escape a fixed ASCII set plus control bytes; every byte >= 0x80 is left as-is, so the physical directory keeps the readable UTF-8 name and add.path URI-encodes the same bytes, which the reader recovers with a single unescapeForFileName. partitionValues stores the true value. Verified café, 日本語, 🚀, a/münchen round-trip under both the kernel reader and the legacy reader; added a Unicode case to the test.
Raw non-UTF-8 bytes do not, and cannot: the Delta _delta_log is JSON, and a non-UTF-8 partition value has no JSON representation. The write currently succeeds but the read then fails with Encountered non-UTF-8 data (DELTA_KERNEL_ERROR) rather than corrupting silently. delta-rs has the same limitation. This is a pre-existing protocol constraint, not something this PR introduces, so I left it out of scope here. If you want, I can add a fail-fast check on the write side so an invalid-UTF-8 partition value is rejected at INSERT time instead of surfacing as a read error later.
Still I am going to try |
Internal second-model review (Gate B) adjudication for the legacy-reader follow-up (click to expand)Reviewed the pushed change (
|
The kernel writer commits a null-equivalent partition value as a JSON null in partitionValues. The legacy (non-kernel) reader parsed every partition value as a String, so a table written with a null partition became unreadable under allow_experimental_delta_kernel_rs = 0 (Poco::InvalidAccessException). Both legacy parsing branches now read a JSON/Map null back as a NULL Field. Also extends the regression test with a Unicode round-trip, a legacy-reader null-partition read, and an assertion that the committed partitionValues entry for a null-equivalent value is exactly a JSON null.
5b56564 to
7abd4a9
Compare
The committed_paths / committed_partition_values helpers piped the add.path listing through a bare `sort`, which orders by the runtime locale's collation. The reference was captured in byte order (C locale: '%' 0x25 < 'a' < 'c'), but CI runners use a UTF-8 locale whose glibc collation orders punctuation after letters, so the 3-value Unicode block was emitted as a/münchen, café, 日本語 instead of the byte-sorted 日本語, a/münchen, café -> deterministic FAIL. Pin both helpers to LC_ALL=C sort so the listing is byte-ordered regardless of the runner locale. The other committed-paths blocks are already locale-stable, so only the Unicode block was affected and the reference is unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
@PedroTadim I need your input on the amd CI abort before pushing anything. The new test I have not been able to reproduce it, and no coredump is uploaded, so I have no stack. What I tried, all producing the correct
The reader parses Two questions:
I would rather not push a speculative guard I cannot back with a repro. Holding for your guidance. |
|
@ PedroTadim thanks for the two pushes. Your I had built your intermediate head The interesting part is why the abort was amd-only and never reproducible for me. I took your head and changed only the sort direction, to emulate a listing that arrives out of version order: That reproduces the abort exactly, first try: So the mechanism is: That explains every axis I had been unable to match: the ordering depends on the local filesystem's directory iteration order, so my fleet host happened to enumerate ascending while the CI amd hosts did not, and it was stable per host. It also explains why arm passed and amd failed rather than looking like a race, and why the CI binary running in the CI container on my host still passed. Your fix is at the right layer and covers the general correctness problem, not just this test. One note on the null handling, so the reasoning is on the record: the branch you removed in If you would prefer the extraction to be branch-free, Nothing further is needed from me on this PR unless you want that cleanup or something else changed. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 137/150 (91.33%) · Uncovered code |
CI finish ledger — 5ff40d9Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260727-170000 |
There was a problem hiding this comment.
@groeneai is it safe from a performance point of view to call std::sort here? What if there are many keys?
There was a problem hiding this comment.
Safe, by about three orders of magnitude, and I measured it rather than reasoning about it.
What is being sorted. keys is the list of _delta_log/*.json commit files, so N is the number of commits in the log, not rows and not data files. It runs once per metadata construction, never inside the per-file loop below it (DeltaLakeMetadata does not override IDataLakeMetadata::supportsUpdate(), so DataLakeConfiguration::update rebuilds the whole thing, DataLakeConfiguration.h:113-118).
Measured on an amd debug build, warm cache, local FS, best of 5: synthetic tables with N commit files, SELECT count() FROM deltaLakeLocal(...) with allow_experimental_delta_kernel_rs = 0, minus the ~96 ms clickhouse-local startup.
| commits | metadata pass | std::sort |
sort share |
|---|---|---|---|
| 200 | 231 ms | 0.015 ms | 0.006% |
| 2 000 | 759 ms | 0.22 ms | 0.03% |
| 20 000 | 2 512 ms | 3.2 ms | 0.13% |
At N = 20 000 one key costs 0.16 us to sort and 97 us to read and parse (marginal cost measured between 2 000 and 20 000). The sort is also cheaper than the listing that produced the vector: on the same directories, directory_iterator + stat + suffix filter is 9.6 ms against 2.9 ms for the sort.
Pessimistic extrapolation (shuffled input, 400-byte keys): 82 ms at 200 000 commits, 1.4 s at 2 000 000. Reading those 2 000 000 JSON files sequentially in the loop below is ~195 s at the measured marginal rate, so the sort stays under 1% of the pass at any N. If the listing already arrives ordered it is ~3x cheaper again (84-byte keys, 2 000 000: 235 ms sorted input vs 709 ms shuffled).
N is bounded in practice. This branch only runs when there is no checkpoint (the else of if (checkpoint_version)). With a checkpoint the other branch walks versions forward from it, so N is bounded by the checkpoint interval. A table that reaches a large N here is one that never checkpointed, and its cost is the N sequential JSON reads, not the ordering of their names.
On dropping it: it is load-bearing. On your head I changed only the comparator to std::greater<String>() and reproduced the amd-only rc134 abort this test used to hit, first try and deterministically: Logical error: 'No such column in schema: part (schema: number Int32)', because the add action was replayed before the metaData that establishes the schema. Detail in #111793 (comment).
If you want the already-ordered case to cost literally nothing I can add an is_sorted early-out, but it buys ~0.1% of a pass that is I/O bound.
… can run 26.3's KeyDescription::getKeyFromAST takes no `virtuals` argument (#102827 is not on 26.3), so drop the `{}` the cherry-pick carried. The test built its Delta tables with INSERT INTO FUNCTION deltaLakeLocal under allow_delta_lake_writes. On 26.3 that setting is still called allow_experimental_delta_lake_writes, and a partitioned INSERT of a NULL value fails with NOT_IMPLEMENTED (#111793 is not on 26.3). Write the same tables by hand instead, as 26.3's 05237 test does: Parquet data files through file() and one add action per file, a NULL partition value committed as a JSON null under __HIVE_DEFAULT_PARTITION__. Two cases fail on 26.3 with and without this change, so they are dropped: `ifNull(p, 0) IN (0)` prunes the NULL partition (a MergeTree table partitioned by the same Nullable column returns the same wrong rows on 26.3), and `has([NULL, 'a'], s)` throws CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN (#115647 is not on 26.3). On 26.3 the fix keeps the NULL partition's file for `has([5, 7], p)`, so that case prunes 1 file instead of 2 (rows unchanged): 26.3 builds no set index for a UInt8 array over a Nullable(Int64) key; 26.3's MergeTree partition pruning does not use that predicate on a Nullable key either. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #111758
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed DeltaLake partitioned
INSERT(allow_experimental_delta_lake_writes=1) corrupting partition values that contain path characters and rejectingNULL. A value likea/bwas silently committed asa,%produced a data file that could not be read back, and aNULLpartition value failed withNOT_IMPLEMENTED. Partition values are now percent-encoded into a single path segment, the true value is stored inpartitionValuesinstead of being parsed back out of the path, and aNULL(or empty-string) partition value is written as__HIVE_DEFAULT_PARTITION__with a nullpartitionValuesentry.Description
Report: partitioned writes to a Delta table mangled several valid partition values (found by fuzzing, confirmed with both
DeltaLakeLocalandDeltaLakeover S3).Root cause, all on the write side (
DeltaLakePartitionedSink):/became a path separator (a/b->part=a/b/...) and%was written literally.onFinish()recoveredpartitionValuesby parsing that directory back, which cannot round-trip a value containing/or=.add.pathwas the raw relative path, but the reader resolves it through a singleunescapeForFileName, so a literal%was decoded into a different, non-existent path.NULLreachedgetDataAton aNullablecolumn and threwNOT_IMPLEMENTED.Fix:
toString(nulls preserved) and keep the true per-column value.col=escapeForFileName(value), and represent a null-equivalent value (SQLNULLor empty string, per the Delta protocol) as__HIVE_DEFAULT_PARTITION__.partitionValuesfrom the true value (a JSON null for null-equivalent values); thepartitionValuesmap value type is nowNullable(String).add.pathone extra level so the reader's singleunescapeForFileNamereproduces the exact on-disk path.NULLand the literal string__HIVE_DEFAULT_PARTITION__stay distinct.The kernel reader already reads these values back correctly. During review the legacy (non-kernel) reader (
DeltaLakeMetadata.cpp, used withallow_experimental_delta_kernel_rs = 0) was found to assume every partition value is aString, so the new JSON-nullpartitionValuesentry made a table with a null partition unreadable there. Both legacy parsing branches (JSON log and checkpoint) now read a JSON/Map null back as aNULLvalue, keeping the fallback reader working.Output verified to round-trip in ClickHouse (both readers) and to be read back identically by delta-rs for
/,%, space,=, Unicode,NULL, empty string,Int/Datepartition columns, and multi-column partitions.