coip-builder 0.2.0

Generic columnar .coi builder and MaxMind .mmdb importer (with simplified English name extraction)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
//! IPv4 / IPv6 transition merging, L1 bucket table generation, Zstd dictionary training,
//! and Granule Block encoding (supporting Zstd, LZ4, None, and all 5 `RidMode`s).

use std::collections::HashMap;

use coip_format::{
    Codec, HostExtEntry, IndexHeader, Ipv6HostExt, NO_ZSTD_DICT, RidMode, crc32c, write_svarint,
    write_uvarint,
};
use rayon::prelude::*;

use crate::column_writer::compress_with_codec;
use crate::error::Result;
use crate::mmdb::{V4Interval, V6HostInterval, V6Interval};

/// Output of encoding an IPv4 or IPv6 index section, along with any newly trained Zstd dictionaries.
pub struct EncodedIpIndex {
    pub bytes: Vec<u8>,
}

/// Merge sorted non-overlapping IPv4 intervals into minimal transition points `(start_ip, record_id)`.
pub fn merge_v4_transitions(intervals: &[V4Interval]) -> Vec<(u32, u64)> {
    if intervals.is_empty() {
        return Vec::new();
    }
    let mut transitions: Vec<(u32, u64)> = Vec::with_capacity(intervals.len());
    let mut prev_end: Option<u32> = None;
    let mut cur_rid: u64 = 0;

    for iv in intervals {
        let rid = iv.record_idx as u64;
        if let Some(pe) = prev_end {
            if iv.start > pe + 1 && cur_rid != 0 {
                transitions.push((pe + 1, 0));
                cur_rid = 0;
            }
        }
        if rid != cur_rid {
            transitions.push((iv.start, rid));
            cur_rid = rid;
        }
        prev_end = Some(iv.end);
    }

    if let Some(pe) = prev_end {
        if pe < u32::MAX && cur_rid != 0 {
            transitions.push((pe + 1, 0));
        }
    }
    transitions
}

/// Merge sorted non-overlapping IPv6 `/64` intervals into minimal transition points `(start_hi64, record_id)`.
pub fn merge_v6_transitions(intervals: &[V6Interval]) -> Vec<(u64, u64)> {
    if intervals.is_empty() {
        return Vec::new();
    }
    let mut transitions: Vec<(u64, u64)> = Vec::with_capacity(intervals.len());
    let mut prev_end: Option<u64> = None;
    let mut cur_rid: u64 = 0;

    for iv in intervals {
        let rid = iv.record_idx as u64;
        if let Some(pe) = prev_end {
            if iv.start > pe + 1 && cur_rid != 0 {
                transitions.push((pe + 1, 0));
                cur_rid = 0;
            }
        }
        if rid != cur_rid {
            transitions.push((iv.start, rid));
            cur_rid = rid;
        }
        prev_end = Some(iv.end);
    }

    if let Some(pe) = prev_end {
        if pe < u64::MAX && cur_rid != 0 {
            transitions.push((pe + 1, 0));
        }
    }
    transitions
}

/// Merge adjacent `Ipv6HostExt` intervals with identical `record_id`.
pub fn build_host_ext(intervals: &[V6HostInterval]) -> Ipv6HostExt {
    let mut entries: Vec<HostExtEntry> = Vec::new();
    for iv in intervals {
        let rid = iv.record_idx as u64;
        if let Some(last) = entries.last_mut() {
            if last.record_id == rid && last.end.checked_add(1) == Some(iv.start) {
                last.end = iv.end;
                continue;
            }
        }
        entries.push(HostExtEntry {
            start: iv.start,
            end: iv.end,
            record_id: rid,
        });
    }
    Ipv6HostExt { entries }
}

