arbor-core 3.1.1

AST parsing and code analysis for Arbor
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
//! Model retirements: which provider model IDs are shut down or scheduled to
//! be, what each provider lists as the replacement, and which call parameters
//! have to change with the model.
//!
//! The facts come from the providers' own deprecation pages (OpenAI,
//! Anthropic, the Gemini API and Gemini on Google Cloud), by way of Arbor's
//! retirement recipes, and are bundled at build time from
//! `data/model-retirements.json`. That file is generated by
//! `scripts/retirements/generate_model_retirements.py`; never edit it by
//! hand. The tests below recompute its digest, so a hand edit fails
//! `cargo test`, and the generator's `--check` mode fails when the recipes
//! have moved on.
//!
//! [`check`] matches the model values that [`crate::usages`] found at SDK
//! calls against this data. Nothing here reads files, runs code or reaches
//! the network.

mod base_url;
mod check;
mod date;
mod gaps;

pub use base_url::BaseUrl;
pub use check::{
    check, python_literal, spread_list, CallKind, ChainStep, Change, ChangeKind, CheckOptions,
    Confidence, DataInfo, Decision, DecisionOption, Finding, FixKind, MatchKind, NextShutdown,
    OptionEffect, ParamValue, ProviderDate, RecipeRef, ReportOptions, RetirementReport, ReviewItem,
    RoutingClass, ScanInput, State, Summary, UncheckedArgs, Unreadable, FINE_TUNING,
    REPORT_VERSION,
};
pub use date::Date;
pub use gaps::{gap_text, routing_gap_text, value_gap_text, GAP_REASONS};

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::OnceLock;

/// The bundled data file.
pub const DATA_JSON: &str = include_str!("../../data/model-retirements.json");

/// Version of the data file's shape.
pub const DATA_SCHEMA: u32 = 1;

/// A provider endpoint with its own retirement schedule.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Table {
    /// The OpenAI API (`api.openai.com`).
    Openai,
    /// Anthropic-operated platforms (the Claude API).
    Anthropic,
    /// The Gemini Developer API (`generativelanguage.googleapis.com`).
    GeminiApi,
    /// Gemini on Google Cloud (Vertex AI, now Gemini Enterprise Agent Platform).
    Vertex,
}

impl Table {
    pub const ALL: [Table; 4] = [
        Table::Openai,
        Table::Anthropic,
        Table::GeminiApi,
        Table::Vertex,
    ];

    /// The snake_case name used in JSON.
    pub fn as_str(self) -> &'static str {
        match self {
            Table::Openai => "openai",
            Table::Anthropic => "anthropic",
            Table::GeminiApi => "gemini_api",
            Table::Vertex => "vertex",
        }
    }

    /// Who sets the schedule, as people say it.
    pub fn provider(self) -> &'static str {
        match self {
            Table::Openai => "OpenAI",
            Table::Anthropic => "Anthropic",
            Table::GeminiApi => "Google",
            Table::Vertex => "Google Cloud",
        }
    }
}

impl std::fmt::Display for Table {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// How firm a listed date is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DateKind {
    /// The model stops working on that date (OpenAI, Anthropic).
    Hard,
    /// The earliest the model may stop working (Gemini API, Google Cloud).
    Earliest,
}

/// What the provider says about a model ID, as of the data date.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EntryStatus {
    /// Shut down: the provider says so, or the API already answers 404.
    ShutDown,
    /// Scheduled to shut down on `date`.
    Retiring,
    /// Deprecated with no shutdown date announced.
    Deprecated,
    /// Probably shut down or retiring, but no provider page says so for this
    /// exact ID (an alias, a spelling variant, a past "earliest" date).
    Unconfirmed,
    /// The provider routes requests for this ID to a newer model.
    AutoRouted,
}

/// How a fact was established.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Verified {
    /// A live API call (`verified_on`).
    Live,
    /// Stated on the provider's documentation.
    Docs,
    /// Not stated for this case; reported so people can check.
    Unverified,
}

/// Whether Arbor's recipe would swap the model string automatically.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Action {
    Rewrite,
    ReportOnly,
}

/// A recipe the data was built from.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RecipeInfo {
    pub id: String,
    pub version: String,
    pub file: String,
    /// SHA-256 of the recipe file the data was generated from.
    pub sha256: String,
    pub table: Table,
    pub provider: String,
    pub date_kind: DateKind,
    pub retrieved_on: String,
    /// The provider pages the recipe was built from; the first is the
    /// deprecations page.
    pub source_urls: Vec<String>,
}

