≈ The Lake

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.

complete ~30 min

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]

  1. Columns in a domain. The clustering columns live in a domainMetadata action (chapter 12) whose domain is delta.clustering. Its configuration is 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}}
  2. 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 needs delta.dataSkippingStatsColumns (chapter 26).[Delta ClusteredTableUtils]

  3. clusteringProvider. When an implementation clusters files, it sets its name in the add action’s clusteringProvider field. Delta’s name is "liquid".[Delta ClusteredTableUtils.clusteringProvider] “By default, a clustering implementation must only recluster files that have the field clusteringProvider set 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.

  4. 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.

  5. 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.

Quiz Check: the featureAnswers are scheduled for spaced review on the Review page.

Q1. Where does a Delta table record its clustering columns?

How sure are you?

Q2. A file's add action has clusteringProvider: "acme-sort". What may Delta's liquid implementation do with it by default?

How sure are you?

Q3. What does the protocol require when a new column is added to the clustering columns?

How sure are you?

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.

Quiz Check: writesAnswers are scheduled for spaced review on the Review page.

Q1. In open-source Delta at the pinned commit, what does a plain INSERT into a clustered table write?

How sure are you?

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.apply calls UUID.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.

Quiz Check: ZCubesAnswers are scheduled for spaced review on the Review page.

Q1. What is a ZCube?

How sure are you?

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)
}
Which files enter incremental OPTIMIZE?
  1. Group the active files Collect unclustered files and group clustered files by ZCube ID.
Candidates
  1. Unclustered or small cubes Keep compatible files and discard a candidate set that is already a single cube.
  2. Rewrite each bin Order by the Hilbert curve and write a new ZCube.
Skipped
  1. Large enough cubes Leave cubes at or above the size threshold in place.
  2. Different clustering Incremental OPTIMIZE leaves foreign providers and old clustering columns alone.
A ZCube is selected as a group. Incremental OPTIMIZE focuses the rewrite on files it can improve together.[Delta clustering strategy]
  1. Sort by ZCube id. Unclustered files come first, then the files of each ZCube together.
  2. Split off foreign files. A file clustered by another provider, or on other clustering columns, goes to skipped.
  3. filterOutLargeZCubes. Walk the sorted files, sum each ZCube’s size, and drop every ZCube whose total is at least minCubeSize. 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]
  4. 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.
  5. Bin. groupFilesIntoBins walks the prepared files in order and starts a new bin when the next file would push it past maxBinSize: the larger of targetCubeSize, 150 GiB by default, and minCubeSize. For clustering every bin is kept, even a bin of one file.[Delta groupFilesIntoBins]
  6. Cluster each bin. runOptimizeBatch computes approxNumFiles = max(1, totalSize / maxFileSize) and calls MultiDimClustering.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 to ZOrderClustering, which for one column is a sort by range id.[Delta MultiDimClustering]
  7. Tag. initNewBin creates a new ZCubeInfo per bin, and tagAddFile writes its tags plus clusteringProvider = "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.

Quiz Check: incremental OPTIMIZEAnswers are scheduled for spaced review on the Review page.

Q1. Which files does OPTIMIZE pick on a clustered table, without FULL? (Select all.) (select all that apply)

How sure are you?

Q2. A clustered table has one small ZCube and no unclustered files. What does OPTIMIZE rewrite?

How sure are you?

Q3. How many files does one clustering bin of 3.5 GiB produce with the default maxFileSize of 1 GiB?

How sure are you?

Q4. Which curve does liquid clustering use, and what happens with one clustering column?

How sure are you?

Replaying Delta’s test

IncrementalZCubeClusteringSuite runs this scenario with maxRecordsPerFile = 2. liquid.test.ts replays it with sizes in rows:

StepFiles beforeOPTIMIZE removesAddsZCubes after
4 unclustered files4421
again, huge minCubeSize20 (single ZCube)01
append 4 files, minCubeSize = 164 (the old ZCube is “large”)22
again, huge minCubeSize44 (both ZCubes partial)41

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.

Quiz Check: changing keysAnswers are scheduled for spaced review on the Review page.

Q1. You run ALTER TABLE t CLUSTER BY (b) on a table clustered by (a). What happens to the existing files?

How sure are you?

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 dayLiquid rows rewritten (total)ZCubesFiles readZ-order rows rewritten (total)Files read
1512125123
43,072275,1207
86,14441518,4329

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.

Quiz Check: trade-offsAnswers are scheduled for spaced review on the Review page.

Q1. Compared with daily OPTIMIZE ZORDER BY, what does incremental liquid OPTIMIZE trade? (Select all.) (select all that apply)

How sure are you?

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 add action with its tags and clusteringProvider.
x →
0files (0 unclustered)
0ZCubes
0files read for the query
0rows rewritten by OPTIMIZE so far
Same appends, OPTIMIZE ZORDER BY (x, y) after each OPTIMIZE
rows rewritten0
files read for the query0

    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 clustering writer feature (with domainMetadata, writer version 7) and no partition columns. Its columns are name paths in the delta.clustering domain, and every file needs stats for them.
    • clusteringProvider names 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_ID and ZCUBE_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

    See how the book's concepts connect →

    Primary sources

    Review this chapter

    This chapter has 11 quiz questions.

    Review this chapter's cards → Review all due cards