/// Train a Zstd dictionary on sampled raw buffers; returns `Some(dict_bytes)` only if
/// using the dict yields a net size reduction across the full dataset (accounting for dict size).
fn maybe_train_zstd_dict(
    samples: &[Vec<u8>],
    total_blocks: usize,
    max_dict_size: usize,
    zstd_level: i32,
) -> Option<Vec<u8>> {
    if samples.len() < 16 || total_blocks < 32 {
        return None;
    }
    let dict = zstd::dict::from_samples(samples, max_dict_size).ok()?;
    if dict.is_empty() {
        return None;
    }

    // Verify net savings on a representative subset of samples
    let eval_count = samples.len().min(96);
    let step = (samples.len() / eval_count).max(1);
    let key = crc32c(&dict);
    let mut no_dict_bytes = 0usize;
    let mut with_dict_bytes = 0usize;
    let mut eval_n = 0usize;

    for s in samples.iter().step_by(step).take(eval_count) {
        let a = compress_with_codec(Codec::Zstd, s, zstd_level.min(6), None).ok()?;
        let b = compress_with_codec(Codec::Zstd, s, zstd_level.min(6), Some((key, &dict))).ok()?;
        no_dict_bytes += a.len();
        with_dict_bytes += b.len();
        eval_n += 1;
    }

    if eval_n == 0 || with_dict_bytes >= no_dict_bytes {
        return None;
    }
    let projected_saving =
        ((no_dict_bytes - with_dict_bytes) as f64 / eval_n as f64) * (total_blocks as f64);
    // Keep dictionary only if projected total savings comfortably exceed the dictionary's own size.
    if projected_saving > (dict.len() as f64) * 1.25 {
        Some(dict)
    } else {
        None
    }
}

/// Encode Section 5 (`Ipv4Index`) from merged `(start_u32, record_id)` transitions.
#[allow(clippy::too_many_arguments)]
pub fn encode_ipv4_index(
    transitions: &[(u32, u64)],
    block_size: u32,
    l1_bits: u8,
    codec: Codec,
    zstd_level: i32,
    train_zstd_dicts: bool,
    zstd_dicts: &mut Vec<Vec<u8>>,
) -> Result<EncodedIpIndex> {
    let block_size = block_size.max(1) as usize;
    let entry_count = transitions.len();
    let block_count = if entry_count == 0 {
        0
    } else {
        entry_count.div_ceil(block_size)
    };
    let effective_l1_bits = if block_count <= 64 { 0 } else { l1_bits };

    let mut first_ips: Vec<u32> = Vec::with_capacity(block_count);
    for b in 0..block_count {
        first_ips.push(transitions[b * block_size].0);
    }

    // Optionally train Zstd dictionaries on sampled raw starts & rids streams.
    let (starts_dict_id, starts_dict_pair) =
        if codec == Codec::Zstd && train_zstd_dicts && block_count >= 32 {
            let sample_n = block_count.min(384);
            let step = (block_count / sample_n).max(1);
            let samples: Vec<Vec<u8>> = (0..block_count)
                .step_by(step)
                .take(sample_n)
                .map(|b| {
                    let s = b * block_size;
                    let e = (s + block_size).min(entry_count);
                    encode_raw_starts_u32(&transitions[s..e])
                })
                .collect();
            if let Some(dict) = maybe_train_zstd_dict(&samples, block_count, 24 * 1024, zstd_level)
            {
                let id = zstd_dicts.len() as u16;
                let key = crc32c(&dict);
                zstd_dicts.push(dict);
                (id, Some((key, id)))
            } else {
                (NO_ZSTD_DICT, None)
            }
        } else {
            (NO_ZSTD_DICT, None)
        };

    let (rids_dict_id, rids_dict_pair) =
        if codec == Codec::Zstd && train_zstd_dicts && block_count >= 32 {
            let sample_n = block_count.min(384);
            let step = (block_count / sample_n).max(1);
            let samples: Vec<Vec<u8>> = (0..block_count)
                .step_by(step)
                .take(sample_n)
                .map(|b| {
                    let s = b * block_size;
                    let e = (s + block_size).min(entry_count);
                    let rids: Vec<u64> = transitions[s..e].iter().map(|x| x.1).collect();
                    best_raw_rids_for_training(&rids)
                })
                .collect();
            if let Some(dict) = maybe_train_zstd_dict(&samples, block_count, 48 * 1024, zstd_level)
            {
                let id = zstd_dicts.len() as u16;
                let key = crc32c(&dict);
                zstd_dicts.push(dict);
                (id, Some((key, id)))
            } else {
                (NO_ZSTD_DICT, None)
            }
        } else {
            (NO_ZSTD_DICT, None)
        };

    let starts_dict_ref = starts_dict_pair.map(|(k, id)| (k, zstd_dicts[id as usize].as_slice()));
    let rids_dict_ref = rids_dict_pair.map(|(k, id)| (k, zstd_dicts[id as usize].as_slice()));

    let blocks: Result<Vec<Vec<u8>>> = (0..block_count)
        .into_par_iter()
        .map(|b| {
            let s = b * block_size;
            let e = (s + block_size).min(entry_count);
            encode_granule_block_u32(
                &transitions[s..e],
                codec,
                zstd_level,
                starts_dict_ref,
                rids_dict_ref,
            )
        })
        .collect();
    let blocks = blocks?;

    let header = IndexHeader {
        entry_count: entry_count as u64,
        block_size: block_size as u32,
        block_count: block_count as u32,
        l1_bits: effective_l1_bits,
        starts_codec: codec,
        rids_codec: codec,
        starts_zstd_dict_id: starts_dict_id,
        rids_zstd_dict_id: rids_dict_id,
    };

    let l1_count = if effective_l1_bits > 0 {
        (1usize << effective_l1_bits) + 1
    } else {
        0
    };
    let total_blocks_bytes: usize = blocks.iter().map(Vec::len).sum();
    let mut out = Vec::with_capacity(
        coip_format::INDEX_HEADER_SIZE
            + l1_count * 4
            + block_count * 4
            + (block_count + 1) * 8
            + total_blocks_bytes,
    );

    out.extend_from_slice(&header.encode());

    if effective_l1_bits > 0 {
        let buckets = build_l1_buckets_u32(&first_ips, effective_l1_bits);
        for b in buckets {
            out.extend_from_slice(&b.to_le_bytes());
        }
    }

    for &ip in &first_ips {
        out.extend_from_slice(&ip.to_le_bytes());
    }
    let mut off = 0u64;
    for blk in &blocks {
        out.extend_from_slice(&off.to_le_bytes());
        off += blk.len() as u64;
    }
    out.extend_from_slice(&off.to_le_bytes());

    for blk in blocks {
        out.extend_from_slice(&blk);
    }
    Ok(EncodedIpIndex { bytes: out })
}