/// One model ID on one provider endpoint.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ModelEntry {
    pub model: String,
    pub table: Table,
    pub recipe: String,
    pub status: EntryStatus,
    /// `YYYY-MM-DD`: the shutdown (or earliest shutdown) date.
    #[serde(default)]
    pub date: Option<String>,
    /// The single replacement the provider lists.
    #[serde(default)]
    pub replacement: Option<String>,
    /// The provider's replacement cell when it lists several, none, or adds
    /// a parameter (`gpt-5.6-sol (reasoning.mode: pro)`).
    #[serde(default)]
    pub replacement_text: Option<String>,
    pub action: Action,
    /// The recipe whose parameter rules apply to calls of this model.
    #[serde(default)]
    pub rule_set: Option<String>,
    /// `non_reasoning`, `reasoning`, `reasoning_pro`, `image`...
    #[serde(default)]
    pub source_family: Option<String>,
    /// `text`, `embedding`, `image`, `video`, `audio`, `agent`...
    pub category: String,
    /// `alias`, `snapshot`, `listed_variant`, `managed_agent`...
    #[serde(default)]
    pub kind: Option<String>,
    pub verified: Verified,
    #[serde(default)]
    pub verified_on: Option<String>,
    #[serde(default)]
    pub notes: Vec<String>,
}

/// Fine-tuned models built on `base` (matched from `ft:<base>:...`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FineTuneEntry {
    pub base: String,
    pub table: Table,
    pub recipe: String,
    pub status: EntryStatus,
    pub date: String,
    /// The base model the provider lists for these fine-tunes, if any.
    #[serde(default)]
    pub replacement_base: Option<String>,
    /// Whether `replacement_base` can itself be fine-tuned. Advice to
    /// retrain is given only when it can.
    #[serde(default)]
    pub fine_tunable: bool,
    /// Why the fine-tune cannot simply move (public wording).
    #[serde(default)]
    pub note: Option<String>,
}

/// What a parameter rule does when it applies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RuleEffect {
    /// Add a parameter (`reasoning_effort="none"`).
    Add,
    /// Rename a parameter and add the parameters in `add`.
    Rename,
    /// The call needs a person: the change is not mechanical.
    Review,
    /// The parameters may stay, under `keep_*` conditions.
    Keep,
    /// Worth knowing; changes nothing.
    Note,
    /// A choice each repository makes (the recipe's `report_choice`): the
    /// call is reported with every option and changed by none until the
    /// repository picks one.
    Choice,
}

/// How firmly an option's effect is established.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OptionStatus {
    /// A provider page states it, or a recorded live call shows it.
    Confirmed,
    /// Neither does yet.
    Unverified,
}

/// One option of a [`RuleEffect::Choice`] rule.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ChoiceOption {
    /// `reasoning_none`, `model_default`.
    pub id: String,
    /// For people: `keep reasoning off`.
    pub label: String,
    #[serde(default)]
    pub add: Vec<AddParam>,
    /// Parameters the option removes (when the call passes them).
    #[serde(default)]
    pub remove: Vec<String>,
    /// Parameters the option keeps (when the call passes them).
    #[serde(default)]
    pub keep: Vec<String>,
    /// What changes for the call: behaviour and cost.
    pub effect: String,
    pub status: OptionStatus,
}

/// A parameter to add, for one endpoint (`*` for any).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AddParam {
    pub endpoint: String,
    pub name: String,
    pub value: serde_json::Value,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RenameParam {
    pub from: String,
    pub to: String,
}

/// A parameter rule that can be checked from a call's keyword-argument names.
/// Every non-empty condition must hold.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ParamRule {
    pub id: String,
    pub rule_set: String,
    pub effect: RuleEffect,
    /// `chat.completions`, `responses`, `completions_legacy`, `assistants`.
    #[serde(default)]
    pub endpoints: Vec<String>,
    /// Client routings (`google_generativeai_legacy`).
    #[serde(default)]
    pub routings: Vec<String>,
    #[serde(default)]
    pub source_families: Vec<String>,
    /// Replacement models the rule is about.
    #[serde(default)]
    pub targets: Vec<String>,
    /// Retiring models the rule is about.
    #[serde(default)]
    pub source_models: Vec<String>,
    /// At least one of these keyword arguments is passed.
    #[serde(default)]
    pub any_kwargs: Vec<String>,
    /// All of these are passed.
    #[serde(default)]
    pub all_kwargs: Vec<String>,
    /// None of these is passed.
    #[serde(default)]
    pub lacks_kwargs: Vec<String>,
    #[serde(default)]
    pub add: Vec<AddParam>,
    #[serde(default)]
    pub rename: Option<RenameParam>,
    /// For `keep`: the targets the parameters were verified on.
    #[serde(default)]
    pub keep_targets: Vec<String>,
    /// For `keep`: verified only at reasoning effort `none`.
    #[serde(default)]
    pub keep_needs_effort_none: bool,
    /// For [`RuleEffect::Choice`]: the choice this rule belongs to. The
    /// rule whose `choice` is its own id is the choice's anchor.
    #[serde(default)]
    pub choice: Option<String>,
    /// For [`RuleEffect::Choice`]: the options, in the anchor's order.
    #[serde(default)]
    pub options: Vec<ChoiceOption>,
    /// An automatic change whose effect depends on a choice.
    #[serde(default)]
    pub see_choice: Option<String>,
    /// What the choice means for this change (with `see_choice`).
    #[serde(default)]
    pub choice_note: Option<String>,
    /// For people; `{target}` is the replacement model.
    pub message: String,
    /// When the rule's change cannot be made at this call.
    #[serde(default)]
    pub else_message: Option<String>,
    pub verified: Verified,
    #[serde(default)]
    pub verified_on: Option<String>,
    /// For a live rule: the models the live calls used. The live label holds
    /// only for these targets.
    #[serde(default)]
    pub live_models: Vec<String>,
    /// For a live rule: the APIs the live calls used (`chat.completions`).
    #[serde(default)]
    pub live_endpoints: Vec<String>,
    /// For a live rule: the label where the live calls did not reach (another
    /// target or another API): `docs` or `unverified`.
    #[serde(default)]
    pub otherwise_verified: Option<Verified>,
    #[serde(default)]
    pub source_url: Option<String>,
}

