bosk 0.1.0

Pure-Rust LightGBM inference: parses the text model format directly — no FFI, zero deps. Optional ONNX Runtime and CatBoost backends behind the same small Model trait.
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
//! Pure-Rust LightGBM inference: parses the `.lgb` text model format and
//! predicts, with no C dependency and no FFI to `lib_lightgbm`.
//!
//! Supported: numerical splits with LightGBM's full missing-value semantics
//! (default direction + missing type), categorical splits (bitset lookup),
//! random-forest averaging (`average_output`), and the output transform of
//! every single-output objective — `binary` (with its `sigmoid` parameter),
//! `cross_entropy`, `cross_entropy_lambda`, `poisson`/`gamma`/`tweedie`
//! (exponential link), the regression family (including `reg_sqrt`), and
//! ranking (raw scores).
//!
//! Deliberately rejected at load — instead of silently mispredicting:
//! multiclass models (`num_class > 1`), linear trees (`is_linear=1`), and
//! objectives or objective tokens this crate does not recognise.

use std::path::Path;
use std::str::FromStr;

use crate::{Error, Model, Result};

/// Output transform implied by the training objective. Applied to the summed
/// (or, under `average_output`, averaged) tree outputs.
///
/// Each mapping is verified bit-for-bit against LightGBM 4.6 in the parity
/// tests below and in `tests/fixtures/README.md`.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Objective {
    /// Raw score: the regression family and ranking objectives.
    Identity,
    /// `sign(raw) * raw^2`: the regression family trained with
    /// `reg_sqrt=true` (the objective line then carries a `sqrt` token).
    Sqrt,
    /// `1 / (1 + exp(-k * raw))`: `binary` (with its `sigmoid` parameter
    /// `k`) and `cross_entropy` (`k = 1`).
    Sigmoid(f64),
    /// `ln(1 + exp(raw))`: `cross_entropy_lambda`.
    Log1pExp,
    /// `exp(raw)`: `poisson`, `gamma`, `tweedie`.
    Exp,
}

impl Objective {
    /// Parse the value of the model file's `objective=` line, e.g.
    /// `"binary sigmoid:1"` or `"regression sqrt"`.
    ///
    /// Tokens after the objective name are whitelisted per objective: an
    /// unrecognised token may change the output transform (as `sqrt` does),
    /// so it is refused rather than skipped.
    ///
    /// The whitelist is exhaustive for released LightGBM versions: every
    /// `ToString()` in LightGBM's `src/objective/*.hpp` was audited across
    /// the v2.1.0–v4.6.0 tags and master (2026-07; the CUDA variants
    /// inherit these), and the complete vocabulary is `sqrt`,
    /// `sigmoid:<k>`, and `num_class:<n>` — the last written only by the
    /// multiclass objectives, which are rejected by name. A refusal can
    /// therefore only fire on a file from a future LightGBM version, where
    /// the unknown token may well be transform-affecting again.
    fn parse(value: &str, lineno: usize) -> Result<Self> {
        let mut tokens = value.split_whitespace();
        let name = tokens.next().unwrap_or("");
        match name {
            "binary" => {
                let mut k: f64 = 1.0;
                for tok in tokens {
                    match tok.strip_prefix("sigmoid:") {
                        Some(v) => {
                            k = parse_scalar(
                                v,
                                "objective sigmoid",
                                lineno,
                            )?;
                        }
                        None => return Err(Self::unknown_token(name, tok)),
                    }
                }
                // `!(finite && positive)` also catches NaN, which passes
                // a plain `k <= 0.0` test.
                if !(k.is_finite() && k > 0.0) {
                    return Err(Error::Parse {
                        line: lineno,
                        message: format!(
                            "sigmoid parameter must be positive and \
                             finite, got {k}"
                        ),
                    });
                }
                Ok(Objective::Sigmoid(k))
            }
            // These five append `sqrt` when trained with `reg_sqrt=true`
            // (`huber` does not, even though it accepts the parameter).
            "regression" | "regression_l1" | "fair" | "quantile"
            | "mape" => {
                let mut sqrt = false;
                for tok in tokens {
                    match tok {
                        "sqrt" => sqrt = true,
                        _ => return Err(Self::unknown_token(name, tok)),
                    }
                }
                Ok(if sqrt {
                    Objective::Sqrt
                } else {
                    Objective::Identity
                })
            }
            "cross_entropy" | "cross_entropy_lambda" | "poisson"
            | "gamma" | "tweedie" | "huber" | "lambdarank"
            | "rank_xendcg" | "custom" | "none" => {
                if let Some(tok) = tokens.next() {
                    return Err(Self::unknown_token(name, tok));
                }
                Ok(match name {
                    "cross_entropy" => Objective::Sigmoid(1.0),
                    "cross_entropy_lambda" => Objective::Log1pExp,
                    "poisson" | "gamma" | "tweedie" => Objective::Exp,
                    _ => Objective::Identity,
                })
            }
            other => Err(Error::Unsupported {
                message: format!(
                    "objective '{other}' is not recognised; loading it \
                     would produce wrong predictions"
                ),
            }),
        }
    }

