coip-builder 0.1.0

Generic columnar .coi builder and 100% lossless MaxMind .mmdb importer
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
//! High-level generic `CoipBuilder` and `.mmdb` -> `.coi` converter.

use std::collections::{BTreeMap, HashMap};
use std::io::Write;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::path::Path;

use coip_format::{
    AliasRule, Codec, FORMAT_MAJOR, FORMAT_MINOR, FileFooter, FileHeader, HEADER_SIZE, Ipv6Aliases,
    SECTION_ENTRY_SIZE, SectionEntry, SectionKind, Value, ZstdDicts, align8, crc32c, header_flags,
    range_to_cidrs_v4, range_to_cidrs_v6,
};

use crate::column_writer::compress_with_codec;
use crate::error::{BuilderError, Result};
use crate::index_writer::{
    build_host_ext, encode_ipv4_index, encode_ipv6_index, merge_v4_transitions,
    merge_v6_transitions,
};
use crate::lpm::{resolve_lpm_v4, resolve_lpm_v6, resolve_lpm_v6_host};
use crate::mmdb::{V4Interval, V6HostInterval, V6Interval, extract_mmdb};
use crate::prune::{PruneConfig, apply_pruning};
use crate::schema_infer::{ColumnarBuildConfig, RowOrderStrategy, infer_and_encode_records};

/// Build options for creating `.coi` files.
#[derive(Debug, Clone)]
pub struct BuildOptions {
    /// Compression profile codec (`Codec::Zstd` for Compact, `Codec::Lz4` for UltraFast, `Codec::None` for raw).
    pub profile_codec: Codec,
    /// Zstd compression level (1..=19, default 9; ignored for non-Zstd profiles).
    pub zstd_level: i32,
    /// Whether to automatically train `Section 3: ZstdDicts` for IP index blocks (Compact profile).
    pub train_zstd_dicts: bool,
    /// Granule block size for IPv4/IPv6 transition indexes (default 2048 for Compact, 512 for UltraFast).
    pub index_block_size: u32,
    /// L1 direct bucket prefix bits for IPv4 index (default 16).
    pub ipv4_l1_bits: u8,
    /// L1 direct bucket prefix bits for IPv6 index (default 0; sparse index is ~11 KB in L1 cache).
    pub ipv6_l1_bits: u8,
    /// RowGroup size for `RecordColumns` (default 4096 for Compact, 1024 for UltraFast).
    pub row_group_size: u32,
    /// RowGroup size for `StructDict` tables (default 2048 for Compact, 512 for UltraFast).
    pub struct_dict_row_group_size: u32,
    /// Block size for large `FlatDict` tables (> 8192 entries, default 4096).
    pub dict_block_size: u32,
    /// Row ordering strategy for unique records.
    pub row_order: RowOrderStrategy,
    /// Optional build-time field & language pruning (auto-deduplicates records & collapses IP transitions).
    pub prune: Option<PruneConfig>,
}

impl BuildOptions {
    /// Default **`Compact`** profile: Zstd blocks + trained Zstd dictionaries for maximum compression (~4.5–5.5×).
    pub fn compact() -> Self {
        Self {
            profile_codec: Codec::Zstd,
            zstd_level: 9,
            train_zstd_dicts: true,
            index_block_size: 2048,
            ipv4_l1_bits: 16,
            ipv6_l1_bits: 0,
            row_group_size: 4096,
            struct_dict_row_group_size: 2048,
            dict_block_size: 4096,
            row_order: RowOrderStrategy::GeoLocality,
            prune: None,
        }
    }

    /// **`UltraFast`** profile: pure-Rust LZ4 blocks + fine-grained 512/1024 chunks for microsecond cold lookups.
    pub fn ultrafast() -> Self {
        Self {
            profile_codec: Codec::Lz4,
            zstd_level: 1,
            train_zstd_dicts: false,
            index_block_size: 512,
            ipv4_l1_bits: 16,
            ipv6_l1_bits: 0,
            row_group_size: 1024,
            struct_dict_row_group_size: 512,
            dict_block_size: 1024,
            row_order: RowOrderStrategy::GeoLocality,
            prune: None,
        }
    }
}