/// A recipe rule the engine does not evaluate, and why.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SkippedRule {
    pub id: String,
    pub rule_set: String,
    pub reason: String,
}

/// The whole data file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RetirementData {
    pub schema: u32,
    /// The oldest date any recipe's pages were read; each recipe keeps its
    /// own `retrieved_on`.
    pub data_as_of: String,
    pub generated_at: String,
    pub generator: String,
    /// Where the recipes came from (`repository@commit:path`). The recipes
    /// are in a private repository; every fact also names its provider page.
    pub source: String,
    /// FNV-1a 64 of the canonical JSON of every key except `digest` and
    /// `generated_at`.
    pub digest: String,
    pub recipes: Vec<RecipeInfo>,
    pub entries: Vec<ModelEntry>,
    pub fine_tunes: Vec<FineTuneEntry>,
    pub rules: Vec<ParamRule>,
    pub skipped_rules: Vec<SkippedRule>,
}

/// The bundled data with lookup indexes.
#[derive(Debug)]
pub struct Retirements {
    pub data: RetirementData,
    pub as_of: Date,
    by_model: HashMap<(Table, String), usize>,
    by_fine_tune: HashMap<(Table, String), usize>,
    recipes: HashMap<String, usize>,
    rules_by_set: HashMap<String, Vec<usize>>,
}

impl Retirements {
    /// Parses and indexes a data file.
    pub fn from_json(json: &str) -> Result<Retirements, String> {
        let data: RetirementData = serde_json::from_str(json)
            .map_err(|e| format!("model retirement data is not valid: {e}"))?;
        if data.schema != DATA_SCHEMA {
            return Err(format!(
                "model retirement data has schema {}, this build reads {DATA_SCHEMA}",
                data.schema
            ));
        }
        let as_of = Date::parse(&data.data_as_of)
            .ok_or_else(|| format!("bad data_as_of {}", data.data_as_of))?;
        let mut by_model = HashMap::new();
        for (index, entry) in data.entries.iter().enumerate() {
            if by_model
                .insert((entry.table, entry.model.clone()), index)
                .is_some()
            {
                return Err(format!(
                    "{} is listed twice for {}",
                    entry.model, entry.table
                ));
            }
        }
        let by_fine_tune = data
            .fine_tunes
            .iter()
            .enumerate()
            .map(|(index, f)| ((f.table, f.base.clone()), index))
            .collect();
        let recipes = data
            .recipes
            .iter()
            .enumerate()
            .map(|(index, r)| (r.id.clone(), index))
            .collect();
        let mut rules_by_set: HashMap<String, Vec<usize>> = HashMap::new();
        for (index, rule) in data.rules.iter().enumerate() {
            rules_by_set
                .entry(rule.rule_set.clone())
                .or_default()
                .push(index);
        }
        Ok(Retirements {
            data,
            as_of,
            by_model,
            by_fine_tune,
            recipes,
            rules_by_set,
        })
    }

    /// The entry for `model` on `table`, matched exactly.
    pub fn entry(&self, table: Table, model: &str) -> Option<&ModelEntry> {
        self.by_model
            .get(&(table, model.to_string()))
            .map(|&i| &self.data.entries[i])
    }

    /// Fine-tunes of `base` on `table`.
    pub fn fine_tune(&self, table: Table, base: &str) -> Option<&FineTuneEntry> {
        self.by_fine_tune
            .get(&(table, base.to_string()))
            .map(|&i| &self.data.fine_tunes[i])
    }

    pub fn recipe(&self, id: &str) -> Option<&RecipeInfo> {
        self.recipes.get(id).map(|&i| &self.data.recipes[i])
    }

    /// The parameter rules of a rule set, in data order.
    pub fn rules(&self, rule_set: &str) -> impl Iterator<Item = &ParamRule> {
        self.rules_by_set
            .get(rule_set)
            .into_iter()
            .flatten()
            .map(move |&i| &self.data.rules[i])
    }
}