    /// The refusal for an objective-line token outside the audited
    /// whitelist — see [`Objective::parse`] for why refusing is correct.
    fn unknown_token(name: &str, tok: &str) -> Error {
        Error::Unsupported {
            message: format!(
                "objective '{name}' carries unrecognised token {tok:?}, \
                 which may change the output transform; loading it would \
                 risk wrong predictions. The accepted tokens cover every \
                 LightGBM release through 4.6 — if a newer LightGBM wrote \
                 this file, please report this token"
            ),
        }
    }

    fn transform(self, raw: f64) -> f64 {
        match self {
            Objective::Identity => raw,
            // sign(raw) * raw^2, bit-for-bit with LightGBM's
            // `Common::Sign(input) * input * input`.
            Objective::Sqrt => raw * raw.abs(),
            Objective::Sigmoid(k) => 1.0 / (1.0 + (-k * raw).exp()),
            Objective::Log1pExp => raw.exp().ln_1p(),
            Objective::Exp => raw.exp(),
        }
    }
}

/// A single decision tree in the ensemble.
///
/// Field arrays follow LightGBM's node encoding: for a tree with `num_leaves`
/// leaves there are `num_leaves - 1` internal nodes, so the per-node arrays
/// have that length and `leaf_value` has `num_leaves` entries. `left_child` /
/// `right_child` hold an internal-node index when `>= 0`, or a leaf index
/// encoded as `!child` when `< 0`.
///
/// For a categorical node (`decision_type` bit 0 set), `threshold` holds an
/// index into `cat_boundaries`, whose consecutive pair `[lo, hi)` delimits the
/// node's bitset in `cat_threshold` (32 category bits per word).
///
/// These invariants are checked once by [`Tree::validate`] at load time, which
/// lets [`Tree::predict`] index without bounds concerns.
#[derive(Debug)]
struct Tree {
    num_leaves: usize,
    split_feature: Vec<usize>,
    threshold: Vec<f64>,
    left_child: Vec<i32>,
    right_child: Vec<i32>,
    leaf_value: Vec<f64>,
    decision_type: Vec<u8>,
    cat_boundaries: Vec<usize>,
    cat_threshold: Vec<u32>,
}

impl Tree {
    /// Predict the raw leaf value for a single sample. A feature index beyond
    /// `features` is treated as missing (NaN).
    fn predict(&self, features: &[f64]) -> f64 {
        // A stump (single leaf, no splits) has no internal nodes to walk.
        if self.split_feature.is_empty() {
            return self.leaf_value[0];
        }

        let mut node: i32 = 0;
        loop {
            if node < 0 {
                // Leaf node: index = !node = -(node + 1)
                return self.leaf_value[(!node) as usize];
            }
            let idx = node as usize;
            let feat_idx = self.split_feature[idx];
            let val = if feat_idx < features.len() {
                features[feat_idx]
            } else {
                f64::NAN
            };

            // decision_type bit 0 selects categorical vs numerical.
            node = if self.decision_type[idx] & 1 != 0 {
                self.decide_categorical(idx, val)
            } else {
                self.decide_numerical(idx, val)
            };
        }
    }

    /// LightGBM's numerical decision: `decision_type` bit 1 is the default
    /// direction for missing values (set = left) and bits 2-3 encode the
    /// missing type (0 = none, 1 = zero, 2 = NaN).
    fn decide_numerical(&self, idx: usize, mut val: f64) -> i32 {
        let dt = self.decision_type[idx];
        let default_left = (dt & 2) != 0;
        let missing_type = (dt >> 2) & 3;

        // Unless NaN is itself the missing marker, LightGBM treats NaN as 0.
        if val.is_nan() && missing_type != 2 {
            val = 0.0;
        }
        // LightGBM's zero test is a band, not equality: IsZero(v) is
        // |v| <= kZeroThreshold with `const double kZeroThreshold = 1e-35f`
        // (include/LightGBM/meta.h) — the f32 literal is deliberate.
        const K_ZERO_THRESHOLD: f64 = 1e-35_f32 as f64;
        let is_missing = (missing_type == 1
            && (-K_ZERO_THRESHOLD..=K_ZERO_THRESHOLD).contains(&val))
            || (missing_type == 2 && val.is_nan());

        if is_missing {
            if default_left {
                self.left_child[idx]
            } else {
                self.right_child[idx]
            }
        } else if val <= self.threshold[idx] {
            self.left_child[idx]
        } else {
            self.right_child[idx]
        }
    }

    /// LightGBM's categorical decision: NaN and negative categories go right;
    /// otherwise go left iff the category's bit is set in the node's bitset
    /// (an unseen category beyond the bitset goes right).
    fn decide_categorical(&self, idx: usize, val: f64) -> i32 {
        if val.is_nan() {
            return self.right_child[idx];
        }
        let cat = val as i64; // saturating cast, truncates toward zero
        if cat < 0 {
            return self.right_child[idx];
        }
        let cat_idx = self.threshold[idx] as usize;
        let bits = &self.cat_threshold[self.cat_boundaries[cat_idx]
            ..self.cat_boundaries[cat_idx + 1]];
        let word = (cat as u64 >> 5) as usize;
        let found = word < bits.len()
            && (bits[word] >> (cat as u64 & 31)) & 1 == 1;
        if found {
            self.left_child[idx]
        } else {
            self.right_child[idx]
        }
    }

