mz_row_spine/lib.rs
1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Types and traits in support of containers for row-encoded byte slices.
11//!
12//! This includes the vanilla `bytes_container` that holds byte slices in contiguous
13//! allocations, as well as a `dictionary` encoding wrapper that is able to rewrite
14//! the byte slices to use spare tags in each column to reference common values.
15
16pub use self::arc_batch::{ArcBatch, ArcBuilder};
17pub use self::dictionary::DatumContainer;
18pub use self::dictionary::DatumSeq;
19pub use self::dictionary::builders::RowRowColPagedState;
20pub use self::offset_opt::OffsetOptimized;
21pub use self::spines::{
22 ArcOrdKeyBatcher, ArcOrdKeyBuilder, ArcOrdKeySpine, ArcOrdValBatcher, ArcOrdValBuilder,
23 ArcOrdValSpine, FundedValRowSpine, RowBatcher, RowBuilder, RowRowBatcher, RowRowBuilder,
24 RowRowColPagedBuilder, RowRowSpine, RowSpine, RowValBatcher, RowValBuilder, RowValSpine,
25 ValRowBatcher, ValRowBuilder, ValRowColPagedBuilder, ValRowSpine,
26};
27
28mod arc_batch;
29
30use differential_dataflow::trace::implementations::OffsetList;
31
32/// Enable per-column dictionary compression in row containers.
33pub static DICTIONARY_COMPRESSION: std::sync::atomic::AtomicBool =
34 std::sync::atomic::AtomicBool::new(false);
35
36/// Spines specialized to contain `Row` types in keys and values.
37mod spines {
38 use columnation::Columnation;
39 use differential_dataflow::trace::implementations::BatchContainer;
40 use differential_dataflow::trace::implementations::Layout;
41 use differential_dataflow::trace::implementations::Update;
42 use differential_dataflow::trace::implementations::Vector;
43 use differential_dataflow::trace::implementations::merge_batcher::{
44 MergeBatcher, chunker::ContainerChunker, vec::VecMerger,
45 };
46 use differential_dataflow::trace::implementations::ord_neu::{
47 OrdKeyBatch, OrdKeyBuilder, OrdValBatch, OrdValBuilder,
48 };
49 use differential_dataflow::trace::implementations::spine_fueled::Spine;
50 use mz_repr::Row;
51 use mz_timely_util::columnation::{ColInternalMerger, ColumnationChunker, ColumnationStack};
52
53 use crate::arc_batch::{ArcBatch, ArcBuilder};
54 use crate::{DatumContainer, OffsetOptimized};
55
56 /// Batcher matching `mz_compute::typedefs::KeyValBatcher`, redeclared
57 /// locally so this crate does not need to depend on `mz_compute`.
58 type KeyValBatcher<K, V, T, D, Se> =
59 MergeBatcher<ColumnationChunker<((K, V), T, D)>, ColInternalMerger<(K, V), T, D>, Se>;
60 type KeyBatcher<K, T, D, Se> = KeyValBatcher<K, (), T, D, Se>;
61
62 pub type RowRowSpine<T, R> = Spine<ArcBatch<OrdValBatch<RowRowLayout<((Row, Row), T, R)>>>>;
63 pub type RowRowBatcher<T, R> = KeyValBatcher<Row, Row, T, R, RowRowBuilder<T, R>>;
64 pub type RowRowBuilder<T, R> = ArcBuilder<crate::dictionary::builders::RowRowBuilder<T, R>>;
65
66 /// `RowRowBuilder` variant that consumes [`ColumnBody`] chunks. Pairs with
67 /// any batcher whose chains are bodies, spillable ([`AccountedChunkBatcher`]
68 /// behind an [`UnchunkBuilder`]) or resident ([`Col2ValColBatcher`]) alike,
69 /// so the `Paged` in the name records where it started rather than a
70 /// restriction. Installs a dictionary codec at seal time, gathering
71 /// statistics from the sealed chain, so columnar arrangements compress on
72 /// the same footing as the columnation-fed [`RowRowBuilder`].
73 ///
74 /// [`AccountedChunkBatcher`]: mz_timely_util::columnar::chunk::AccountedChunkBatcher
75 /// [`Col2ValColBatcher`]: mz_timely_util::columnar::Col2ValColBatcher
76 /// [`ColumnBody`]: mz_timely_util::columnar::body::ColumnBody
77 /// [`UnchunkBuilder`]: mz_timely_util::columnar::chunk::UnchunkBuilder
78 pub type RowRowColPagedBuilder<T, R> =
79 ArcBuilder<crate::dictionary::builders::RowRowColPagedBuilder<T, R>>;
80
81 pub type RowValSpine<V, T, R> = Spine<ArcBatch<OrdValBatch<RowValLayout<((Row, V), T, R)>>>>;
82 pub type RowValBatcher<V, T, R> = KeyValBatcher<Row, V, T, R, RowValBuilder<V, T, R>>;
83 pub type RowValBuilder<V, T, R> =
84 ArcBuilder<crate::dictionary::builders::RowValBuilder<V, T, R>>;
85
86 /// Key-only `Row` spine. `DC` is the diff container, see `RowLayout`.
87 pub type RowSpine<T, R, DC = ColumnationStack<R>> =
88 Spine<ArcBatch<OrdKeyBatch<RowLayout<((Row, ()), T, R), DC>>>>;
89 pub type RowBatcher<T, R, DC = ColumnationStack<R>> =
90 KeyBatcher<Row, T, R, RowBuilder<T, R, DC>>;
91 pub type RowBuilder<T, R, DC = ColumnationStack<R>> =
92 ArcBuilder<crate::dictionary::builders::RowBuilder<T, R, DC>>;
93
94 pub type ValRowSpine<K, T, R> = Spine<ArcBatch<OrdValBatch<ValRowLayout<((K, Row), T, R)>>>>;
95 /// A `ValRowSpine` whose optional exertion is funded by its input.
96 pub type FundedValRowSpine<K, T, R> =
97 mz_timely_util::funded_spine::Spine<ArcBatch<OrdValBatch<ValRowLayout<((K, Row), T, R)>>>>;
98 pub type ValRowBatcher<K, T, R> = KeyValBatcher<K, Row, T, R, ValRowBuilder<K, T, R>>;
99 pub type ValRowBuilder<K, T, R> =
100 ArcBuilder<crate::dictionary::builders::ValRowBuilder<K, T, R>>;
101
102 /// `ValRowBuilder` variant that consumes [`Column`] chunks, for arrangements where
103 /// keys are arbitrary `Columnar` values (e.g. `UpsertKey`) and values are
104 /// packed `Row` bytes. Installs a dictionary codec on the value container at
105 /// seal time, gathering statistics from the sealed `Column` chain; keys are
106 /// not `Row`-shaped and so are left uncompressed.
107 ///
108 /// [`Column`]: mz_timely_util::columnar::Column
109 pub type ValRowColPagedBuilder<K, T, R> =
110 ArcBuilder<crate::dictionary::builders::ValRowColPagedBuilder<K, T, R>>;
111
112 /// A generic `Arc`-backed key/value spine, for callers outside `mz_compute` that need an
113 /// arrangement over non-`Row`-specialized types. The `Arc` handle rides on the local
114 /// [`ArcBatch`] newtype, so no differential-side `Arc` batch impls are required.
115 pub type ArcOrdValSpine<K, V, T, R> = Spine<ArcBatch<OrdValBatch<Vector<((K, V), T, R)>>>>;
116 /// Generic `Arc`-backed key-only spine. See [`ArcOrdValSpine`].
117 pub type ArcOrdKeySpine<K, T, R> = Spine<ArcBatch<OrdKeyBatch<Vector<((K, ()), T, R)>>>>;
118 /// Builder pairing with [`ArcOrdValSpine`].
119 pub type ArcOrdValBuilder<K, V, T, R> =
120 ArcBuilder<OrdValBuilder<Vector<((K, V), T, R)>, Vec<((K, V), T, R)>>>;
121 /// Builder pairing with [`ArcOrdKeySpine`].
122 pub type ArcOrdKeyBuilder<K, T, R> =
123 ArcBuilder<OrdKeyBuilder<Vector<((K, ()), T, R)>, Vec<((K, ()), T, R)>>>;
124 /// Batcher pairing with [`ArcOrdValSpine`], over `Vec` input.
125 pub type ArcOrdValBatcher<K, V, T, R> = MergeBatcher<
126 ContainerChunker<Vec<((K, V), T, R)>>,
127 VecMerger<(K, V), T, R>,
128 ArcOrdValBuilder<K, V, T, R>,
129 >;
130 /// Batcher pairing with [`ArcOrdKeySpine`], over `Vec` input.
131 pub type ArcOrdKeyBatcher<K, T, R> = MergeBatcher<
132 ContainerChunker<Vec<((K, ()), T, R)>>,
133 VecMerger<(K, ()), T, R>,
134 ArcOrdKeyBuilder<K, T, R>,
135 >;
136
137 /// A layout based on timely stacks
138 pub struct RowRowLayout<U>
139 where
140 U: Update<Key = Row, Val = Row>,
141 {
142 phantom: std::marker::PhantomData<U>,
143 }
144 pub struct RowValLayout<U>
145 where
146 U: Update<Key = Row>,
147 {
148 phantom: std::marker::PhantomData<U>,
149 }
150 /// Layout for key-only `Row` updates. `DC` is the diff `BatchContainer`, a
151 /// columnation stack by default.
152 pub struct RowLayout<U, DC = ColumnationStack<<U as Update>::Diff>>
153 where
154 U: Update<Key = Row, Val = ()>,
155 {
156 phantom: std::marker::PhantomData<(U, DC)>,
157 }
158 /// Mirror of [`RowValLayout`] with the roles swapped: arbitrary `Columnation`
159 /// keys with `Row` values stored as packed bytes in a [`DatumContainer`].
160 pub struct ValRowLayout<U>
161 where
162 U: Update<Val = Row>,
163 {
164 phantom: std::marker::PhantomData<U>,
165 }
166
167 impl<U> Layout for RowRowLayout<U>
168 where
169 U: Update<Key = Row, Val = Row>,
170 U::Time: Columnation,
171 U::Diff: Columnation,
172 {
173 type KeyContainer = DatumContainer;
174 type ValContainer = DatumContainer;
175 type TimeContainer = ColumnationStack<U::Time>;
176 type DiffContainer = ColumnationStack<U::Diff>;
177 type OffsetContainer = OffsetOptimized;
178 }
179 impl<U> Layout for RowValLayout<U>
180 where
181 U: Update<Key = Row>,
182 U::Val: Columnation,
183 U::Time: Columnation,
184 U::Diff: Columnation,
185 {
186 type KeyContainer = DatumContainer;
187 type ValContainer = ColumnationStack<U::Val>;
188 type TimeContainer = ColumnationStack<U::Time>;
189 type DiffContainer = ColumnationStack<U::Diff>;
190 type OffsetContainer = OffsetOptimized;
191 }
192 impl<U, DC> Layout for RowLayout<U, DC>
193 where
194 U: Update<Key = Row, Val = ()>,
195 U::Time: Columnation,
196 DC: BatchContainer<Owned = U::Diff>,
197 {
198 type KeyContainer = DatumContainer;
199 type ValContainer = ColumnationStack<()>;
200 type TimeContainer = ColumnationStack<U::Time>;
201 type DiffContainer = DC;
202 type OffsetContainer = OffsetOptimized;
203 }
204 impl<U> Layout for ValRowLayout<U>
205 where
206 U: Update<Val = Row>,
207 U::Key: Columnation,
208 U::Time: Columnation,
209 U::Diff: Columnation,
210 {
211 type KeyContainer = ColumnationStack<U::Key>;
212 type ValContainer = DatumContainer;
213 type TimeContainer = ColumnationStack<U::Time>;
214 type DiffContainer = ColumnationStack<U::Diff>;
215 type OffsetContainer = OffsetOptimized;
216 }
217}
218
219#[cfg(test)]
220mod tests {
221 use crate::DatumContainer;
222 use crate::spines::{RowLayout, RowRowLayout, RowValLayout};
223 use differential_dataflow::trace::implementations::BatchContainer;
224 use differential_dataflow::trace::implementations::ord_neu::{OrdKeyBatch, OrdValBatch};
225 use mz_repr::adt::date::Date;
226 use mz_repr::adt::interval::Interval;
227 use mz_repr::{Datum, Diff, Row, SqlScalarType, Timestamp};
228 use mz_timely_util::columnation::ColumnationStack;
229
230 fn assert_send_sync<T: Send + Sync>() {}
231
232 /// The batch types backing our spines must stay `Send + Sync`, so that batches
233 /// can be shared across threads (for example behind an `Arc`) to serve reads
234 /// from outside the worker that maintains the trace. This holds because the
235 /// backing containers bottom out in `Vec`s, lgalloc regions, and `CompactBytes`,
236 /// all of which are thread-safe.
237 #[mz_ore::test]
238 fn batches_are_send_sync() {
239 assert_send_sync::<OrdValBatch<RowRowLayout<((Row, Row), Timestamp, Diff)>>>();
240 assert_send_sync::<OrdValBatch<RowValLayout<((Row, Row), Timestamp, Diff)>>>();
241 assert_send_sync::<OrdKeyBatch<RowLayout<((Row, ()), Timestamp, Diff)>>>();
242 assert_send_sync::<ColumnationStack<((Row, Row), Timestamp, Diff)>>();
243 }
244
245 /// A chain of chunks seals with the chain's dictionary codecs installed,
246 /// so its batch compresses like one sealed from columns directly. A seal
247 /// that skips the install stores raw bytes and, per
248 /// `DatumContainer::promote_stats_to_codec`, drags every merge it joins
249 /// down with it.
250 #[mz_ore::test]
251 #[cfg_attr(miri, ignore)] // integer-to-pointer casts in row decoding are unsupported under miri
252 fn chunked_seal_installs_codecs() {
253 use std::sync::atomic::Ordering;
254
255 use differential_dataflow::trace::implementations::merge_batcher::Sealer;
256 use differential_dataflow::trace::implementations::ord_neu::OrdValBatch;
257 use mz_timely_util::columnar::body::ColumnBody;
258 use mz_timely_util::columnar::chunk::{ColumnChunk, ComputeSpill, UnchunkBuilder};
259 use timely::container::PushInto;
260 use timely::progress::Timestamp as _;
261
262 use crate::ArcBatch;
263
264 // Gate the dictionary path on. Safe for other tests: the flag only
265 // controls whether codecs are built, never decode results.
266 crate::DICTIONARY_COMPRESSION.store(true, Ordering::Relaxed);
267
268 // Low-cardinality rows, well under `STATS_THRESHOLD` (64Ki pushes), so
269 // a codec can only come from the seal-time install.
270 let time = Timestamp::minimum();
271 let updates: Vec<((Row, Row), Timestamp, i64)> = (0..2_000i64)
272 .map(|i| {
273 (
274 (
275 Row::pack_slice(&[Datum::Int64(i)]),
276 Row::pack_slice(&[Datum::String("a repeated string value")]),
277 ),
278 time,
279 1i64,
280 )
281 })
282 .collect();
283
284 // Cut the sorted run the way a merge batcher's chain is cut.
285 let columns = || -> Vec<ColumnBody<((Row, Row), Timestamp, i64)>> {
286 updates
287 .chunks(250)
288 .map(|part| {
289 let mut column: ColumnBody<((Row, Row), Timestamp, i64)> = Default::default();
290 for update in part {
291 column.push_into(update);
292 }
293 column
294 })
295 .collect()
296 };
297 type Paged = crate::RowRowColPagedBuilder<Timestamp, i64>;
298 type Chunked = UnchunkBuilder<Paged, (Row, Row), Timestamp, i64, ComputeSpill>;
299
300 let mut chain = columns();
301 let from_columns = <Paged as Sealer<_>>::seal(&mut chain).expect("chain holds updates");
302
303 let mut chain: Vec<ColumnChunk<(Row, Row), Timestamp, i64, ComputeSpill>> =
304 columns().into_iter().map(ColumnChunk::from_body).collect();
305 let from_chunks = <Chunked as Sealer<_>>::seal(&mut chain).expect("chain holds updates");
306
307 assert!(
308 from_chunks.0.storage.keys.has_codec() && from_chunks.0.storage.vals.vals.has_codec(),
309 "the sealed batch carries the chain's codecs"
310 );
311
312 // Same updates and same cuts, so the chunked seal has to reach the
313 // encoded size the column seal does.
314 let heap = |c: &DatumContainer| {
315 let mut size = 0;
316 c.heap_size(|_, cap| size += cap);
317 size
318 };
319 let encoded = |b: &ArcBatch<OrdValBatch<RowRowLayout<((Row, Row), Timestamp, i64)>>>| {
320 heap(&b.0.storage.keys) + heap(&b.0.storage.vals.vals)
321 };
322
323 assert!(
324 encoded(&from_chunks) <= encoded(&from_columns),
325 "chunked seal should compress like the column seal: chunks={} columns={}",
326 encoded(&from_chunks),
327 encoded(&from_columns),
328 );
329 }
330
331 #[mz_ore::test]
332 #[cfg_attr(miri, ignore)] // unsupported operation: integer-to-pointer casts and `ptr::with_exposed_provenance` are not supported
333 fn test_round_trip() {
334 fn round_trip(datums: Vec<Datum>) {
335 let row = Row::pack(datums.clone());
336
337 let mut container = DatumContainer::with_capacity(row.byte_len());
338 container.push_own(&row);
339
340 // When run under miri this catches undefined bytes written to data
341 // eg by calling push_copy! on a type which contains undefined padding values
342 println!("{:?}", container.index(0).iter.data);
343
344 let datums2 = container.index(0).collect::<Vec<_>>();
345 assert_eq!(datums, datums2);
346 }
347
348 round_trip(vec![]);
349 round_trip(
350 SqlScalarType::enumerate()
351 .iter()
352 .flat_map(|r#type| r#type.interesting_datums())
353 .collect(),
354 );
355 round_trip(vec![
356 Datum::Null,
357 Datum::Null,
358 Datum::False,
359 Datum::True,
360 Datum::Int16(-21),
361 Datum::Int32(-42),
362 Datum::Int64(-2_147_483_648 - 42),
363 Datum::UInt8(0),
364 Datum::UInt8(1),
365 Datum::UInt16(0),
366 Datum::UInt16(1),
367 Datum::UInt16(1 << 8),
368 Datum::UInt32(0),
369 Datum::UInt32(1),
370 Datum::UInt32(1 << 8),
371 Datum::UInt32(1 << 16),
372 Datum::UInt32(1 << 24),
373 Datum::UInt64(0),
374 Datum::UInt64(1),
375 Datum::UInt64(1 << 8),
376 Datum::UInt64(1 << 16),
377 Datum::UInt64(1 << 24),
378 Datum::UInt64(1 << 32),
379 Datum::UInt64(1 << 40),
380 Datum::UInt64(1 << 48),
381 Datum::UInt64(1 << 56),
382 Datum::Date(Date::from_pg_epoch(365 * 45 + 21).unwrap()),
383 Datum::Interval(Interval {
384 months: 312,
385 ..Default::default()
386 }),
387 Datum::Interval(Interval::new(0, 0, 1_012_312)),
388 Datum::Bytes(&[]),
389 Datum::Bytes(&[0, 2, 1, 255]),
390 Datum::String(""),
391 Datum::String("العَرَبِيَّة"),
392 ]);
393 }
394
395 /// Exercises the *compressed* encode→decode paths, which the dyncfg-gated
396 /// `test_round_trip` never reaches (it installs no codec). We drive the codec
397 /// directly: observe a sample, build a codec via both `new_from([c1, c2])`
398 /// (the merge path) and `new_safe` (the safe-tag path), then round-trip every
399 /// row through it. We additionally assert the dictionary actually engaged, so
400 /// the test keeps covering the compressed branch rather than silently
401 /// degrading to raw fall-through.
402 #[mz_ore::test]
403 #[cfg_attr(miri, ignore)] // integer-to-pointer casts in row decoding are unsupported under miri
404 fn test_codec_round_trip() {
405 use crate::row_codec::ColumnsCodec;
406
407 // Rows with a small set of repeated, multi-byte string values, so the
408 // dictionary installs entries (MisraGries keeps values with len > 1 and
409 // count > 1). Mixing in an integer column exercises the raw fall-through
410 // (and thus the new soundness `debug_assert`) alongside dictionary hits.
411 let values = ["apple", "banana", "cherry"];
412 let rows: Vec<Row> = (0..3_000)
413 .map(|i| {
414 Row::pack_slice(&[
415 Datum::String(values[i % values.len()]),
416 Datum::Int64(i64::try_from(i).unwrap()),
417 Datum::String(values[(i / 7) % values.len()]),
418 ])
419 })
420 .collect();
421
422 // Accumulate statistics in two independent observers, so the merge in
423 // `new_from([&stats1, &stats2])` is actually exercised.
424 let mut stats1 = ColumnsCodec::default();
425 let mut stats2 = ColumnsCodec::default();
426 let mut scratch = Vec::new();
427 for (i, row) in rows.iter().enumerate() {
428 scratch.clear();
429 let stats = if i % 2 == 0 { &mut stats1 } else { &mut stats2 };
430 stats.encode(ColumnsCodec::borrow_row(row), &mut scratch);
431 }
432
433 let merged = ColumnsCodec::new_from([&stats1, &stats2]);
434 let safe = stats1.new_safe();
435 for mut codec in [merged, safe] {
436 let mut compressed_any = false;
437 for row in &rows {
438 let mut buf = Vec::new();
439 codec.encode(ColumnsCodec::borrow_row(row), &mut buf);
440
441 let decoded = codec.decode(&buf).collect::<Vec<_>>();
442 let expected = ColumnsCodec::borrow_row(row).collect::<Vec<_>>();
443 assert_eq!(decoded, expected, "round-trip mismatch for {row:?}");
444
445 compressed_any |= buf.len() < row.data().len();
446 }
447 assert!(
448 compressed_any,
449 "dictionary never engaged; test no longer covers the compressed path",
450 );
451 }
452 }
453
454 /// Regression test for a dictionary-codec soundness bug in the safe-install
455 /// path (`new_safe`), reachable with the paged batcher enabled.
456 ///
457 /// A from-scratch container stores its pre-install rows *raw* while gathering
458 /// statistics, then installs a *safe* codec via `new_safe`. `new_safe` used to
459 /// discard the first-byte bitmap gathered over those raw rows. That bitmap is
460 /// soundness-critical: a later `new_from` merge consults it to decide which
461 /// one-byte tags are free to hand out as dictionary keys. With the bitmap
462 /// dropped, the merge could assign a dictionary tag equal to a raw datum's
463 /// first byte, after which `decode` resolves that literal datum to the
464 /// dictionary entry — returning the wrong value.
465 ///
466 /// We drive the lifecycle directly: observe short strings (first byte
467 /// `StringTiny`) into the pre-install statistics, install a safe codec, then
468 /// feed it many distinct *long* strings (first byte `StringShort`)
469 /// post-install so the merge has heavy hitters to compress. Merging via
470 /// `new_from` and re-encoding the short strings then exercises the raw
471 /// fall-through whose first byte the merge must not have claimed as a tag.
472 /// Before the fix the `StringTiny` tag was handed out and the round-trip
473 /// produced a long string (and tripped `encode`'s soundness `debug_assert`).
474 #[mz_ore::test]
475 #[cfg_attr(miri, ignore)] // integer-to-pointer casts in row decoding are unsupported under miri
476 fn test_safe_codec_merge_bitmap_carryover() {
477 use crate::row_codec::ColumnsCodec;
478
479 // Short strings: length < 256, so they encode with the `StringTiny` tag.
480 // Unique, so MisraGries never makes them dictionary entries; they always
481 // fall through raw, exposing their first byte.
482 let short_rows: Vec<Row> = (0..256)
483 .map(|i| Row::pack_slice(&[Datum::String(&format!("s{i}"))]))
484 .collect();
485 // Long strings: length >= 256, so they encode with the `StringShort` tag —
486 // a *different* first byte than the short strings. Distinct values, each
487 // repeated, so the post-install codec accrues many heavy hitters and the
488 // merge assigns dictionary tags across the low byte range, reaching the
489 // short strings' `StringTiny` tag unless the bitmap reserves it.
490 let long_values: Vec<String> = (0..64).map(|i| format!("{i:0>300}")).collect();
491
492 // Pre-install statistics observe only the short strings' first bytes.
493 let mut stats = ColumnsCodec::default();
494 let mut scratch = Vec::new();
495 for row in &short_rows {
496 scratch.clear();
497 stats.encode(ColumnsCodec::borrow_row(row), &mut scratch);
498 }
499
500 // Install a safe codec, then feed it the long strings post-install so it
501 // accrues heavy hitters (and observes only the `StringShort` first byte).
502 let mut safe = stats.new_safe();
503 for _ in 0..8 {
504 for v in &long_values {
505 let row = Row::pack_slice(&[Datum::String(v)]);
506 scratch.clear();
507 safe.encode(ColumnsCodec::borrow_row(&row), &mut scratch);
508 }
509 }
510
511 // Merge, then round-trip the short strings. With the bitmap carried over,
512 // no dictionary tag collides with the short strings' first byte; without
513 // it, one does.
514 let mut merged = ColumnsCodec::new_from([&safe]);
515 for row in &short_rows {
516 let mut buf = Vec::new();
517 merged.encode(ColumnsCodec::borrow_row(row), &mut buf);
518 let decoded = merged.decode(&buf).collect::<Vec<_>>();
519 let expected = ColumnsCodec::borrow_row(row).collect::<Vec<_>>();
520 assert_eq!(decoded, expected, "round-trip mismatch for {row:?}");
521 }
522 }
523
524 /// Confirms the structural assumption underpinning `SAFE_TAG_BASE`: every
525 /// datum the row format produces encodes with a first byte strictly less
526 /// than `SAFE_TAG_BASE`. If `mz_repr` ever introduces a tag that crosses
527 /// the boundary, `DictionaryCodec::new_safe` would assign a dictionary tag
528 /// that collides with a literal datum first-byte, breaking decoding.
529 #[mz_ore::test]
530 fn test_safe_tag_base() {
531 use crate::row_codec::SAFE_TAG_BASE;
532 let check = |datum: Datum| {
533 let row = Row::pack_slice(&[datum]);
534 let data = row.data();
535 assert!(!data.is_empty(), "empty encoding for {datum:?}");
536 assert!(
537 data[0] < SAFE_TAG_BASE,
538 "datum {datum:?} encodes with first byte {} >= SAFE_TAG_BASE ({}); \
539 a new row tag has crossed the safe boundary",
540 data[0],
541 SAFE_TAG_BASE,
542 );
543 };
544 for ty in SqlScalarType::enumerate().iter() {
545 for datum in ty.interesting_datums() {
546 check(datum);
547 }
548 }
549 }
550
551 /// A batch built via the builder's `push`/`done` path (as the `reduce` operator
552 /// does) that stays under `STATS_THRESHOLD` never installs a codec at build time.
553 /// `done` now promotes the gathered statistics into the codec slot, so the batch
554 /// carries a codec + heavy-hitter summary and does not poison a later merge.
555 ///
556 /// This drives that container lifecycle directly: gather raw (well under the
557 /// threshold), promote at "done", then merge two such containers the way a spine
558 /// compaction does. With promotion the merge takes the `new_from` path and
559 /// compresses; without it both inputs are codec-less and the merge stays raw.
560 /// Every merged row must still round-trip.
561 #[mz_ore::test]
562 #[cfg_attr(miri, ignore)] // integer-to-pointer casts in row decoding are unsupported under miri
563 fn push_done_promotion_avoids_merge_poison() {
564 use std::sync::atomic::Ordering;
565 use timely::container::PushInto;
566
567 // Gate the dictionary path on. Safe for other tests: the flag only controls
568 // whether `DatumContainer` gathers stats; it never changes decode results.
569 crate::DICTIONARY_COMPRESSION.store(true, Ordering::Relaxed);
570
571 // Low-cardinality rows, well under `STATS_THRESHOLD` (64Ki): a repeated
572 // multi-byte string the dictionary compresses, plus an integer column that
573 // exercises raw fall-through.
574 let rows: Vec<Row> = (0..2_000i64)
575 .map(|i| {
576 Row::pack_slice(&[
577 Datum::Int64(i % 8),
578 Datum::String("a repeated string value"),
579 ])
580 })
581 .collect();
582
583 // Build a container the way the push/done path does: gather raw without ever
584 // crossing `STATS_THRESHOLD`, optionally promoting at "done".
585 let build = |promote: bool| {
586 let mut c = DatumContainer::with_capacity(rows.len());
587 for row in &rows {
588 c.push_into(row);
589 }
590 if promote {
591 c.promote_stats_to_codec();
592 }
593 c
594 };
595
596 // Merge two containers as a spine compaction does: allocate via
597 // `merge_capacity`, then copy every row through.
598 let merge = |a: &DatumContainer, b: &DatumContainer| {
599 let mut m = DatumContainer::merge_capacity(a, b);
600 for i in 0..a.len() {
601 m.push_into(a.index(i));
602 }
603 for i in 0..b.len() {
604 m.push_into(b.index(i));
605 }
606 m
607 };
608
609 let heap = |c: &DatumContainer| {
610 let mut size = 0;
611 c.heap_size(|_, cap| size += cap);
612 size
613 };
614
615 // Codec-less inputs (no promotion): the merge cannot `new_from` and stays raw.
616 let poisoned = merge(&build(false), &build(false));
617 // Promoted inputs carry a codec + summary: the merge `new_from`s and compresses.
618 let compressed = merge(&build(true), &build(true));
619
620 // Round-trip: every merged row decodes back to the corresponding input row
621 // (the merge here concatenates a's rows then b's rows, no consolidation).
622 assert_eq!(compressed.len(), rows.len() * 2);
623 for i in 0..compressed.len() {
624 let got = compressed.index(i).collect::<Vec<_>>();
625 let want = rows[i % rows.len()].iter().collect::<Vec<_>>();
626 assert_eq!(got, want, "merged row {i} round-trips");
627 }
628
629 // The promoted merge must actually compress relative to the poisoned one,
630 // confirming promotion carried a usable summary into `new_from`.
631 assert!(
632 heap(&compressed) < heap(&poisoned),
633 "promotion should let the merge compress: compressed={} poisoned={}",
634 heap(&compressed),
635 heap(&poisoned),
636 );
637 }
638}
639
640/// A `[u8]`-specialized container.
641mod bytes_container {
642
643 use differential_dataflow::trace::implementations::BatchContainer;
644 use timely::container::PushInto;
645
646 use mz_ore::region::Region;
647
648 /// A slice container with four bytes overhead per slice.
649 pub struct BytesContainer {
650 /// Total length of `batches`, maintained because recomputation is expensive.
651 length: usize,
652 batches: Vec<BytesBatch>,
653 }
654
655 impl BytesContainer {
656 /// Visit contained allocations to determine their size and capacity.
657 #[inline]
658 pub fn heap_size(&self, mut callback: impl FnMut(usize, usize)) {
659 // Calculate heap size for local, stash, and stash entries
660 callback(
661 self.batches.len() * std::mem::size_of::<BytesBatch>(),
662 self.batches.capacity() * std::mem::size_of::<BytesBatch>(),
663 );
664 for batch in self.batches.iter() {
665 batch.offsets.heap_size(&mut callback);
666 callback(batch.storage.len(), batch.storage.capacity());
667 }
668 }
669 }
670
671 impl BatchContainer for BytesContainer {
672 type Owned = Vec<u8>;
673 type ReadItem<'a> = &'a [u8];
674
675 #[inline]
676 fn into_owned<'a>(item: Self::ReadItem<'a>) -> Self::Owned {
677 item.to_vec()
678 }
679
680 #[inline]
681 fn clone_onto<'a>(item: Self::ReadItem<'a>, other: &mut Self::Owned) {
682 other.clear();
683 other.extend_from_slice(item);
684 }
685
686 #[inline(always)]
687 fn push_ref(&mut self, item: Self::ReadItem<'_>) {
688 self.push_into(item);
689 }
690
691 #[inline(always)]
692 fn push_own(&mut self, item: &Self::Owned) {
693 self.push_into(item.as_slice())
694 }
695
696 fn clear(&mut self) {
697 self.batches.clear();
698 self.batches.push(BytesBatch::with_capacities(0, 0));
699 self.length = 0;
700 }
701
702 fn with_capacity(size: usize) -> Self {
703 Self {
704 length: 0,
705 batches: vec![BytesBatch::with_capacities(size, size)],
706 }
707 }
708
709 fn merge_capacity(cont1: &Self, cont2: &Self) -> Self {
710 let mut item_cap = 1;
711 let mut byte_cap = 0;
712 for batch in cont1.batches.iter() {
713 item_cap += batch.offsets.len() - 1;
714 byte_cap += batch.storage.len();
715 }
716 for batch in cont2.batches.iter() {
717 item_cap += batch.offsets.len() - 1;
718 byte_cap += batch.storage.len();
719 }
720 Self {
721 length: 0,
722 batches: vec![BytesBatch::with_capacities(item_cap, byte_cap)],
723 }
724 }
725
726 #[inline(always)]
727 fn reborrow<'b, 'a: 'b>(item: Self::ReadItem<'a>) -> Self::ReadItem<'b> {
728 item
729 }
730
731 #[inline]
732 fn index(&self, mut index: usize) -> Self::ReadItem<'_> {
733 for batch in self.batches.iter() {
734 if index < batch.len() {
735 return batch.index(index);
736 }
737 index -= batch.len();
738 }
739 panic!("Index out of bounds");
740 }
741
742 #[inline(always)]
743 fn len(&self) -> usize {
744 self.length
745 }
746 }
747
748 impl PushInto<&[u8]> for BytesContainer {
749 #[inline]
750 fn push_into(&mut self, item: &[u8]) {
751 self.length += 1;
752 if let Some(batch) = self.batches.last_mut() {
753 let success = batch.try_push(item);
754 if !success {
755 // double the lengths from `batch`.
756 let item_cap = 2 * batch.offsets.len();
757 let byte_cap = std::cmp::max(2 * batch.storage.capacity(), item.len());
758 let mut new_batch = BytesBatch::with_capacities(item_cap, byte_cap);
759 assert!(new_batch.try_push(item));
760 self.batches.push(new_batch);
761 }
762 }
763 }
764 }
765
766 /// A batch of slice storage.
767 ///
768 /// The backing storage for this batch will not be resized.
769 pub struct BytesBatch {
770 offsets: crate::OffsetOptimized,
771 storage: Region<u8>,
772 len: usize,
773 }
774
775 impl BytesBatch {
776 /// Either accepts the slice and returns true,
777 /// or does not and returns false.
778 fn try_push(&mut self, slice: &[u8]) -> bool {
779 if self.storage.len() + slice.len() <= self.storage.capacity() {
780 self.storage.extend_from_slice(slice);
781 self.offsets.push_into(self.storage.len());
782 self.len += 1;
783 true
784 } else {
785 false
786 }
787 }
788 #[inline]
789 fn index(&self, index: usize) -> &[u8] {
790 let lower = self.offsets.index(index);
791 let upper = self.offsets.index(index + 1);
792 &self.storage[lower..upper]
793 }
794 #[inline(always)]
795 fn len(&self) -> usize {
796 mz_ore::soft_assert_eq_no_log!(self.len, self.offsets.len() - 1);
797 self.len
798 }
799
800 fn with_capacities(item_cap: usize, byte_cap: usize) -> Self {
801 // TODO: be wary of `byte_cap` greater than 2^32.
802 let mut offsets = crate::OffsetOptimized::with_capacity(item_cap + 1);
803 offsets.push_into(0);
804 Self {
805 offsets,
806 storage: Region::new_auto(byte_cap.next_power_of_two()),
807 len: 0,
808 }
809 }
810 }
811}
812
813mod offset_opt {
814 use differential_dataflow::trace::implementations::BatchContainer;
815 use differential_dataflow::trace::implementations::OffsetList;
816 use timely::container::PushInto;
817
818 enum OffsetStride {
819 Empty,
820 Zero,
821 Striding(usize, usize),
822 Saturated(usize, usize, usize),
823 }
824
825 impl OffsetStride {
826 /// Accepts or rejects a newly pushed element.
827 #[inline]
828 fn push(&mut self, item: usize) -> bool {
829 match self {
830 OffsetStride::Empty => {
831 if item == 0 {
832 *self = OffsetStride::Zero;
833 true
834 } else {
835 false
836 }
837 }
838 OffsetStride::Zero => {
839 *self = OffsetStride::Striding(item, 2);
840 true
841 }
842 OffsetStride::Striding(stride, count) => {
843 if item == *stride * *count {
844 *count += 1;
845 true
846 } else if item == *stride * (*count - 1) {
847 *self = OffsetStride::Saturated(*stride, *count, 1);
848 true
849 } else {
850 false
851 }
852 }
853 OffsetStride::Saturated(stride, count, reps) => {
854 if item == *stride * (*count - 1) {
855 *reps += 1;
856 true
857 } else {
858 false
859 }
860 }
861 }
862 }
863
864 #[inline]
865 fn index(&self, index: usize) -> usize {
866 match self {
867 OffsetStride::Empty => {
868 panic!("Empty OffsetStride")
869 }
870 OffsetStride::Zero => 0,
871 OffsetStride::Striding(stride, _steps) => *stride * index,
872 OffsetStride::Saturated(stride, steps, _reps) => {
873 if index < *steps {
874 *stride * index
875 } else {
876 *stride * (*steps - 1)
877 }
878 }
879 }
880 }
881
882 #[inline]
883 fn len(&self) -> usize {
884 match self {
885 OffsetStride::Empty => 0,
886 OffsetStride::Zero => 1,
887 OffsetStride::Striding(_stride, steps) => *steps,
888 OffsetStride::Saturated(_stride, steps, reps) => *steps + *reps,
889 }
890 }
891 }
892
893 pub struct OffsetOptimized {
894 strided: OffsetStride,
895 spilled: OffsetList,
896 }
897
898 impl BatchContainer for OffsetOptimized {
899 type Owned = usize;
900 type ReadItem<'a> = usize;
901
902 #[inline]
903 fn into_owned<'a>(item: Self::ReadItem<'a>) -> Self::Owned {
904 item
905 }
906
907 #[inline]
908 fn push_ref(&mut self, item: Self::ReadItem<'_>) {
909 self.push_into(item)
910 }
911
912 #[inline]
913 fn push_own(&mut self, item: &Self::Owned) {
914 self.push_into(*item)
915 }
916
917 fn clear(&mut self) {
918 self.strided = OffsetStride::Empty;
919 self.spilled.clear();
920 }
921
922 fn with_capacity(_size: usize) -> Self {
923 Self {
924 strided: OffsetStride::Empty,
925 spilled: OffsetList::with_capacity(0),
926 }
927 }
928
929 fn merge_capacity(_cont1: &Self, _cont2: &Self) -> Self {
930 Self {
931 strided: OffsetStride::Empty,
932 spilled: OffsetList::with_capacity(0),
933 }
934 }
935
936 #[inline]
937 fn reborrow<'b, 'a: 'b>(item: Self::ReadItem<'a>) -> Self::ReadItem<'b> {
938 item
939 }
940
941 #[inline]
942 fn index(&self, index: usize) -> Self::ReadItem<'_> {
943 if index < self.strided.len() {
944 self.strided.index(index)
945 } else {
946 self.spilled.index(index - self.strided.len())
947 }
948 }
949
950 #[inline]
951 fn len(&self) -> usize {
952 self.strided.len() + self.spilled.len()
953 }
954 }
955
956 impl PushInto<usize> for OffsetOptimized {
957 #[inline]
958 fn push_into(&mut self, item: usize) {
959 if !self.spilled.is_empty() {
960 self.spilled.push(item);
961 } else {
962 let inserted = self.strided.push(item);
963 if !inserted {
964 self.spilled.push(item);
965 }
966 }
967 }
968 }
969
970 impl OffsetOptimized {
971 pub fn heap_size(&self, callback: impl FnMut(usize, usize)) {
972 crate::offset_list_size(&self.spilled, callback);
973 }
974 }
975}
976
977/// Helper to compute the size of an [`OffsetList`] in memory.
978#[inline]
979pub(crate) fn offset_list_size(data: &OffsetList, mut callback: impl FnMut(usize, usize)) {
980 // Private `vec_size` because we should only use it where data isn't region-allocated.
981 // `T: Copy` makes sure the implementation is correct even if types change!
982 #[inline(always)]
983 fn vec_size<T: Copy>(data: &Vec<T>, mut callback: impl FnMut(usize, usize)) {
984 let size_of_t = std::mem::size_of::<T>();
985 callback(data.len() * size_of_t, data.capacity() * size_of_t);
986 }
987
988 vec_size(&data.smol, &mut callback);
989 vec_size(&data.chonk, callback);
990}
991
992/// A `Row`-specialized container using dictionary compression.
993///
994/// The approach is to establish for each column lists of common values, and to use "unoccupied"
995/// tags in the row encoding (e.g. where we would indicate types) to replace these common values.
996/// This substitution is opt-in, in that we don't need to do it, and in particular do not do it
997/// while we are collecting preliminary information about common values, and then start to use it
998/// once we believe we have enough information. Once we have started to use the substitutions we
999/// cannot change the meaning of a reserved byte pattern, for the container we are populating.
1000///
1001/// Each from-scratch container observes `STATS_THRESHOLD` records before establishing a mapping
1002/// from spare tags to common values. Containers that are formed from merging other containers
1003/// use those input containers' common values to populate a codec and use it immediately.
1004///
1005/// The dictionary behavior is controlled by the `DICTIONARY_COMPRESSION` flag, which if disabled
1006/// prevents the construction of codecs, which when absent simply cause the wrapper to behave as
1007/// a no-op that fails to use any spare tags for common values. The flag is set once, when a
1008/// replica is created (from compute's `InstanceConfig::arrangement_dictionary_compression`, itself
1009/// captured from the `enable_arrangement_dictionary_compression_alpha` dyncfg at that moment), and is
1010/// not changed for the life of the process; flipping the dyncfg only affects replicas created
1011/// afterwards. Even with the flag fixed, a single replica can hold a mix of compressed and
1012/// uncompressed containers — e.g. containers that never observed enough records to install a
1013/// codec, or that were merged from uncompressed inputs.
1014mod dictionary {
1015
1016 use differential_dataflow::trace::implementations::BatchContainer;
1017
1018 use mz_repr::{Row, RowRef};
1019
1020 use super::row_codec::{ColumnsCodec, ColumnsIter};
1021
1022 /// Wrapper types that exist to support the creation of dictionary codecs.
1023 ///
1024 /// These types interpose at the seal() call, to traverse the data that is being sealed and
1025 /// then construct codecs that are used to encode the row-shaped keys and values. There are
1026 /// several variants, corresponding to the RowRow, RowVal, and Row-only spine types.
1027 pub mod builders {
1028 use columnar::{Columnar, Index};
1029 use columnation::Columnation;
1030 use differential_dataflow::difference::Semigroup;
1031 use differential_dataflow::lattice::Lattice;
1032 use differential_dataflow::trace::Builder;
1033 use differential_dataflow::trace::implementations::BatchContainer;
1034 use differential_dataflow::trace::implementations::merge_batcher::Sealer;
1035 use differential_dataflow::trace::implementations::ord_neu::{
1036 BuilderInput, OrdValBatch, OrdValBuilder,
1037 };
1038 use differential_dataflow::trace::implementations::ord_neu::{OrdKeyBatch, OrdKeyBuilder};
1039 use mz_timely_util::columnar::Column;
1040 use mz_timely_util::columnar::body::ColumnBody;
1041 use mz_timely_util::columnar::chunk::ChainState;
1042 use mz_timely_util::columnation::ColumnationStack as TimelyStack;
1043 use timely::progress::Timestamp;
1044
1045 use mz_repr::{Row, RowRef};
1046
1047 use super::super::row_codec::ColumnsCodec;
1048 use super::{DatumContainer, DatumSeq};
1049 use crate::DICTIONARY_COMPRESSION;
1050 use crate::spines::{RowLayout, RowRowLayout, RowValLayout, ValRowLayout};
1051
1052 /// Gather encoding statistics across `rows` and produce a codec from them.
1053 ///
1054 /// Accepts anything that borrows as a [`RowRef`], so it serves both the
1055 /// columnation-fed builders (which yield `&Row`) and the paged builders
1056 /// (which yield `&RowRef` straight out of a [`Column`] chunk).
1057 ///
1058 /// Returns `None` when dictionary compression is disabled.
1059 fn build_codec<'a, B>(rows: impl IntoIterator<Item = &'a B>) -> Option<ColumnsCodec>
1060 where
1061 B: std::borrow::Borrow<RowRef> + ?Sized + 'a,
1062 {
1063 if !DICTIONARY_COMPRESSION.load(std::sync::atomic::Ordering::Relaxed) {
1064 return None;
1065 }
1066 let mut stats = ColumnsCodec::default();
1067 observe_rows(&mut stats, rows);
1068 Some(ColumnsCodec::new_from([&stats]))
1069 }
1070
1071 /// Fold `rows` into `stats`, the accumulator a codec is built from.
1072 fn observe_rows<'a, B>(stats: &mut ColumnsCodec, rows: impl IntoIterator<Item = &'a B>)
1073 where
1074 B: std::borrow::Borrow<RowRef> + ?Sized + 'a,
1075 {
1076 for row in rows {
1077 let row = row.borrow();
1078 if !row.is_empty() {
1079 // Gather stats only; the encoded output would be thrown away here, so
1080 // `observe` skips the per-value lookup and the throwaway-buffer memcpy
1081 // that `encode` would do (see `ColumnsCodec::observe`).
1082 stats.observe(DatumSeq::borrow_as(row).bytes_iter());
1083 }
1084 }
1085 }
1086
1087 pub struct RowRowBuilder<T, R>
1088 where
1089 T: Lattice + Timestamp + Columnation,
1090 R: Ord + Semigroup + Columnation + 'static,
1091 {
1092 inner: OrdValBuilder<RowRowLayout<((Row, Row), T, R)>, TimelyStack<((Row, Row), T, R)>>,
1093 }
1094
1095 impl<T, R> Builder for RowRowBuilder<T, R>
1096 where
1097 T: Lattice + Timestamp + Columnation,
1098 R: Ord + Semigroup + Columnation + 'static,
1099 {
1100 type Input = TimelyStack<((Row, Row), T, R)>;
1101 type Time = T;
1102 type Output = OrdValBatch<RowRowLayout<((Row, Row), T, R)>>;
1103
1104 fn push(&mut self, chunk: &mut Self::Input) {
1105 self.inner.push(chunk)
1106 }
1107 fn done(self) -> Option<Self::Output> {
1108 // The push/done build path (e.g. the `reduce` operator, which builds
1109 // batches with `Builder::new()` + `push` + `done` rather than `seal`)
1110 // never runs `seal`'s codec install. Install a codec here from the
1111 // statistics gathered during `push`, mirroring `seal` — but without
1112 // building a dictionary or re-encoding the rows; see
1113 // `DatumContainer::promote_stats_to_codec` for why a codec-less batch
1114 // must be avoided even though its rows stay raw.
1115 let mut inner = self.inner;
1116 inner.result.keys.promote_stats_to_codec();
1117 inner.result.vals.vals.promote_stats_to_codec();
1118 inner.done()
1119 }
1120 }
1121
1122 impl<T, R> Default for RowRowBuilder<T, R>
1123 where
1124 T: Lattice + Timestamp + Columnation,
1125 R: Ord + Semigroup + Columnation + 'static,
1126 {
1127 fn default() -> Self {
1128 Self {
1129 inner: Default::default(),
1130 }
1131 }
1132 }
1133
1134 impl<T, R> Sealer<TimelyStack<((Row, Row), T, R)>> for RowRowBuilder<T, R>
1135 where
1136 T: Lattice + Timestamp + Columnation,
1137 R: Ord + Semigroup + Columnation + 'static,
1138 {
1139 type Output = OrdValBatch<RowRowLayout<((Row, Row), T, R)>>;
1140
1141 fn seal(chain: &mut Vec<TimelyStack<((Row, Row), T, R)>>) -> Option<Self::Output> {
1142 let key_codec = build_codec(
1143 chain
1144 .iter()
1145 .flat_map(|link| link.iter().map(|((k, _), _, _)| k)),
1146 );
1147 let val_codec = build_codec(
1148 chain
1149 .iter()
1150 .flat_map(|link| link.iter().map(|((_, v), _, _)| v)),
1151 );
1152
1153 let (keys, vals, upds) =
1154 <_ as BuilderInput<DatumContainer, DatumContainer>>::key_val_upd_counts(
1155 &chain[..],
1156 );
1157 let mut builder = Self {
1158 inner: OrdValBuilder::with_capacity(keys, vals, upds),
1159 };
1160 // The seal path installs a codec directly, so the per-container stats
1161 // gatherer (which `with_capacity` may have allocated) is dead weight and
1162 // would contradict the `stats: None once codec installed` invariant.
1163 builder.inner.result.keys.codec = key_codec;
1164 builder.inner.result.keys.stats = None;
1165 builder.inner.result.vals.vals.codec = val_codec;
1166 builder.inner.result.vals.vals.stats = None;
1167
1168 for mut chunk in chain.drain(..) {
1169 builder.push(&mut chunk);
1170 }
1171
1172 builder.done()
1173 }
1174 }
1175
1176 pub struct RowValBuilder<V, T, R>
1177 where
1178 V: Ord + Clone + Columnation + 'static,
1179 T: Lattice + Timestamp + Columnation,
1180 R: Ord + Semigroup + Columnation + 'static,
1181 {
1182 inner: OrdValBuilder<RowValLayout<((Row, V), T, R)>, TimelyStack<((Row, V), T, R)>>,
1183 }
1184
1185 impl<V, T, R> Builder for RowValBuilder<V, T, R>
1186 where
1187 V: Ord + Clone + Columnation,
1188 T: Lattice + Timestamp + Columnation,
1189 R: Ord + Semigroup + Columnation + 'static,
1190 {
1191 type Input = TimelyStack<((Row, V), T, R)>;
1192 type Time = T;
1193 type Output = OrdValBatch<RowValLayout<((Row, V), T, R)>>;
1194
1195 fn push(&mut self, chunk: &mut Self::Input) {
1196 self.inner.push(chunk)
1197 }
1198 fn done(self) -> Option<Self::Output> {
1199 // See `RowRowBuilder::done`: install a codec on the `Row`-shaped key
1200 // container for the push/done (e.g. `reduce`) path that skips `seal`.
1201 let mut inner = self.inner;
1202 inner.result.keys.promote_stats_to_codec();
1203 inner.done()
1204 }
1205 }
1206
1207 impl<V, T, R> Default for RowValBuilder<V, T, R>
1208 where
1209 V: Ord + Clone + Columnation,
1210 T: Lattice + Timestamp + Columnation,
1211 R: Ord + Semigroup + Columnation + 'static,
1212 {
1213 fn default() -> Self {
1214 Self {
1215 inner: Default::default(),
1216 }
1217 }
1218 }
1219
1220 impl<V, T, R> Sealer<TimelyStack<((Row, V), T, R)>> for RowValBuilder<V, T, R>
1221 where
1222 V: Ord + Clone + Columnation,
1223 T: Lattice + Timestamp + Columnation,
1224 R: Ord + Semigroup + Columnation + 'static,
1225 {
1226 type Output = OrdValBatch<RowValLayout<((Row, V), T, R)>>;
1227
1228 fn seal(chain: &mut Vec<TimelyStack<((Row, V), T, R)>>) -> Option<Self::Output> {
1229 let key_codec = build_codec(
1230 chain
1231 .iter()
1232 .flat_map(|link| link.iter().map(|((k, _), _, _)| k)),
1233 );
1234
1235 let (keys, vals, upds) =
1236 <_ as BuilderInput<DatumContainer, TimelyStack<V>>>::key_val_upd_counts(
1237 &chain[..],
1238 );
1239 let mut builder = Self {
1240 inner: OrdValBuilder::with_capacity(keys, vals, upds),
1241 };
1242 // See `RowRowBuilder::seal`: drop the now-redundant stats gatherer.
1243 builder.inner.result.keys.codec = key_codec;
1244 builder.inner.result.keys.stats = None;
1245
1246 for mut chunk in chain.drain(..) {
1247 builder.push(&mut chunk);
1248 }
1249
1250 builder.done()
1251 }
1252 }
1253
1254 pub struct RowBuilder<T, R, DC = TimelyStack<R>>
1255 where
1256 T: Lattice + Timestamp + Columnation,
1257 R: Ord + Semigroup + Columnation + 'static,
1258 DC: BatchContainer<Owned = R>,
1259 {
1260 inner: OrdKeyBuilder<RowLayout<((Row, ()), T, R), DC>, TimelyStack<((Row, ()), T, R)>>,
1261 }
1262
1263 impl<T, R, DC> Builder for RowBuilder<T, R, DC>
1264 where
1265 T: Lattice + Timestamp + Columnation,
1266 R: Ord + Semigroup + Columnation + 'static,
1267 DC: BatchContainer<Owned = R>,
1268 {
1269 type Input = TimelyStack<((Row, ()), T, R)>;
1270 type Time = T;
1271 type Output = OrdKeyBatch<RowLayout<((Row, ()), T, R), DC>>;
1272
1273 fn push(&mut self, chunk: &mut Self::Input) {
1274 self.inner.push(chunk)
1275 }
1276 fn done(self) -> Option<Self::Output> {
1277 // See `RowRowBuilder::done`: install a codec on the `Row`-shaped key
1278 // container for the push/done (e.g. `reduce`) path that skips `seal`.
1279 let mut inner = self.inner;
1280 inner.result.keys.promote_stats_to_codec();
1281 inner.done()
1282 }
1283 }
1284
1285 impl<T, R, DC> Default for RowBuilder<T, R, DC>
1286 where
1287 T: Lattice + Timestamp + Columnation,
1288 R: Ord + Semigroup + Columnation + 'static,
1289 DC: BatchContainer<Owned = R>,
1290 {
1291 fn default() -> Self {
1292 Self {
1293 inner: Default::default(),
1294 }
1295 }
1296 }
1297
1298 impl<T, R, DC> Sealer<TimelyStack<((Row, ()), T, R)>> for RowBuilder<T, R, DC>
1299 where
1300 T: Lattice + Timestamp + Columnation,
1301 R: Ord + Semigroup + Columnation + 'static,
1302 DC: BatchContainer<Owned = R>,
1303 {
1304 type Output = OrdKeyBatch<RowLayout<((Row, ()), T, R), DC>>;
1305
1306 fn seal(chain: &mut Vec<TimelyStack<((Row, ()), T, R)>>) -> Option<Self::Output> {
1307 let key_codec = build_codec(
1308 chain
1309 .iter()
1310 .flat_map(|link| link.iter().map(|((k, _), _, _)| k)),
1311 );
1312
1313 let (keys, vals, upds) =
1314 <_ as BuilderInput<DatumContainer, TimelyStack<()>>>::key_val_upd_counts(
1315 &chain[..],
1316 );
1317 let mut builder = Self {
1318 inner: OrdKeyBuilder::with_capacity(keys, vals, upds),
1319 };
1320 // See `RowRowBuilder::seal`: drop the now-redundant stats gatherer.
1321 builder.inner.result.keys.codec = key_codec;
1322 builder.inner.result.keys.stats = None;
1323
1324 for mut chunk in chain.drain(..) {
1325 builder.push(&mut chunk);
1326 }
1327
1328 builder.done()
1329 }
1330 }
1331
1332 /// Mirror of [`RowValBuilder`] with the roles swapped: arbitrary keys and
1333 /// `Row` *values*, so the dictionary codec is built for and installed on the
1334 /// value container.
1335 pub struct ValRowBuilder<K, T, R>
1336 where
1337 K: Ord + Clone + Columnation + 'static,
1338 T: Lattice + Timestamp + Columnation,
1339 R: Ord + Semigroup + Columnation + 'static,
1340 {
1341 inner: OrdValBuilder<ValRowLayout<((K, Row), T, R)>, TimelyStack<((K, Row), T, R)>>,
1342 }
1343
1344 impl<K, T, R> Builder for ValRowBuilder<K, T, R>
1345 where
1346 K: Ord + Clone + Columnation,
1347 T: Lattice + Timestamp + Columnation,
1348 R: Ord + Semigroup + Columnation + 'static,
1349 {
1350 type Input = TimelyStack<((K, Row), T, R)>;
1351 type Time = T;
1352 type Output = OrdValBatch<ValRowLayout<((K, Row), T, R)>>;
1353
1354 fn push(&mut self, chunk: &mut Self::Input) {
1355 self.inner.push(chunk)
1356 }
1357 fn done(self) -> Option<Self::Output> {
1358 // See `RowRowBuilder::done`: install a codec on the `Row`-shaped value
1359 // container for the push/done (e.g. `reduce`) path that skips `seal`.
1360 let mut inner = self.inner;
1361 inner.result.vals.vals.promote_stats_to_codec();
1362 inner.done()
1363 }
1364 }
1365
1366 impl<K, T, R> Default for ValRowBuilder<K, T, R>
1367 where
1368 K: Ord + Clone + Columnation,
1369 T: Lattice + Timestamp + Columnation,
1370 R: Ord + Semigroup + Columnation + 'static,
1371 {
1372 fn default() -> Self {
1373 Self {
1374 inner: Default::default(),
1375 }
1376 }
1377 }
1378
1379 impl<K, T, R> Sealer<TimelyStack<((K, Row), T, R)>> for ValRowBuilder<K, T, R>
1380 where
1381 K: Ord + Clone + Columnation,
1382 T: Lattice + Timestamp + Columnation,
1383 R: Ord + Semigroup + Columnation + 'static,
1384 {
1385 type Output = OrdValBatch<ValRowLayout<((K, Row), T, R)>>;
1386
1387 fn seal(chain: &mut Vec<TimelyStack<((K, Row), T, R)>>) -> Option<Self::Output> {
1388 let val_codec = build_codec(
1389 chain
1390 .iter()
1391 .flat_map(|link| link.iter().map(|((_, v), _, _)| v)),
1392 );
1393
1394 let (keys, vals, upds) =
1395 <_ as BuilderInput<TimelyStack<K>, DatumContainer>>::key_val_upd_counts(
1396 &chain[..],
1397 );
1398 let mut builder = Self {
1399 inner: OrdValBuilder::with_capacity(keys, vals, upds),
1400 };
1401 // See `RowRowBuilder::seal`: drop the now-redundant stats gatherer.
1402 builder.inner.result.vals.vals.codec = val_codec;
1403 builder.inner.result.vals.vals.stats = None;
1404
1405 for mut chunk in chain.drain(..) {
1406 builder.push(&mut chunk);
1407 }
1408
1409 builder.done()
1410 }
1411 }
1412
1413 /// Counterpart of [`RowRowBuilder`] that consumes [`ColumnBody`] chunks
1414 /// instead of columnation stacks, whether or not the batcher that
1415 /// produced them spills. Mirrors `RowRowBuilder::seal`:
1416 /// it gathers key and value statistics from the sealed chain and
1417 /// installs codecs directly, then drops the per-container stats gatherer.
1418 pub struct RowRowColPagedBuilder<T, R>
1419 where
1420 T: Lattice + Timestamp + Columnation + Columnar,
1421 R: Ord + Semigroup + Columnation + Columnar + Clone + 'static,
1422 {
1423 inner: OrdValBuilder<RowRowLayout<((Row, Row), T, R)>, ColumnBody<((Row, Row), T, R)>>,
1424 }
1425
1426 impl<T, R> Builder for RowRowColPagedBuilder<T, R>
1427 where
1428 T: Lattice + Timestamp + Columnation + Columnar,
1429 R: Ord + Semigroup + Columnation + Columnar + Clone + 'static,
1430 {
1431 type Input = ColumnBody<((Row, Row), T, R)>;
1432 type Time = T;
1433 type Output = OrdValBatch<RowRowLayout<((Row, Row), T, R)>>;
1434
1435 fn push(&mut self, chunk: &mut Self::Input) {
1436 self.inner.push(chunk)
1437 }
1438 fn done(self) -> Option<Self::Output> {
1439 // See `RowRowBuilder::done`: a builder driven by `push` and `done`
1440 // alone gets its codec from the statistics gathered during the
1441 // pushes, since a codec-less batch poisons the merges it joins.
1442 // Installing a codec here is a no-op once one is installed.
1443 let mut inner = self.inner;
1444 inner.result.keys.promote_stats_to_codec();
1445 inner.result.vals.vals.promote_stats_to_codec();
1446 inner.done()
1447 }
1448 }
1449
1450 impl<T, R> Default for RowRowColPagedBuilder<T, R>
1451 where
1452 T: Lattice + Timestamp + Columnation + Columnar,
1453 R: Ord + Semigroup + Columnation + Columnar + Clone + 'static,
1454 {
1455 fn default() -> Self {
1456 Self {
1457 inner: Default::default(),
1458 }
1459 }
1460 }
1461
1462 impl<T, R> Sealer<ColumnBody<((Row, Row), T, R)>> for RowRowColPagedBuilder<T, R>
1463 where
1464 T: Lattice + Timestamp + Columnation + Columnar,
1465 R: Ord + Semigroup + Columnation + Columnar + Clone + 'static,
1466 {
1467 type Output = OrdValBatch<RowRowLayout<((Row, Row), T, R)>>;
1468
1469 fn seal(chain: &mut Vec<ColumnBody<((Row, Row), T, R)>>) -> Option<Self::Output> {
1470 // `into_index_iter` yields the value column's `Row`s as `&RowRef`,
1471 // which `build_codec` consumes directly.
1472 let key_codec = build_codec(
1473 chain
1474 .iter()
1475 .flat_map(|c| c.borrow().into_index_iter().map(|((k, _), _, _)| k)),
1476 );
1477 let val_codec = build_codec(
1478 chain
1479 .iter()
1480 .flat_map(|c| c.borrow().into_index_iter().map(|((_, v), _, _)| v)),
1481 );
1482
1483 let (keys, vals, upds) =
1484 <_ as BuilderInput<DatumContainer, DatumContainer>>::key_val_upd_counts(
1485 &chain[..],
1486 );
1487 let mut builder = Self {
1488 inner: OrdValBuilder::with_capacity(keys, vals, upds),
1489 };
1490 // See `RowRowBuilder::seal`: install the codecs and drop the
1491 // now-redundant per-container stats gatherer.
1492 builder.inner.result.keys.codec = key_codec;
1493 builder.inner.result.keys.stats = None;
1494 builder.inner.result.vals.vals.codec = val_codec;
1495 builder.inner.result.vals.vals.stats = None;
1496
1497 for mut chunk in chain.drain(..) {
1498 builder.push(&mut chunk);
1499 }
1500
1501 builder.done()
1502 }
1503 }
1504
1505 /// The chain-wide state of [`RowRowColPagedBuilder`]: the statistics its
1506 /// key and value codecs are built from, and the container sizes the
1507 /// chain implies.
1508 ///
1509 /// [`RowRowColPagedBuilder`]: crate::RowRowColPagedBuilder
1510 #[derive(Default)]
1511 pub struct RowRowColPagedState {
1512 keys: ColumnsCodec,
1513 vals: ColumnsCodec,
1514 /// Whether `keys` and `vals` hold statistics from any body.
1515 gathered: bool,
1516 counts: (usize, usize, usize),
1517 }
1518
1519 impl<T, R> ChainState for RowRowColPagedBuilder<T, R>
1520 where
1521 T: Lattice + Timestamp + Columnation + Columnar,
1522 R: Ord + Semigroup + Columnation + Columnar + Clone + 'static,
1523 {
1524 type State = RowRowColPagedState;
1525
1526 fn wants_bodies() -> bool {
1527 DICTIONARY_COMPRESSION.load(std::sync::atomic::Ordering::Relaxed)
1528 }
1529
1530 fn observe(state: &mut Self::State, input: &Self::Input) {
1531 if Self::wants_bodies() {
1532 // `into_index_iter` yields the key and value columns' `Row`s
1533 // as `&RowRef`, which `observe_rows` consumes directly.
1534 observe_rows(
1535 &mut state.keys,
1536 input.borrow().into_index_iter().map(|((k, _), _, _)| k),
1537 );
1538 observe_rows(
1539 &mut state.vals,
1540 input.borrow().into_index_iter().map(|((_, v), _, _)| v),
1541 );
1542 state.gathered = true;
1543 }
1544
1545 let (keys, vals, upds) =
1546 <_ as BuilderInput<DatumContainer, DatumContainer>>::key_val_upd_counts(
1547 std::slice::from_ref(input),
1548 );
1549 state.counts.0 += keys;
1550 state.counts.1 += vals;
1551 state.counts.2 += upds;
1552 }
1553
1554 fn observe_records(state: &mut Self::State, records: usize) {
1555 // Key and value counts need the bodies. Sizing the update
1556 // containers alone is what a record count buys.
1557 state.counts.2 += records;
1558 }
1559
1560 fn from_state(state: Self::State) -> Self {
1561 let mut builder = Self {
1562 inner: OrdValBuilder::with_capacity(
1563 state.counts.0,
1564 state.counts.1,
1565 state.counts.2,
1566 ),
1567 };
1568 // Install from the statistics that were gathered, not from the
1569 // compression flag: the flag is process-global and a worker can
1570 // flip it mid-seal, and a codec built from no observations would
1571 // carry an empty summary and displace the gatherer that `done`
1572 // would otherwise promote.
1573 if state.gathered {
1574 // See `RowRowBuilder::seal`: install the codecs the chain's
1575 // statistics imply and drop the now-redundant per-container
1576 // stats gatherer.
1577 builder.inner.result.keys.codec = Some(ColumnsCodec::new_from([&state.keys]));
1578 builder.inner.result.keys.stats = None;
1579 builder.inner.result.vals.vals.codec =
1580 Some(ColumnsCodec::new_from([&state.vals]));
1581 builder.inner.result.vals.vals.stats = None;
1582 }
1583 builder
1584 }
1585 }
1586
1587 /// Paged counterpart of [`ValRowBuilder`] that consumes [`Column`]
1588 /// chunks. Keys are arbitrary `Columnar` values (not `Row`-shaped) and
1589 /// stay uncompressed; only the value container receives a codec.
1590 pub struct ValRowColPagedBuilder<K, T, R>
1591 where
1592 K: Ord + Clone + Columnation + Columnar + 'static,
1593 T: Lattice + Timestamp + Columnation + Columnar,
1594 R: Ord + Semigroup + Columnation + Columnar + Clone + 'static,
1595 {
1596 inner: OrdValBuilder<ValRowLayout<((K, Row), T, R)>, Column<((K, Row), T, R)>>,
1597 }
1598
1599 impl<K, T, R> Builder for ValRowColPagedBuilder<K, T, R>
1600 where
1601 K: Ord + Clone + Columnation + Columnar + 'static,
1602 T: Lattice + Timestamp + Columnation + Columnar,
1603 R: Ord + Semigroup + Columnation + Columnar + Clone + 'static,
1604 for<'a> columnar::Ref<'a, K>: Copy + Ord,
1605 for<'a, 'b> &'a K: PartialEq<columnar::Ref<'b, K>>,
1606 for<'a> TimelyStack<K>: timely::container::PushInto<columnar::Ref<'a, K>>,
1607 {
1608 type Input = Column<((K, Row), T, R)>;
1609 type Time = T;
1610 type Output = OrdValBatch<ValRowLayout<((K, Row), T, R)>>;
1611
1612 fn push(&mut self, chunk: &mut Self::Input) {
1613 self.inner.push(chunk)
1614 }
1615 fn done(self) -> Option<Self::Output> {
1616 self.inner.done()
1617 }
1618 }
1619
1620 impl<K, T, R> Default for ValRowColPagedBuilder<K, T, R>
1621 where
1622 K: Ord + Clone + Columnation + Columnar + 'static,
1623 T: Lattice + Timestamp + Columnation + Columnar,
1624 R: Ord + Semigroup + Columnation + Columnar + Clone + 'static,
1625 for<'a> columnar::Ref<'a, K>: Copy + Ord,
1626 for<'a, 'b> &'a K: PartialEq<columnar::Ref<'b, K>>,
1627 for<'a> TimelyStack<K>: timely::container::PushInto<columnar::Ref<'a, K>>,
1628 {
1629 fn default() -> Self {
1630 Self {
1631 inner: Default::default(),
1632 }
1633 }
1634 }
1635
1636 impl<K, T, R> Sealer<Column<((K, Row), T, R)>> for ValRowColPagedBuilder<K, T, R>
1637 where
1638 K: Ord + Clone + Columnation + Columnar + 'static,
1639 T: Lattice + Timestamp + Columnation + Columnar,
1640 R: Ord + Semigroup + Columnation + Columnar + Clone + 'static,
1641 for<'a> columnar::Ref<'a, K>: Copy + Ord,
1642 for<'a, 'b> &'a K: PartialEq<columnar::Ref<'b, K>>,
1643 for<'a> TimelyStack<K>: timely::container::PushInto<columnar::Ref<'a, K>>,
1644 {
1645 type Output = OrdValBatch<ValRowLayout<((K, Row), T, R)>>;
1646
1647 fn seal(chain: &mut Vec<Column<((K, Row), T, R)>>) -> Option<Self::Output> {
1648 let val_codec = build_codec(
1649 chain
1650 .iter()
1651 .flat_map(|c| c.borrow().into_index_iter().map(|((_, v), _, _)| v)),
1652 );
1653
1654 let (keys, vals, upds) =
1655 <_ as BuilderInput<TimelyStack<K>, DatumContainer>>::key_val_upd_counts(
1656 &chain[..],
1657 );
1658 let mut builder = Self {
1659 inner: OrdValBuilder::with_capacity(keys, vals, upds),
1660 };
1661 // See `RowRowBuilder::seal`: drop the now-redundant stats gatherer.
1662 builder.inner.result.vals.vals.codec = val_codec;
1663 builder.inner.result.vals.vals.stats = None;
1664
1665 for mut chunk in chain.drain(..) {
1666 builder.push(&mut chunk);
1667 }
1668
1669 builder.done()
1670 }
1671 }
1672 }
1673
1674 pub struct DatumContainer {
1675 /// Encoder/decoder used to translate between row bytes and the stored bytes.
1676 /// `None` until enough pushes have been observed (or if compression is disabled).
1677 codec: Option<ColumnsCodec>,
1678 /// The stored, possibly-encoded, row bytes.
1679 inner: super::bytes_container::BytesContainer,
1680 /// Staging buffer for ingested `Row` types.
1681 staging: Vec<u8>,
1682 /// Statistics gatherer, used to build a safe codec after enough pushes.
1683 /// `None` once the codec has been installed or if compression is disabled.
1684 stats: Option<ColumnsCodec>,
1685 }
1686
1687 impl BatchContainer for DatumContainer {
1688 type Owned = Row;
1689 type ReadItem<'a> = DatumSeq<'a>;
1690
1691 fn with_capacity(size: usize) -> Self {
1692 let stats = if crate::DICTIONARY_COMPRESSION.load(std::sync::atomic::Ordering::Relaxed)
1693 {
1694 Some(Default::default())
1695 } else {
1696 None
1697 };
1698
1699 Self {
1700 codec: None,
1701 inner: BatchContainer::with_capacity(size),
1702 staging: Vec::new(),
1703 stats,
1704 }
1705 }
1706 fn merge_capacity(cont1: &Self, cont2: &Self) -> Self {
1707 // We only build a merged codec when *both* inputs carry one. A codec is
1708 // sound only for the data whose tag usage it observed, so we cannot reuse
1709 // one side's codec to decode the other side's rows. When exactly one side
1710 // is compressed we conservatively produce an uncompressed container rather
1711 // than risk a tag collision; the merged container re-gathers stats and may
1712 // install a fresh codec later via the `STATS_THRESHOLD` path.
1713 let codec = match (&cont1.codec, &cont2.codec) {
1714 (Some(c1), Some(c2)) => Some(ColumnsCodec::new_from([c1, c2])),
1715 _ => None,
1716 };
1717
1718 Self {
1719 codec,
1720 inner: BatchContainer::merge_capacity(&cont1.inner, &cont2.inner),
1721 staging: Vec::new(),
1722 stats: None,
1723 }
1724 }
1725 #[inline]
1726 fn index(&self, index: usize) -> Self::ReadItem<'_> {
1727 let data = self.inner.index(index);
1728 let iter = if let Some(codec) = &self.codec {
1729 codec.decode(data)
1730 } else {
1731 // Safety: without a codec we only push rows or datumseqs into `self.inner`.
1732 // Each retrieved byte slice should be row-encoded data, as long as we have
1733 // not unset the codec in the interim.
1734 unsafe { ColumnsIter::without_codec(data) }
1735 };
1736 DatumSeq { iter }
1737 }
1738 #[inline(always)]
1739 fn len(&self) -> usize {
1740 self.inner.len()
1741 }
1742
1743 #[inline(always)]
1744 fn reborrow<'b, 'a: 'b>(item: Self::ReadItem<'a>) -> Self::ReadItem<'b> {
1745 item
1746 }
1747
1748 #[inline(always)]
1749 fn into_owned<'a>(item: Self::ReadItem<'a>) -> Self::Owned {
1750 // Fast path: unencoded data is already row-formatted bytes.
1751 if item.iter.index.is_none() {
1752 // SAFETY: `iter.data` is raw row-encoded bytes when there is no codec.
1753 return unsafe { Row::from_bytes_unchecked(item.iter.data) };
1754 }
1755 Row::pack(item)
1756 }
1757
1758 #[inline(always)]
1759 fn clone_onto<'a>(item: Self::ReadItem<'a>, other: &mut Self::Owned) {
1760 // Fast path: unencoded data is already row-formatted bytes.
1761 if item.iter.index.is_none() {
1762 let mut packer = other.packer();
1763 // SAFETY: `iter.data` is raw row-encoded bytes when there is no codec.
1764 unsafe { packer.extend_by_slice_unchecked(item.iter.data) };
1765 return;
1766 }
1767 other.packer().extend(item);
1768 }
1769
1770 #[inline(always)]
1771 fn push_ref(&mut self, item: Self::ReadItem<'_>) {
1772 // Fast path: both sides unencoded — push raw bytes directly.
1773 if self.codec.is_none() && self.stats.is_none() && item.iter.index.is_none() {
1774 self.inner.push_ref(item.iter.data);
1775 return;
1776 }
1777 self.push_into(item);
1778 }
1779
1780 #[inline(always)]
1781 fn push_own(&mut self, item: &Self::Owned) {
1782 // Fast path: container is unencoded — push raw row bytes directly.
1783 if self.codec.is_none() && self.stats.is_none() {
1784 self.inner.push_ref(item.data());
1785 return;
1786 }
1787 self.push_into(item);
1788 }
1789
1790 #[inline(always)]
1791 fn clear(&mut self) {
1792 self.inner.clear();
1793 self.staging.clear();
1794 // Reset to the same state as a fresh `with_capacity`: drop any installed
1795 // codec and restore stats gathering (if compression is enabled). Keeping a
1796 // now-empty codec would leave `codec.is_some()`, which permanently routes
1797 // pushes down the encode path with an empty dictionary and prevents the
1798 // `STATS_THRESHOLD` install logic from ever re-engaging compression.
1799 self.codec = None;
1800 self.stats = if crate::DICTIONARY_COMPRESSION.load(std::sync::atomic::Ordering::Relaxed)
1801 {
1802 Some(Default::default())
1803 } else {
1804 None
1805 };
1806 }
1807 }
1808
1809 impl DatumContainer {
1810 /// Visit contained allocations to determine their size and capacity.
1811 #[inline]
1812 pub fn heap_size(&self, mut callback: impl FnMut(usize, usize)) {
1813 self.inner.heap_size(&mut callback);
1814 // The staging buffer and the (possibly absent) codec and stats gatherer all
1815 // hold heap allocations that the bare `inner` accounting misses.
1816 callback(self.staging.len(), self.staging.capacity());
1817 if let Some(codec) = &self.codec {
1818 codec.heap_size(&mut callback);
1819 }
1820 if let Some(stats) = &self.stats {
1821 stats.heap_size(&mut callback);
1822 }
1823 }
1824
1825 /// Promote a gathered-but-uninstalled statistics summary into the codec slot.
1826 ///
1827 /// A container filled via the builder's `push`/`done` path — as the `reduce`
1828 /// operator does, building batches with `Builder::new()` + `push` + `done`
1829 /// rather than `seal` — gathers statistics on every push but never reaches
1830 /// `seal`'s codec install, and only crosses the mid-formation
1831 /// `STATS_THRESHOLD` install if it grows past it. A smaller such container
1832 /// would otherwise be finalized with no codec at all, even with the flag on.
1833 ///
1834 /// That is a problem not because this batch needs compressing — its rows are
1835 /// already stored raw and we deliberately do *not* re-encode them here — but
1836 /// because a codec-less batch poisons future merges: [`Self::merge_capacity`]
1837 /// keys off the presence of a codec, so a codec-less input forces the merged
1838 /// container onto the uncompressed path. Moving the gathered statistics into
1839 /// the codec slot leaves the batch carrying a codec whose retained heavy-hitter
1840 /// summary a later merge can rebuild from via `ColumnsCodec::new_from`, while
1841 /// installing no dictionary: the empty `decode` map resolves every stored
1842 /// (raw) column through the literal-datum fall-through, so reads stay correct.
1843 ///
1844 /// We move the summary as-is rather than building a dictionary via `new_safe`
1845 /// / `new_from` (which reset the summary): unlike `seal` and the mid-formation
1846 /// install, `done` has no further rows to re-observe, so a reset summary would
1847 /// leave the eventual merge nothing to rebuild from.
1848 pub(crate) fn promote_stats_to_codec(&mut self) {
1849 if self.codec.is_none() {
1850 self.codec = self.stats.take();
1851 }
1852 }
1853
1854 /// Whether a codec is installed. A container without one stores raw
1855 /// bytes and blocks compression in every merge it takes part in.
1856 #[cfg(test)]
1857 pub(crate) fn has_codec(&self) -> bool {
1858 self.codec.is_some()
1859 }
1860 }
1861
1862 use timely::container::PushInto;
1863 impl PushInto<Row> for DatumContainer {
1864 #[inline(always)]
1865 fn push_into(&mut self, item: Row) {
1866 self.push_into(&item);
1867 }
1868 }
1869
1870 impl PushInto<&Row> for DatumContainer {
1871 #[inline(always)]
1872 fn push_into(&mut self, item: &Row) {
1873 self.push_into(DatumSeq::borrow_as(item));
1874 }
1875 }
1876
1877 impl PushInto<&RowRef> for DatumContainer {
1878 #[inline(always)]
1879 fn push_into(&mut self, item: &RowRef) {
1880 self.push_into(DatumSeq::borrow_as(item));
1881 }
1882 }
1883
1884 /// Number of pushes a from-scratch container observes before it turns its
1885 /// gathered stats into a safe codec.
1886 ///
1887 /// A safe codec has at most `256 - SAFE_TAG_BASE` (= 134) dictionary slots per
1888 /// column, so we only need to identify ~134 genuinely-popular values. The
1889 /// `MisraGries` summary retains up to `2 * k` (= 1024) distinct candidates
1890 /// between tidies and reduces to `k` (= 512), comfortably more than 134, so the
1891 /// threshold just needs to be large enough that heavy hitters accumulate counts
1892 /// well above 1 before we freeze the codec. 64Ki pushes gives that headroom while
1893 /// keeping the pre-codec (uncompressed) window short.
1894 const STATS_THRESHOLD: usize = 64 * 1024;
1895
1896 impl PushInto<DatumSeq<'_>> for DatumContainer {
1897 #[inline]
1898 fn push_into(&mut self, item: DatumSeq<'_>) {
1899 // Fast path: container and item are both unencoded.
1900 // This is the hot path when dictionary compression is disabled.
1901 if self.codec.is_none() && self.stats.is_none() && item.iter.index.is_none() {
1902 self.inner.push_ref(item.iter.data);
1903 return;
1904 }
1905
1906 // Check if we've gathered enough stats to install a safe codec.
1907 if self.codec.is_none() && self.stats.is_some() && self.inner.len() >= STATS_THRESHOLD {
1908 let stats = self.stats.take().unwrap();
1909 self.codec = Some(stats.new_safe());
1910 }
1911
1912 if let Some(codec) = &mut self.codec {
1913 // Encode using the installed codec.
1914 codec.encode(item.bytes_iter(), &mut self.staging);
1915 } else if let Some(stats) = &mut self.stats {
1916 // Stats-gathering phase: feed the statistics but store raw bytes.
1917 // `observe` updates the heavy-hitter/tag summaries without encoding, so
1918 // we copy each row exactly once (below) instead of also encoding it into
1919 // a buffer we would immediately discard.
1920 stats.observe(item.bytes_iter());
1921 for slice in item.bytes_iter() {
1922 self.staging.extend_from_slice(slice);
1923 }
1924 } else {
1925 // No codec, no stats: raw copy.
1926 for slice in item.bytes_iter() {
1927 self.staging.extend_from_slice(slice);
1928 }
1929 }
1930 self.inner.push_ref(&self.staging[..]);
1931 self.staging.clear();
1932 }
1933 }
1934
1935 use mz_repr::{Datum, read_datum};
1936
1937 /// A reference that can be resolved to a sequence of `Datum`s.
1938 ///
1939 /// This type must "compare" as if decoded to a `Row`, which means it needs to track
1940 /// various nuances of `Row::cmp`, which at the moment is first by length, and then by
1941 /// the raw binary slice backing the row. Neither of those are explicit in this struct.
1942 /// We will need to produce them in order to perform comparisons.
1943 #[derive(Debug)]
1944 pub struct DatumSeq<'a> {
1945 pub iter: ColumnsIter<'a>,
1946 }
1947
1948 impl<'a> DatumSeq<'a> {
1949 #[inline(always)]
1950 fn borrow_as(other: &'a RowRef) -> Self {
1951 Self {
1952 iter: ColumnsCodec::borrow_row(other),
1953 }
1954 }
1955
1956 /// Borrow a `Row` as a `DatumSeq` so that it can be used to seek into a
1957 /// trace whose key/value container is a [`DatumContainer`].
1958 #[inline]
1959 pub fn from_row(row: &'a Row) -> Self {
1960 Self::borrow_as(row)
1961 }
1962
1963 #[inline]
1964 pub fn to_row(&self) -> Row {
1965 // Fast path: unencoded data is already row-formatted bytes.
1966 if self.iter.index.is_none() {
1967 return unsafe { Row::from_bytes_unchecked(self.iter.data) };
1968 }
1969 Row::pack(*self)
1970 }
1971 }
1972
1973 impl<'a> Copy for DatumSeq<'a> {}
1974 impl<'a> Clone for DatumSeq<'a> {
1975 #[inline(always)]
1976 fn clone(&self) -> Self {
1977 *self
1978 }
1979 }
1980
1981 use std::cmp::Ordering;
1982 impl<'a, 'b> PartialEq<DatumSeq<'a>> for DatumSeq<'b> {
1983 #[inline(always)]
1984 fn eq(&self, other: &DatumSeq<'a>) -> bool {
1985 // Fast path: both sides are unencoded raw row bytes.
1986 if self.iter.index.is_none() && other.iter.index.is_none() {
1987 return self.iter.data == other.iter.data;
1988 }
1989 Iterator::eq(self.iter, other.iter)
1990 }
1991 }
1992 impl<'a> Eq for DatumSeq<'a> {}
1993 impl<'a, 'b> PartialOrd<DatumSeq<'a>> for DatumSeq<'b> {
1994 #[inline(always)]
1995 fn partial_cmp(&self, other: &DatumSeq<'a>) -> Option<Ordering> {
1996 // Fast path: both sides are unencoded raw row bytes.
1997 if self.iter.index.is_none() && other.iter.index.is_none() {
1998 let left = self.iter.data;
1999 let right = other.iter.data;
2000 return Some(match left.len().cmp(&right.len()) {
2001 Ordering::Equal => left.cmp(right),
2002 other => other,
2003 });
2004 }
2005 // Slow path: at least one side is dictionary-encoded.
2006 // Fused length + lexicographic comparison in a single pass per side.
2007 // Row ordering is: shorter < longer; equal lengths compared lexicographically.
2008 //
2009 // We compare byte-by-byte (via `flatten`) rather than slice-by-slice on
2010 // purpose: a dictionary tag expands to a multi-byte value on one side while
2011 // the other side may store those same bytes raw, so the per-column slice
2012 // boundaries do not line up between the two iterators. Decoding to a flat
2013 // byte stream is the only representation in which both sides are directly
2014 // comparable. This path is cold — it only runs when at least one operand is
2015 // dictionary-encoded; the common unencoded case is handled by the fast path
2016 // above with a single slice comparison.
2017 let mut left = self.iter.flatten();
2018 let mut right = other.iter.flatten();
2019 let mut first_diff = Ordering::Equal;
2020 loop {
2021 match (left.next(), right.next()) {
2022 (Some(l), Some(r)) => {
2023 if first_diff == Ordering::Equal {
2024 first_diff = l.cmp(r);
2025 }
2026 }
2027 // Left exhausted first: left is shorter, so Less.
2028 (None, Some(_)) => return Some(Ordering::Less),
2029 // Right exhausted first: right is shorter, so Greater.
2030 (Some(_), None) => return Some(Ordering::Greater),
2031 // Same length: use first lexicographic difference.
2032 (None, None) => return Some(first_diff),
2033 }
2034 }
2035 }
2036 }
2037 impl<'a> Ord for DatumSeq<'a> {
2038 #[inline(always)]
2039 fn cmp(&self, other: &Self) -> Ordering {
2040 self.partial_cmp(other).unwrap()
2041 }
2042 }
2043
2044 impl<'a> PartialEq<&'a Row> for DatumSeq<'a> {
2045 #[inline(always)]
2046 fn eq(&self, other: &&'a Row) -> bool {
2047 self.eq(&Self::borrow_as(*other))
2048 }
2049 }
2050
2051 // Lifetimes decoupled (`'b` independent of `'a`): the arrange machinery
2052 // requires `for<'b> DatumSeq<'a>: PartialEq<&'b RowRef>`, i.e. a fixed
2053 // `DatumSeq` must compare against a `&RowRef` of any lifetime.
2054 impl<'a, 'b> PartialEq<&'b RowRef> for DatumSeq<'a> {
2055 #[inline(always)]
2056 fn eq(&self, other: &&'b RowRef) -> bool {
2057 self.eq(&DatumSeq::borrow_as(*other))
2058 }
2059 }
2060
2061 impl<'a> DatumSeq<'a> {
2062 #[inline(always)]
2063 pub fn bytes_iter(self) -> ColumnsIter<'a> {
2064 self.iter
2065 }
2066 }
2067
2068 impl<'a> Iterator for DatumSeq<'a> {
2069 type Item = Datum<'a>;
2070 #[inline(always)]
2071 fn next(&mut self) -> Option<Self::Item> {
2072 // Delegate to `ColumnsIter`, which handles both the codec and no-codec
2073 // cases. The no-codec scan hot path is served directly by `extend_datums`
2074 // (which decodes without going through this iterator), so the only callers
2075 // left here are the codec-encoded `extend_datums`/`to_row` paths and tests;
2076 // none warrant a dedicated no-codec fast path.
2077 self.iter
2078 .next()
2079 .map(|mut bytes| unsafe { read_datum(&mut bytes) })
2080 }
2081 }
2082
2083 use mz_repr::RowArena;
2084 use mz_repr::fixed_length::ExtendDatums;
2085 impl<'long> ExtendDatums for DatumSeq<'long> {
2086 #[inline]
2087 fn extend_datums<'a>(
2088 &'a self,
2089 _arena: &'a RowArena,
2090 target: &mut Vec<Datum<'a>>,
2091 max: Option<usize>,
2092 ) {
2093 // Branch on codec presence ONCE per row rather than once per datum.
2094 // With no codec (the common, feature-off case) push raw datums in a
2095 // tight loop, matching the pre-dictionary path; with a codec, fall
2096 // back to the per-column iterator. This keeps the codec check out of
2097 // the per-datum loop — the source of the feature-off scan overhead.
2098 if self.iter.index.is_none() {
2099 let mut data = self.iter.data;
2100 match max {
2101 Some(max) => {
2102 let mut n = 0;
2103 while n < max && !data.is_empty() {
2104 target.push(unsafe { read_datum(&mut data) });
2105 n += 1;
2106 }
2107 }
2108 None => {
2109 while !data.is_empty() {
2110 target.push(unsafe { read_datum(&mut data) });
2111 }
2112 }
2113 }
2114 } else {
2115 match max {
2116 Some(max) => target.extend((*self).take(max)),
2117 None => target.extend(*self),
2118 }
2119 }
2120 }
2121 }
2122}
2123
2124/// Traits abstracting the processes of encoding and decoding row-encoded byte sequences.
2125///
2126/// It is unsafe to use these types to encode byte sequences that are not row-encoded,
2127/// as they are parsed out of contiguous `[u8]` slices using `mz_repr::read_datum`.
2128mod row_codec {
2129
2130 pub use self::misra_gries::MisraGries;
2131 pub use columns::{ColumnsCodec, ColumnsIter};
2132 pub use dictionary::DictionaryCodec;
2133 #[cfg(test)]
2134 pub use dictionary::SAFE_TAG_BASE;
2135
2136 // Deterministic hasher state for the codecs' hash maps: a fixed-seed
2137 // `ahash::RandomState` shared with `mz_timely_util`'s consolidation hasher, so
2138 // the heavy-hitter summaries — and therefore which values each codec compresses
2139 // — are identical across runs and replicas, as the old `BTreeMap` backing was.
2140 use mz_timely_util::hash::fixed_state;
2141
2142 // The codecs encode and decode `[u8]` data specific to the `[Row]` encoding. They
2143 // soundly decode data they themselves encoded from valid `[Row]` data, but may be
2144 // unsound if asked to decode data that was not row-encoded, or was encoded with a
2145 // different codec. `ColumnsCodec` (a per-column wrapper around `DictionaryCodec`) is
2146 // the only codec the spine instantiates; the methods are inherent rather than behind
2147 // a `Codec` trait because nothing ever dispatches over codecs generically.
2148
2149 mod columns {
2150
2151 use mz_repr::{RowRef, read_datum};
2152
2153 use super::DictionaryCodec;
2154
2155 /// Independently encodes each column.
2156 #[derive(Default, Debug)]
2157 pub struct ColumnsCodec {
2158 columns: Vec<DictionaryCodec>,
2159 }
2160
2161 impl ColumnsCodec {
2162 /// Decode a row-encoded byte slice into per-column byte slices.
2163 pub(crate) fn decode<'a>(&'a self, bytes: &'a [u8]) -> ColumnsIter<'a> {
2164 ColumnsIter {
2165 index: Some(self),
2166 column: 0,
2167 data: bytes,
2168 }
2169 }
2170 /// Encode a sequence of column byte slices, updating per-column statistics.
2171 pub(crate) fn encode<'a, I>(&mut self, iter: I, output: &mut Vec<u8>)
2172 where
2173 I: IntoIterator<Item = &'a [u8]>,
2174 {
2175 for (index, bytes) in iter.into_iter().enumerate() {
2176 if self.columns.len() <= index {
2177 self.columns.push(Default::default());
2178 }
2179 self.columns[index].encode(std::iter::once(bytes), output);
2180 }
2181 }
2182
2183 /// Construct a codec valid for the union of the supplied codecs' data.
2184 pub(crate) fn new_from<'a>(stats: impl IntoIterator<Item = &'a Self>) -> Self {
2185 // An empty `stats` iterator yields a zero-column codec, which encodes and
2186 // decodes nothing; callers merging no inputs get an inert (but sound) codec.
2187 let stats = stats.into_iter().collect::<Vec<_>>();
2188 let cols = stats.iter().map(|s| s.columns.len()).max().unwrap_or(0);
2189 let mut columns = Vec::with_capacity(cols);
2190 let default: DictionaryCodec = Default::default();
2191 for index in 0..cols {
2192 columns.push(DictionaryCodec::new_from(
2193 stats
2194 .iter()
2195 .map(|s| s.columns.get(index).unwrap_or(&default)),
2196 ));
2197 }
2198 Self { columns }
2199 }
2200
2201 /// Reveal a row's bytes for fast-path comparison, with no codec to consult.
2202 #[inline(always)]
2203 pub(crate) fn borrow_row(row: &RowRef) -> ColumnsIter<'_> {
2204 ColumnsIter {
2205 index: None,
2206 column: 0,
2207 data: row.data(),
2208 }
2209 }
2210 }
2211
2212 impl ColumnsCodec {
2213 /// Visit contained allocations to determine their size and capacity.
2214 pub(crate) fn heap_size(&self, callback: &mut impl FnMut(usize, usize)) {
2215 let elem = std::mem::size_of::<DictionaryCodec>();
2216 callback(self.columns.len() * elem, self.columns.capacity() * elem);
2217 for column in &self.columns {
2218 column.heap_size(callback);
2219 }
2220 }
2221 }
2222
2223 impl ColumnsCodec {
2224 /// Record a row's column values in the statistics without encoding.
2225 ///
2226 /// Used during the stats-gathering phase, where we want the heavy-hitter
2227 /// and tag-usage information but store the row raw, so encoding into a
2228 /// throwaway buffer would be pure waste.
2229 #[inline]
2230 pub(crate) fn observe<'a, I>(&mut self, iter: I)
2231 where
2232 I: IntoIterator<Item = &'a [u8]>,
2233 {
2234 for (index, bytes) in iter.into_iter().enumerate() {
2235 if self.columns.len() <= index {
2236 self.columns.push(Default::default());
2237 }
2238 self.columns[index].observe(bytes);
2239 }
2240 }
2241 }
2242
2243 impl ColumnsCodec {
2244 /// Construct a codec using only structurally safe tags.
2245 ///
2246 /// Consumes `self`: this is only ever called on stats that have just been
2247 /// `take`n out of a container and are about to be discarded, so we move the
2248 /// per-column `MisraGries` summaries through rather than cloning them.
2249 pub(crate) fn new_safe(self) -> Self {
2250 let columns = self
2251 .columns
2252 .into_iter()
2253 .map(DictionaryCodec::new_safe)
2254 .collect();
2255 Self { columns }
2256 }
2257 }
2258
2259 #[derive(Debug, Copy, Clone)]
2260 pub struct ColumnsIter<'a> {
2261 // `None` when iterating an owned row directly, with no codec to consult.
2262 pub index: Option<&'a ColumnsCodec>,
2263 pub column: usize,
2264 pub data: &'a [u8],
2265 }
2266
2267 impl<'a> Iterator for ColumnsIter<'a> {
2268 type Item = &'a [u8];
2269 #[inline(always)]
2270 fn next(&mut self) -> Option<Self::Item> {
2271 if self.data.is_empty() {
2272 None
2273 } else if let Some(bytes) = self
2274 .index
2275 .as_ref()
2276 .and_then(|i| i.columns.get(self.column))
2277 .and_then(|i| i.decode.get(self.data[0].into()))
2278 {
2279 self.data = &self.data[1..];
2280 self.column += 1;
2281 Some(bytes)
2282 } else {
2283 let mut data = self.data;
2284 let data_len = data.len();
2285 unsafe {
2286 read_datum(&mut data);
2287 }
2288 let (prev, next) = self.data.split_at(data_len - data.len());
2289 self.data = next;
2290 self.column += 1;
2291 Some(prev)
2292 }
2293 }
2294 }
2295
2296 impl<'a> ColumnsIter<'a> {
2297 /// Create a column iterator without a codec.
2298 ///
2299 /// This requires the data to be row-formatted, and it will be erroneous otherwise.
2300 #[inline(always)]
2301 pub unsafe fn without_codec(data: &'a [u8]) -> Self {
2302 Self {
2303 index: None,
2304 column: 0,
2305 data,
2306 }
2307 }
2308 }
2309 }
2310
2311 /// A dictionary encoding codec for `[Row]` data.
2312 ///
2313 /// The dictionary harvests unused tags within each column and uses them to
2314 /// represent popular values within that column. There are two mechanisms it
2315 /// uses to accomplish this:
2316 ///
2317 /// 1. Statically free tags: `SAFE_TAG_BASE` is taken as an exclusive upper bound
2318 /// on the tags that will be used by `[Row]`, and tags greater or equal to this
2319 /// value are always safe to use.
2320 /// 2. Dynamically free tags: having seen an entire collection, we can use any
2321 /// tag not otherwise used by the collection, as it would not be ambiguous.
2322 ///
2323 /// It goes without saying that if either of these approaches are incorrect,
2324 /// there are calamitous unsoundness implications.
2325 mod dictionary {
2326 // The `encode` map is a pure value->tag lookup table (never iterated for logic),
2327 // so `mz_ore::collections::HashMap`'s order-hiding would suffice — but it offers
2328 // no fixed-seed constructor, and we want the same deterministic hasher as the
2329 // summary above. `heap_size`'s `keys()` walk is an order-insensitive sum.
2330 #![allow(clippy::disallowed_types)]
2331
2332 use std::collections::HashMap;
2333
2334 use super::fixed_state;
2335 pub use super::{BytesMap, MisraGries};
2336
2337 /// First byte value that is structurally unused by the datum encoding.
2338 /// All byte values >= this are safe to use as dictionary tags without
2339 /// observing the data, since no datum's first byte can have this value.
2340 ///
2341 /// `mz_repr`'s `Row` `Tag` enum currently has 84 variants (discriminants
2342 /// 0..=83), so the truly tight bound is 84. We deliberately pick a larger,
2343 /// round-ish constant to leave headroom for new tags without having to also
2344 /// bump the safe set, and the `test_safe_tag_base` test pins the real
2345 /// invariant: every datum the row format produces must encode with a first
2346 /// byte strictly less than this value. If a future tag crosses the boundary
2347 /// that test fails loudly rather than silently corrupting decoding.
2348 pub const SAFE_TAG_BASE: u8 = 122;
2349
2350 /// Per-column dictionary codec. Encodes column byte slices, replacing popular
2351 /// values with spare tags; decoding is performed by `ColumnsIter` reading the
2352 /// `decode` map directly.
2353 #[derive(Default, Debug)]
2354 pub struct DictionaryCodec {
2355 // Looked up once per value on the encode path; mostly misses (only popular
2356 // values compress), so a hash map beats a `BTreeMap`'s byte-slice walk. The
2357 // map is only ever read via `get` — never iterated — so its hasher seed has
2358 // no observable effect; the populated maps are built with `fixed_state` in
2359 // `new_from`/`new_safe` for consistency, while the derived-`Default` (stats
2360 // accumulator) variant stays empty and is never consulted.
2361 encode: HashMap<Vec<u8>, u8, ahash::RandomState>,
2362 pub decode: BytesMap,
2363 stats: (MisraGries<Vec<u8>>, [u64; 4]),
2364 }
2365
2366 impl DictionaryCodec {
2367 /// Encode a sequence of byte slices.
2368 ///
2369 /// Encoding also records statistics about the structure of the input.
2370 ///
2371 /// Decoding has no symmetric method here: a column's bytes are decoded by
2372 /// `ColumnsIter`, which consults the `decode` map directly.
2373 pub(super) fn encode<'a, I>(&mut self, iter: I, output: &mut Vec<u8>)
2374 where
2375 I: IntoIterator<Item = &'a [u8]>,
2376 {
2377 for bytes in iter.into_iter() {
2378 mz_ore::soft_assert_no_log!(
2379 !bytes.is_empty(),
2380 "row encoding never yields empty column slices",
2381 );
2382 // If we have an index referencing `bytes`, use the index key.
2383 if let Some(b) = self.encode.get(bytes) {
2384 output.push(*b);
2385 } else {
2386 // Raw fall-through. Soundness rests on `bytes[0]` never being a
2387 // tag we hand out as a dictionary key: `new_from`/`new_safe` only
2388 // assign dictionary tags from first-byte values that were never
2389 // observed (or are `>= SAFE_TAG_BASE`, which no datum first-byte
2390 // can equal). If a literal datum's first byte collided with a
2391 // dictionary tag, `decode` would resolve it to the dictionary
2392 // entry instead of reading the datum. This `debug_assert` makes
2393 // the load-bearing "no later first-byte outside the observed
2394 // union" invariant self-checking.
2395 mz_ore::soft_assert_no_log!(
2396 self.decode.get(bytes[0].into()).is_none(),
2397 "raw datum first-byte {} collides with a dictionary tag; \
2398 decode would be ambiguous",
2399 bytes[0],
2400 );
2401 output.extend(bytes);
2402 }
2403 self.observe(bytes);
2404 }
2405 }
2406
2407 /// Construct a new encoder from supplied statistics.
2408 pub(super) fn new_from<'a>(stats: impl IntoIterator<Item = &'a Self>) -> Self {
2409 // Collect most popular bytes from combined containers.
2410 let mut mg = MisraGries::default();
2411 let mut tags: [u64; 4] = [0; 4];
2412 for stat in stats.into_iter() {
2413 for (thing, count) in stat.stats.0.clone().done() {
2414 mg.update(thing, count);
2415 }
2416 tags[0] |= stat.stats.1[0];
2417 tags[1] |= stat.stats.1[1];
2418 tags[2] |= stat.stats.1[2];
2419 tags[3] |= stat.stats.1[3];
2420 }
2421 let mut mg = mg
2422 .done()
2423 .into_iter()
2424 .filter(|(next_bytes, count)| next_bytes.len() > 1 && count > &1);
2425 // Establish encoding and decoding rules.
2426 let mut encode = HashMap::with_hasher(fixed_state());
2427 let mut decode = BytesMap::default();
2428 for tag in 0..=255 {
2429 let tag_idx: usize = (tag % 4).into();
2430 let shift = tag >> 2;
2431 if (tags[tag_idx] >> shift) & 0x01 != 0 {
2432 // Tag is used by a literal datum first-byte; reserve the slot.
2433 decode.push(None);
2434 } else if let Some((next_bytes, _count)) = mg.next() {
2435 decode.push(Some(&next_bytes[..]));
2436 encode.insert(next_bytes, tag);
2437 } else {
2438 // Unused tag, but the heavy-hitter supply is exhausted. We must
2439 // still push a slot so that `decode`'s index stays aligned with
2440 // the tag value: every iteration pushes exactly once, keeping the
2441 // map length 256 and `decode.get(tag)` addressable by tag.
2442 decode.push(None);
2443 }
2444 }
2445
2446 Self {
2447 encode,
2448 decode,
2449 stats: (MisraGries::default(), [0u64; 4]),
2450 }
2451 }
2452 }
2453
2454 impl DictionaryCodec {
2455 /// Visit contained allocations to determine their size and capacity.
2456 ///
2457 /// The `encode` table is approximated as one logical entry's worth of bytes
2458 /// per element for size and its reserved `capacity()` for capacity; the
2459 /// dominant terms (the owned key bytes and the `decode` map's byte arena)
2460 /// are accounted exactly.
2461 pub fn heap_size(&self, callback: &mut impl FnMut(usize, usize)) {
2462 let entry = std::mem::size_of::<(Vec<u8>, u8)>();
2463 callback(self.encode.len() * entry, self.encode.capacity() * entry);
2464 for key in self.encode.keys() {
2465 callback(key.len(), key.capacity());
2466 }
2467 self.decode.heap_size(callback);
2468 self.stats.0.heap_size(callback);
2469 }
2470
2471 /// Record a single column value in this codec's statistics without
2472 /// producing any encoded output.
2473 ///
2474 /// Statistics come in two decoupled parts, with very different costs and
2475 /// purposes:
2476 ///
2477 /// 1. The tag bitmap (`stats.1`) records which first-byte values have been
2478 /// observed. It is cheap (four `u64` ORs) and *soundness critical*:
2479 /// `new_from`'s dynamic-tag path only hands out tags that this bitmap
2480 /// reports as unused, so it must stay accurate for the entire life of the
2481 /// codec, including on the hot encode path.
2482 /// 2. The MisraGries summary (`stats.0`) tracks heavy hitters and only
2483 /// affects *which* values a future codec compresses, never correctness.
2484 /// It is the expensive part (a `BTreeMap` insert per column per row). We
2485 /// keep feeding it after install, on the hot encode path, on purpose: a
2486 /// later merge rebuilds the merged codec from these summaries via
2487 /// `new_from`. If we froze the summary at install time, then as the
2488 /// collection evolves — records cancel under consolidation, the popular
2489 /// set drifts — the codec could never reclaim slots for newly-popular
2490 /// values and would eventually be left compressing values that no longer
2491 /// occur, ceasing to compress the ones that do.
2492 #[inline]
2493 pub fn observe(&mut self, bytes: &[u8]) {
2494 mz_ore::soft_assert_no_log!(
2495 !bytes.is_empty(),
2496 "row encoding never yields empty column slices",
2497 );
2498 let tag = bytes[0];
2499 let tag_idx: usize = (tag % 4).into();
2500 self.stats.1[tag_idx] |= 1 << (tag >> 2);
2501 self.stats.0.insert_ref(bytes);
2502 }
2503
2504 /// Construct a codec using only structurally safe tags (>= SAFE_TAG_BASE).
2505 /// These tags never collide with datum first-bytes, so the codec can be
2506 /// installed without observing all data first.
2507 pub(super) fn new_safe(stats: Self) -> Self {
2508 // The container stores its pre-install rows raw, so the first-byte
2509 // bitmap (`stats.1`) gathered while observing them must carry over to
2510 // the installed codec. The bitmap is soundness-critical: a later
2511 // `new_from` merge consults it to decide which one-byte tags are free
2512 // to hand out as dictionary keys. If we dropped it here, the merge
2513 // could assign a dictionary tag equal to a pre-install datum's first
2514 // byte, after which `decode` would resolve that literal datum to the
2515 // dictionary entry. The MisraGries summary (`stats.0`), by contrast,
2516 // is consumed below to seed the dictionary and is reset, since the
2517 // installed codec re-accumulates it from rows it sees post-install.
2518 let (mg, observed_tags) = stats.stats;
2519 let mut mg = mg
2520 .done()
2521 .into_iter()
2522 .filter(|(next_bytes, count)| next_bytes.len() > 1 && count > &1);
2523 let mut encode = HashMap::with_hasher(fixed_state());
2524 let mut decode = BytesMap::default();
2525 // Fill slots 0..SAFE_TAG_BASE with None (reserved for datum tags).
2526 for _ in 0..SAFE_TAG_BASE {
2527 decode.push(None);
2528 }
2529 // Assign dictionary entries to safe tags.
2530 for tag in SAFE_TAG_BASE..=255 {
2531 if let Some((next_bytes, _count)) = mg.next() {
2532 decode.push(Some(&next_bytes[..]));
2533 encode.insert(next_bytes, tag);
2534 }
2535 }
2536 Self {
2537 encode,
2538 decode,
2539 stats: (MisraGries::default(), observed_tags),
2540 }
2541 }
2542 }
2543 }
2544
2545 /// A map from `0 .. something` to `Option<&[u8]>`.
2546 ///
2547 /// Non-empty slices are pushed in order, and can be retrieved by index.
2548 /// Pushing an empty slice is equivalent to pushing `None`.
2549 #[derive(Debug)]
2550 pub struct BytesMap {
2551 offsets: Vec<usize>,
2552 bytes: Vec<u8>,
2553 }
2554 impl Default for BytesMap {
2555 #[inline(always)]
2556 fn default() -> Self {
2557 Self {
2558 offsets: vec![0],
2559 bytes: Vec::new(),
2560 }
2561 }
2562 }
2563 impl BytesMap {
2564 #[inline]
2565 fn push(&mut self, input: Option<&[u8]>) {
2566 if let Some(bytes) = input {
2567 self.bytes.extend(bytes);
2568 }
2569 self.offsets.push(self.bytes.len());
2570 }
2571 /// Visit contained allocations to determine their size and capacity.
2572 fn heap_size(&self, callback: &mut impl FnMut(usize, usize)) {
2573 let off = std::mem::size_of::<usize>();
2574 callback(self.offsets.len() * off, self.offsets.capacity() * off);
2575 callback(self.bytes.len(), self.bytes.capacity());
2576 }
2577 #[inline]
2578 fn get(&self, index: usize) -> Option<&[u8]> {
2579 if index < self.offsets.len() - 1 {
2580 let lower = self.offsets[index];
2581 let upper = self.offsets[index + 1];
2582 if lower < upper {
2583 Some(&self.bytes[lower..upper])
2584 } else {
2585 None
2586 }
2587 } else {
2588 None
2589 }
2590 }
2591 }
2592
2593 mod misra_gries {
2594 // The summary must iterate its entries (to extract heavy hitters in `done`, to
2595 // `tidy`, and to size itself), which `mz_ore::collections::HashMap` deliberately
2596 // forbids. We instead get determinism from the fixed-seed hasher (`fixed_state`)
2597 // plus the total-order sort in `done`; `tidy`/`heap_size` are order-insensitive.
2598 #![allow(clippy::disallowed_types)]
2599
2600 use std::collections::HashMap;
2601 use std::hash::Hash;
2602
2603 use super::fixed_state;
2604
2605 /// Maintains a summary of "heavy hitters" in a presented collection of items.
2606 ///
2607 /// Uses a hash map internally so that repeated observations of the same
2608 /// element only allocate once (on first sighting), and so the per-element
2609 /// `insert_ref` is an O(1) hash rather than an O(log n) walk of byte-slice
2610 /// comparisons. This is the hot path: one lookup per column per row, fed both
2611 /// while gathering stats and on the steady-state encode path. The hasher is
2612 /// fixed-seed (see [`fixed_state`]) so the summary — and thus which values a
2613 /// codec compresses — stays deterministic across runs and replicas.
2614 ///
2615 /// Tidy is performed when the number of *distinct* elements exceeds `2 * k`,
2616 /// reducing to at most `k` entries.
2617 #[derive(Clone, Debug)]
2618 pub struct MisraGries<T>
2619 where
2620 T: Ord + Hash,
2621 {
2622 inner: HashMap<T, usize, ahash::RandomState>,
2623 k: usize,
2624 }
2625
2626 impl<T> Default for MisraGries<T>
2627 where
2628 T: Ord + Hash,
2629 {
2630 #[inline(always)]
2631 fn default() -> Self {
2632 Self {
2633 inner: HashMap::with_hasher(fixed_state()),
2634 k: 512,
2635 }
2636 }
2637 }
2638
2639 impl<T> MisraGries<T>
2640 where
2641 T: Ord + Hash,
2642 {
2643 /// Inserts an additional element to the summary.
2644 #[inline(always)]
2645 pub fn insert(&mut self, element: T) {
2646 self.update(element, 1);
2647 }
2648 /// Inserts multiple copies of an element to the summary.
2649 #[inline]
2650 pub fn update(&mut self, element: T, count: usize) {
2651 *self.inner.entry(element).or_insert(0) += count;
2652 if self.inner.len() > 2 * self.k {
2653 self.tidy();
2654 }
2655 }
2656
2657 /// Completes the summary, and extracts the items and their counts.
2658 pub fn done(self) -> Vec<(T, usize)> {
2659 let mut result: Vec<_> = self.inner.into_iter().collect();
2660 // Descending count, ties broken by key, so the values a codec selects
2661 // are deterministic regardless of hash-map iteration order.
2662 result.sort_by(|x, y| y.1.cmp(&x.1).then_with(|| x.0.cmp(&y.0)));
2663 result
2664 }
2665
2666 /// Reduces the summary down to at most `k` distinct items by
2667 /// subtracting the (k+1)-th largest count from all entries and
2668 /// discarding those that drop to zero or below.
2669 fn tidy(&mut self) {
2670 let mut counts: Vec<usize> = self.inner.values().copied().collect();
2671 counts.sort_unstable_by(|a, b| b.cmp(a));
2672 // The (k+1)-th largest count, or 0 if fewer than k+1 entries.
2673 let sub_weight = counts.get(self.k).copied().unwrap_or(0);
2674 if sub_weight > 0 {
2675 self.inner.retain(|_, count| {
2676 *count = count.saturating_sub(sub_weight);
2677 *count > 0
2678 });
2679 }
2680 }
2681 }
2682
2683 impl MisraGries<Vec<u8>> {
2684 /// Visit contained allocations to determine their size and capacity.
2685 ///
2686 /// The hash table is approximated as one logical entry per element for
2687 /// size and its reserved `capacity()` for capacity; the owned key bytes
2688 /// are accounted exactly.
2689 pub fn heap_size(&self, callback: &mut impl FnMut(usize, usize)) {
2690 let entry = std::mem::size_of::<(Vec<u8>, usize)>();
2691 callback(self.inner.len() * entry, self.inner.capacity() * entry);
2692 for key in self.inner.keys() {
2693 callback(key.len(), key.capacity());
2694 }
2695 }
2696
2697 /// Insert a borrowed byte slice, only allocating if the key is new.
2698 #[inline]
2699 pub fn insert_ref(&mut self, element: &[u8]) {
2700 if let Some(count) = self.inner.get_mut(element) {
2701 *count += 1;
2702 } else {
2703 self.insert(element.to_owned());
2704 }
2705 }
2706 }
2707
2708 impl<T> std::ops::AddAssign for MisraGries<T>
2709 where
2710 T: Ord + Hash,
2711 {
2712 fn add_assign(&mut self, rhs: Self) {
2713 for (element, count) in rhs.done() {
2714 self.update(element, count);
2715 }
2716 }
2717 }
2718 }
2719}