crystal-click
crystal-click
crystal-click reads and writes ClickHouse MergeTree data parts from Crystal. Open a local ClickHouse Atomic catalog to inspect tables and parts, read typed column batches, and prune granules by primary key. Apply row filters and transformations in Crystal code. The library also writes standalone Wide and Compact parts and provides a small embedded MergeTree table.
Quick start
To build the examples, install Crystal >= 1.21.0, GNU Make, and a linkable system libzstd. Run the following write examples on macOS, where the exclusive atomic publisher uses renamex_np.
Clone the public repository and build a self-contained standalone part example. The writer creates a part inside a temporary directory.
git clone https://github.com/skuznetsov/crystal-click.git
cd crystal-click
make example-write_w15_decimal_part
tmp_root="$(mktemp -d)"
build/examples/write_w15_decimal_part "$tmp_root/decimal-part"
The example writes a UInt64 key and Decimal32(2) payload. The readback prints the canonical type and raw scaled integers.
Decimal(9, 2): [123, -456, 0]
The embedded table example also runs without external data. It creates a new Crystal-owned table below a temporary directory, inserts two parts, merges them, reopens the table, and scans the rows.
make example-embedded_merge_tree_table
tmp_root="$(mktemp -d)"
build/examples/embedded_merge_tree_table "$tmp_root/table"
The first output line contains generated part names and the destination. The scan then prints four tab-separated rows with keys 1, 2, 3, and 3. Their values are alpha, beta, an empty string, and é.
Keep standalone and embedded output directories outside ClickHouse server data roots. Each destination must be unused.
Install and use as a library
Add the shard to an application's shard.yml, then install dependencies with Shards.
dependencies:
crystal-click:
github: skuznetsov/crystal-click
branch: main
shards install
The public entry point is require "crystal-click". This small program reads a bounded row window from two UInt64 columns in a local table. Save it as reader.cr in the consuming application.
require "crystal-click"
unless ARGV.size == 7
STDERR.puts "usage: reader DATA_ROOT DATABASE TABLE LEFT_UINT64 RIGHT_UINT64 START_ROW MAX_ROWS"
exit 2
end
start_row = ARGV[5].to_u64
max_rows = ARGV[6].to_i
left_column = ARGV[3]
right_column = ARGV[4]
table = CrystalClick::OfflineCatalog.open(ARGV[0])[ARGV[1]][ARGV[2]]
table.scan_typed_window([left_column, right_column], start_row, max_rows) do |batch|
left = batch.values_for(left_column)
right = batch.values_for(right_column)
left.each_with_index do |value, index|
puts "row=#{batch.source_row_offset + index.to_u64} #{left_column}=#{value} #{right_column}=#{right[index]}"
end
end
Run it with a quiescent local data root, database, table, two declared UInt64 columns, a starting row offset, and a positive row limit.
crystal run reader.cr -- /path/to/immutable/clickhouse-data-root analytics events left right 0 100
Build read_typed_window to run the same scan from the checkout.
make example-read_typed_window
build/examples/read_typed_window /path/to/immutable/clickhouse-data-root analytics events left right 0 100
Examples load the checkout source directly. See the examples guide for their complete argument lists, profiles, and operational limits.
Read and write profiles
Compatibility depends on the part format, column types, serialization, codec, and mark layout. Each reader and writer has its own supported combinations. The profiles document the ClickHouse builds and layouts used for native ATTACH PART, CHECK TABLE, and readback where those checks were exercised.
| Surface | Profile reference |
|---|---|
| Wide table reads | Wide table reader, ragged columns, and compressed marks and ZSTD |
| Wide part writes | Schema-aware Wide writer |
| Compact typed reads | Compact reader profiles |
| Compact part writes | Compact writer profiles |
| Offline table scans and part resolution | Offline catalog and MergeTree part resolution |
Wide readers have profiles for adaptive .mrk2 and compressed .cmrk2 marks. Compact parts share data.bin across columns, with qualified .mrk3, .mrk4, .cmrk3, and .cmrk4 layouts. The linked profiles give the supported combinations for the following type families.
- Fixed-width signed and unsigned integers, including raw
Int128,UInt128,Int256, andUInt256carriers,Float32,Float64, andBFloat16. String,FixedString, temporal values, UUID, IPv4, IPv6, Decimal coefficients, Bool, and declared Enum8/Enum16 mappings.- Recursive Array, Tuple, Map, Nullable, LowCardinality, and flattened
Nestedcompositions for explicitly admitted schemas. - Specialized
Variant,Dynamic, JSON/Object, QBit, and Geo paths with API-specific storage and type profiles. - Selected serialized
AggregateFunctionstates and raw storage values for supportedSimpleAggregateFunctiondeclarations.
Useful family references include Decimal precision, identifiers, temporal tuples, recursive Tuples, Array of Tuple composition, Variant binding, Dynamic table consumers, JSON/Object storage, recursive Compact JSON and Dynamic, QBit, Geo types, SimpleAggregateFunction, and AggregateFunction sum states.
Offline Atomic catalog and scans
Open an immutable, quiescent copy of a single-disk Atomic data root. OfflineCatalog.open(data_root) reads metadata/ and store/. Use catalog.databases and database.tables to enumerate metadata, or index by name. table.part_candidates lists physical parts with row counts and partition IDs (part.info.partition_id).
For scans of stored MergeTree rows, the resolver chooses maximal covering parts and rejects partial overlaps, ambiguous duplicates, and transactional metadata. The full physical inventory remains available. The resolved set describes the files selected for this scan. Server Active state requires the server's own catalog.
The synthetic system.part_candidates table exposes the physical inventory through the same indexing API. Its rows column comes from count.txt.
data_root = "/path/to/immutable/clickhouse-data-root"
catalog = CrystalClick::OfflineCatalog.open(data_root)
candidate_rows = catalog["system"]["part_candidates"]["rows"].values
candidate_rows.each { |row_count| puts row_count }
table = catalog["analytics"]["events"]
left_values = table["left"].values(max_rows: 10_000_u64)
.values returns an owned array for a supported column and raises if the complete result exceeds its limits. See the physical column profile and synthetic candidate profile.
OfflineTable supports typed scans and bounded windows. Window limits bound rows delivered to callbacks. The reader may decode complete marks that intersect a window. For a table with ORDER BY pk and UInt64 columns pk and metric, select candidate granules and apply the inclusive key predicate inside the callback.
table = catalog["analytics"]["metrics"]
table.scan_uint64_pk_candidates(
["pk", "metric"],
lower_bound: 100_u64,
upper_bound: 200_u64
) do |batch|
keys = batch.values_for("pk")
values = batch.values_for("metric")
keys.each_with_index do |key, index|
puts "#{key}\t#{values[index]}" if 100_u64 <= key && key <= 200_u64
end
end
Scan callbacks receive borrowed slices. Copy data you intend to retain after the callback returns.
For direct part use, TypedPartTable.open_selected_typed(parts, columns) opens a caller-selected ordered list of compatible Wide and Compact part paths. Its scan_typed and scan_typed_window methods provide aligned batches over that explicit list. The preflight checks selected schemas and rejects overlapping part identities within a partition.
To decode ordinary Wide and Compact parts concurrently, opt in from the catalog or the direct part reader. The catalog checks the DDL and resolves the parts as it does for scan_typed.
total = 0_u64
table.scan_typed_parallel(["metric"], workers: 4) do |batch|
batch.values_for("metric", UInt64).each { |value| total &+= value }
end
The callback runs on the calling fiber in part and row order. The reader assigns distinct physical marks to workers, including within a single part. The threaded path supports primitive 8–64-bit integer and 32/64-bit float columns with Crystal execution contexts. On little-endian hosts it also supports one root LowCardinality(String) column with optional ordinary UInt64 columns in Compact MRK3 and MRK4 parts. See the Compact LowCardinality scan profile.
For repeated Compact LowCardinality(String) scans of the same sealed parts, keep the TypedPartTable returned by open_selected_typed and call scan_typed_parallel on it again. It reuses the admitted metadata and mark index and checks the data frames on each scan. See the retained reader contract.
To also keep the read-only data.bin mappings between scans, open a scoped session on that reader.
reader = CrystalClick::TypedPartTable.open_selected_typed([part_path], ["id", "lc"])
reader.with_retained_compact_mmaps do |session|
[1, 4].each do |workers|
session.scan_typed_parallel(workers: workers) do |batch|
pp batch.values_for("id", UInt64).first
end
end
end
Use the session for sequential scans of sealed parts. The mappings open on first use and close at block exit. Each scan still checks the frame headers and selected checksums. See the mapping session contract.
Workers share one plan per part for a Compact MRK4 JSON root using Advanced SharedData v2 or v3 with two buckets. The selection can include ordinary UInt64 columns. See the shared part plan.
For path-oriented access to that Compact JSON profile, call TypedPartTable#scan_compact_json_columnar with the JSON root and any ordinary UInt64 companions selected. The callback receives reusable JSON path columns aligned with the companion columns. See the columnar JSON example.
For one Compact MRK4 part with an Advanced JSON root, select the root and one ordinary UInt64 column. The filtered scan reads the key first and decodes JSON only for marks with matching rows. Use the packed-row API to work directly with the matches inside those marks.
reader = CrystalClick::TypedPartTable.open_selected_typed([part_path], ["id", "doc"])
predicate = ->(id : UInt64) { id % 4_u64 == 0 }
reader.scan_compact_json_filtered_rows("id", predicate, workers: 4) do |batch, matching_rows|
ids = batch.uint64_column("id")
rank = batch.column_for("rank")
matching_rows.each_with_index do |mark_row, i|
source_row = batch.source_row_offset + mark_row.to_u64
pp({source_row, ids[i], rank.try(&.value_at(i))})
end
end
The callback borrows the packed batch and physical offsets until it returns. scan_compact_json_filtered yields the full mark with the same matching offsets. Both scans check the frames read for the key and selected JSON marks before delivery. They assemble SharedData from Copy and skip its per-path Data streams. Pass verify_copy_data: true to read both representations and compare them across each selected mark. See the filtered JSON read policy.
workers: 1 scans serially. For repeated scans of ordinary Wide numeric parts with .mrk2 marks, retain the TypedPartTable instance and call scan_typed_parallel(workers: 4) on it for each pass. The reader reuses the admitted metadata and mark indexes and opens fresh data mappings for each scan. For direct UInt64 selections from these parts, scans requesting two to four workers can also reuse idle worker contexts and channels. Nested scans use their own workers while the outer scan holds the pool. Keep the parts immutable for the reader's lifetime and use a separate reader for each concurrent scan. See the parallel scan profile and comparison.
Materialized views and projections
The offline catalog exposes persisted materialized-view targets and SELECT text. In an exclusively owned offline copy, materialize_view_part handles the qualified identity SELECT shape. transform_materialized_view_part uses a caller-supplied Crystal transformation and writes Wide output by default. Pass mark_format: and return a CompactPartTransformOutput to write Compact output for the supported target schema. Both operations take one source part and publish a detached part under the declared target. The caller chooses when to recompute and attach it. See the MV metadata profile and transform profile.
For a target with a simple PROJECTION p (SELECT key, value ORDER BY key), compute the projection rows from the transformed rows in the callback. Pass the precomputed child to WidePartTransformOutput.new(keys, columns, projections: [child]) or use the same keyword with CompactPartTransformOutput. Each child may be Wide or Compact and has its own mark grid. The transform binds the returned children to the target DDL and publishes them with the parent in detached. See the transform projection profile.
For PROJECTION by_group (SELECT group_key, count() GROUP BY group_key), group_keys below contains the UInt64 group key of every transformed parent row. Count them in the callback and pass the child through the same projections: keyword for a Wide or Compact parent.
counts = Hash(UInt64, UInt64).new(0_u64)
group_keys.each { |key| counts[key] += 1_u64 }
keys = counts.keys.sort!
states = keys.map { |key| counts[key] }
child = CrystalClick::WidePartProjection.precomputed_count(
"by_group", "group_key",
keys.to_unsafe.to_slice(keys.size), states.to_unsafe.to_slice(states.size),
)
The child stores one AggregateFunction(count) state per group. The writer checks that the counts add up to the parent row count. Use CompactPartProjection.precomputed_count with the same arguments to write a Compact MRK4 child. See the Wide Count profile and Compact Count profile.
For PROJECTION by_group (SELECT group_key, count(), sum(value) GROUP BY group_key), let values hold the UInt64 value column aligned with group_keys. Build both state columns in SELECT order and pass the child through the same projections: keyword.
counts = Hash(UInt64, UInt64).new(0_u64)
sums = Hash(UInt64, UInt64).new(0_u64)
group_keys.each_with_index do |key, index|
counts[key] += 1_u64
sums[key] = sums[key] &+ values[index]
end
keys = counts.keys.sort!
count_states = keys.map { |key| counts[key] }
sum_states = keys.map { |key| sums[key] }
child = CrystalClick::WidePartProjection.precomputed_aggregate(
"by_group", "group_key", keys.to_unsafe.to_slice(keys.size),
[
CrystalClick::WidePartProjectionAggregate.count(count_states.to_unsafe.to_slice(count_states.size)),
CrystalClick::WidePartProjectionAggregate.sum_uint64("value", sum_states.to_unsafe.to_slice(sum_states.size)),
],
)
sum(value) can also be the sole aggregate. Its state is a little-endian UInt64, so &+ matches ClickHouse's wraparound. See the Sum projection profile.
For PROJECTION by_group (SELECT min(value), max(value) GROUP BY group_key), compute the extrema in the same callback using the aligned UInt64 columns group_keys and values. Each state column follows the same sorted group keys.
minima = Hash(UInt64, UInt64).new(UInt64::MAX)
maxima = Hash(UInt64, UInt64).new(0_u64)
group_keys.each_with_index do |key, index|
value = values[index]
minima[key] = Math.min(minima[key], value)
maxima[key] = Math.max(maxima[key], value)
end
keys = minima.keys.sort!
min_states = keys.map { |key| minima[key] }
max_states = keys.map { |key| maxima[key] }
child = CrystalClick::WidePartProjection.precomputed_aggregate(
"by_group", "group_key", keys.to_unsafe.to_slice(keys.size),
[
CrystalClick::WidePartProjectionAggregate.min_uint64("value", min_states.to_unsafe.to_slice(min_states.size)),
CrystalClick::WidePartProjectionAggregate.max_uint64("value", max_states.to_unsafe.to_slice(max_states.size)),
],
)
Pass the child through projections: for either parent layout. Use CompactPartProjection.precomputed_aggregate with the same arguments to write a Compact MRK4 child with one UInt64 group key. The Compact API accepts sum, min, max, and count states individually or together in SELECT order. Read Sum and extrema through batch.binary_bulk_values_for. See the Wide Min and Max profile and Compact aggregate profile.
For PROJECTION by_group (SELECT count() GROUP BY region, day, bucket), pass the UInt64 key columns in GROUP BY order. Here regions, days and buckets are aligned arrays from the transformed rows.
counts = Hash(Tuple(UInt64, UInt64, UInt64), UInt64).new(0_u64)
regions.each_with_index do |region, index|
counts[{region, days[index], buckets[index]}] += 1_u64
end
groups = counts.keys.sort!
key_columns = [groups.map(&.[0]), groups.map(&.[1]), groups.map(&.[2])]
states = groups.map { |group| counts[group] }
child = CrystalClick::WidePartProjection.precomputed_aggregate(
"by_group", ["region", "day", "bucket"],
key_columns.map { |keys| keys.to_unsafe.to_slice(keys.size) },
[CrystalClick::WidePartProjectionAggregate.count(states.to_unsafe.to_slice(states.size))],
)
The groups must be distinct and lexicographically sorted. The API also accepts sum(value), min(value), and max(value) states. Use CompactPartProjection.precomputed_aggregate with the same arguments to write a Compact MRK4 child. Both child layouts work under either parent layout. See the ordered UInt64 key profile.
Pass compress_marks: true to WidePartProjection.precomputed_aggregate or WidePartProjection.precomputed_count to write .cmrk2 marks for all keys and states in the Wide child. The default is .mrk2. Either parent layout can use either Wide child mark format. See the compressed Wide mark profile.
Pass compress_primary_key: true to precomputed_aggregate or precomputed_count on WidePartProjection or CompactPartProjection to write the child's primary.cidx. With either parent layout, the Wide child can use .mrk2 or .cmrk2 and the Compact child can use data.mrk4 or data.cmrk4. The default writes primary.idx. See the Wide index profile and Compact index profile.
OfflineTable#projections exposes declared projection metadata. For a table with a physical Wide or Compact projection p containing a UInt64 column pk, call scan_projection_typed_window with the projection name and row range. The reader matches each selected child's checksum manifest to its parent before yielding rows. Offsets follow the child's marks, and batches identify the parent part.
table.scan_projection_typed_window("p", ["pk"], 0_u64, 64) do |batch|
batch.values_for("pk", UInt64).each { |key| puts key }
end
Compute projection rows in your application and pass them as projections: to either part writer's write_uint64_columns. Use WidePartProjection.precomputed or CompactPartProjection.precomputed for each child. Children keep their own mark grids and are published with the parent in one directory rename. See the projection window profile and projection publication profile.
Standalone parts and embedded storage
WidePartWriter and CompactPartWriter create complete standalone parts for their supported profiles. Write to a new destination outside a running server's data root, then manage attachment separately. Exclusive atomic publication currently uses Darwin renamex_np to publish the complete part directory in one step.
EmbeddedMergeTreeTable is a separate Crystal-owned local table built from bounded immutable parts in one partition. Use a sorted UInt64 key with a String payload or the separate profile for declared scalar JSON paths. It supports insert, adjacent-part merge, reopen, and typed scans. Store it outside ClickHouse server data roots. Its publication also uses the Darwin publisher. See the embedded table profile.
Build and verify
The Makefile discovers standalone programs under examples/*.cr. Use make help to list them, or build one by its source basename.
make help
make examples
make example-read_typed_window
make examples BUILD_DIR=build/release CRYSTAL_FLAGS=--release
make clean BUILD_DIR=build/release
make clean
make example-<basename> builds one top-level example to $(BUILD_DIR)/examples/<basename>. BUILD_DIR defaults to build and accepts paths with spaces. Set CRYSTAL to choose a compiler. Use a separate build directory for each compiler flag set. make clean removes example and TUI binaries and their debug sidecars from the specified build directory.
The optional make tui target builds $(BUILD_DIR)/examples/offline_tui. It needs an external crystal_tui/src directory on CRYSTAL_PATH and is excluded from make examples.
CRYSTAL_PATH="/path/to/crystal_tui/src:$(crystal env CRYSTAL_PATH)" make tui
build/examples/offline_tui /path/to/immutable/clickhouse-data-root
If LLD reports an Xcode TAPI parsing error on macOS, use Apple's linker for the build.
CRYSTAL_FLAGS="--link-flags=-fuse-ld=ld" make example-list_atomic_catalog
Run the standalone catalog spec with Crystal.
crystal spec spec/offline_catalog_spec.cr
The full spec suite also requires native ClickHouse captures. See the Compact JSON reader profile for the authenticated W263 fixture selected by CRYSTAL_CLICK_W263_EVIDENCE_ROOT.
Architecture and further reading
OfflineCatalog and OfflineTable resolve local metadata and parts. TypedPartTable dispatches to Wide and Compact readers and reports batches in selected part order with table-wide row offsets. Format-specific code handles stream and mark locations. Typed codecs decode column values, including supported recursive substreams. Writers build and validate a staged part before publishing it.
- Table class decomposition describes public entry points and reader ownership boundaries.
- Offline catalog frontier describes local metadata discovery and candidate resolution.
- Examples guide lists runnable examples and arguments.
- ClickHouse format references and source references record upstream format anchors.
- Project status tracks current qualification and remaining compatibility work.
- Performance backlog records measurements and deferred optimization work.
License
crystal-click is licensed under the Apache License 2.0.
crystal-click
- 5
- 0
- 0
- 0
- 0
- 2 days ago
- September 24, 2026
Apache License 2.0
Sun, 29 Nov 2026 15:40:36 GMT