    /// Check the structural invariants documented on [`Tree`]. `header_line` is
    /// the 1-based line of the `Tree=` header, used for error context.
    /// `max_feature_idx` is the header's declared feature bound, when present.
    fn validate(
        &self,
        header_line: usize,
        max_feature_idx: Option<usize>,
    ) -> Result<()> {
        let err = |message: String| Error::Parse {
            line: header_line,
            message,
        };
        if self.num_leaves == 0 {
            return Err(err("num_leaves must be >= 1".into()));
        }
        if self.leaf_value.len() != self.num_leaves {
            return Err(err(format!(
                "num_leaves={} but {} leaf_value entries",
                self.num_leaves,
                self.leaf_value.len()
            )));
        }

        let internal = self.num_leaves - 1;
        for (name, len) in [
            ("split_feature", self.split_feature.len()),
            ("threshold", self.threshold.len()),
            ("decision_type", self.decision_type.len()),
            ("left_child", self.left_child.len()),
            ("right_child", self.right_child.len()),
        ] {
            if len != internal {
                return Err(err(format!(
                    "{name} has {len} entries, expected num_leaves-1 = {internal}"
                )));
            }
        }

        if self.cat_boundaries.windows(2).any(|w| w[0] > w[1])
            || self.cat_boundaries.last().copied().unwrap_or(0)
                > self.cat_threshold.len()
        {
            return Err(err(
                "cat_boundaries must be non-decreasing and within cat_threshold"
                    .into(),
            ));
        }

        // LightGBM stores feature indices as C ints, so even without a
        // header bound anything larger is corrupt (and keeping indices below
        // i32::MAX means the `+ 1` deriving `num_features` cannot overflow).
        let max_idx =
            max_feature_idx.unwrap_or(i32::MAX as usize - 1);
        for (k, &feat) in self.split_feature.iter().enumerate() {
            if feat > max_idx {
                return Err(err(format!(
                    "split_feature[{k}] = {feat} exceeds max_feature_idx = {max_idx}"
                )));
            }
        }

        for k in 0..internal {
            if self.decision_type[k] & 1 != 0 {
                let cat_idx = self.threshold[k];
                let max = self.cat_boundaries.len().saturating_sub(1);
                if cat_idx.fract() != 0.0
                    || cat_idx < 0.0
                    || cat_idx as usize >= max
                {
                    return Err(err(format!(
                        "categorical node {k} references invalid bitset index {cat_idx}"
                    )));
                }
            }
            for (side, child) in [
                ("left_child", self.left_child[k]),
                ("right_child", self.right_child[k]),
            ] {
                let ok = if child >= 0 {
                    (child as usize) < internal
                } else {
                    ((!child) as usize) < self.num_leaves
                };
                if !ok {
                    return Err(err(format!(
                        "{side}[{k}] = {child} is out of range"
                    )));
                }
            }
        }

        // Range checks alone admit cyclic child pointers, which would make
        // `predict` loop forever. Walk from the root: in a well-formed tree
        // every internal node and every leaf is reached exactly once.
        if internal > 0 {
            let mut node_seen = vec![false; internal];
            let mut leaf_seen = vec![false; self.num_leaves];
            let mut stack: Vec<i32> = vec![0];
            while let Some(child) = stack.pop() {
                let seen = if child >= 0 {
                    &mut node_seen[child as usize]
                } else {
                    &mut leaf_seen[(!child) as usize]
                };
                if *seen {
                    return Err(err(format!(
                        "node {child} is reachable more than once — child \
                         pointers do not form a tree"
                    )));
                }
                *seen = true;
                if child >= 0 {
                    stack.push(self.left_child[child as usize]);
                    stack.push(self.right_child[child as usize]);
                }
            }
            if node_seen.iter().any(|&v| !v)
                || leaf_seen.iter().any(|&v| !v)
            {
                return Err(err(
                    "tree has internal nodes or leaves unreachable from the \
                     root"
                        .into(),
                ));
            }
        }
        Ok(())
    }
}

/// A LightGBM model loaded from the `.lgb` text format.
#[derive(Debug)]
pub struct LgbModel {
    trees: Vec<Tree>,
    objective: Objective,
    /// Random-forest mode (`average_output` header): tree outputs are
    /// averaged rather than summed.
    average_output: bool,
    /// Feature count the model was trained on: `max_feature_idx + 1` from the
    /// header, or the highest split feature + 1 when the header is absent.
    num_features: usize,
}

/// Parse a whitespace-separated list of values, attributing any failure to
/// `field` on `line`.
fn parse_list<T>(s: &str, field: &str, line: usize) -> Result<Vec<T>>
where
    T: FromStr,
    T::Err: std::fmt::Display,
{
    s.split_whitespace()
        .map(|tok| {
            tok.parse::<T>().map_err(|e| Error::Parse {
                line,
                message: format!(
                    "{field}: invalid value {tok:?}: {e}"
                ),
            })
        })
        .collect()
}