impl Default for BuildOptions {
    fn default() -> Self {
        Self::compact()
    }
}

/// Statistics returned after building a `.coi` file.
#[derive(Debug, Clone)]
pub struct BuildStats {
    pub total_bytes: u64,
    pub record_count: u64,
    pub v4_transitions: usize,
    pub v6_transitions: usize,
    pub v6_host_ext_entries: usize,
    pub ipv6_alias_count: usize,
    pub dict_count: usize,
    pub section_sizes: Vec<(SectionKind, u64)>,
}

/// Generic builder for arbitrary IPv4/IPv6 columnar `.coi` databases.
pub struct CoipBuilder {
    options: BuildOptions,
    build_epoch: u64,
    metadata: serde_json::Map<String, serde_json::Value>,
    ipv6_aliases: Vec<AliasRule>,
    v4_intervals: Vec<V4Interval>,
    v6_intervals: Vec<V6Interval>,
    v6_host_ext: Vec<V6HostInterval>,
    record_dedup: HashMap<BTreeMap<String, Value>, u32>,
    unique_records: Vec<BTreeMap<String, Value>>,
}

impl CoipBuilder {
    pub fn new(options: BuildOptions) -> Self {
        let mut metadata = serde_json::Map::new();
        metadata.insert(
            "generator".into(),
            serde_json::Value::String(format!("coip-builder {}", env!("CARGO_PKG_VERSION"))),
        );
        Self {
            options,
            build_epoch: 0,
            metadata,
            ipv6_aliases: Vec::new(),
            v4_intervals: Vec::new(),
            v6_intervals: Vec::new(),
            v6_host_ext: Vec::new(),
            record_dedup: HashMap::new(),
            unique_records: Vec::new(),
        }
    }

    pub fn set_build_epoch(&mut self, epoch: u64) -> &mut Self {
        self.build_epoch = epoch;
        self.metadata
            .insert("build_epoch".into(), serde_json::Value::from(epoch));
        self
    }

    pub fn set_metadata_field(
        &mut self,
        key: impl Into<String>,
        val: serde_json::Value,
    ) -> &mut Self {
        self.metadata.insert(key.into(), val);
        self
    }

    pub fn add_ipv6_alias(&mut self, rule: AliasRule) -> &mut Self {
        self.ipv6_aliases.push(rule);
        self
    }

    fn intern_record(&mut self, record: BTreeMap<String, Value>) -> u32 {
        if let Some(&id) = self.record_dedup.get(&record) {
            return id;
        }
        let id = (self.unique_records.len() + 1) as u32;
        self.record_dedup.insert(record.clone(), id);
        self.unique_records.push(record);
        id
    }

    /// Insert an IPv4 CIDR block (`addr/prefix_len`) mapped to `record`.
    /// Overlapping CIDRs are automatically resolved via Longest-Prefix-Match (last-insert-wins on ties).
    pub fn insert_ipv4_cidr(
        &mut self,
        addr: Ipv4Addr,
        prefix_len: u8,
        record: BTreeMap<String, Value>,
    ) -> Result<&mut Self> {
        let rid = self.intern_record(record);
        self.push_ipv4_cidr_rid(addr, prefix_len, rid)
    }

    /// Punch an explicit NotFound hole (`record_id = 0`) at an IPv4 CIDR (overrides broader prefixes via LPM).
    pub fn delete_ipv4_cidr(&mut self, addr: Ipv4Addr, prefix_len: u8) -> Result<&mut Self> {
        self.push_ipv4_cidr_rid(addr, prefix_len, 0)
    }

    fn push_ipv4_cidr_rid(
        &mut self,
        addr: Ipv4Addr,
        prefix_len: u8,
        rid: u32,
    ) -> Result<&mut Self> {
        if prefix_len > 32 {
            return Err(BuilderError::InvalidInput(format!(
                "invalid IPv4 prefix length {prefix_len}"
            )));
        }
        let ip = u32::from(addr);
        let (start, end) = if prefix_len == 0 {
            (0u32, u32::MAX)
        } else if prefix_len == 32 {
            (ip, ip)
        } else {
            let mask = !((1u32 << (32 - prefix_len)) - 1);
            let s = ip & mask;
            let e = s | !mask;
            (s, e)
        };
        self.v4_intervals.push(V4Interval {
            start,
            end,
            record_idx: rid,
        });
        Ok(self)
    }