/// Encode Section 6 (`Ipv6Index`) from merged `(start_hi64, record_id)` transitions.
#[allow(clippy::too_many_arguments)]
pub fn encode_ipv6_index(
    transitions: &[(u64, u64)],
    block_size: u32,
    l1_bits: u8,
    codec: Codec,
    zstd_level: i32,
    train_zstd_dicts: bool,
    zstd_dicts: &mut Vec<Vec<u8>>,
) -> Result<EncodedIpIndex> {
    let block_size = block_size.max(1) as usize;
    let entry_count = transitions.len();
    let block_count = if entry_count == 0 {
        0
    } else {
        entry_count.div_ceil(block_size)
    };
    let effective_l1_bits = if block_count <= 64 { 0 } else { l1_bits };

    let mut first_ips: Vec<u64> = Vec::with_capacity(block_count);
    for b in 0..block_count {
        first_ips.push(transitions[b * block_size].0);
    }

    let (starts_dict_id, starts_dict_pair) =
        if codec == Codec::Zstd && train_zstd_dicts && block_count >= 32 {
            let sample_n = block_count.min(384);
            let step = (block_count / sample_n).max(1);
            let samples: Vec<Vec<u8>> = (0..block_count)
                .step_by(step)
                .take(sample_n)
                .map(|b| {
                    let s = b * block_size;
                    let e = (s + block_size).min(entry_count);
                    encode_raw_starts_u64(&transitions[s..e])
                })
                .collect();
            if let Some(dict) = maybe_train_zstd_dict(&samples, block_count, 24 * 1024, zstd_level)
            {
                let id = zstd_dicts.len() as u16;
                let key = crc32c(&dict);
                zstd_dicts.push(dict);
                (id, Some((key, id)))
            } else {
                (NO_ZSTD_DICT, None)
            }
        } else {
            (NO_ZSTD_DICT, None)
        };

    let (rids_dict_id, rids_dict_pair) =
        if codec == Codec::Zstd && train_zstd_dicts && block_count >= 32 {
            let sample_n = block_count.min(384);
            let step = (block_count / sample_n).max(1);
            let samples: Vec<Vec<u8>> = (0..block_count)
                .step_by(step)
                .take(sample_n)
                .map(|b| {
                    let s = b * block_size;
                    let e = (s + block_size).min(entry_count);
                    let rids: Vec<u64> = transitions[s..e].iter().map(|x| x.1).collect();
                    best_raw_rids_for_training(&rids)
                })
                .collect();
            if let Some(dict) = maybe_train_zstd_dict(&samples, block_count, 32 * 1024, zstd_level)
            {
                let id = zstd_dicts.len() as u16;
                let key = crc32c(&dict);
                zstd_dicts.push(dict);
                (id, Some((key, id)))
            } else {
                (NO_ZSTD_DICT, None)
            }
        } else {
            (NO_ZSTD_DICT, None)
        };

    let starts_dict_ref = starts_dict_pair.map(|(k, id)| (k, zstd_dicts[id as usize].as_slice()));
    let rids_dict_ref = rids_dict_pair.map(|(k, id)| (k, zstd_dicts[id as usize].as_slice()));

    let blocks: Result<Vec<Vec<u8>>> = (0..block_count)
        .into_par_iter()
        .map(|b| {
            let s = b * block_size;
            let e = (s + block_size).min(entry_count);
            encode_granule_block_u64(
                &transitions[s..e],
                codec,
                zstd_level,
                starts_dict_ref,
                rids_dict_ref,
            )
        })
        .collect();
    let blocks = blocks?;

    let header = IndexHeader {
        entry_count: entry_count as u64,
        block_size: block_size as u32,
        block_count: block_count as u32,
        l1_bits: effective_l1_bits,
        starts_codec: codec,
        rids_codec: codec,
        starts_zstd_dict_id: starts_dict_id,
        rids_zstd_dict_id: rids_dict_id,
    };

    let l1_count = if effective_l1_bits > 0 {
        (1usize << effective_l1_bits) + 1
    } else {
        0
    };
    let total_blocks_bytes: usize = blocks.iter().map(Vec::len).sum();
    let mut out = Vec::with_capacity(
        coip_format::INDEX_HEADER_SIZE
            + l1_count * 4
            + block_count * 8
            + (block_count + 1) * 8
            + total_blocks_bytes,
    );

    out.extend_from_slice(&header.encode());

    if effective_l1_bits > 0 {
        let buckets = build_l1_buckets_u64(&first_ips, effective_l1_bits);
        for b in buckets {
            out.extend_from_slice(&b.to_le_bytes());
        }
    }

    for &ip in &first_ips {
        out.extend_from_slice(&ip.to_le_bytes());
    }
    let mut off = 0u64;
    for blk in &blocks {
        out.extend_from_slice(&off.to_le_bytes());
        off += blk.len() as u64;
    }
    out.extend_from_slice(&off.to_le_bytes());

    for blk in blocks {
        out.extend_from_slice(&blk);
    }
    Ok(EncodedIpIndex { bytes: out })
}