/// Parse a single scalar value, attributing any failure to `field` on `line`.
fn parse_scalar<T>(s: &str, field: &str, line: usize) -> Result<T>
where
    T: FromStr,
    T::Err: std::fmt::Display,
{
    s.trim().parse::<T>().map_err(|e| Error::Parse {
        line,
        message: format!("{field}: {e}"),
    })
}

impl LgbModel {
    /// Load a model from a LightGBM text file.
    pub fn load(path: &Path) -> Result<Self> {
        let content =
            std::fs::read_to_string(path).map_err(|source| {
                Error::Io {
                    path: path.to_path_buf(),
                    source,
                }
            })?;
        Self::parse(&content)
    }

    /// Parse a model from the contents of a LightGBM text file.
    ///
    /// Returns [`Error::Unsupported`] for models this crate cannot evaluate
    /// faithfully (multiclass, linear trees, unrecognised objectives or
    /// objective tokens) — a refusal to load is preferred over silently
    /// wrong predictions.
    ///
    /// A file without an `objective=` line (LightGBM itself always writes
    /// one) is evaluated with the identity transform, i.e. raw scores.
    pub fn parse(content: &str) -> Result<Self> {
        let lines: Vec<&str> = content.lines().collect();

        // Header: everything before the first tree section.
        let mut objective = Objective::Identity;
        let mut average_output = false;
        let mut max_feature_idx: Option<usize> = None;
        for (i, line) in lines.iter().enumerate() {
            if line.starts_with("Tree=") {
                break;
            }
            if let Some(v) = line.strip_prefix("objective=") {
                objective = Objective::parse(v, i + 1)?;
            } else if let Some(v) =
                line.strip_prefix("max_feature_idx=")
            {
                let m: usize =
                    parse_scalar(v, "max_feature_idx", i + 1)?;
                // LightGBM stores feature indices as C ints; anything larger
                // is a corrupt file (and `m + 1` below must not overflow).
                if m >= i32::MAX as usize {
                    return Err(Error::Parse {
                        line: i + 1,
                        message: format!(
                            "max_feature_idx = {m} is out of range"
                        ),
                    });
                }
                max_feature_idx = Some(m);
            } else if let Some(v) = line.strip_prefix("num_class=") {
                let n: usize = parse_scalar(v, "num_class", i + 1)?;
                if n > 1 {
                    return Err(Error::Unsupported {
                        message: format!(
                            "multiclass model (num_class={n}); only \
                             single-output models are supported"
                        ),
                    });
                }
            } else if *line == "average_output" {
                average_output = true;
            }
        }

        let mut trees = Vec::new();
        let mut i = 0;
        while i < lines.len() {
            if !lines[i].starts_with("Tree=") {
                i += 1;
                continue;
            }
            let header_line = i + 1;
            i += 1;

            let mut num_leaves: Option<usize> = None;
            let mut split_feature = Vec::new();
            let mut threshold = Vec::new();
            let mut left_child = Vec::new();
            let mut right_child = Vec::new();
            let mut leaf_value = Vec::new();
            let mut decision_type = Vec::new();
            let mut cat_boundaries = Vec::new();
            let mut cat_threshold = Vec::new();

            while i < lines.len() && !lines[i].starts_with("Tree=") {
                let line = lines[i];
                let lineno = i + 1;
                if let Some(v) = line.strip_prefix("num_leaves=") {
                    num_leaves =
                        Some(parse_scalar(v, "num_leaves", lineno)?);
                } else if let Some(v) =
                    line.strip_prefix("split_feature=")
                {
                    split_feature =
                        parse_list(v, "split_feature", lineno)?;
                } else if let Some(v) =
                    line.strip_prefix("threshold=")
                {
                    threshold = parse_list(v, "threshold", lineno)?;
                } else if let Some(v) =
                    line.strip_prefix("decision_type=")
                {
                    decision_type =
                        parse_list(v, "decision_type", lineno)?;
                } else if let Some(v) =
                    line.strip_prefix("left_child=")
                {
                    left_child = parse_list(v, "left_child", lineno)?;
                } else if let Some(v) =
                    line.strip_prefix("right_child=")
                {
                    right_child =
                        parse_list(v, "right_child", lineno)?;
                } else if let Some(v) =
                    line.strip_prefix("leaf_value=")
                {
                    leaf_value = parse_list(v, "leaf_value", lineno)?;
                } else if let Some(v) =
                    line.strip_prefix("cat_boundaries=")
                {
                    cat_boundaries =
                        parse_list(v, "cat_boundaries", lineno)?;
                } else if let Some(v) =
                    line.strip_prefix("cat_threshold=")
                {
                    cat_threshold =
                        parse_list(v, "cat_threshold", lineno)?;
                } else if let Some(v) =
                    line.strip_prefix("is_linear=")
                {
                    let is_linear: u8 =
                        parse_scalar(v, "is_linear", lineno)?;
                    if is_linear != 0 {
                        return Err(Error::Unsupported {
                            message:
                                "linear trees (is_linear=1) are \
                                      not supported"
                                    .into(),
                        });
                    }
                }
                i += 1;
            }

            // A section without num_leaves is not a tree body (e.g. trailing
            // metadata that happens to follow the last `Tree=`); skip it.
            let Some(num_leaves) = num_leaves else {
                continue;
            };
            let tree = Tree {
                num_leaves,
                split_feature,
                threshold,
                left_child,
                right_child,
                leaf_value,
                decision_type,
                cat_boundaries,
                cat_threshold,
            };
            tree.validate(header_line, max_feature_idx)?;
            trees.push(tree);
        }

        if trees.is_empty() {
            return Err(Error::EmptyModel);
        }

        let max_split = trees
            .iter()
            .flat_map(|t| &t.split_feature)
            .max()
            .copied();
        let num_features = match (max_feature_idx, max_split) {
            (Some(m), _) => m + 1,
            (None, Some(s)) => s + 1,
            (None, None) => 0,
        };

        Ok(Self {
            trees,
            objective,
            average_output,
            num_features,
        })
    }