    /// Insert an inclusive IPv4 address range `[start..=end]` (auto-decomposed into aligned CIDRs).
    pub fn insert_ipv4_range(
        &mut self,
        start: Ipv4Addr,
        end: Ipv4Addr,
        record: BTreeMap<String, Value>,
    ) -> Result<&mut Self> {
        let s = u32::from(start);
        let e = u32::from(end);
        if s > e {
            return Err(BuilderError::InvalidInput(format!(
                "IPv4 start {start} > end {end}"
            )));
        }
        let rid = self.intern_record(record);
        for (net, plen) in range_to_cidrs_v4(s, e) {
            self.push_ipv4_cidr_rid(Ipv4Addr::from(net), plen, rid)?;
        }
        Ok(self)
    }

    /// Insert an IPv6 CIDR block (`addr/prefix_len`) mapped to `record`.
    /// Overlapping CIDRs are automatically resolved via Longest-Prefix-Match (last-insert-wins on ties).
    pub fn insert_ipv6_cidr(
        &mut self,
        addr: Ipv6Addr,
        prefix_len: u8,
        record: BTreeMap<String, Value>,
    ) -> Result<&mut Self> {
        let rid = self.intern_record(record);
        self.push_ipv6_cidr_rid(addr, prefix_len, rid)
    }

    /// Punch an explicit NotFound hole (`record_id = 0`) at an IPv6 CIDR (including `> /64` holes inside a broader `<= /64` prefix).
    pub fn delete_ipv6_cidr(&mut self, addr: Ipv6Addr, prefix_len: u8) -> Result<&mut Self> {
        self.push_ipv6_cidr_rid(addr, prefix_len, 0)
    }

    fn push_ipv6_cidr_rid(
        &mut self,
        addr: Ipv6Addr,
        prefix_len: u8,
        rid: u32,
    ) -> Result<&mut Self> {
        if prefix_len > 128 {
            return Err(BuilderError::InvalidInput(format!(
                "invalid IPv6 prefix length {prefix_len}"
            )));
        }
        let ip = u128::from(addr);
        if prefix_len <= 64 {
            let hi = (ip >> 64) as u64;
            let (start, end) = if prefix_len == 0 {
                (0u64, u64::MAX)
            } else if prefix_len == 64 {
                (hi, hi)
            } else {
                let mask = !((1u64 << (64 - prefix_len)) - 1);
                let s = hi & mask;
                let e = s | !mask;
                (s, e)
            };
            self.v6_intervals.push(V6Interval {
                start,
                end,
                record_idx: rid,
            });
        } else {
            let (start, end) = if prefix_len == 128 {
                (ip, ip)
            } else {
                let mask = !((1u128 << (128 - prefix_len)) - 1);
                let s = ip & mask;
                let e = s | !mask;
                (s, e)
            };
            self.v6_host_ext.push(V6HostInterval {
                start,
                end,
                record_idx: rid,
            });
        }
        Ok(self)
    }

    /// Insert an inclusive IPv6 address range `[start..=end]` (auto-decomposed into aligned CIDRs).
    pub fn insert_ipv6_range(
        &mut self,
        start: Ipv6Addr,
        end: Ipv6Addr,
        record: BTreeMap<String, Value>,
    ) -> Result<&mut Self> {
        let s = u128::from(start);
        let e = u128::from(end);
        if s > e {
            return Err(BuilderError::InvalidInput(format!(
                "IPv6 start {start} > end {end}"
            )));
        }
        let rid = self.intern_record(record);
        for (net, plen) in range_to_cidrs_v6(s, e) {
            self.push_ipv6_cidr_rid(Ipv6Addr::from(net), plen, rid)?;
        }
        Ok(self)
    }