fn build_l1_buckets_u32(first_ips: &[u32], l1_bits: u8) -> Vec<u32> {
    let n = 1usize << l1_bits;
    let shift = 32 - l1_bits;
    let mut buckets = Vec::with_capacity(n + 1);
    let mut b = 0usize;
    for p in 0..n {
        let prefix_start = (p as u32) << shift;
        while b + 1 < first_ips.len() && first_ips[b + 1] <= prefix_start {
            b += 1;
        }
        if first_ips[b] <= prefix_start {
            buckets.push(b as u32);
        } else {
            buckets.push(0);
        }
    }
    buckets.push((first_ips.len().saturating_sub(1)) as u32);
    buckets
}

fn build_l1_buckets_u64(first_ips: &[u64], l1_bits: u8) -> Vec<u32> {
    let n = 1usize << l1_bits;
    let shift = 64 - l1_bits;
    let mut buckets = Vec::with_capacity(n + 1);
    let mut b = 0usize;
    for p in 0..n {
        let prefix_start = (p as u64) << shift;
        while b + 1 < first_ips.len() && first_ips[b + 1] <= prefix_start {
            b += 1;
        }
        if first_ips[b] <= prefix_start {
            buckets.push(b as u32);
        } else {
            buckets.push(0);
        }
    }
    buckets.push((first_ips.len().saturating_sub(1)) as u32);
    buckets
}