    /// The number of features the model was trained on
    /// ([`Model::predict`] requires exactly this many).
    #[must_use]
    pub fn num_features(&self) -> usize {
        self.num_features
    }

    /// The number of trees in the ensemble.
    #[must_use]
    pub fn num_trees(&self) -> usize {
        self.trees.len()
    }

    /// Predict a single sample without the feature-count check: tree outputs
    /// summed (or averaged in random-forest mode) and passed through the
    /// objective's output transform.
    ///
    /// This is infallible — the pure-Rust path cannot fail once the model is
    /// loaded and validated — which makes it useful where a `Result` branch
    /// or a panic path is unwelcome. The cost: unlike [`Model::predict`], a
    /// wrong-length `features` is **not** refused; any feature index beyond
    /// the slice is evaluated as missing (NaN), following LightGBM's
    /// missing-value semantics. Prefer [`Model::predict`] unless you need
    /// exactly this.
    ///
    /// Note this is not a raw-score prediction — the objective's output
    /// transform (e.g. the binary sigmoid) is applied.
    #[must_use]
    pub fn predict_unchecked(&self, features: &[f64]) -> f64 {
        let mut raw: f64 =
            self.trees.iter().map(|t| t.predict(features)).sum();
        if self.average_output {
            raw /= self.trees.len() as f64;
        }
        self.objective.transform(raw)
    }
}