    /// Convenience helper accepting a CIDR or single IP string (e.g. `"1.1.1.0/24"`, `"2001:db8::1"`).
    pub fn insert_cidr_str(
        &mut self,
        cidr: &str,
        record: BTreeMap<String, Value>,
    ) -> Result<&mut Self> {
        let (addr, plen) = crate::import::parse_cidr_or_ip(cidr)?;
        match addr {
            std::net::IpAddr::V4(v4) => self.insert_ipv4_cidr(v4, plen, record),
            std::net::IpAddr::V6(v6) => self.insert_ipv6_cidr(v6, plen, record),
        }
    }

    /// Build the complete `.coi` binary image in memory.
    pub fn build(self) -> Result<(Vec<u8>, BuildStats)> {
        assemble_coi(
            &self.options,
            self.build_epoch,
            serde_json::Value::Object(self.metadata),
            self.ipv6_aliases,
            self.v4_intervals,
            self.v6_intervals,
            self.v6_host_ext,
            self.unique_records,
        )
    }
}

/// Low-level entry point to assemble a `.coi` file from pre-extracted intervals and unique records
/// (used by `.coi -> .coi` repacking, profile switching, and build-time pruning).
#[allow(clippy::too_many_arguments)]
pub fn build_from_parts(
    options: &BuildOptions,
    build_epoch: u64,
    metadata_json: serde_json::Value,
    ipv6_aliases: Vec<AliasRule>,
    v4_intervals: Vec<V4Interval>,
    v6_intervals: Vec<V6Interval>,
    v6_host_ext: Vec<V6HostInterval>,
    unique_records: Vec<BTreeMap<String, Value>>,
) -> Result<(Vec<u8>, BuildStats)> {
    assemble_coi(
        options,
        build_epoch,
        metadata_json,
        ipv6_aliases,
        v4_intervals,
        v6_intervals,
        v6_host_ext,
        unique_records,
    )
}

/// Convert a `.mmdb` file on disk directly into a `.coi` file on disk.
pub fn convert_mmdb_file(
    src_mmdb: impl AsRef<Path>,
    dst_coi: impl AsRef<Path>,
    options: &BuildOptions,
) -> Result<BuildStats> {
    let mmdb_bytes = std::fs::read(src_mmdb)?;
    let (coi_bytes, stats) = build_from_mmdb_bytes(&mmdb_bytes, options)?;
    let mut f = std::fs::File::create(dst_coi)?;
    f.write_all(&coi_bytes)?;
    f.flush()?;
    Ok(stats)
}

/// Convert an in-memory `.mmdb` byte slice into `.coi` bytes.
pub fn build_from_mmdb_bytes(
    mmdb_bytes: &[u8],
    options: &BuildOptions,
) -> Result<(Vec<u8>, BuildStats)> {
    let extracted = extract_mmdb(mmdb_bytes)?;

    let mut meta = serde_json::Map::new();
    meta.insert(
        "database_type".into(),
        serde_json::Value::String(extracted.metadata.database_type.clone()),
    );
    meta.insert(
        "description".into(),
        serde_json::to_value(&extracted.metadata.description)?,
    );
    meta.insert(
        "languages".into(),
        serde_json::to_value(&extracted.metadata.languages)?,
    );
    meta.insert(
        "build_epoch".into(),
        serde_json::Value::from(extracted.metadata.build_epoch),
    );
    meta.insert(
        "ip_version".into(),
        serde_json::Value::from(extracted.metadata.ip_version),
    );
    meta.insert(
        "source_format".into(),
        serde_json::Value::String(format!(
            "mmdb-{}.{}",
            extracted.metadata.binary_format_major_version,
            extracted.metadata.binary_format_minor_version
        )),
    );
    meta.insert(
        "generator".into(),
        serde_json::Value::String(format!("coip-builder {}", env!("CARGO_PKG_VERSION"))),
    );

    assemble_coi(
        options,
        extracted.metadata.build_epoch,
        serde_json::Value::Object(meta),
        extracted.ipv6_aliases,
        extracted.v4_intervals,
        extracted.v6_intervals,
        extracted.v6_host_ext,
        extracted.unique_records,
    )
}