fn encode_raw_starts_u32(entries: &[(u32, u64)]) -> Vec<u8> {
    let mut raw = Vec::with_capacity(entries.len() * 3);
    for w in entries.windows(2) {
        let delta = (w[1].0 - w[0].0) as u64;
        write_uvarint(&mut raw, delta);
    }
    raw
}

fn encode_raw_starts_u64(entries: &[(u64, u64)]) -> Vec<u8> {
    let mut raw = Vec::with_capacity(entries.len() * 4);
    for w in entries.windows(2) {
        let delta = w[1].0 - w[0].0;
        write_uvarint(&mut raw, delta);
    }
    raw
}

fn encode_granule_block_u32(
    entries: &[(u32, u64)],
    codec: Codec,
    zstd_level: i32,
    starts_dict: Option<(u32, &[u8])>,
    rids_dict: Option<(u32, &[u8])>,
) -> Result<Vec<u8>> {
    let raw_starts = encode_raw_starts_u32(entries);
    let starts_blob = compress_with_codec(codec, &raw_starts, zstd_level, starts_dict)?;

    let rids: Vec<u64> = entries.iter().map(|e| e.1).collect();
    let rids_blob = encode_best_rids_blob(&rids, codec, zstd_level, rids_dict)?;

    let mut block = Vec::with_capacity(4 + starts_blob.len() + rids_blob.len());
    block.extend_from_slice(&(starts_blob.len() as u32).to_le_bytes());
    block.extend_from_slice(&starts_blob);
    block.extend_from_slice(&rids_blob);
    Ok(block)
}

fn encode_granule_block_u64(
    entries: &[(u64, u64)],
    codec: Codec,
    zstd_level: i32,
    starts_dict: Option<(u32, &[u8])>,
    rids_dict: Option<(u32, &[u8])>,
) -> Result<Vec<u8>> {
    let raw_starts = encode_raw_starts_u64(entries);
    let starts_blob = compress_with_codec(codec, &raw_starts, zstd_level, starts_dict)?;

    let rids: Vec<u64> = entries.iter().map(|e| e.1).collect();
    let rids_blob = encode_best_rids_blob(&rids, codec, zstd_level, rids_dict)?;

    let mut block = Vec::with_capacity(4 + starts_blob.len() + rids_blob.len());
    block.extend_from_slice(&(starts_blob.len() as u32).to_le_bytes());
    block.extend_from_slice(&starts_blob);
    block.extend_from_slice(&rids_blob);
    Ok(block)
}