/// The bundled data, parsed once.
pub fn bundled() -> Result<&'static Retirements, String> {
    static DATA: OnceLock<Result<Retirements, String>> = OnceLock::new();
    DATA.get_or_init(|| Retirements::from_json(DATA_JSON))
        .as_ref()
        .map_err(Clone::clone)
}

/// Keys the digest leaves out: the digest itself, and the day the file was
/// written.
const UNDIGESTED: [&str; 2] = ["digest", "generated_at"];

/// FNV-1a 64 over the canonical JSON (sorted keys, no whitespace) of every
/// key except [`UNDIGESTED`], as `fnv1a64:<hex>`. The generator computes the
/// same.
pub fn content_digest(json: &str) -> Result<String, String> {
    let value: serde_json::Value = serde_json::from_str(json).map_err(|e| e.to_string())?;
    let object = value
        .as_object()
        .ok_or_else(|| "the data is not a JSON object".to_string())?;
    let mut body = serde_json::Map::new();
    for (key, item) in object {
        if !UNDIGESTED.contains(&key.as_str()) {
            body.insert(key.clone(), item.clone());
        }
    }
    let mut canonical = String::new();
    write_canonical(&serde_json::Value::Object(body), &mut canonical);
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for byte in canonical.bytes() {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    Ok(format!("fnv1a64:{hash:016x}"))
}

fn write_canonical(value: &serde_json::Value, out: &mut String) {
    match value {
        serde_json::Value::Object(map) => {
            let mut keys: Vec<&String> = map.keys().collect();
            keys.sort();
            out.push('{');
            for (i, key) in keys.into_iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                out.push_str(&serde_json::Value::String(key.clone()).to_string());
                out.push(':');
                write_canonical(&map[key], out);
            }
            out.push('}');
        }
        serde_json::Value::Array(items) => {
            out.push('[');
            for (i, item) in items.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                write_canonical(item, out);
            }
            out.push(']');
        }
        other => out.push_str(&other.to_string()),
    }
}

#[cfg(test)]
mod data_tests {
    //! The bundled file must be exactly what the generator writes. These run
    //! on every `cargo test`, so a hand edit or a half-applied regeneration
    //! fails CI; `--check` in the generator catches recipes that moved on.

    use super::*;
    use std::collections::HashSet;