#[allow(clippy::too_many_arguments)]
fn assemble_coi(
    options: &BuildOptions,
    build_epoch: u64,
    mut metadata_json: serde_json::Value,
    ipv6_aliases: Vec<AliasRule>,
    v4_intervals: Vec<V4Interval>,
    v6_intervals: Vec<V6Interval>,
    v6_host_ext: Vec<V6HostInterval>,
    mut unique_records: Vec<BTreeMap<String, Value>>,
) -> Result<(Vec<u8>, BuildStats)> {
    let codec = options.profile_codec;
    let zstd_level = options.zstd_level;

    // 0a. Resolve any overlapping CIDRs or explicit delete holes via exact LPM sweep.
    let mut v4_intervals = resolve_lpm_v4(v4_intervals);
    let mut v6_intervals = resolve_lpm_v6(v6_intervals);
    let mut v6_host_ext = resolve_lpm_v6_host(v6_host_ext);

    // 0b. Apply optional build-time field/language pruning & re-deduplicate records.
    if let Some(ref prune) = options.prune {
        unique_records = apply_pruning(
            prune,
            unique_records,
            &mut v4_intervals,
            &mut v6_intervals,
            &mut v6_host_ext,
            &mut metadata_json,
        )?;
    }

    // 1. Compute first-appearance IP position for each unique record (for IP-locality ordering).
    let mut ip_first_pos = vec![u64::MAX; unique_records.len()];
    let mut seq = 0u64;
    for iv in &v4_intervals {
        let idx = (iv.record_idx as usize).saturating_sub(1);
        if iv.record_idx > 0 && ip_first_pos[idx] == u64::MAX {
            ip_first_pos[idx] = seq;
        }
        seq += 1;
    }
    for iv in &v6_intervals {
        let idx = (iv.record_idx as usize).saturating_sub(1);
        if iv.record_idx > 0 && ip_first_pos[idx] == u64::MAX {
            ip_first_pos[idx] = seq;
        }
        seq += 1;
    }
    for iv in &v6_host_ext {
        let idx = (iv.record_idx as usize).saturating_sub(1);
        if iv.record_idx > 0 && ip_first_pos[idx] == u64::MAX {
            ip_first_pos[idx] = seq;
        }
        seq += 1;
    }

    // 2. Infer schema, normalize dicts, compute row ordering, encode RecordColumns & DictTables.
    let col_cfg = ColumnarBuildConfig {
        row_group_size: options.row_group_size,
        struct_dict_row_group_size: options.struct_dict_row_group_size,
        dict_block_size: options.dict_block_size,
        codec,
        zstd_level,
        row_order: options.row_order,
    };
    let built_cols = infer_and_encode_records(&unique_records, &ip_first_pos, &col_cfg)?;

    // 3. Remap all IP intervals to ordered record_ids!
    for iv in &mut v4_intervals {
        iv.record_idx = built_cols.old_to_new_rid[iv.record_idx as usize];
    }
    for iv in &mut v6_intervals {
        iv.record_idx = built_cols.old_to_new_rid[iv.record_idx as usize];
    }
    for iv in &mut v6_host_ext {
        iv.record_idx = built_cols.old_to_new_rid[iv.record_idx as usize];
    }

    // 4. Merge transitions & encode IP index sections (with optional trained ZstdDicts)
    let v4_transitions = merge_v4_transitions(&v4_intervals);
    let v6_transitions = merge_v6_transitions(&v6_intervals);
    let host_ext = build_host_ext(&v6_host_ext);

    let has_ipv4 = !v4_transitions.is_empty();
    let has_ipv6 =
        !v6_transitions.is_empty() || !ipv6_aliases.is_empty() || !host_ext.entries.is_empty();
    let has_host_ext = !host_ext.entries.is_empty();

    let mut trained_zstd_dicts: Vec<Vec<u8>> = Vec::new();
    let v4_blob = if has_ipv4 {
        Some(
            encode_ipv4_index(
                &v4_transitions,
                options.index_block_size,
                options.ipv4_l1_bits,
                codec,
                zstd_level,
                options.train_zstd_dicts,
                &mut trained_zstd_dicts,
            )?
            .bytes,
        )
    } else {
        None
    };

    let v6_blob = if !v6_transitions.is_empty() {
        Some(
            encode_ipv6_index(
                &v6_transitions,
                options.index_block_size,
                options.ipv6_l1_bits,
                codec,
                zstd_level,
                options.train_zstd_dicts,
                &mut trained_zstd_dicts,
            )?
            .bytes,
        )
    } else {
        None
    };

    let has_zstd_dicts = !trained_zstd_dicts.is_empty();

    struct PendingSection {
        kind: SectionKind,
        flags: u16,
        bytes: Vec<u8>,
        uncompressed_len: u64,
    }
    let mut sections: Vec<PendingSection> = Vec::new();

    let push_small_section =
        |sections: &mut Vec<PendingSection>, kind: SectionKind, raw: Vec<u8>| -> Result<()> {
            let uncompressed_len = raw.len() as u64;
            if codec != Codec::None && raw.len() > 32 {
                let comp = compress_with_codec(codec, &raw, zstd_level, None)?;
                if comp.len() < raw.len() {
                    sections.push(PendingSection {
                        kind,
                        flags: codec as u16,
                        bytes: comp,
                        uncompressed_len,
                    });
                    return Ok(());
                }
            }
            sections.push(PendingSection {
                kind,
                flags: Codec::None as u16,
                bytes: raw,
                uncompressed_len,
            });
            Ok(())
        };

    // Section 1: Metadata
    let meta_raw = serde_json::to_vec(&metadata_json)?;
    push_small_section(&mut sections, SectionKind::Metadata, meta_raw)?;

    // Section 2: Schema
    let schema_raw = built_cols.schema.encode();
    push_small_section(&mut sections, SectionKind::Schema, schema_raw)?;

    // Section 3: ZstdDicts (optional)
    if has_zstd_dicts {
        let zd_raw = ZstdDicts {
            dicts: trained_zstd_dicts,
        }
        .encode();
        push_small_section(&mut sections, SectionKind::ZstdDicts, zd_raw)?;
    }

    // Section 4: Ipv6Aliases (optional)
    if !ipv6_aliases.is_empty() {
        let alias_raw = Ipv6Aliases {
            rules: ipv6_aliases.clone(),
        }
        .encode();
        push_small_section(&mut sections, SectionKind::Ipv6Aliases, alias_raw)?;
    }

    // Section 5: Ipv4Index (optional)
    if let Some(blob) = v4_blob {
        let len = blob.len() as u64;
        sections.push(PendingSection {
            kind: SectionKind::Ipv4Index,
            flags: 0,
            bytes: blob,
            uncompressed_len: len,
        });
    }

    // Section 6: Ipv6Index (optional)
    if let Some(blob) = v6_blob {
        let len = blob.len() as u64;
        sections.push(PendingSection {
            kind: SectionKind::Ipv6Index,
            flags: 0,
            bytes: blob,
            uncompressed_len: len,
        });
    }

    // Section 7: Ipv6HostExt (optional)
    if has_host_ext {
        let he_raw = host_ext.encode();
        push_small_section(&mut sections, SectionKind::Ipv6HostExt, he_raw)?;
    }

    // Section 8: RecordColumns
    {
        let len = built_cols.record_columns_blob.len() as u64;
        sections.push(PendingSection {
            kind: SectionKind::RecordColumns,
            flags: 0,
            bytes: built_cols.record_columns_blob,
            uncompressed_len: len,
        });
    }

    // Section 9: DictTables (optional)
    if !built_cols.dict_blobs.is_empty() {
        let dict_section = encode_dict_tables_section(&built_cols.dict_blobs);
        let len = dict_section.len() as u64;
        sections.push(PendingSection {
            kind: SectionKind::DictTables,
            flags: 0,
            bytes: dict_section,
            uncompressed_len: len,
        });
    }

    // 5. Layout Header + Section Directory + 8-byte aligned Sections + 8-byte aligned Footer
    let section_count = sections.len();
    let section_dir_offset = HEADER_SIZE as u64;
    let dir_bytes_len = (section_count * SECTION_ENTRY_SIZE) as u64;

    let mut cur_offset = align8(section_dir_offset + dir_bytes_len);
    let mut dir_entries = Vec::with_capacity(section_count);
    let mut section_sizes = Vec::with_capacity(section_count);

    for sec in &sections {
        let offset = align8(cur_offset);
        let length = sec.bytes.len() as u64;
        let checksum = crc32c(&sec.bytes);
        dir_entries.push(SectionEntry {
            kind: sec.kind,
            flags: sec.flags,
            crc32c: checksum,
            offset,
            length,
            uncompressed_length: sec.uncompressed_len,
        });
        section_sizes.push((sec.kind, length));
        cur_offset = offset + length;
    }

    let footer_offset = align8(cur_offset);
    let file_size = footer_offset + (coip_format::FOOTER_SIZE as u64);

    let mut dir_buf = Vec::with_capacity(dir_bytes_len as usize);
    for entry in &dir_entries {
        entry.encode(&mut dir_buf);
    }
    let dir_crc = crc32c(&dir_buf);

    let mut flags = 0u32;
    if has_ipv4 {
        flags |= header_flags::HAS_IPV4;
    }
    if has_ipv6 {
        flags |= header_flags::HAS_IPV6;
    }
    if has_host_ext {
        flags |= header_flags::HAS_IPV6_HOST_EXT;
    }
    if has_zstd_dicts {
        flags |= header_flags::HAS_ZSTD_DICTS;
    }

    let header = FileHeader {
        format_major: FORMAT_MAJOR,
        format_minor: FORMAT_MINOR,
        flags,
        profile_codec: options.profile_codec,
        section_count: section_count as u8,
        header_ext_len: 0,
        build_epoch,
        record_count: unique_records.len() as u64,
        section_dir_offset,
        file_size,
        header_crc32c: 0,
    };
    let footer = FileFooter {
        dir_crc32c: dir_crc,
        section_dir_offset,
    };

    let mut out = Vec::with_capacity(file_size as usize);
    out.extend_from_slice(&header.encode());
    out.extend_from_slice(&dir_buf);
    for (sec, entry) in sections.iter().zip(dir_entries.iter()) {
        out.resize(entry.offset as usize, 0);
        out.extend_from_slice(&sec.bytes);
    }
    out.resize(footer_offset as usize, 0);
    out.extend_from_slice(&footer.encode());
    debug_assert_eq!(out.len() as u64, file_size);

    let stats = BuildStats {
        total_bytes: file_size,
        record_count: unique_records.len() as u64,
        v4_transitions: v4_transitions.len(),
        v6_transitions: v6_transitions.len(),
        v6_host_ext_entries: host_ext.entries.len(),
        ipv6_alias_count: ipv6_aliases.len(),
        dict_count: built_cols.schema.dicts.len(),
        section_sizes,
    };

    Ok((out, stats))
}

fn encode_dict_tables_section(dict_blobs: &[Vec<u8>]) -> Vec<u8> {
    let count = dict_blobs.len();
    let mut cur_off = 0u64;
    let mut entries: Vec<(u64, u64)> = Vec::with_capacity(count);
    for blob in dict_blobs {
        let aligned = align8(cur_off);
        entries.push((aligned, blob.len() as u64));
        cur_off = aligned + blob.len() as u64;
    }

    let header_len = 8 + count * 16;
    let mut out = Vec::with_capacity(header_len + cur_off as usize);
    out.extend_from_slice(&(count as u16).to_le_bytes());
    out.extend_from_slice(&[0u8; 6]);
    for &(off, len) in &entries {
        out.extend_from_slice(&off.to_le_bytes());
        out.extend_from_slice(&len.to_le_bytes());
    }
    for (blob, &(off, _)) in dict_blobs.iter().zip(entries.iter()) {
        out.resize(header_len + off as usize, 0);
        out.extend_from_slice(blob);
    }
    out
}