fn build_rids_candidates(rids: &[u64]) -> Vec<Vec<u8>> {
    let mut candidates: Vec<Vec<u8>> = Vec::with_capacity(5);
    let has_zero = rids.contains(&0);

    // Mode 0: ZigZagDeltaVarint
    let mut raw_delta = Vec::with_capacity(1 + rids.len() * 3);
    raw_delta.push(RidMode::ZigZagDeltaVarint as u8);
    if let Some(&first) = rids.first() {
        write_uvarint(&mut raw_delta, first);
        let mut prev = first;
        for &r in &rids[1..] {
            let d = r.wrapping_sub(prev) as i64;
            write_svarint(&mut raw_delta, d);
            prev = r;
        }
    }
    candidates.push(raw_delta);

    // Mode 3: ZeroSkipDelta (whenever block contains at least one `0` gap)
    if has_zero && !rids.is_empty() {
        let bm_len = rids.len().div_ceil(8);
        let mut raw_zs = Vec::with_capacity(1 + bm_len + rids.len() * 2);
        raw_zs.push(RidMode::ZeroSkipDelta as u8);
        let bm_start = raw_zs.len();
        raw_zs.resize(bm_start + bm_len, 0);
        let mut prev_nz: Option<u64> = None;
        for (i, &r) in rids.iter().enumerate() {
            if r != 0 {
                raw_zs[bm_start + (i >> 3)] |= 1u8 << (i & 7);
                match prev_nz {
                    None => write_uvarint(&mut raw_zs, r),
                    Some(p) => write_svarint(&mut raw_zs, r.wrapping_sub(p) as i64),
                }
                prev_nz = Some(r);
            }
        }
        candidates.push(raw_zs);
    }

    // Mode 1 (LocalDict) and Mode 4 (LocalDictSplit for > 256 unique rids)
    let mut sorted_unique: Vec<u64> = rids.to_vec();
    sorted_unique.sort_unstable();
    sorted_unique.dedup();
    if !sorted_unique.is_empty()
        && sorted_unique.len() <= 65_536
        && sorted_unique.len() < rids.len()
    {
        let mut map: HashMap<u64, u16> = HashMap::with_capacity(sorted_unique.len());
        for (idx, &val) in sorted_unique.iter().enumerate() {
            map.insert(val, idx as u16);
        }

        // Common dictionary prefix: dict_len + sorted delta-varints
        let mut dict_header = Vec::with_capacity(sorted_unique.len() * 3 + 8);
        write_uvarint(&mut dict_header, sorted_unique.len() as u64);
        write_uvarint(&mut dict_header, sorted_unique[0]);
        for w in sorted_unique.windows(2) {
            write_uvarint(&mut dict_header, w[1] - w[0]);
        }

        if sorted_unique.len() <= 256 {
            let mut raw_dict = Vec::with_capacity(1 + dict_header.len() + rids.len());
            raw_dict.push(RidMode::LocalDict as u8);
            raw_dict.extend_from_slice(&dict_header);
            for &r in rids {
                raw_dict.push(map[&r] as u8);
            }
            candidates.push(raw_dict);
        } else {
            // Mode 1: interleaved u16 LE
            let mut raw_dict = Vec::with_capacity(1 + dict_header.len() + rids.len() * 2);
            raw_dict.push(RidMode::LocalDict as u8);
            raw_dict.extend_from_slice(&dict_header);
            for &r in rids {
                raw_dict.extend_from_slice(&map[&r].to_le_bytes());
            }
            candidates.push(raw_dict);

            // Mode 4: byte-plane split [lo_0..lo_{n-1}][hi_0..hi_{n-1}]
            let mut raw_split = Vec::with_capacity(1 + dict_header.len() + rids.len() * 2);
            raw_split.push(RidMode::LocalDictSplit as u8);
            raw_split.extend_from_slice(&dict_header);
            for &r in rids {
                raw_split.push((map[&r] & 0xFF) as u8);
            }
            for &r in rids {
                raw_split.push((map[&r] >> 8) as u8);
            }
            candidates.push(raw_split);
        }
    }

    // Mode 2: RLE
    let runs = if rids.is_empty() {
        0
    } else {
        1 + rids.windows(2).filter(|w| w[0] != w[1]).count()
    };
    if runs > 0 && runs * 3 <= rids.len() * 2 {
        let mut raw_rle = Vec::with_capacity(1 + runs * 4);
        raw_rle.push(RidMode::Rle as u8);
        let mut i = 0;
        while i < rids.len() {
            let cur = rids[i];
            let mut run = 1u64;
            while i + (run as usize) < rids.len() && rids[i + (run as usize)] == cur {
                run += 1;
            }
            write_uvarint(&mut raw_rle, cur);
            write_uvarint(&mut raw_rle, run);
            i += run as usize;
        }
        candidates.push(raw_rle);
    }

    candidates
}

/// Pick the best raw candidate quickly (level 3 Zstd) for dictionary training samples.
fn best_raw_rids_for_training(rids: &[u64]) -> Vec<u8> {
    let candidates = build_rids_candidates(rids);
    candidates
        .into_iter()
        .min_by_key(|raw| {
            compress_with_codec(Codec::Zstd, raw, 3, None)
                .map(|c| c.len())
                .unwrap_or(raw.len())
        })
        .unwrap()
}

fn encode_best_rids_blob(
    rids: &[u64],
    codec: Codec,
    zstd_level: i32,
    rids_dict: Option<(u32, &[u8])>,
) -> Result<Vec<u8>> {
    let candidates = build_rids_candidates(rids);
    if codec == Codec::None {
        return Ok(candidates.into_iter().min_by_key(Vec::len).unwrap());
    }

    let mut best: Option<Vec<u8>> = None;
    for raw in &candidates {
        let comp = compress_with_codec(codec, raw, zstd_level, rids_dict)?;
        if best.as_ref().is_none_or(|b| comp.len() < b.len()) {
            best = Some(comp);
        }
    }
    Ok(best.unwrap())
}