Part 8 · Data layout · Chapter 27
Liquid clustering
Clustering without partitions and without full rewrites: the Clustered Table feature and its domain metadata, the clusteringProvider field, ZCubes, and how Delta's incremental OPTIMIZE picks unclustered files and small ZCubes, packs them into bins and Hilbert-clusters each bin.
After this chapter you should be able to:
- Explain what the Clustered Table feature requires of writers, and what clusteringProvider is for.
- Trace which files an incremental OPTIMIZE picks, and how it groups them into new ZCubes.
- Predict what changing clustering columns and OPTIMIZE FULL do to existing files.
- Compare the rewrite cost and skipping of liquid clustering with partitioning plus Z-order.
Chapter 25 ended with two limits of partitioning: it only suits a few low-cardinality columns, and the choice is fixed once data is written. Chapter 26 ended with the limit of Z-order: every OPTIMIZE ZORDER BY rewrites every file of the partitions it touches. Liquid clustering removes both. A table names up to four clustering columns, which can change at any time. OPTIMIZE then clusters only what is new or poorly clustered, and leaves well-clustered data alone.
The protocol part is small: where the columns are stored, and a field that says which implementation clustered a file. The rest is the algorithm in Delta’s ClusteringStrategy and ZCube, which src/sim/layout/liquid.ts ports. The tests replay Delta’s own IncrementalZCubeClusteringSuite.[Delta IncrementalZCubeClusteringSuite]
The clustered table feature
A table is clustered when its protocol lists the clustering writer feature. That feature needs domainMetadata too, and writer version 7. It can be enabled at creation or later, “provided the table does not have partition columns”.[PROTOCOL.md: Clustered Table] The writer requirements are:[PROTOCOL.md: writer requirements]
-
Columns in a domain. The clustering columns live in a
domainMetadataaction (chapter 12) whose domain isdelta.clustering. Itsconfigurationis a JSON string. Each column is a name path, so a nested column is["user", "address", "city"], and physical names are used under column mapping:{"domainMetadata": { "domain": "delta.clustering", "configuration": "{\"clusteringColumns\":[[\"event_time\"],[\"user_id\"]]}", "removed": false}} -
Statistics. Writers must write per-file stats for the clustering columns. “If a new column is included in the clustering columns list, it is required for all table files to have statistics for these added columns.” Delta checks this with
validateClusteringColumnsInStatsSchema, so a column beyond the first 32 needsdelta.dataSkippingStatsColumns(chapter 26).[Delta ClusteredTableUtils] -
clusteringProvider. When an implementation clusters files, it sets its name in theaddaction’sclusteringProviderfield. Delta’s name is"liquid".[Delta ClusteredTableUtils.clusteringProvider] “By default, a clustering implementation must only recluster files that have the fieldclusteringProviderset to the name of the same clustering implementation”, or of one it supersedes. It may also cluster files with no provider, which are unclustered files. -
No moment is required. “Writer is not required to cluster a specific file at any specific moment.” Clustering is a property a table works towards, not an invariant on every commit.
-
Not partitioned. “Writers must not define clustered and partitioned table at the same time.”
Delta’s implementation also limits the number of clustering columns to 4 (clusteredTable.numClusteringColumnsLimit).[Delta DeltaSQLConf] The provider field is what lets two engines share a table. Each one reclusters its own files and new ones, and never rewrites another engine’s layout behind its back.
Q1. Where does a Delta table record its clustering columns?
Q2. A file's add action has clusteringProvider: "acme-sort". What may Delta's liquid implementation do with it by default?
Q3. What does the protocol require when a new column is added to the clustering columns?
What a write does
In open-source Delta at this commit, a plain INSERT into a clustered table writes ordinary files. The only code that sets clusteringProvider is ClusteringStrategy.tagAddFile, which runs inside OPTIMIZE.[Delta ClusteringStrategy] New files have no provider and no ZCube tags, and their min/max boxes are as wide as the batch they came from. Data skipping still works on them, just badly. Clustering them is deferred to the next OPTIMIZE, which the protocol’s “not required … at any specific moment” allows.
Q1. In open-source Delta at the pinned commit, what does a plain INSERT into a clustered table write?
ZCubes
A ZCube is the set of files that one bin of one OPTIMIZE run produced. The name comes from Z-order, which uses the same tags. Every output file carries two add action tags:[Delta AddFile.Tags][Delta ZCubeInfo]
ZCUBE_ID: a fresh UUID per bin.ZCubeInfo.applycallsUUID.randomUUID.ZCUBE_ZORDER_BY: the JSON list of columns the bin was clustered on.
{"add": {"path": "part-0042.parquet", "size": 1073741824, "dataChange": false,
"stats": "{\"numRecords\":...,\"minValues\":{...},\"maxValues\":{...}}",
"tags": {"ZCUBE_ID": "6f1c...", "ZCUBE_ZORDER_BY": "[\"event_time\",\"user_id\"]"},
"clusteringProvider": "liquid"}}
The files of one ZCube were cut from one curve over the same rows, so together they tile the ZCube’s data into compact boxes. Two ZCubes are clustered independently: each one spans the whole key space, with its own tiling. That is the trade liquid clustering makes. A table is a handful of large, well-clustered ZCubes plus some new, unclustered files, and not one global curve.
Q1. What is a ZCube?
Incremental OPTIMIZE
OPTIMIZE on a clustered table takes no ZORDER BY and no WHERE; both are rejected.[Delta OptimizeTableCommand] It uses ClusteringStrategy, whose curve is "hilbert". As for Z-order, filterCandidateFileList keeps every file of the snapshot. The selection happens in prepareFilesPerPartition, in this order:[Delta ClusteringStrategy][Delta applyMinZCube]
// ClusteringStrategy (trimmed)
override val curve = "hilbert"
override val maxBinSize = max(TARGET_CUBE_SIZE, MIN_CUBE_SIZE)
override def prepareFilesPerPartition(files: Seq[AddFile]) =
applyMinZCube(files.sortBy(_.tag(ZCUBE_ID))) // None (unclustered) sorts first
private def applyMinZCube(files: Seq[AddFile]) = {
val (candidates, skipped) = files.partition { f =>
f.clusteringProvider.forall(_ == "liquid") &&
!ZCubeInfo.getForFile(f).exists(_.zOrderBy != clusteringColumns) }
val small = ZCube.filterOutLargeZCubes(candidates, MIN_CUBE_SIZE)
if (isFull && skipped.nonEmpty) small ++ skipped
else ZCube.filterOutSingleZCubes(small)
}
- Group the active files Collect unclustered files and group clustered files by ZCube ID.
- Unclustered or small cubes Keep compatible files and discard a candidate set that is already a single cube.
- Rewrite each bin Order by the Hilbert curve and write a new ZCube.
- Large enough cubes Leave cubes at or above the size threshold in place.
- Different clustering Incremental OPTIMIZE leaves foreign providers and old clustering columns alone.
- Sort by ZCube id. Unclustered files come first, then the files of each ZCube together.
- Split off foreign files. A file clustered by another provider, or on other clustering columns, goes to
skipped. filterOutLargeZCubes. Walk the sorted files, sum each ZCube’s size, and drop every ZCube whose total is at leastminCubeSize. Unclustered files always stay.[Delta ZCube] The default threshold is 100 ×optimize.maxFileSize, so 100 GiB. Its doc reads: “Z-cube size at which new data will no longer be merged with it during incremental OPTIMIZE”.[Delta DeltaSQLConf: cube sizes]filterOutSingleZCubes. If what is left is a single ZCube and no unclustered file, drop it too. Reclustering one ZCube by itself would produce the same layout.- Bin.
groupFilesIntoBinswalks the prepared files in order and starts a new bin when the next file would push it pastmaxBinSize: the larger oftargetCubeSize, 150 GiB by default, andminCubeSize. For clustering every bin is kept, even a bin of one file.[Delta groupFilesIntoBins] - Cluster each bin.
runOptimizeBatchcomputesapproxNumFiles = max(1, totalSize / maxFileSize)and callsMultiDimClustering.cluster(input, approxNumFiles, clusteringColumns, "hilbert").[Delta runOptimizeBatch] With two or more columns that is the Hilbert index over range ids, from chapter 26. With one column it falls back toZOrderClustering, which for one column is a sort by range id.[Delta MultiDimClustering] - Tag.
initNewBincreates a newZCubeInfoper bin, andtagAddFilewrites its tags plusclusteringProvider = "liquid"on every output file.
Because unclustered files sort first, they always land in the first bins, together with the partial ZCubes that follow them. A small ZCube keeps absorbing new data run after run until it crosses minCubeSize. After that it is never touched again by a plain OPTIMIZE. The cost of a run is therefore proportional to new data plus at most one partial ZCube’s worth, not to the table.
The commit is an ordinary transaction (chapter 10). It removes the files it read and adds the new ones with dataChange: false. An append that commits meanwhile only adds files, so both succeed, and its files are picked up next time.
Q1. Which files does OPTIMIZE pick on a clustered table, without FULL? (Select all.) (select all that apply)
Q2. A clustered table has one small ZCube and no unclustered files. What does OPTIMIZE rewrite?
Q3. How many files does one clustering bin of 3.5 GiB produce with the default maxFileSize of 1 GiB?
Q4. Which curve does liquid clustering use, and what happens with one clustering column?
Replaying Delta’s test
IncrementalZCubeClusteringSuite runs this scenario with maxRecordsPerFile = 2. liquid.test.ts replays it with sizes in rows:
| Step | Files before | OPTIMIZE removes | Adds | ZCubes after |
|---|---|---|---|---|
| 4 unclustered files | 4 | 4 | 2 | 1 |
again, huge minCubeSize | 2 | 0 (single ZCube) | 0 | 1 |
append 4 files, minCubeSize = 1 | 6 | 4 (the old ZCube is “large”) | 2 | 2 |
again, huge minCubeSize | 4 | 4 (both ZCubes partial) | 4 | 1 |
Changing clustering columns
ALTER TABLE t CLUSTER BY (b) writes a new delta.clustering domain, and that is all it does. Existing files keep ZCUBE_ZORDER_BY = ["a"]. The next OPTIMIZE puts them in skipped and clusters only new files on b. The old layout stays in place, and still serves queries on a.
OPTIMIZE t FULL is the way to move old data to the new columns. It is only allowed on a clustered table with clustering columns.[Delta OptimizeTableCommand] In applyMinZCube it adds skipped back to the selection. At this commit, ZCubes already on the current columns still go through filterOutLargeZCubes, so FULL reclusters foreign and unclustered files and small ZCubes, and leaves large up-to-date ZCubes alone.
Q1. You run ALTER TABLE t CLUSTER BY (b) on a table clustered by (a). What happens to the existing files?
Liquid versus partitioning and Z-order
The test liquid rewrites only the new data appends 512 rows a day for eight days, with maxFileSize 64 rows and minCubeSize 1,024 rows. After each append it runs OPTIMIZE on a liquid table, and OPTIMIZE ZORDER BY (x, y) on a copy. The box query x 100–250 AND y 600–750 gives:
| After day | Liquid rows rewritten (total) | ZCubes | Files read | Z-order rows rewritten (total) | Files read |
|---|---|---|---|---|---|
| 1 | 512 | 1 | 2 | 512 | 3 |
| 4 | 3,072 | 2 | 7 | 5,120 | 7 |
| 8 | 6,144 | 4 | 15 | 18,432 | 9 |
Z-order’s cost grows with the square of the number of days, because day n rewrites n days of data. Liquid’s cost grows linearly, because each run rewrites one day plus at most one partial ZCube. The price is skipping: with four ZCubes the query reads some files in each, 15 against Z-order’s 9. With no clustering it would read all 32 files. At Delta’s default sizes a ZCube holds 100 to 150 GiB, so a 10 TB table has about a hundred of them, each tiled into about a hundred 1 GiB files.
Against partitioning, the gains are flexibility and file sizes. There is no directory per value, so a high-cardinality key does not produce small files, and keys can change without a rewrite. What is lost is the hard guarantee: a partition filter is exact and free, while clustering skips only as well as the file boxes allow.
Iceberg has no clustering feature in its table spec. Its closest concept is the sort order, a list of sort fields with transforms, declared per data file. “Writers should use this default sort order to sort the data on write, but are not required to if the default order is prohibitively expensive”.[Iceberg spec: sorting] Multi-column layouts such as Z-order are done by maintenance jobs, outside the spec.
Q1. Compared with daily OPTIMIZE ZORDER BY, what does incremental liquid OPTIMIZE trade? (Select all.) (select all that apply)
Try it
The lab runs the chapter’s code at a small scale. Each rectangle is a file’s [min, max] box, colored by ZCube; dashed grey boxes are unclustered. Things to try:
- Append three times, then OPTIMIZE. One ZCube appears. Append again and OPTIMIZE: the first ZCube (1,536 rows, above
minCubeSize) is left alone and the new rows form a second one. - OPTIMIZE twice in a row. The second run does nothing.
- Switch to
CLUSTER BY (y), append, and OPTIMIZE: the new ZCube is a stack of horizontal bands, and the old ones are untouched. Then OPTIMIZE FULL. - Compare the comparison table’s rewritten rows after six or eight days.
- Click a file to see the
addaction with its tags andclusteringProvider.
| rows rewritten | 0 |
| files read for the query | 0 |
Scaled down: maxFileSize is 64 rows, minCubeSize 1,024 and targetCubeSize 1,536 (Delta: 1 GiB, 100 GiB, 150 GiB). Click a file to see its add action. Dashed grey boxes are unclustered files.
Summary
- A clustered table has the
clusteringwriter feature (withdomainMetadata, writer version 7) and no partition columns. Its columns are name paths in thedelta.clusteringdomain, and every file needs stats for them. clusteringProvidernames the implementation that clustered a file. By default an implementation reclusters only its own files and unclustered ones. Delta’s name is"liquid", and it is set only by OPTIMIZE.- A ZCube is the set of files from one OPTIMIZE bin, tagged with
ZCUBE_IDandZCUBE_ZORDER_BY. - Incremental OPTIMIZE takes unclustered files and ZCubes below
minCubeSize(100 GiB), skips a lone ZCube, packs files greedily into bins of up to 150 GiB, and Hilbert-clusters each bin into size / 1 GiB files. - Changing clustering columns rewrites nothing. OPTIMIZE FULL brings in files on old columns or from other providers.
- Compared with daily Z-order, rewrite cost grows with new data instead of table size, and skipping is per ZCube.
Concepts in this chapter
Explained here
Primary sources
Review this chapter
This chapter has 11 quiz questions.