impl Model for LgbModel {
    /// Checked prediction: returns [`Error::FeatureCount`] unless `features`
    /// has exactly [`num_features`](LgbModel::num_features) values — a short
    /// vector would otherwise be silently evaluated with missing values.
    fn predict(&self, features: &[f64]) -> Result<f64> {
        if features.len() != self.num_features {
            return Err(Error::FeatureCount {
                expected: self.num_features,
                got: features.len(),
            });
        }
        Ok(self.predict_unchecked(features))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Minimal single-stump model text for exercising header handling.
    fn stump(header: &str, leaf: f64) -> String {
        format!("{header}\nTree=0\nnum_leaves=1\nleaf_value={leaf}\n")
    }

    #[test]
    fn test_objective_transforms() {
        // Pins which transform each objective name selects; the formulas
        // themselves are verified against LightGBM 4.6 by the fixture parity
        // matrix (tests/fixtures/README.md).
        let cases = [
            ("objective=regression", 0.5f64),
            ("objective=regression sqrt", 0.25f64),
            (
                "objective=binary sigmoid:1",
                1.0 / (1.0 + (-0.5f64).exp()),
            ),
            (
                "objective=binary sigmoid:2",
                1.0 / (1.0 + (-1.0f64).exp()),
            ),
            (
                "objective=cross_entropy",
                1.0 / (1.0 + (-0.5f64).exp()),
            ),
            ("objective=cross_entropy_lambda", 0.5f64.exp().ln_1p()),
            ("objective=poisson", 0.5f64.exp()),
            ("objective=tweedie", 0.5f64.exp()),
        ];
        for (header, expected) in cases {
            let model = LgbModel::parse(&stump(header, 0.5)).unwrap();
            let got = model.predict(&[]).unwrap();
            assert!(
                (got - expected).abs() < 1e-15,
                "{header}: got {got}, expected {expected}"
            );
        }

        // The sqrt transform must keep the raw score's sign.
        let model = LgbModel::parse(&stump(
            "objective=regression sqrt",
            -0.5,
        ))
        .unwrap();
        assert_eq!(model.predict(&[]).unwrap(), -0.25);
    }

    /// Exactly five objectives write a `sqrt` token when trained with
    /// `reg_sqrt=true`, and all five square their output — each verified
    /// against LightGBM 4.6 (see `tests/fixtures/README.md`; the shared
    /// transform's parity against a real booster is pinned by
    /// `test_lightgbm_sqrt_parity`).
    #[test]
    fn test_sqrt_objective_selection() {
        for name in [
            "regression", "regression_l1", "fair", "quantile", "mape",
        ] {
            let sqrt = LgbModel::parse(&stump(
                &format!("objective={name} sqrt"),
                0.5,
            ))
            .unwrap();
            assert_eq!(
                sqrt.objective,
                Objective::Sqrt,
                "{name} sqrt"
            );
            let plain = LgbModel::parse(&stump(
                &format!("objective={name}"),
                0.5,
            ))
            .unwrap();
            assert_eq!(
                plain.objective,
                Objective::Identity,
                "{name}"
            );
        }
    }

    #[test]
    fn test_average_output() {
        let text = "objective=regression\naverage_output\n\
                    Tree=0\nnum_leaves=1\nleaf_value=0.4\n\
                    Tree=1\nnum_leaves=1\nleaf_value=0.8\n";
        let model = LgbModel::parse(text).unwrap();
        assert!((model.predict(&[]).unwrap() - 0.6).abs() < 1e-15);
    }

    #[test]
    fn test_unsupported_models_are_rejected() {
        for (name, text) in [
            ("multiclass", stump("objective=multiclass num_class:3\nnum_class=3", 0.5)),
            ("unknown objective", stump("objective=who_knows", 0.5)),
            // Unknown trailing tokens may change the output transform (as
            // `sqrt` does) and must be refused, not skipped.
            ("unknown binary token", stump("objective=binary who_knows", 0.5)),
            ("unknown regression token", stump("objective=regression who_knows", 0.5)),
            ("sqrt on non-sqrt objective", stump("objective=huber sqrt", 0.5)),
            (
                "linear tree",
                "objective=regression\nTree=0\nnum_leaves=1\nleaf_value=0.5\nis_linear=1\n"
                    .to_string(),
            ),
        ] {
            let err = LgbModel::parse(&text).unwrap_err();
            assert!(
                matches!(err, Error::Unsupported { .. }),
                "{name}: expected Unsupported, got {err:?}"
            );
        }
    }

    #[test]
    fn test_invalid_sigmoid_parameter_is_rejected() {
        // NaN passes a plain `k <= 0.0` test; zero, negatives, and infinity
        // are equally meaningless as a sigmoid coefficient.
        for bad in ["nan", "inf", "0", "-1"] {
            let text = stump(
                &format!("objective=binary sigmoid:{bad}"),
                0.5,
            );
            let err = LgbModel::parse(&text).unwrap_err();
            assert!(
                matches!(err, Error::Parse { .. }),
                "sigmoid:{bad}: got {err:?}"
            );
        }
    }

    /// Parity against a real LightGBM booster. The fixture is a tiny binary
    /// model (8 trees, 5 features) trained with `boost_from_average=false`, so
    /// the raw prediction is exactly the sum of tree outputs — see
    /// `tests/fixtures/README.md` for how it was generated. `expected` is the
    /// probability LightGBM 4.6 returns for `features`.
    #[test]
    fn test_lightgbm_parity() {
        let model_path = Path::new("tests/fixtures/tiny_binary.lgb");
        let model = LgbModel::load(model_path)
            .expect("Failed to load fixture model");
        assert_eq!(
            model.num_trees(),
            8,
            "fixture should have 8 trees"
        );
        assert_eq!(
            model.num_features(),
            5,
            "fixture header declares max_feature_idx=4"
        );
        assert_eq!(
            model.objective,
            Objective::Sigmoid(1.0),
            "Expected sigmoid (binary) objective"
        );

        let features = [0.5, -0.2, 0.7, 1.1, -0.9];
        let pred = model.predict(&features).unwrap();
        let expected = 0.879687246542221;
        let diff = (pred - expected).abs();
        assert!(
            diff < 1e-9,
            "Prediction mismatch vs LightGBM: rust={pred}, python={expected}, diff={diff:.2e}"
        );
    }

    /// Parity on missing values. `tiny_nan.lgb` was trained with NaNs so its
    /// splits carry non-default missing directions; the input below routes
    /// through several of them. This is the regression guard for the
    /// missing-value decision logic (default direction + missing type), which
    /// `tiny_binary.lgb` — trained without NaNs — does not exercise.
    #[test]
    fn test_lightgbm_nan_parity() {
        let model_path = Path::new("tests/fixtures/tiny_nan.lgb");
        let model = LgbModel::load(model_path)
            .expect("Failed to load NaN fixture model");

        let features = [f64::NAN, 0.3, f64::NAN, -0.5, 1.2];
        let pred = model.predict(&features).unwrap();
        let expected = 0.18514897124790036;
        let diff = (pred - expected).abs();
        assert!(
            diff < 1e-9,
            "NaN prediction mismatch vs LightGBM: rust={pred}, python={expected}, diff={diff:.2e}"
        );
    }

    /// Parity on zero-as-missing. `tiny_zero.lgb` was trained with
    /// `zero_as_missing=true`, so its splits carry `missing_type=Zero` — the
    /// branch the other fixtures never exercise. The cases pin LightGBM's
    /// zero *band*: |v| <= kZeroThreshold (1e-35, meta.h) counts as zero, so
    /// `1e-40` must predict identically to an exact `0.0` while `1e-30` must
    /// not. Expected values are LightGBM 4.6 outputs — see
    /// `tests/fixtures/README.md`.
    #[test]
    fn test_lightgbm_zero_as_missing_parity() {
        let model =
            LgbModel::load(Path::new("tests/fixtures/tiny_zero.lgb"))
                .expect(
                    "Failed to load zero-as-missing fixture model",
                );
        let n_zero_splits: usize = model
            .trees
            .iter()
            .flat_map(|t| &t.decision_type)
            .filter(|&&dt| (dt >> 2) & 3 == 1)
            .count();
        assert!(
            n_zero_splits > 0,
            "fixture must contain missing_type=Zero splits"
        );

        let cases: [([f64; 5], f64); 5] = [
            ([0.0, 0.3, 0.0, -0.5, 1.2], 0.30046007383088824),
            ([1e-40, 0.3, 1e-40, -0.5, 1.2], 0.30046007383088824),
            ([1e-30, 0.3, 1e-30, -0.5, 1.2], 0.3412099306576426),
            ([0.5, -0.2, 0.7, 1.1, -0.9], 0.9178425581052003),
            ([0.0, 0.0, 0.0, 0.0, 0.0], 0.5302747959214583),
        ];
        for (features, expected) in cases {
            let pred = model.predict(&features).unwrap();
            let diff = (pred - expected).abs();
            assert!(
                diff < 1e-9,
                "zero-as-missing mismatch on {features:?}: rust={pred}, python={expected}, diff={diff:.2e}"
            );
        }
    }

    /// Parity on `reg_sqrt`. `tiny_sqrt.lgb` was trained with
    /// `objective=regression, reg_sqrt=true`, so its objective line is
    /// `regression sqrt` and the prediction is `sign(raw) * raw^2` — the
    /// transform a plain `regression` model never exercises. The second case
    /// has a negative raw score, pinning the sign handling. Expected values
    /// are LightGBM 4.6 outputs — see `tests/fixtures/README.md`.
    #[test]
    fn test_lightgbm_sqrt_parity() {
        let model =
            LgbModel::load(Path::new("tests/fixtures/tiny_sqrt.lgb"))
                .expect("Failed to load sqrt fixture model");
        assert_eq!(model.objective, Objective::Sqrt);

        let cases: [([f64; 5], f64); 3] = [
            ([0.5, -0.2, 0.7, 1.1, -0.9], 0.6882935825372578),
            ([-1.0, 0.3, -0.4, 0.2, 0.6], -1.305067557709267),
            ([0.0, 0.0, 0.0, 0.0, 0.0], -0.04682388288592408),
        ];
        for (features, expected) in cases {
            let pred = model.predict(&features).unwrap();
            let diff = (pred - expected).abs();
            assert!(
                diff < 1e-9,
                "reg_sqrt mismatch on {features:?}: rust={pred}, python={expected}, diff={diff:.2e}"
            );
        }
    }

    /// Parity on categorical splits. `tiny_cat.lgb` was trained with two
    /// categorical features, so its trees carry bitset splits; the inputs
    /// cover in-bitset, unseen (beyond the bitset), negative, and NaN
    /// categories. Expected values are LightGBM 4.6 outputs — see
    /// `tests/fixtures/README.md`.
    #[test]
    fn test_lightgbm_categorical_parity() {
        let model_path = Path::new("tests/fixtures/tiny_cat.lgb");
        let model = LgbModel::load(model_path)
            .expect("Failed to load categorical fixture model");
        let n_cat_splits: usize = model
            .trees
            .iter()
            .flat_map(|t| &t.decision_type)
            .filter(|&&dt| dt & 1 != 0)
            .count();
        assert!(
            n_cat_splits > 0,
            "fixture must contain categorical splits"
        );

        for (features, expected) in CAT_FIXTURE_CASES {
            let pred = model.predict(features).unwrap();
            let diff = (pred - expected).abs();
            assert!(
                diff < 1e-9,
                "categorical mismatch on {features:?}: rust={pred}, python={expected}, diff={diff:.2e}"
            );
        }
    }

    /// `(features, LightGBM 4.6 prediction)` pairs for `tiny_cat.lgb`;
    /// features 3 and 4 are categorical.
    const CAT_FIXTURE_CASES: &[([f64; 5], f64)] = &[
        ([0.5, -0.2, 0.7, 1.0, 3.0], CAT_EXPECTED[0]),
        ([0.5, -0.2, 0.7, 15.0, 0.0], CAT_EXPECTED[1]),
        ([-1.0, 0.3, -0.4, 29.0, 11.0], CAT_EXPECTED[2]),
        ([-1.0, 0.3, -0.4, 40.0, 25.0], CAT_EXPECTED[3]), // unseen cats
        ([0.0, 0.0, 0.0, -1.0, -2.0], CAT_EXPECTED[4]), // negative cats
        ([0.0, 0.0, 0.0, f64::NAN, f64::NAN], CAT_EXPECTED[5]), // NaN cats
    ];

    /// LightGBM 4.6 predictions, regenerated alongside the fixture — see
    /// `tests/fixtures/README.md`.
    const CAT_EXPECTED: [f64; 6] = [
        0.973622176489283, 0.9740570762683468, 0.02734900954762666,
        0.027716944663299832, 0.038079953138787107,
        0.038079953138787107,
    ];

    /// A model body whose single internal node is `split_feature=0`,
    /// `threshold=0.5` and the given children.
    fn one_split(left: i32, right: i32) -> String {
        format!(
            "Tree=0\nnum_leaves=2\nsplit_feature=0\nthreshold=0.5\n\
             decision_type=0\nleft_child={left}\nright_child={right}\n\
             leaf_value=0.1 0.2\n"
        )
    }

    #[test]
    fn test_cyclic_tree_is_rejected() {
        // Both children point back at node 0: passes the range checks but
        // would make predict() loop forever if accepted.
        let err = LgbModel::parse(&one_split(0, 0)).unwrap_err();
        assert!(matches!(err, Error::Parse { .. }), "got {err:?}");
    }

    #[test]
    fn test_unreachable_leaf_is_rejected() {
        // Leaf 0 is referenced twice, leaf 1 never: not a tree.
        let err = LgbModel::parse(&one_split(-1, -1)).unwrap_err();
        assert!(matches!(err, Error::Parse { .. }), "got {err:?}");
    }

    #[test]
    fn test_feature_count_is_checked() {
        let model = LgbModel::load(Path::new(
            "tests/fixtures/tiny_binary.lgb",
        ))
        .unwrap();
        // 4 features instead of 5: predict() must refuse rather than treat
        // the missing one as NaN.
        let err = model.predict(&[0.5, -0.2, 0.7, 1.1]).unwrap_err();
        assert!(
            matches!(
                err,
                Error::FeatureCount {
                    expected: 5,
                    got: 4
                }
            ),
            "got {err:?}"
        );
        // predict_unchecked keeps the lenient semantics: the out-of-range
        // feature is evaluated as missing instead of being refused.
        let lenient = model.predict_unchecked(&[0.5, -0.2, 0.7, 1.1]);
        assert!(lenient.is_finite(), "got {lenient}");
        assert_eq!(
            lenient,
            model.predict(&[0.5, -0.2, 0.7, 1.1, f64::NAN]).unwrap()
        );
    }

    #[test]
    fn test_huge_feature_indices_are_rejected() {
        // usize::MAX would overflow the `+ 1` deriving num_features: both
        // the header field and a headerless split index must be refused.
        let huge_header = format!(
            "max_feature_idx={}\nTree=0\nnum_leaves=1\nleaf_value=0.5\n",
            usize::MAX
        );
        let huge_split = one_split(-1, -2).replace(
            "split_feature=0",
            &format!("split_feature={}", usize::MAX),
        );
        for text in [huge_header, huge_split] {
            let err = LgbModel::parse(&text).unwrap_err();
            assert!(
                matches!(err, Error::Parse { .. }),
                "got {err:?}"
            );
        }
    }

    #[test]
    fn test_split_feature_beyond_header_bound_is_rejected() {
        let text =
            format!("max_feature_idx=0\n{}", one_split(-1, -2));
        // split_feature=0 is fine under max_feature_idx=0…
        LgbModel::parse(&text).unwrap();
        // …but a split on feature 3 exceeds the declared bound.
        let bad = text.replace("split_feature=0", "split_feature=3");
        let err = LgbModel::parse(&bad).unwrap_err();
        assert!(matches!(err, Error::Parse { .. }), "got {err:?}");
    }

    #[test]
    fn test_predict_batch_default_impl() {
        let model = LgbModel::load(Path::new(
            "tests/fixtures/tiny_binary.lgb",
        ))
        .unwrap();
        let a = [0.5, -0.2, 0.7, 1.1, -0.9];
        let b = [-1.0, 0.3, -0.4, 0.2, 0.6];
        let flat: Vec<f64> =
            a.iter().chain(b.iter()).copied().collect();

        let batch = model.predict_batch(&flat, 5).unwrap();
        assert_eq!(batch.len(), 2);
        assert_eq!(batch[0], model.predict(&a).unwrap());
        assert_eq!(batch[1], model.predict(&b).unwrap());

        // Non-rectangular input and a zero row width must be refused.
        for (flat, n) in [(&flat[..7], 5), (&flat[..], 0)] {
            let err = model.predict_batch(flat, n).unwrap_err();
            assert!(
                matches!(err, Error::BatchShape { .. }),
                "got {err:?}"
            );
        }
    }

    #[test]
    fn test_parse_error_is_reported() {
        // A malformed threshold value must surface as an error, not a silent 0.
        let bad = "Tree=0\nnum_leaves=2\nsplit_feature=0\nthreshold=not_a_number\n\
                   decision_type=2\nleft_child=-1\nright_child=-2\nleaf_value=0.1 0.2\n";
        let err = LgbModel::parse(bad).unwrap_err();
        assert!(matches!(err, Error::Parse { .. }), "got {err:?}");
    }

    #[test]
    fn test_empty_model_is_reported() {
        assert!(matches!(
            LgbModel::parse("objective=binary sigmoid:1\n")
                .unwrap_err(),
            Error::EmptyModel
        ));
    }
}