    fn data() -> &'static Retirements {
        bundled().expect("bundled data parses")
    }

    #[test]
    fn digest_matches_the_generator() {
        let digest = content_digest(DATA_JSON).unwrap();
        assert_eq!(
            digest,
            data().data.digest,
            "data/model-retirements.json was edited by hand: regenerate it with \
             scripts/retirements/generate_model_retirements.py"
        );
    }

    #[test]
    fn digest_notices_a_one_character_edit() {
        let edited = DATA_JSON.replacen("\"2027-01-14\"", "\"2027-01-15\"", 1);
        assert_ne!(edited, DATA_JSON);
        assert_ne!(content_digest(&edited).unwrap(), data().data.digest);
    }

    #[test]
    fn digest_covers_provenance_but_not_the_write_date() {
        let original = &data().data.digest;
        let edit = |key: &str, value: serde_json::Value| {
            let mut json: serde_json::Value = serde_json::from_str(DATA_JSON).unwrap();
            json[key] = value;
            content_digest(&json.to_string()).unwrap()
        };
        // Hand edits to the dates, the source, the recipe hashes or the
        // skipped rules all change the digest.
        assert_ne!(&edit("data_as_of", "2026-12-31".into()), original);
        assert_ne!(&edit("source", "someone@else:recipes/".into()), original);
        let mut recipes = serde_json::to_value(&data().data.recipes).unwrap();
        recipes[0]["sha256"] = "0".repeat(64).into();
        assert_ne!(&edit("recipes", recipes), original);
        assert_ne!(&edit("skipped_rules", serde_json::json!([])), original);
        // The day the file was written is not content.
        assert_eq!(&edit("generated_at", "2030-01-01".into()), original);
    }

    #[test]
    fn provenance_is_recorded() {
        let d = &data().data;
        assert_eq!(d.schema, DATA_SCHEMA);
        assert!(Date::parse(&d.generated_at).is_some());
        assert!(data().as_of <= Date::parse(&d.generated_at).unwrap());
        // The data date is the oldest page date, never a newer one.
        let oldest = d
            .recipes
            .iter()
            .map(|r| Date::parse(&r.retrieved_on).unwrap())
            .min()
            .unwrap();
        assert_eq!(data().as_of, oldest);
        assert!(
            d.source.contains('@'),
            "source names a commit: {}",
            d.source
        );
        assert!(d.generator.ends_with(".py"));
        let tables: HashSet<Table> = d.recipes.iter().map(|r| r.table).collect();
        assert_eq!(
            tables.len(),
            Table::ALL.len(),
            "every provider has a recipe"
        );
        for recipe in &d.recipes {
            assert!(!recipe.version.is_empty(), "{}", recipe.id);
            assert_eq!(recipe.sha256.len(), 64, "{}", recipe.id);
            assert!(Date::parse(&recipe.retrieved_on).is_some(), "{}", recipe.id);
            assert!(!recipe.source_urls.is_empty(), "{}", recipe.id);
            for url in &recipe.source_urls {
                assert!(url.starts_with("https://"), "{url}");
            }
        }
    }

    #[test]
    fn entries_are_consistent() {
        let r = data();
        for entry in &r.data.entries {
            let what = format!("{} ({})", entry.model, entry.table);
            assert!(r.recipe(&entry.recipe).is_some(), "{what}: unknown recipe");
            assert_eq!(
                r.recipe(&entry.recipe).unwrap().table,
                entry.table,
                "{what}"
            );
            if let Some(date) = &entry.date {
                assert!(Date::parse(date).is_some(), "{what}: bad date {date}");
            }
            if entry.status == EntryStatus::Retiring {
                assert!(entry.date.is_some(), "{what}: retiring without a date");
            }
            assert_ne!(
                entry.replacement.as_deref(),
                Some(entry.model.as_str()),
                "{what}"
            );
            if entry.action == Action::Rewrite {
                assert!(
                    entry.replacement.is_some(),
                    "{what}: rewrite needs a replacement"
                );
            }
            if let Some(set) = &entry.rule_set {
                assert!(r.recipe(set).is_some(), "{what}: unknown rule set {set}");
            }
            if entry.verified == Verified::Live {
                assert!(
                    entry.verified_on.as_deref().and_then(Date::parse).is_some(),
                    "{what}"
                );
            }
            assert!(
                !entry.model.is_empty() && !entry.model.chars().any(char::is_whitespace),
                "{what}"
            );
        }
        for fine in &r.data.fine_tunes {
            assert!(Date::parse(&fine.date).is_some(), "{}", fine.base);
            assert!(r.recipe(&fine.recipe).is_some(), "{}", fine.base);
        }
    }

    #[test]
    fn rules_point_at_real_models() {
        let r = data();
        for rule in &r.data.rules {
            let entries: Vec<&ModelEntry> = r
                .data
                .entries
                .iter()
                .filter(|e| e.rule_set.as_deref() == Some(rule.rule_set.as_str()))
                .collect();
            assert!(!entries.is_empty(), "{}: empty rule set", rule.id);
            let replacements: HashSet<&str> = entries
                .iter()
                .filter_map(|e| e.replacement.as_deref())
                .collect();
            for target in rule.targets.iter().chain(&rule.keep_targets) {
                assert!(
                    replacements.contains(target.as_str()),
                    "{}: target {target} is no replacement in {}",
                    rule.id,
                    rule.rule_set
                );
            }
            for model in &rule.source_models {
                assert!(
                    entries.iter().any(|e| &e.model == model),
                    "{}: {model} is not in {}",
                    rule.id,
                    rule.rule_set
                );
            }
            assert!(!rule.message.trim().is_empty(), "{}", rule.id);
            match rule.effect {
                RuleEffect::Add => assert!(!rule.add.is_empty(), "{}", rule.id),
                RuleEffect::Rename => assert!(rule.rename.is_some(), "{}", rule.id),
                _ => {}
            }
            if rule.verified == Verified::Live {
                assert!(
                    rule.verified_on.as_deref().and_then(Date::parse).is_some(),
                    "{}",
                    rule.id
                );
                // A live label names what the live calls covered.
                assert!(!rule.live_models.is_empty(), "{}", rule.id);
                assert_eq!(rule.live_endpoints, ["chat.completions"], "{}", rule.id);
                assert!(rule.otherwise_verified.is_some(), "{}", rule.id);
                assert_ne!(rule.otherwise_verified, Some(Verified::Live), "{}", rule.id);
            }
        }
    }

    #[test]
    fn choices_offer_their_anchors_options() {
        let r = data();
        let mut anchors = 0;
        for rule in &r.data.rules {
            if let Some(choice) = &rule.choice {
                assert_eq!(rule.effect, RuleEffect::Choice, "{}", rule.id);
                let anchor = r
                    .rules(&rule.rule_set)
                    .find(|a| &a.id == choice && a.choice.as_deref() == Some(choice))
                    .unwrap_or_else(|| panic!("{}: no anchor {choice}", rule.id));
                anchors += usize::from(anchor.id == rule.id);
                let ids = |rule: &ParamRule| -> Vec<String> {
                    rule.options.iter().map(|o| o.id.clone()).collect()
                };
                assert!(rule.options.len() >= 2, "{}", rule.id);
                assert_eq!(ids(rule), ids(anchor), "{}", rule.id);
                for option in &rule.options {
                    assert!(!option.label.is_empty() && !option.effect.is_empty());
                }
            } else {
                assert_ne!(rule.effect, RuleEffect::Choice, "{}", rule.id);
                assert!(rule.options.is_empty(), "{}", rule.id);
            }
            if let Some(choice) = &rule.see_choice {
                assert!(rule.choice_note.is_some(), "{}", rule.id);
                assert!(
                    r.rules(&rule.rule_set).any(|a| &a.id == choice),
                    "{}: see_choice {choice}",
                    rule.id
                );
            }
        }
        // One reasoning choice per OpenAI dated recipe, and Claude's thinking.
        assert_eq!(anchors, 3);
    }

    #[test]
    fn no_automatic_change_sets_the_reasoning_effort() {
        // The founder's 18 Oct decision: the reasoning effort is asked per
        // repository; the lead's 20 Oct decision does the same for Claude's
        // thinking. Only a choice's options may name them.
        for rule in &data().data.rules {
            if !matches!(
                rule.effect,
                RuleEffect::Add | RuleEffect::Rename | RuleEffect::Keep
            ) {
                continue;
            }
            for add in &rule.add {
                let named = add.name.contains("effort")
                    || add.name == "thinking"
                    || (add.name == "reasoning" && add.value.get("effort").is_some());
                assert!(!named, "{} sets {} automatically", rule.id, add.name);
            }
            if let Some(rename) = &rule.rename {
                assert_ne!(rename.to, "thinking", "{}", rule.id);
            }
        }
        for id in ["ANT-THINKING-DEFAULT", "ANT-THINKING-DISABLED"] {
            let rule = data().data.rules.iter().find(|r| r.id == id).expect(id);
            assert_eq!(rule.effect, RuleEffect::Choice, "{id}");
            assert_eq!(rule.choice.as_deref(), Some("ANT-THINKING-DEFAULT"), "{id}");
        }
        for id in [
            "OAI-REASONING-DEFAULT",
            "OAI-TOOLS-CC",
            "OAI-LEGACY-FUNCTIONS",
            "OAI-SAMPLING",
            "G6-REASONING-DEFAULT",
            "G6-TOOLS-CC",
            "G6-LEGACY-FUNCTIONS",
            "G6-SAMPLING",
        ] {
            let rule = data().data.rules.iter().find(|r| r.id == id).expect(id);
            assert_eq!(rule.effect, RuleEffect::Choice, "{id}");
        }
    }

    #[test]
    fn fine_tunes_name_a_base_only_when_it_can_be_fine_tuned() {
        let r = data();
        for fine in &r.data.fine_tunes {
            assert!(fine.note.is_some(), "{}", fine.base);
            assert!(
                !fine.fine_tunable,
                "{}: no listed base supports fine-tuning today",
                fine.base
            );
        }
        // gpt-6-luna does not support fine-tuning: no base is listed.
        let mini = r
            .fine_tune(Table::Openai, "gpt-4o-mini-2024-07-18")
            .expect("fine-tunes of the gpt-4o mini snapshot are matched");
        assert_eq!(mini.replacement_base, None);
        assert_eq!(mini.date, "2027-01-14");
    }

    #[test]
    fn launch_facts_are_in_the_data() {
        // The soft-launch check leans on these; if a regeneration drops one,
        // the README and the launch copy are wrong.
        let r = data();
        for alias in ["gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini"] {
            let entry = r.entry(Table::Openai, alias).expect(alias);
            assert_eq!(entry.status, EntryStatus::Retiring);
            assert_eq!(entry.date.as_deref(), Some("2027-01-14"));
            assert_eq!(entry.replacement.as_deref(), Some("gpt-6-luna"));
        }
        // OpenAI's deprecations page lists these bare IDs in its own 11 Dec
        // rows (read 28 Oct 2026), so they cite the page, not the models API.
        for (alias, replacement) in [
            ("gpt-5", "gpt-5.6-sol"),
            ("gpt-5-mini", "gpt-5.6-terra"),
            ("gpt-5-nano", "gpt-5.6-luna"),
            ("gpt-5-pro", "gpt-5.6-sol"),
            ("o3", "gpt-5.6-sol"),
            ("o3-pro", "gpt-5.6-sol"),
        ] {
            let entry = r.entry(Table::Openai, alias).expect(alias);
            assert_eq!(entry.status, EntryStatus::Retiring, "{alias}");
            assert_eq!(entry.date.as_deref(), Some("2026-12-11"), "{alias}");
            assert_eq!(entry.replacement.as_deref(), Some(replacement), "{alias}");
            assert_eq!(entry.recipe, "openai-2026-10-23", "{alias}");
            assert!(entry.notes.is_empty(), "{alias}: {:?}", entry.notes);
        }
        let sonnet = r
            .entry(Table::Anthropic, "claude-3-5-sonnet-20241022")
            .unwrap();
        assert_eq!(sonnet.status, EntryStatus::ShutDown);
        assert!(r
            .entry(Table::Openai, "claude-3-5-sonnet-20241022")
            .is_none());
        assert!(r.entry(Table::Openai, "gpt-6-luna").is_none());
        let max_tokens = r
            .rules("openai-2027-01-14")
            .find(|rule| rule.id == "G6-MAX-TOKENS")
            .unwrap();
        assert_eq!(max_tokens.verified, Verified::Live);
        assert_eq!(
            max_tokens.rename,
            Some(RenameParam {
                from: "max_tokens".into(),
                to: "max_completion_tokens".into()
            })
        );
        // The rename stays automatic and adds nothing; the reasoning effort
        // is the per-repo choice it points to.
        assert!(max_tokens.add.is_empty());
        assert_eq!(
            max_tokens.see_choice.as_deref(),
            Some("G6-REASONING-DEFAULT")
        );
    }

    #[test]
    fn ids_the_page_added_after_23_october_follow_their_rows() {
        // Between 23 and 26 Oct 2026 OpenAI's deprecations page started listing
        // bare IDs and dated snapshots together in its rows, which added these
        // 15 IDs (7 bare, 8 snapshots). Each value is its row's date and
        // replacement cell as read on 28 Oct 2026. No recipe has argument rules
        // for them, so they are report-only with no rule set.
        const PRO: Option<&str> = Some("gpt-5.6-sol (reasoning.mode: pro)");
        const IMAGE: Option<&str> = Some("gpt-image-2.5-sunburst or gpt-image-2.5-flare");
        const TRANSCRIBE: Option<&str> = Some("gpt-live-transcribe or gpt-transcribe");
        let r = data();
        for (model, date, replacement, text) in [
            ("gpt-5", "2026-12-11", Some("gpt-5.6-sol"), None),
            ("gpt-5-mini", "2026-12-11", Some("gpt-5.6-terra"), None),
            ("gpt-5-nano", "2026-12-11", Some("gpt-5.6-luna"), None),
            ("gpt-5-pro", "2026-12-11", Some("gpt-5.6-sol"), PRO),
            ("o3", "2026-12-11", Some("gpt-5.6-sol"), None),
            ("o3-pro", "2026-12-11", Some("gpt-5.6-sol"), PRO),
            ("gpt-image-1.5-2025-12-16", "2026-12-01", None, IMAGE),
            (
                "gpt-4o-mini-tts",
                "2027-01-06",
                Some("gpt-realtime-2.1-mini"),
                None,
            ),
            (
                "gpt-realtime-2025-08-28",
                "2027-01-20",
                Some("gpt-realtime-2.1"),
                None,
            ),
            (
                "gpt-audio-2025-08-28",
                "2027-01-20",
                Some("gpt-audio-1.5"),
                None,
            ),
            (
                "gpt-realtime-mini-2025-12-15",
                "2027-01-20",
                Some("gpt-realtime-2.1-mini"),
                None,
            ),
            (
                "gpt-audio-mini-2025-12-15",
                "2027-01-20",
                Some("gpt-audio-1.5"),
                None,
            ),
            (
                "gpt-4o-mini-transcribe-2025-12-15",
                "2027-02-26",
                None,
                TRANSCRIBE,
            ),
            ("gpt-5.1-2025-11-13", "2027-04-01", Some("gpt-6-sol"), None),
            (
                "gpt-5.4-nano-2026-03-17",
                "2027-04-01",
                Some("gpt-6-luna"),
                None,
            ),
        ] {
            let entry = r.entry(Table::Openai, model).expect(model);
            assert_eq!(entry.status, EntryStatus::Retiring, "{model}");
            assert_eq!(entry.date.as_deref(), Some(date), "{model}");
            assert_eq!(entry.replacement.as_deref(), replacement, "{model}");
            assert_eq!(entry.replacement_text.as_deref(), text, "{model}");
            assert_eq!(entry.action, Action::ReportOnly, "{model}");
            assert_eq!(entry.rule_set, None, "{model}");
            assert_eq!(entry.recipe, "openai-2026-10-23", "{model}");
            assert!(entry.notes.is_empty(), "{model}: {:?}", entry.notes);
        }
        // The five snapshots the 14 Jan rows list keep their rewrite and rules.
        for snapshot in [
            "gpt-4o-2024-08-06",
            "gpt-4o-2024-11-20",
            "gpt-4o-mini-2024-07-18",
            "gpt-4.1-2025-04-14",
            "gpt-4.1-mini-2025-04-14",
        ] {
            let entry = r.entry(Table::Openai, snapshot).expect(snapshot);
            assert_eq!(entry.date.as_deref(), Some("2027-01-14"), "{snapshot}");
            assert_eq!(
                entry.replacement.as_deref(),
                Some("gpt-6-luna"),
                "{snapshot}"
            );
            assert_eq!(entry.action, Action::Rewrite, "{snapshot}");
            assert_eq!(
                entry.rule_set.as_deref(),
                Some("openai-2027-01-14"),
                "{snapshot}"
            );
            assert_eq!(entry.kind.as_deref(), Some("snapshot"), "{snapshot}");
        }
    }

    #[test]
    fn the_28_october_page_reading_reaches_what_people_are_told() {
        // Each assertion fails on the data generated from the 20 Oct recipes.
        let r = data();
        let rule = |set: &str, id: &str| {
            r.rules(set)
                .find(|rule| rule.id == id)
                .unwrap_or_else(|| panic!("{set} {id}"))
        };
        // The deprecations page gives the bare aliases no row; OpenAI's API
        // reference lists each "Deprecated. Announced shutdown date:
        // 2027-01-14", and its models API gave that date on 18 Oct.
        for alias in ["gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini"] {
            let entry = r.entry(Table::Openai, alias).expect(alias);
            assert_eq!(entry.notes.len(), 1, "{alias}: {:?}", entry.notes);
            let note = &entry.notes[0];
            assert!(
                note.contains("deprecations page gives it no shutdown date"),
                "{note}"
            );
            assert!(
                note.contains(
                    "API reference lists it as deprecated with shutdown date 14 Jan 2027"
                ),
                "{note}"
            );
            assert!(
                note.contains("models API gave that date on 18 Oct 2026"),
                "{note}"
            );
            assert!(!note.contains("does not list"), "{note}");
        }
        // Haiku 4.5 is no longer said to accept the sampling parameters: API
        // version 2026-10-21 rejects them on every model.
        let haiku = rule("anthropic-retirements", "ANT-SAMPLING-HAIKU45");
        assert_eq!(haiku.effect, RuleEffect::Review);
        assert_eq!(haiku.verified, Verified::Unverified);
        assert!(!haiku.message.contains("accepts"), "{}", haiku.message);
        assert!(haiku.message.contains("2026-10-21"), "{}", haiku.message);
        let claude = rule("anthropic-retirements", "ANT-SAMPLING");
        assert!(claude
            .message
            .contains("at any value under API version 2026-10-21"));
        // The "Using GPT-6" guide states the Responses rule; no Responses
        // call was made, and the message says so.
        let responses = rule("openai-2027-01-14", "G6-SAMPLING-RESPONSES");
        assert_eq!(responses.verified, Verified::Docs);
        assert!(responses.message.contains("\"Using GPT-6\" guide"));
        assert!(responses
            .message
            .contains("has not tested this on the Responses API"));
        let tier = rule("openai-2027-01-14", "G6-TIER-CHANGE");
        assert!(!tier.message.contains("flagship"), "{}", tier.message);
        assert!(tier.source_url.is_some());
        // stop and logit_bias were called on gpt-5.6-terra only, and no page
        // backs them on the other GPT-5.6 tiers.
        for id in ["OAI-STOP", "OAI-LOGIT-BIAS"] {
            let check = rule("openai-2026-10-23", id);
            assert_eq!(check.verified, Verified::Live, "{id}");
            assert_eq!(check.live_models, ["gpt-5.6-terra"], "{id}");
            assert_eq!(check.otherwise_verified, Some(Verified::Unverified), "{id}");
            assert!(
                check
                    .message
                    .contains("not tested on gpt-5.6-sol, gpt-5.6-luna"),
                "{id}: {}",
                check.message
            );
        }
        let max_tokens = rule("openai-2026-10-23", "OAI-MAX-TOKENS");
        assert!(max_tokens
            .message
            .contains("deprecated in favour of max_completion_tokens"));
        // top_p and logprobs were sent only at "none" on GPT-5.6, and only on Chat
        // Completions; no GPT-5.6 page states the rule, so it is not `docs` elsewhere.
        let reasoning = rule("openai-2026-10-23", "OAI-SAMPLING-REASONING-SOURCE");
        assert_eq!(reasoning.verified, Verified::Live);
        assert_eq!(reasoning.live_endpoints, ["chat.completions"]);
        assert_eq!(reasoning.otherwise_verified, Some(Verified::Unverified));
        assert!(reasoning
            .message
            .contains("top_p and logprobs were tested only at"));
        // The 23 Oct section's only fine-tune row is ft-o4-mini-2025-04-16.
        let oct23: Vec<&str> = r
            .data
            .fine_tunes
            .iter()
            .filter(|fine| fine.recipe == "openai-2026-10-23")
            .map(|fine| fine.base.as_str())
            .collect();
        assert_eq!(oct23, ["o4-mini-2025-04-16"]);
    }

    #[test]
    fn rejects_unknown_fields_and_schemas() {
        let mut value: serde_json::Value = serde_json::from_str(DATA_JSON).unwrap();
        value["entries"][0]["surprise"] = serde_json::json!(true);
        assert!(Retirements::from_json(&value.to_string()).is_err());
        let mut value: serde_json::Value = serde_json::from_str(DATA_JSON).unwrap();
        value["schema"] = serde_json::json!(99);
        assert!(Retirements::from_json(&value.to_string())
            .unwrap_err()
            .contains("schema"));
    }
}