Skip to main content

dupehell_core/
gt.rs

1// DupeHell -- MIT License
2//
3// Synthetic multi-domain dataset generator for record linkage benchmarking.
4// No liability for misuse.
5
6use arrow::array::{Array, ArrayRef, AsArray, BooleanArray};
7use arrow::buffer::BooleanBuffer;
8use arrow::datatypes::{DataType, Field, Schema};
9use arrow::record_batch::RecordBatch;
10use std::collections::HashMap;
11use std::sync::Arc;
12
13/// Compressed-sparse-row representation of the duplicate-cluster
14/// membership previously held as `HashMap<String, Vec<(String, bool)>>`.
15/// Built once, in `GtAccumulator::finish`, from every `(master_id,
16/// record_id, is_identical)` triple belonging to a duplicated master.
17///
18/// Avoids one `String` allocation per `record_id` and one per distinct
19/// `master_id` (the dominant RAM cost of `cluster_map` at 200M+ records,
20/// see `project_csr_cluster_map_backlog`): `master_id`/`record_id` are
21/// packed into `u64`s (`pipeline::pack_master_key`/`parse_record_idx` —
22/// both are pure functions of the fixed-width ID shapes `pipeline.rs`
23/// already generates, so the packing/unpacking is lossless and exact) and
24/// stored in two flat, contiguous buffers instead of a hash map of
25/// per-cluster `Vec`s.
26///
27/// `master_id` itself is never needed downstream as a string — the only
28/// consumer (`graph_gen::push_dup_clusters`) only ever used it to get a
29/// deterministic cluster iteration order (`master_ids.sort()`), and
30/// numeric comparison of the packed key preserves that exact order (both
31/// segments of the original string are zero-padded to a fixed width, so
32/// lexicographic and numeric order agree).
33/// Bit-packed boolean buffer — 1 bit per entry instead of `Vec<bool>`'s 1
34/// byte, an 8x reduction on `ClusterCsr::is_identical`, which parallels
35/// `records` (potentially tens of millions of entries at 100M+ hell scale
36/// with `--graph`, a low singleton fraction). Found via a triage of
37/// reusable Rust perf patterns (hunt3007/H7, Linkars trick #22).
38/// A `BooleanArray` of `n` copies of `value`, built directly from a
39/// `BooleanBuffer` (one bitmap allocation, `n/8` bytes) instead of
40/// `BooleanArray::from(vec![value; n])` (an `n`-byte `Vec<bool>` allocated
41/// and memset, then re-packed into a bitmap by `From`).
42fn const_bool_array(n: usize, value: bool) -> ArrayRef {
43    let buf = if value {
44        BooleanBuffer::new_set(n)
45    } else {
46        BooleanBuffer::new_unset(n)
47    };
48    Arc::new(BooleanArray::new(buf, None))
49}
50
51struct Bitset {
52    words: Vec<u64>,
53    len: usize,
54}
55
56impl Bitset {
57    fn with_capacity(n: usize) -> Self {
58        Self {
59            words: vec![0u64; n.div_ceil(64).max(1)],
60            len: 0,
61        }
62    }
63
64    fn push(&mut self, val: bool) {
65        let word_idx = self.len / 64;
66        if word_idx >= self.words.len() {
67            self.words.push(0);
68        }
69        if val {
70            self.words[word_idx] |= 1u64 << (self.len % 64);
71        }
72        self.len += 1;
73    }
74
75    fn get(&self, i: usize) -> bool {
76        (self.words[i / 64] >> (i % 64)) & 1 != 0
77    }
78}
79
80/// View into a contiguous range of a [`Bitset`], returned per-cluster by
81/// [`ClusterCsr::groups`] — parallel to the `&[u64]` record-index slice for
82/// the same cluster.
83pub struct BitspanRef<'a> {
84    bits: &'a Bitset,
85    start: usize,
86    end: usize,
87}
88
89impl BitspanRef<'_> {
90    /// `i` is local to this span (`0..self.len()`), matching how callers
91    /// already index the parallel `&[u64]` records slice.
92    pub fn get(&self, i: usize) -> bool {
93        self.bits.get(self.start + i)
94    }
95
96    pub fn len(&self) -> usize {
97        self.end - self.start
98    }
99
100    pub fn is_empty(&self) -> bool {
101        self.start == self.end
102    }
103
104    #[cfg(test)]
105    fn to_vec(&self) -> Vec<bool> {
106        (0..self.len()).map(|i| self.get(i)).collect()
107    }
108}
109
110pub struct ClusterCsr {
111    /// `offsets.len() == n_clusters + 1`; cluster `k`'s members are
112    /// `records[offsets[k]..offsets[k+1]]` (and the parallel span of
113    /// `is_identical`). Sorted ascending by packed master key.
114    offsets: Vec<u32>,
115    /// Flat, cluster-grouped buffer of global record indices (see
116    /// `pipeline::record_id_string`/`parse_record_idx`), ascending within
117    /// each cluster.
118    records: Vec<u64>,
119    /// Parallel to `records`: whether that record is byte-identical to its
120    /// cluster's master.
121    is_identical: Bitset,
122}
123
124/// `record_idx` (from `parse_record_idx`) is bounded by `PAD_LEN` (13)
125/// decimal digits — `< 10^13 ≈ 2^43.2` — so bit 63 is always free to carry
126/// `is_identical` alongside it in one `u64`, the same trick
127/// `pack_master_key` already uses for its own high bits (hunt1808/H-RAM3).
128/// Packing this into `ClusterCsr::build`'s transient pair list drops it
129/// from `(u64, u64, bool)` (24 bytes/entry — `bool` pads the tuple to the
130/// next 8-byte alignment boundary, measured on this machine) to `(u64,
131/// u64)` (16 bytes/entry, −33%), at potentially tens of millions of
132/// entries (every row of every duplicated cluster, `--graph` mode).
133const RIDX_IDENTICAL_BIT: u64 = 1 << 63;
134const RIDX_MASK: u64 = !RIDX_IDENTICAL_BIT;
135
136/// Packs `(record_idx, is_identical)` into `ClusterCsr::build`'s pair
137/// representation — see `RIDX_IDENTICAL_BIT`.
138pub(crate) fn pack_ridx_identical(record_idx: u64, is_identical: bool) -> u64 {
139    debug_assert_eq!(
140        record_idx & RIDX_IDENTICAL_BIT,
141        0,
142        "record_idx must fit in the low 63 bits"
143    );
144    record_idx | if is_identical { RIDX_IDENTICAL_BIT } else { 0 }
145}
146
147impl ClusterCsr {
148    /// Builds the CSR from an unordered flat list of `(packed_master_key,
149    /// packed_ridx_identical)` pairs (see `pack_ridx_identical`). Sorting
150    /// once by `(master_key, record_idx)` — masking off the packed
151    /// `is_identical` bit for the comparison, so it can't perturb member
152    /// order within a cluster — both groups every pair by cluster and
153    /// orders each cluster's members ascending, in one pass; no need to
154    /// pre-count group sizes or build the structure incrementally.
155    ///
156    /// Sorted in parallel (`rayon`, already a warm dependency by this point
157    /// in the run): the sort key `(master_key, record_idx)` is unique per
158    /// entry (one record belongs to exactly one cluster, and a
159    /// `record_idx` is unique across the whole run), so an unstable
160    /// parallel sort produces the exact same total order as the previous
161    /// single-threaded one — determinism doesn't depend on stability here.
162    pub(crate) fn build(mut pairs: Vec<(u64, u64)>) -> Self {
163        use rayon::slice::ParallelSliceMut;
164        pairs.par_sort_unstable_by_key(|&(mk, r)| (mk, r & RIDX_MASK));
165
166        let mut offsets = Vec::new();
167        let mut records = Vec::with_capacity(pairs.len());
168        let mut is_identical = Bitset::with_capacity(pairs.len());
169        let mut last_key: Option<u64> = None;
170
171        for (mk, r) in pairs {
172            if last_key != Some(mk) {
173                offsets.push(records.len() as u32);
174                last_key = Some(mk);
175            }
176            records.push(r & RIDX_MASK);
177            is_identical.push(r & RIDX_IDENTICAL_BIT != 0);
178        }
179        offsets.push(records.len() as u32);
180
181        Self {
182            offsets,
183            records,
184            is_identical,
185        }
186    }
187
188    /// Iterates clusters in ascending packed-master-key order (matches the
189    /// previous `master_ids.sort()` determinism exactly), yielding each
190    /// cluster's `(record_indices, is_identical)` pair. A cluster's
191    /// `record_indices` are already ascending, so callers that used to sort
192    /// members themselves (`push_dup_clusters`) no longer need to.
193    pub fn groups(&self) -> impl Iterator<Item = (&[u64], BitspanRef<'_>)> {
194        self.offsets.windows(2).map(move |w| {
195            let (start, end) = (w[0] as usize, w[1] as usize);
196            (
197                &self.records[start..end],
198                BitspanRef {
199                    bits: &self.is_identical,
200                    start,
201                    end,
202                },
203            )
204        })
205    }
206
207    #[cfg(test)]
208    fn n_clusters(&self) -> usize {
209        self.offsets.len().saturating_sub(1)
210    }
211}
212
213/// Result of [`GtAccumulator::finish`].
214pub struct GtResult {
215    /// Cluster members that are genuinely byte-for-byte identical to their
216    /// master (the master itself, plus any duplicate copy whose assigned
217    /// noise ended up a no-op — see `pipeline::unchanged_row_mask`).
218    pub n_exact_dup: usize,
219    /// Cluster members that are duplicates of a master but differ from it
220    /// on at least one column (noise was actually applied). Distinguished
221    /// from `n_exact_dup` so a consumer can't mistake a fuzzy duplicate for
222    /// a trivial byte-for-byte match.
223    pub n_fuzzy_dup: usize,
224    pub n_hard_neg: usize,
225    pub n_unique: usize,
226    pub n_masters: usize,
227    /// Maps each duplicated `master_id` to the full set of `(record_id,
228    /// is_identical)` pairs in its cluster (base + duplicate copies, exact
229    /// and fuzzy alike) — `is_identical` mirrors that record's own
230    /// `exact_dup`/`fuzzy_dup` classification. Consumed by
231    /// `graph_gen::push_dup_clusters` to decide, per edge, whether the pair
232    /// it connects is `exact_dup` (both ends byte-identical to the master,
233    /// hence to each other) or `fuzzy_dup` (at least one end was noised).
234    pub cluster_map: ClusterCsr,
235}
236
237/// `Dictionary(Int32, Utf8)` for `entity_type`/`match_type`/`difficulty` —
238/// hunt1808/H11, an explicit output-contract change (not bit-identical:
239/// the declared column type changes from `Utf8`), applied on explicit user
240/// request. `entity_type` here must match `pipeline::low_cardinality_dict_type`
241/// exactly — this column's data is `add_metadata_and_align`'s `et_arr`,
242/// pushed straight through by `push_*_batch`, so draft/final schema must
243/// declare the same type it's actually built as.
244fn low_cardinality_dict_type() -> DataType {
245    DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8))
246}
247
248fn draft_schema() -> Arc<Schema> {
249    Arc::new(Schema::new(vec![
250        Field::new("record_id", DataType::Utf8, false),
251        Field::new("master_id", DataType::Utf8, false),
252        Field::new("entity_type", low_cardinality_dict_type(), false),
253        // `true` for duplicate-copy rows whose assigned noise ended up not
254        // changing anything visible; `false` for duplicate copies that were
255        // genuinely altered, and for base/master rows (a base row is never
256        // itself "a copy that happened to match" — see `is_base` below for
257        // how its match_type is actually resolved). Meaningless for
258        // hard_neg/canary rows (classified by master_id prefix regardless).
259        Field::new("is_identical", DataType::Boolean, false),
260        // `true` only for base/master rows (one per entity, written by
261        // `push_base_batch`); `false` for every duplicate copy and for
262        // hard_neg/canary rows. Lets `finish` tell a base row apart from a
263        // genuine fuzzy copy when both carry `is_identical = false` — without
264        // it, a duplicated master's own base row would be misclassified
265        // `exact_dup` unconditionally (it used to hardcode
266        // `is_identical = true` for every base row, regardless of whether
267        // any of its actual duplicate copies were byte-identical to it).
268        Field::new("is_base", DataType::Boolean, false),
269    ]))
270}
271
272/// Streaming, two-pass ground-truth builder.
273///
274/// Duplicate detection needs a genuinely global view of which masters are
275/// duplicated (a master can be duplicated anywhere in the record stream),
276/// but that's the *only* thing that needs to be global — everything else
277/// can be processed one batch at a time. Previously the whole run
278/// accumulated three full-dataset `Vec<ArrayRef>` (record_id/entity_type/
279/// master_id) in RAM to concat and classify at the very end; at 200M+
280/// records that's multiple GB held for the entire run just for GT
281/// bookkeeping.
282///
283/// This accumulator instead:
284/// 1. streams each batch straight to a small "draft" IPC file as it's
285///    generated. The pipeline already knows, at the point each batch is
286///    produced, whether its rows introduce brand-new masters
287///    (`push_base_batch`) or are duplicate copies of masters seen earlier
288///    (`push_dup_batch`) — that's how `pipeline::run_pipeline` builds
289///    `dup_mids_buf` today. So instead of *discovering* duplication by
290///    folding occurrence counts over every master ever seen (O(n_base) —
291///    one entry per base record, duplicated or not), this only records the
292///    (much smaller) set of masters that are *actually* duplicated —
293///    O(n_dup_masters), a fraction of the dataset determined by the
294///    doublet/triplet ratios, not the full base population. HN/CANARY rows
295///    (`push_other_batch`) need no bookkeeping at all: their prefix alone
296///    determines their classification.
297/// 2. on `finish`, re-reads that draft file batch by batch — now that the
298///    full duplicated-master set is known — to classify each row and
299///    stream the definitive ground-truth file (IPC or Parquet), same
300///    batch-by-batch pattern already used elsewhere in this codebase for
301///    the IPC→Parquet dataset conversion (see `pipeline::run_pipeline`).
302///
303/// Duplicate detection is keyed on the **full** master_id (entity prefix
304/// included, via `pipeline::pack_master_key` into a `u64`), not just a
305/// numeric suffix: master_ids are assigned per-entity-plan starting from
306/// index 0, so two unrelated entities of different types can share the
307/// same numeric suffix. Keying on the full identity avoids counting those
308/// as duplicates of each other.
309pub struct GtAccumulator {
310    draft_path: String,
311    writer: arrow::ipc::writer::FileWriter<std::fs::File>,
312    schema: Arc<Schema>,
313    /// Keyed on `pipeline::pack_master_key(mid)` rather than the raw
314    /// `String` — avoids a per-row string hash/allocation on a set queried
315    /// 2-3x per duplicated row (`push_dup_batch` + classification in
316    /// `finish`), which VTune hotspots (hunt3007) showed costing ~5% of
317    /// total CPU on its own. `push_dup_batch` never receives an
318    /// HN-/CANARY- master_id, so every key here is guaranteed
319    /// pack_master_key-compatible.
320    dup_masters: rustc_hash::FxHashSet<u64>,
321    /// Masters that have at least one duplicate copy whose assigned noise
322    /// ended up a genuine no-op (byte-identical to the base) — as opposed to
323    /// `dup_masters`, which just means "has any duplicate copy at all,
324    /// exact or fuzzy". Used at `finish` so a base row can tell whether it
325    /// actually has an identical twin instead of unconditionally claiming
326    /// one.
327    masters_with_exact_copy: rustc_hash::FxHashSet<u64>,
328    n_base_masters: usize,
329}
330
331impl GtAccumulator {
332    /// Current size of `dup_masters` (hunt2808, RAM-first pass) -- lets
333    /// call sites log this cumulative-over-the-whole-run set's growth
334    /// directly, instead of inferring it from RSS deltas that also include
335    /// unrelated per-entity batch buffers.
336    pub(crate) fn dup_masters_len(&self) -> usize {
337        self.dup_masters.len()
338    }
339
340    /// Current size of `masters_with_exact_copy` (hunt2808, RAM-first
341    /// pass) -- see `dup_masters_len`.
342    pub(crate) fn masters_with_exact_copy_len(&self) -> usize {
343        self.masters_with_exact_copy.len()
344    }
345
346    pub fn new(draft_path: &str) -> Result<Self, String> {
347        let schema = draft_schema();
348        let file = std::fs::File::create(draft_path)
349            .map_err(|e| format!("create gt draft {draft_path}: {e}"))?;
350        let writer = arrow::ipc::writer::FileWriter::try_new(file, &schema)
351            .map_err(|e| format!("gt draft writer: {e}"))?;
352        Ok(Self {
353            draft_path: draft_path.to_string(),
354            writer,
355            schema,
356            dup_masters: rustc_hash::FxHashSet::default(),
357            masters_with_exact_copy: rustc_hash::FxHashSet::default(),
358            n_base_masters: 0,
359        })
360    }
361
362    fn write_draft(
363        &mut self,
364        record_ids: &ArrayRef,
365        entity_types: &ArrayRef,
366        master_ids: &ArrayRef,
367        is_identical: &ArrayRef,
368        is_base: &ArrayRef,
369    ) -> Result<(), String> {
370        let batch = RecordBatch::try_new(
371            self.schema.clone(),
372            vec![
373                record_ids.clone(),
374                master_ids.clone(),
375                entity_types.clone(),
376                is_identical.clone(),
377                is_base.clone(),
378            ],
379        )
380        .map_err(|e| format!("build gt draft batch: {e}"))?;
381        self.writer
382            .write(&batch)
383            .map_err(|e| format!("write gt draft: {e}"))
384    }
385
386    /// Feed a batch of rows that each introduce a brand-new, not-yet-seen
387    /// master (base records — one master per row, never a duplicate copy).
388    pub fn push_base_batch(
389        &mut self,
390        record_ids: &ArrayRef,
391        entity_types: &ArrayRef,
392        master_ids: &ArrayRef,
393    ) -> Result<(), String> {
394        let mids = master_ids.as_string::<i32>();
395        self.n_base_masters += mids.len() - mids.null_count();
396        // `is_identical = false`: a base row is not itself a "copy that
397        // happened to match" — whether it should read as `exact_dup` is
398        // resolved at `finish` from `masters_with_exact_copy`, not hardcoded
399        // here (this used to be `true` unconditionally, which mislabeled
400        // every duplicated master's base row `exact_dup` even when all of
401        // its actual duplicate copies were fuzzy — none byte-identical).
402        let all_false = const_bool_array(mids.len(), false);
403        let all_true = const_bool_array(mids.len(), true);
404        self.write_draft(record_ids, entity_types, master_ids, &all_false, &all_true)
405    }
406
407    /// Feed a batch of duplicate-copy rows (each `master_id` matches an
408    /// existing base record already fed via `push_base_batch`). Records the
409    /// *set* of duplicated masters — every row sharing one of these
410    /// master_ids (the original base row included) belongs to a duplicated
411    /// cluster at `finish`, classified `exact_dup` or `fuzzy_dup` per-row
412    /// based on `is_identical` (`true` when the noise assigned to this copy
413    /// ended up a no-op — see `pipeline::unchanged_row_mask` — `false` when
414    /// it produced a real, visible change). Also records which masters have
415    /// at least one genuinely identical copy, for the base row's own
416    /// classification at `finish`.
417    pub fn push_dup_batch(
418        &mut self,
419        record_ids: &ArrayRef,
420        entity_types: &ArrayRef,
421        master_ids: &ArrayRef,
422        is_identical: &ArrayRef,
423    ) -> Result<(), String> {
424        let mids = master_ids.as_string::<i32>();
425        let idents = is_identical.as_boolean();
426        for i in 0..mids.len() {
427            if !mids.is_null(i) {
428                let mid = mids.value(i);
429                let key = crate::pipeline::pack_master_key(mid).unwrap_or_else(|| {
430                    panic!(
431                        "push_dup_batch: master_id {mid:?} isn't the fixed \
432                         \"{{entity_prefix}}-{{pad_string}}\" shape -- \
433                         push_dup_batch never receives an HN-/CANARY- master_id"
434                    )
435                });
436                self.dup_masters.insert(key);
437                if !idents.is_null(i) && idents.value(i) {
438                    self.masters_with_exact_copy.insert(key);
439                }
440            }
441        }
442        let all_false = const_bool_array(mids.len(), false);
443        self.write_draft(
444            record_ids,
445            entity_types,
446            master_ids,
447            is_identical,
448            &all_false,
449        )
450    }
451
452    /// Feed a batch of rows whose classification is fully determined by
453    /// their `master_id` prefix (hard negatives `HN-...`, canaries
454    /// `CANARY-...`) — no bookkeeping needed beyond streaming to the draft.
455    pub fn push_other_batch(
456        &mut self,
457        record_ids: &ArrayRef,
458        entity_types: &ArrayRef,
459        master_ids: &ArrayRef,
460    ) -> Result<(), String> {
461        // `is_identical`/`is_base` are meaningless for hard_neg/canary rows
462        // (classified by master_id prefix regardless), so the values don't
463        // matter.
464        let all_false = const_bool_array(record_ids.len(), false);
465        self.write_draft(record_ids, entity_types, master_ids, &all_false, &all_false)
466    }
467
468    /// Consumes the accumulator: closes the draft, re-reads it batch by
469    /// batch to classify each row now that the full duplicated-master set
470    /// is known, and streams the definitive ground-truth file (IPC or
471    /// Parquet). Returns a [`GtResult`].
472    pub fn finish(
473        self,
474        difficulty: &str,
475        output_format: &str,
476        final_path: &str,
477        metadata: &HashMap<String, String>,
478        track_clusters: bool,
479    ) -> Result<GtResult, String> {
480        let GtAccumulator {
481            draft_path,
482            mut writer,
483            dup_masters,
484            masters_with_exact_copy,
485            n_base_masters,
486            ..
487        } = self;
488        writer
489            .finish()
490            .map_err(|e| format!("finish gt draft: {e}"))?;
491        drop(writer);
492
493        let final_schema = Arc::new(
494            Schema::new(vec![
495                Field::new("record_id", DataType::Utf8, false),
496                Field::new("master_id", DataType::Utf8, false),
497                Field::new("entity_type", low_cardinality_dict_type(), false),
498                Field::new("match_type", low_cardinality_dict_type(), false),
499                Field::new("difficulty", low_cardinality_dict_type(), false),
500            ])
501            .with_metadata(metadata.clone()),
502        );
503
504        let draft_file = std::fs::File::open(&draft_path)
505            .map_err(|e| format!("reopen gt draft {draft_path}: {e}"))?;
506        let reader = arrow::ipc::reader::FileReader::try_new(draft_file, None)
507            .map_err(|e| format!("gt draft reader: {e}"))?;
508
509        let mut sink = GtSink::new(output_format, final_path, &final_schema, metadata)?;
510
511        let mut n_exact_dup = 0usize;
512        let mut n_fuzzy_dup = 0usize;
513        let mut n_hard_neg = 0usize;
514        let mut n_unique = 0usize;
515        // Cluster membership for duplicated masters (base + duplicate copies,
516        // exact and fuzzy alike), for emitting duplicate-cluster edges after
517        // this pass. Accumulated as a flat `Vec` of packed triples (see
518        // `ClusterCsr`) instead of a `HashMap<String, Vec<...>>` -- avoids a
519        // `String` allocation per record_id/master_id, the dominant RAM cost
520        // of this bookkeeping at 200M+ records.
521        let mut cluster_pairs: Vec<(u64, u64)> = Vec::new();
522        // `difficulty` is constant for the whole run and `n` only ever takes
523        // two values across all batches (the draft's batch size, and the
524        // final remainder) — cache the built column by `n` instead of
525        // reallocating+refilling it every batch (same pattern as
526        // `pipeline.rs`'s `const_arr_cache`).
527        let mut diff_arr_cache: Option<(usize, ArrayRef)> = None;
528        // Fixed, fully-known value sets — built once, before any batch is
529        // written, and reused for every batch's `DictionaryArray` (hunt1808/
530        // H11; see `pipeline::DictValues`'s doc comment for why a *shared*
531        // dictionary is required for IPC output, not just a same-content
532        // one built fresh per batch).
533        let match_type_dict = crate::pipeline::DictValues::new([
534            "hard_neg",
535            "canary",
536            "exact_dup",
537            "fuzzy_dup",
538            "unique",
539        ]);
540        let difficulty_dict = crate::pipeline::DictValues::new([difficulty.to_string()]);
541
542        for batch_result in reader {
543            let batch = batch_result.map_err(|e| format!("read gt draft batch: {e}"))?;
544            let n = batch.num_rows();
545            let mid_col = batch.column(1).as_string::<i32>();
546            let rid_col = batch.column(0).as_string::<i32>();
547            let ident_col = batch.column(3).as_boolean();
548            let base_col = batch.column(4).as_boolean();
549
550            let mut mt_keys = arrow::array::Int32Builder::with_capacity(n);
551            for i in 0..n {
552                let mid = if mid_col.is_null(i) {
553                    ""
554                } else {
555                    mid_col.value(i)
556                };
557                let is_base = !base_col.is_null(i) && base_col.value(i);
558                let is_hn = mid.starts_with("HN-");
559                let is_canary = !is_hn && mid.starts_with("CANARY-");
560                // `dup_masters`/`masters_with_exact_copy` are keyed on
561                // `pack_master_key`, not the raw string (hunt3007/H3) --
562                // never `Some` for HN-/CANARY- ids, consistent with
563                // `push_dup_batch` never inserting those.
564                let master_key = if is_hn || is_canary {
565                    None
566                } else {
567                    crate::pipeline::pack_master_key(mid)
568                };
569                // Per-row, not per-cluster: a cluster can mix a base row, a
570                // copy the noise happened not to change, and a copy that's
571                // genuinely different. A base row has no noise of its own —
572                // it reads `exact_dup` only if the cluster actually contains
573                // a byte-identical copy (`masters_with_exact_copy`), never
574                // unconditionally (that used to mislabel every duplicated
575                // master's base row `exact_dup` even when all of its copies
576                // were fuzzy).
577                let is_identical = if is_base {
578                    master_key.is_some_and(|k| masters_with_exact_copy.contains(&k))
579                } else {
580                    !ident_col.is_null(i) && ident_col.value(i)
581                };
582                let is_dup_master = master_key.is_some_and(|k| dup_masters.contains(&k));
583                let mt = if is_hn {
584                    n_hard_neg += 1;
585                    "hard_neg"
586                } else if is_canary {
587                    "canary"
588                } else if is_dup_master {
589                    if is_identical {
590                        n_exact_dup += 1;
591                        "exact_dup"
592                    } else {
593                        n_fuzzy_dup += 1;
594                        "fuzzy_dup"
595                    }
596                } else {
597                    n_unique += 1;
598                    "unique"
599                };
600                mt_keys.append_value(match_type_dict.key(mt));
601                // Every row of a duplicated master belongs to its cluster,
602                // tagged with its own identical/fuzzy status. Only tracked
603                // when `--graph` is enabled: `cluster_pairs` is exclusively
604                // consumed by `graph_gen::push_dup_clusters` to emit
605                // exact_dup/fuzzy_dup edges, so building it when there's no
606                // graph output to write is pure wasted RAM -- one entry per
607                // duplicate-cluster row (base + every copy), which at
608                // 100M+ records with a low singleton fraction (hell tier)
609                // can be the majority of the dataset.
610                if track_clusters && is_dup_master {
611                    let master_key = master_key.expect("is_dup_master implies master_key is Some");
612                    let record_idx = crate::pipeline::parse_record_idx(rid_col.value(i))
613                        .unwrap_or_else(|| {
614                            panic!(
615                                "cluster_map: record_id {:?} isn't the fixed \
616                                 \"R-\" + 13-digit shape produced by \
617                                 `record_id_string`",
618                                rid_col.value(i)
619                            )
620                        });
621                    cluster_pairs.push((master_key, pack_ridx_identical(record_idx, is_identical)));
622                }
623            }
624            let mt_arr = match_type_dict.finish_keys(mt_keys.finish());
625            let diff_arr = match &diff_arr_cache {
626                Some((cached_n, arr)) if *cached_n == n => arr.clone(),
627                _ => {
628                    let arr = difficulty_dict.const_array(difficulty, n);
629                    diff_arr_cache = Some((n, arr.clone()));
630                    arr
631                }
632            };
633
634            let final_batch = RecordBatch::try_new(
635                final_schema.clone(),
636                vec![
637                    batch.column(0).clone(),
638                    batch.column(1).clone(),
639                    batch.column(2).clone(),
640                    mt_arr,
641                    diff_arr,
642                ],
643            )
644            .map_err(|e| format!("build final gt batch: {e}"))?;
645
646            sink.write(&final_batch)?;
647        }
648
649        sink.finish()?;
650        std::fs::remove_file(&draft_path).ok();
651
652        Ok(GtResult {
653            n_exact_dup,
654            n_fuzzy_dup,
655            n_hard_neg,
656            n_unique,
657            n_masters: n_base_masters,
658            cluster_map: ClusterCsr::build(cluster_pairs),
659        })
660    }
661}
662
663enum GtSink {
664    Ipc(Box<arrow::ipc::writer::FileWriter<std::fs::File>>),
665    Parquet(Box<parquet::arrow::ArrowWriter<std::fs::File>>),
666}
667
668impl GtSink {
669    fn new(
670        output_format: &str,
671        path: &str,
672        schema: &Arc<Schema>,
673        metadata: &HashMap<String, String>,
674    ) -> Result<Self, String> {
675        let file = std::fs::File::create(path).map_err(|e| format!("create {path}: {e}"))?;
676        if output_format == "parquet" {
677            use parquet::basic::{Compression, ZstdLevel};
678            use parquet::file::properties::WriterProperties;
679            let zstd = ZstdLevel::try_new(3).map_err(|e| format!("zstd: {e}"))?;
680            let meta_kv: Vec<parquet::file::metadata::KeyValue> = metadata
681                .iter()
682                .map(|(k, v)| parquet::file::metadata::KeyValue {
683                    key: k.clone(),
684                    value: Some(v.clone()),
685                })
686                .collect();
687            let props = WriterProperties::builder()
688                .set_compression(Compression::ZSTD(zstd))
689                .set_data_page_size_limit(1_048_576)
690                .set_key_value_metadata(Some(meta_kv))
691                .build();
692            let writer = parquet::arrow::ArrowWriter::try_new(file, schema.clone(), Some(props))
693                .map_err(|e| format!("gt parquet writer: {e}"))?;
694            Ok(GtSink::Parquet(Box::new(writer)))
695        } else {
696            let writer = arrow::ipc::writer::FileWriter::try_new(file, schema)
697                .map_err(|e| format!("gt ipc writer: {e}"))?;
698            Ok(GtSink::Ipc(Box::new(writer)))
699        }
700    }
701
702    fn write(&mut self, batch: &RecordBatch) -> Result<(), String> {
703        match self {
704            GtSink::Ipc(w) => w.write(batch).map_err(|e| format!("write gt ipc: {e}")),
705            GtSink::Parquet(w) => w.write(batch).map_err(|e| format!("write gt parquet: {e}")),
706        }
707    }
708
709    fn finish(self) -> Result<(), String> {
710        match self {
711            GtSink::Ipc(mut w) => w.finish().map_err(|e| format!("finish gt ipc: {e}")),
712            GtSink::Parquet(w) => w
713                .close()
714                .map(|_| ())
715                .map_err(|e| format!("close gt parquet: {e}")),
716        }
717    }
718}
719
720#[cfg(test)]
721mod tests {
722    use super::*;
723    use arrow::array::StringArray;
724
725    fn tmp_path(name: &str) -> String {
726        let mut p = std::env::temp_dir();
727        p.push(format!(
728            "dupehell_gt_test_{name}_{}.ipc",
729            std::process::id()
730        ));
731        p.to_string_lossy().into_owned()
732    }
733
734    fn arr(values: Vec<&str>) -> ArrayRef {
735        Arc::new(StringArray::from(values))
736    }
737
738    /// Same as `arr`, but for computed (owned) strings -- used to build
739    /// `record_id`/`master_id` fixtures matching the exact fixed-width shape
740    /// `ClusterCsr`'s packing relies on (`pipeline::record_id_string`/
741    /// `entity_prefix`/`pad_string`), which a bare string literal like
742    /// `"R2"` doesn't.
743    fn arr_owned(values: Vec<String>) -> ArrayRef {
744        Arc::new(StringArray::from(values))
745    }
746
747    fn barr(values: Vec<bool>) -> ArrayRef {
748        Arc::new(BooleanArray::from(values))
749    }
750
751    /// `entity_type` fixtures (hunt1808/H11): the real column is
752    /// `Dictionary(Int32, Utf8)`, built from `add_metadata_and_align`'s
753    /// `entity_type_dict` — these tests build the draft schema directly,
754    /// so they need to hand `push_*_batch` a matching dictionary array
755    /// rather than the plain `StringArray` `arr()` builds. `dict` must be
756    /// the SAME `DictValues` instance across every `dict_arr` call feeding
757    /// one draft file — a fresh dictionary per call is exactly the
758    /// "Dictionary replacement" bug this whole hunt/H11 fixes in the real
759    /// pipeline code, and IPC enforces it just as strictly in tests.
760    fn dict_arr(dict: &crate::pipeline::DictValues, values: Vec<&str>) -> ArrayRef {
761        let keys =
762            arrow::array::Int32Array::from(values.iter().map(|v| dict.key(v)).collect::<Vec<_>>());
763        dict.finish_keys(keys)
764    }
765
766    /// Reads the final GT file into a `record_id -> match_type` map. A map
767    /// (rather than a positional `Vec`) keeps the assertions independent of
768    /// draft row order, which is caller-determined (base/dup/other batches
769    /// are pushed as separate, non-interleaved groups in the real pipeline).
770    fn read_match_types(final_path: &str) -> HashMap<String, String> {
771        let file = std::fs::File::open(final_path).unwrap();
772        let reader = arrow::ipc::reader::FileReader::try_new(file, None).unwrap();
773        let mut out = HashMap::new();
774        for batch in reader {
775            let batch = batch.unwrap();
776            let rid = batch
777                .column_by_name("record_id")
778                .unwrap()
779                .as_string::<i32>();
780            // `match_type` is `Dictionary(Int32, Utf8)` (hunt1808/H11) —
781            // cast back to plain `Utf8` for this test-only comparison.
782            let mt_col =
783                arrow::compute::cast(batch.column_by_name("match_type").unwrap(), &DataType::Utf8)
784                    .unwrap();
785            let mt = mt_col.as_string::<i32>();
786            for i in 0..batch.num_rows() {
787                out.insert(rid.value(i).to_string(), mt.value(i).to_string());
788            }
789        }
790        out
791    }
792
793    /// Builds the fixed-width `"{entity_prefix}-{pad_string}"` master_id
794    /// shape `ClusterCsr`'s packing relies on -- all these fixture-building
795    /// tests use a single entity index (0).
796    fn mid(n: usize) -> String {
797        format!(
798            "{}-{}",
799            crate::pipeline::entity_prefix(0),
800            crate::pipeline::pad_string(n)
801        )
802    }
803
804    /// Alias for `pipeline::record_id_string`, for brevity in fixtures.
805    fn rid(i: usize) -> String {
806        crate::pipeline::record_id_string(i)
807    }
808
809    #[test]
810    fn test_gt_accumulator_basic() {
811        let draft = tmp_path("basic_draft");
812        let final_path = tmp_path("basic_final");
813
814        let mut acc = GtAccumulator::new(&draft).unwrap();
815        let et_dict = crate::pipeline::DictValues::new(["person"]);
816        // Base rows: rid(1) (master mid(1), later duplicated), rid(3)
817        // (singleton mid(2)), rid(6) (singleton mid(5)).
818        acc.push_base_batch(
819            &arr_owned(vec![rid(1), rid(3), rid(6)]),
820            &dict_arr(&et_dict, vec!["person", "person", "person"]),
821            &arr_owned(vec![mid(1), mid(2), mid(5)]),
822        )
823        .unwrap();
824        // Dup row: rid(2) duplicates mid(1), unchanged by its noise pass.
825        acc.push_dup_batch(
826            &arr_owned(vec![rid(2)]),
827            &dict_arr(&et_dict, vec!["person"]),
828            &arr_owned(vec![mid(1)]),
829            &barr(vec![true]),
830        )
831        .unwrap();
832        // Hard negatives: rid(4), rid(5).
833        acc.push_other_batch(
834            &arr_owned(vec![rid(4), rid(5)]),
835            &dict_arr(&et_dict, vec!["person", "person"]),
836            &arr(vec!["HN-0000003", "HN-0000004"]),
837        )
838        .unwrap();
839
840        let GtResult {
841            n_exact_dup: ed,
842            n_hard_neg: hn,
843            n_unique: un,
844            n_masters: masters,
845            ..
846        } = acc
847            .finish("medium", "ipc", &final_path, &HashMap::new(), false)
848            .unwrap();
849        assert_eq!(ed, 2);
850        assert_eq!(hn, 2);
851        assert_eq!(un, 2);
852        assert_eq!(masters, 3); // mid(1), mid(2), mid(5)
853
854        let match_types = read_match_types(&final_path);
855        assert_eq!(match_types[&rid(1)], "exact_dup");
856        assert_eq!(match_types[&rid(2)], "exact_dup");
857        assert_eq!(match_types[&rid(3)], "unique");
858        assert_eq!(match_types[&rid(4)], "hard_neg");
859        assert_eq!(match_types[&rid(5)], "hard_neg");
860        assert_eq!(match_types[&rid(6)], "unique");
861
862        std::fs::remove_file(&final_path).ok();
863    }
864
865    /// A duplicate copy whose noise pass actually changed something
866    /// (`is_identical = false`) must be classified `fuzzy_dup`, not
867    /// `exact_dup` — the master itself, and any sibling copy that was left
868    /// unchanged, keep `exact_dup` independently, per row.
869    #[test]
870    fn test_gt_accumulator_fuzzy_dup() {
871        let draft = tmp_path("fuzzy_draft");
872        let final_path = tmp_path("fuzzy_final");
873
874        let mut acc = GtAccumulator::new(&draft).unwrap();
875        let et_dict = crate::pipeline::DictValues::new(["person"]);
876        // Triplet: rid(1) is the master, rid(2) was left unchanged by its
877        // noise pass, rid(3) was genuinely altered.
878        acc.push_base_batch(
879            &arr_owned(vec![rid(1)]),
880            &dict_arr(&et_dict, vec!["person"]),
881            &arr_owned(vec![mid(1)]),
882        )
883        .unwrap();
884        acc.push_dup_batch(
885            &arr_owned(vec![rid(2), rid(3)]),
886            &dict_arr(&et_dict, vec!["person", "person"]),
887            &arr_owned(vec![mid(1), mid(1)]),
888            &barr(vec![true, false]),
889        )
890        .unwrap();
891
892        let GtResult {
893            n_exact_dup: ed,
894            n_fuzzy_dup: fd,
895            n_unique: un,
896            n_masters: masters,
897            ..
898        } = acc
899            .finish("medium", "ipc", &final_path, &HashMap::new(), false)
900            .unwrap();
901        assert_eq!(ed, 2); // rid(1) (master) + rid(2) (unchanged copy)
902        assert_eq!(fd, 1); // rid(3) (genuinely noised copy)
903        assert_eq!(un, 0);
904        assert_eq!(masters, 1);
905
906        let match_types = read_match_types(&final_path);
907        assert_eq!(match_types[&rid(1)], "exact_dup");
908        assert_eq!(match_types[&rid(2)], "exact_dup");
909        assert_eq!(match_types[&rid(3)], "fuzzy_dup");
910
911        std::fs::remove_file(&final_path).ok();
912    }
913
914    #[test]
915    fn test_gt_accumulator_multi_batch() {
916        let draft = tmp_path("multi_draft");
917        let final_path = tmp_path("multi_final");
918
919        let mut acc = GtAccumulator::new(&draft).unwrap();
920        let et_dict = crate::pipeline::DictValues::new(["person"]);
921        // Base batch: two masters, one of which (mid(1)) is duplicated in a
922        // later, separate dup batch — simulating a master's duplicate
923        // landing in a different batch than its base row.
924        acc.push_base_batch(
925            &arr_owned(vec![rid(1), rid(3)]),
926            &dict_arr(&et_dict, vec!["person", "person"]),
927            &arr_owned(vec![mid(1), mid(2)]),
928        )
929        .unwrap();
930        acc.push_dup_batch(
931            &arr_owned(vec![rid(2)]),
932            &dict_arr(&et_dict, vec!["person"]),
933            &arr_owned(vec![mid(1)]),
934            &barr(vec![true]),
935        )
936        .unwrap();
937
938        let GtResult {
939            n_exact_dup: ed,
940            n_hard_neg: hn,
941            n_unique: un,
942            n_masters: masters,
943            ..
944        } = acc
945            .finish("medium", "ipc", &final_path, &HashMap::new(), false)
946            .unwrap();
947        assert_eq!(ed, 2); // both rows of M-0000001
948        assert_eq!(hn, 0);
949        assert_eq!(un, 1);
950        assert_eq!(masters, 2);
951
952        std::fs::remove_file(&final_path).ok();
953    }
954
955    /// Regression: two different entity types can produce master_ids that
956    /// share the same numeric suffix (each entity's index restarts at 0),
957    /// but must not be counted as duplicates of each other.
958    #[test]
959    fn test_no_cross_entity_suffix_collision() {
960        let draft = tmp_path("suffix_draft");
961        let final_path = tmp_path("suffix_final");
962
963        let mut acc = GtAccumulator::new(&draft).unwrap();
964        let et_dict = crate::pipeline::DictValues::new(["person", "account"]);
965        acc.push_base_batch(
966            &arr(vec!["R1", "R2"]),
967            &dict_arr(&et_dict, vec!["person", "account"]),
968            &arr(vec!["PERSON-0000001", "ACCOUNT-0000001"]),
969        )
970        .unwrap();
971
972        let GtResult {
973            n_exact_dup: ed,
974            n_unique: un,
975            n_masters: masters,
976            ..
977        } = acc
978            .finish("medium", "ipc", &final_path, &HashMap::new(), false)
979            .unwrap();
980        assert_eq!(ed, 0);
981        assert_eq!(un, 2);
982        assert_eq!(masters, 2);
983
984        std::fs::remove_file(&final_path).ok();
985    }
986
987    /// `finish()` returns a `cluster_map` mapping each duplicated master_id
988    /// to the full set of `(record_id, is_identical)` pairs in its cluster
989    /// (base + duplicate copies). This is the structure consumed by
990    /// `push_dup_clusters` to decide, per edge, `exact_dup` vs `fuzzy_dup`.
991    #[test]
992    fn test_cluster_map_contents() {
993        let draft = tmp_path("cm_draft");
994        let final_path = tmp_path("cm_final");
995
996        let mut acc = GtAccumulator::new(&draft).unwrap();
997        let et_dict = crate::pipeline::DictValues::new(["person"]);
998        acc.push_base_batch(
999            &arr_owned(vec![rid(1), rid(3), rid(6)]),
1000            &dict_arr(&et_dict, vec!["person", "person", "person"]),
1001            &arr_owned(vec![mid(1), mid(2), mid(5)]),
1002        )
1003        .unwrap();
1004        // rid(2) (mid(1)) stayed identical; rid(7) (mid(5)) was genuinely noised.
1005        acc.push_dup_batch(
1006            &arr_owned(vec![rid(2), rid(7)]),
1007            &dict_arr(&et_dict, vec!["person", "person"]),
1008            &arr_owned(vec![mid(1), mid(5)]),
1009            &barr(vec![true, false]),
1010        )
1011        .unwrap();
1012        acc.push_other_batch(
1013            &arr_owned(vec![rid(4), rid(5)]),
1014            &dict_arr(&et_dict, vec!["person", "person"]),
1015            &arr(vec!["HN-0000003", "HN-0000004"]),
1016        )
1017        .unwrap();
1018
1019        let GtResult {
1020            cluster_map: cm, ..
1021        } = acc
1022            .finish("medium", "ipc", &final_path, &HashMap::new(), true)
1023            .unwrap();
1024
1025        // Only duplicated masters appear; singletons (mid(2)) do not. Groups
1026        // come out in ascending packed-master-key order, i.e. mid(1) (local
1027        // index 1) before mid(5) (local index 5).
1028        assert_eq!(cm.n_clusters(), 2);
1029        let mut groups = cm.groups();
1030        let (records1, idents1) = groups.next().unwrap();
1031        assert_eq!(records1, &[1, 2]);
1032        assert_eq!(idents1.to_vec(), vec![true, true]);
1033        // rid(6) is the base of mid(5); its only copy (rid(7)) was genuinely
1034        // noised, so the cluster has no byte-identical pair at all — rid(6)
1035        // must NOT read as identical just because it's the base (that was
1036        // the bug: base rows used to hardcode `is_identical = true`).
1037        let (records5, idents5) = groups.next().unwrap();
1038        assert_eq!(records5, &[6, 7]);
1039        assert_eq!(idents5.to_vec(), vec![false, false]);
1040        assert!(groups.next().is_none());
1041
1042        std::fs::remove_file(&final_path).ok();
1043    }
1044
1045    // ── perf-hunt RAM pass (hunt1708.md) ─────────────────────────────────
1046    //
1047    // Not a correctness test -- #[ignore]'d so it never runs in normal
1048    // `cargo test`. Isolated measurement (never a full pipeline run, per
1049    // perf-hunt rule 4): compares process RSS growth for two separate
1050    // `FxHashSet<u64>` (`dup_masters` + `masters_with_exact_copy` as they
1051    // exist today) against one combined `FxHashMap<u64, bool>`, at the
1052    // cardinality actually observed on a real run (aviation/hell/50M:
1053    // masters=21,666,666, uniques=5,855,236 -> dup_masters.len() ~=
1054    // 15,811,430; masters_with_exact_copy is a subset, sized here at 70%
1055    // of that as a representative estimate -- exact_dups=23,237,057 of
1056    // fuzzy+exact=44,144,764 total duplicate rows is ~53% at the row
1057    // level, but a master with ANY identical copy is more common than
1058    // that row-level fraction suggests, so 70% is a deliberately
1059    // generous (not cherry-picked-low) estimate for this comparison).
1060    // Run with:
1061    //   cargo test --release gt::tests::hunt_ram_dup_masters_vs_combined_map -- --ignored --nocapture
1062    #[test]
1063    #[ignore]
1064    fn hunt_ram_dup_masters_vs_combined_map() {
1065        fn rss_mb() -> f64 {
1066            let pid = sysinfo::Pid::from_u32(std::process::id());
1067            let mut sys = sysinfo::System::new();
1068            sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
1069            sys.process(pid)
1070                .map(|p| p.memory() as f64 / 1e6)
1071                .unwrap_or(0.0)
1072        }
1073
1074        const N_DUP_MASTERS: usize = 15_811_430;
1075        const N_EXACT_COPY: usize = (N_DUP_MASTERS as f64 * 0.70) as usize;
1076
1077        // Deterministic, well-spread u64 keys (not sequential -- sequential
1078        // keys would let the hash table's bucket layout be unrealistically
1079        // cache-friendly compared to the real `pack_master_key` output,
1080        // which mixes an entity_idx high-bit prefix with a local counter).
1081        // A cheap SplitMix64-style mix is enough to spread bits without
1082        // pulling in a new dependency for a throwaway measurement.
1083        fn mix(i: u64) -> u64 {
1084            let mut z = i.wrapping_add(0x9E3779B97F4A7C15);
1085            z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
1086            z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
1087            z ^ (z >> 31)
1088        }
1089
1090        // ── Scenario A: two separate FxHashSet<u64> (today's shape) ────────
1091        let rss0 = rss_mb();
1092        let mut dup_masters: rustc_hash::FxHashSet<u64> =
1093            rustc_hash::FxHashSet::with_capacity_and_hasher(N_DUP_MASTERS, Default::default());
1094        for i in 0..N_DUP_MASTERS as u64 {
1095            dup_masters.insert(mix(i));
1096        }
1097        let mut masters_with_exact_copy: rustc_hash::FxHashSet<u64> =
1098            rustc_hash::FxHashSet::with_capacity_and_hasher(N_EXACT_COPY, Default::default());
1099        for i in 0..N_EXACT_COPY as u64 {
1100            // Subset of the same key space as dup_masters (every master
1101            // with an exact copy is also in dup_masters), same mix.
1102            masters_with_exact_copy.insert(mix(i));
1103        }
1104        let rss_two_sets = rss_mb();
1105        println!(
1106            "[hunt_ram] two FxHashSet<u64> ({} + {} entries): rss delta = {:.1} Mo (rss0={:.1} -> {:.1})",
1107            dup_masters.len(),
1108            masters_with_exact_copy.len(),
1109            rss_two_sets - rss0,
1110            rss0,
1111            rss_two_sets
1112        );
1113        drop(dup_masters);
1114        drop(masters_with_exact_copy);
1115
1116        // ── Scenario B: one combined FxHashMap<u64, bool> ──────────────────
1117        let rss1 = rss_mb();
1118        let mut combined: rustc_hash::FxHashMap<u64, bool> =
1119            rustc_hash::FxHashMap::with_capacity_and_hasher(N_DUP_MASTERS, Default::default());
1120        for i in 0..N_DUP_MASTERS as u64 {
1121            combined.insert(mix(i), i < N_EXACT_COPY as u64);
1122        }
1123        let rss_combined = rss_mb();
1124        println!(
1125            "[hunt_ram] one FxHashMap<u64,bool> ({} entries): rss delta = {:.1} Mo (rss1={:.1} -> {:.1})",
1126            combined.len(),
1127            rss_combined - rss1,
1128            rss1,
1129            rss_combined
1130        );
1131        drop(combined);
1132
1133        let delta_two = rss_two_sets - rss0;
1134        let delta_one = rss_combined - rss1;
1135        println!(
1136            "[hunt_ram] combined map saves {:.1} Mo ({:.1}%) vs two separate sets, at this cardinality",
1137            delta_two - delta_one,
1138            100.0 * (delta_two - delta_one) / delta_two.max(1.0)
1139        );
1140    }
1141}