Skip to main content

arbor_core/retirements/
mod.rs

1//! Model retirements: which provider model IDs are shut down or scheduled to
2//! be, what each provider lists as the replacement, and which call parameters
3//! have to change with the model.
4//!
5//! The facts come from the providers' own deprecation pages (OpenAI,
6//! Anthropic, the Gemini API and Gemini on Google Cloud), by way of Arbor's
7//! retirement recipes, and are bundled at build time from
8//! `data/model-retirements.json`. That file is generated by
9//! `scripts/retirements/generate_model_retirements.py`; never edit it by
10//! hand. The tests below recompute its digest, so a hand edit fails
11//! `cargo test`, and the generator's `--check` mode fails when the recipes
12//! have moved on.
13//!
14//! [`check`] matches the model values that [`crate::usages`] found at SDK
15//! calls against this data. Nothing here reads files, runs code or reaches
16//! the network.
17
18mod base_url;
19mod check;
20mod date;
21mod gaps;
22
23pub use base_url::BaseUrl;
24pub use check::{
25    check, python_literal, CallKind, ChainStep, Change, ChangeKind, CheckOptions, Confidence,
26    DataInfo, Decision, DecisionOption, Finding, FixKind, MatchKind, NextShutdown, OptionEffect,
27    ParamValue, ProviderDate, RecipeRef, ReportOptions, RetirementReport, ReviewItem, RoutingClass,
28    ScanInput, State, Summary, Unreadable, FINE_TUNING, REPORT_VERSION,
29};
30pub use date::Date;
31pub use gaps::{gap_text, routing_gap_text, value_gap_text, GAP_REASONS};
32
33use serde::{Deserialize, Serialize};
34use std::collections::HashMap;
35use std::sync::OnceLock;
36
37/// The bundled data file.
38pub const DATA_JSON: &str = include_str!("../../data/model-retirements.json");
39
40/// Version of the data file's shape.
41pub const DATA_SCHEMA: u32 = 1;
42
43/// A provider endpoint with its own retirement schedule.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
45#[serde(rename_all = "snake_case")]
46pub enum Table {
47    /// The OpenAI API (`api.openai.com`).
48    Openai,
49    /// Anthropic-operated platforms (the Claude API).
50    Anthropic,
51    /// The Gemini Developer API (`generativelanguage.googleapis.com`).
52    GeminiApi,
53    /// Gemini on Google Cloud (Vertex AI, now Gemini Enterprise Agent Platform).
54    Vertex,
55}
56
57impl Table {
58    pub const ALL: [Table; 4] = [
59        Table::Openai,
60        Table::Anthropic,
61        Table::GeminiApi,
62        Table::Vertex,
63    ];
64
65    /// The snake_case name used in JSON.
66    pub fn as_str(self) -> &'static str {
67        match self {
68            Table::Openai => "openai",
69            Table::Anthropic => "anthropic",
70            Table::GeminiApi => "gemini_api",
71            Table::Vertex => "vertex",
72        }
73    }
74
75    /// Who sets the schedule, as people say it.
76    pub fn provider(self) -> &'static str {
77        match self {
78            Table::Openai => "OpenAI",
79            Table::Anthropic => "Anthropic",
80            Table::GeminiApi => "Google",
81            Table::Vertex => "Google Cloud",
82        }
83    }
84}
85
86impl std::fmt::Display for Table {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        f.write_str(self.as_str())
89    }
90}
91
92/// How firm a listed date is.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
94#[serde(rename_all = "snake_case")]
95pub enum DateKind {
96    /// The model stops working on that date (OpenAI, Anthropic).
97    Hard,
98    /// The earliest the model may stop working (Gemini API, Google Cloud).
99    Earliest,
100}
101
102/// What the provider says about a model ID, as of the data date.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
104#[serde(rename_all = "snake_case")]
105pub enum EntryStatus {
106    /// Shut down: the provider says so, or the API already answers 404.
107    ShutDown,
108    /// Scheduled to shut down on `date`.
109    Retiring,
110    /// Deprecated with no shutdown date announced.
111    Deprecated,
112    /// Probably shut down or retiring, but no provider page says so for this
113    /// exact ID (an alias, a spelling variant, a past "earliest" date).
114    Unconfirmed,
115    /// The provider routes requests for this ID to a newer model.
116    AutoRouted,
117}
118
119/// How a fact was established.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
121#[serde(rename_all = "snake_case")]
122pub enum Verified {
123    /// A live API call (`verified_on`).
124    Live,
125    /// Stated on the provider's documentation.
126    Docs,
127    /// Not stated for this case; reported so people can check.
128    Unverified,
129}
130
131/// Whether Arbor's recipe would swap the model string automatically.
132#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
133#[serde(rename_all = "snake_case")]
134pub enum Action {
135    Rewrite,
136    ReportOnly,
137}
138
139/// A recipe the data was built from.
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141#[serde(deny_unknown_fields)]
142pub struct RecipeInfo {
143    pub id: String,
144    pub version: String,
145    pub file: String,
146    /// SHA-256 of the recipe file the data was generated from.
147    pub sha256: String,
148    pub table: Table,
149    pub provider: String,
150    pub date_kind: DateKind,
151    pub retrieved_on: String,
152    /// The provider pages the recipe was built from; the first is the
153    /// deprecations page.
154    pub source_urls: Vec<String>,
155}
156
157/// One model ID on one provider endpoint.
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
159#[serde(deny_unknown_fields)]
160pub struct ModelEntry {
161    pub model: String,
162    pub table: Table,
163    pub recipe: String,
164    pub status: EntryStatus,
165    /// `YYYY-MM-DD`: the shutdown (or earliest shutdown) date.
166    #[serde(default)]
167    pub date: Option<String>,
168    /// The single replacement the provider lists.
169    #[serde(default)]
170    pub replacement: Option<String>,
171    /// The provider's replacement cell when it lists several, none, or adds
172    /// a parameter (`gpt-5.6-sol (reasoning.mode: pro)`).
173    #[serde(default)]
174    pub replacement_text: Option<String>,
175    pub action: Action,
176    /// The recipe whose parameter rules apply to calls of this model.
177    #[serde(default)]
178    pub rule_set: Option<String>,
179    /// `non_reasoning`, `reasoning`, `reasoning_pro`, `image`...
180    #[serde(default)]
181    pub source_family: Option<String>,
182    /// `text`, `embedding`, `image`, `video`, `audio`, `agent`...
183    pub category: String,
184    /// `alias`, `snapshot`, `listed_variant`, `managed_agent`...
185    #[serde(default)]
186    pub kind: Option<String>,
187    pub verified: Verified,
188    #[serde(default)]
189    pub verified_on: Option<String>,
190    #[serde(default)]
191    pub notes: Vec<String>,
192}
193
194/// Fine-tuned models built on `base` (matched from `ft:<base>:...`).
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196#[serde(deny_unknown_fields)]
197pub struct FineTuneEntry {
198    pub base: String,
199    pub table: Table,
200    pub recipe: String,
201    pub status: EntryStatus,
202    pub date: String,
203    /// The base model the provider lists for these fine-tunes, if any.
204    #[serde(default)]
205    pub replacement_base: Option<String>,
206    /// Whether `replacement_base` can itself be fine-tuned. Advice to
207    /// retrain is given only when it can.
208    #[serde(default)]
209    pub fine_tunable: bool,
210    /// Why the fine-tune cannot simply move (public wording).
211    #[serde(default)]
212    pub note: Option<String>,
213}
214
215/// What a parameter rule does when it applies.
216#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
217#[serde(rename_all = "snake_case")]
218pub enum RuleEffect {
219    /// Add a parameter (`reasoning_effort="none"`).
220    Add,
221    /// Rename a parameter and add the parameters in `add`.
222    Rename,
223    /// The call needs a person: the change is not mechanical.
224    Review,
225    /// The parameters may stay, under `keep_*` conditions.
226    Keep,
227    /// Worth knowing; changes nothing.
228    Note,
229    /// A choice each repository makes (the recipe's `report_choice`): the
230    /// call is reported with every option and changed by none until the
231    /// repository picks one.
232    Choice,
233}
234
235/// How firmly an option's effect is established.
236#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
237#[serde(rename_all = "snake_case")]
238pub enum OptionStatus {
239    /// A provider page states it, or a recorded live call shows it.
240    Confirmed,
241    /// Neither does yet.
242    Unverified,
243}
244
245/// One option of a [`RuleEffect::Choice`] rule.
246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247#[serde(deny_unknown_fields)]
248pub struct ChoiceOption {
249    /// `reasoning_none`, `model_default`.
250    pub id: String,
251    /// For people: `keep reasoning off`.
252    pub label: String,
253    #[serde(default)]
254    pub add: Vec<AddParam>,
255    /// Parameters the option removes (when the call passes them).
256    #[serde(default)]
257    pub remove: Vec<String>,
258    /// Parameters the option keeps (when the call passes them).
259    #[serde(default)]
260    pub keep: Vec<String>,
261    /// What changes for the call: behaviour and cost.
262    pub effect: String,
263    pub status: OptionStatus,
264}
265
266/// A parameter to add, for one endpoint (`*` for any).
267#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
268#[serde(deny_unknown_fields)]
269pub struct AddParam {
270    pub endpoint: String,
271    pub name: String,
272    pub value: serde_json::Value,
273}
274
275#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
276#[serde(deny_unknown_fields)]
277pub struct RenameParam {
278    pub from: String,
279    pub to: String,
280}
281
282/// A parameter rule that can be checked from a call's keyword-argument names.
283/// Every non-empty condition must hold.
284#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
285#[serde(deny_unknown_fields)]
286pub struct ParamRule {
287    pub id: String,
288    pub rule_set: String,
289    pub effect: RuleEffect,
290    /// `chat.completions`, `responses`, `completions_legacy`, `assistants`.
291    #[serde(default)]
292    pub endpoints: Vec<String>,
293    /// Client routings (`google_generativeai_legacy`).
294    #[serde(default)]
295    pub routings: Vec<String>,
296    #[serde(default)]
297    pub source_families: Vec<String>,
298    /// Replacement models the rule is about.
299    #[serde(default)]
300    pub targets: Vec<String>,
301    /// Retiring models the rule is about.
302    #[serde(default)]
303    pub source_models: Vec<String>,
304    /// At least one of these keyword arguments is passed.
305    #[serde(default)]
306    pub any_kwargs: Vec<String>,
307    /// All of these are passed.
308    #[serde(default)]
309    pub all_kwargs: Vec<String>,
310    /// None of these is passed.
311    #[serde(default)]
312    pub lacks_kwargs: Vec<String>,
313    #[serde(default)]
314    pub add: Vec<AddParam>,
315    #[serde(default)]
316    pub rename: Option<RenameParam>,
317    /// For `keep`: the targets the parameters were verified on.
318    #[serde(default)]
319    pub keep_targets: Vec<String>,
320    /// For `keep`: verified only at reasoning effort `none`.
321    #[serde(default)]
322    pub keep_needs_effort_none: bool,
323    /// For [`RuleEffect::Choice`]: the choice this rule belongs to. The
324    /// rule whose `choice` is its own id is the choice's anchor.
325    #[serde(default)]
326    pub choice: Option<String>,
327    /// For [`RuleEffect::Choice`]: the options, in the anchor's order.
328    #[serde(default)]
329    pub options: Vec<ChoiceOption>,
330    /// An automatic change whose effect depends on a choice.
331    #[serde(default)]
332    pub see_choice: Option<String>,
333    /// What the choice means for this change (with `see_choice`).
334    #[serde(default)]
335    pub choice_note: Option<String>,
336    /// For people; `{target}` is the replacement model.
337    pub message: String,
338    /// When the rule's change cannot be made at this call.
339    #[serde(default)]
340    pub else_message: Option<String>,
341    pub verified: Verified,
342    #[serde(default)]
343    pub verified_on: Option<String>,
344    /// For a live rule: the models the live calls used. The live label holds
345    /// only for these targets.
346    #[serde(default)]
347    pub live_models: Vec<String>,
348    /// For a live rule: the APIs the live calls used (`chat.completions`).
349    #[serde(default)]
350    pub live_endpoints: Vec<String>,
351    /// For a live rule: the label where the live calls did not reach (another
352    /// target or another API): `docs` or `unverified`.
353    #[serde(default)]
354    pub otherwise_verified: Option<Verified>,
355    #[serde(default)]
356    pub source_url: Option<String>,
357}
358
359/// A recipe rule the engine does not evaluate, and why.
360#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
361#[serde(deny_unknown_fields)]
362pub struct SkippedRule {
363    pub id: String,
364    pub rule_set: String,
365    pub reason: String,
366}
367
368/// The whole data file.
369#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
370#[serde(deny_unknown_fields)]
371pub struct RetirementData {
372    pub schema: u32,
373    /// The oldest date any recipe's pages were read; each recipe keeps its
374    /// own `retrieved_on`.
375    pub data_as_of: String,
376    pub generated_at: String,
377    pub generator: String,
378    /// Where the recipes came from (`repository@commit:path`). The recipes
379    /// are in a private repository; every fact also names its provider page.
380    pub source: String,
381    /// FNV-1a 64 of the canonical JSON of every key except `digest` and
382    /// `generated_at`.
383    pub digest: String,
384    pub recipes: Vec<RecipeInfo>,
385    pub entries: Vec<ModelEntry>,
386    pub fine_tunes: Vec<FineTuneEntry>,
387    pub rules: Vec<ParamRule>,
388    pub skipped_rules: Vec<SkippedRule>,
389}
390
391/// The bundled data with lookup indexes.
392#[derive(Debug)]
393pub struct Retirements {
394    pub data: RetirementData,
395    pub as_of: Date,
396    by_model: HashMap<(Table, String), usize>,
397    by_fine_tune: HashMap<(Table, String), usize>,
398    recipes: HashMap<String, usize>,
399    rules_by_set: HashMap<String, Vec<usize>>,
400}
401
402impl Retirements {
403    /// Parses and indexes a data file.
404    pub fn from_json(json: &str) -> Result<Retirements, String> {
405        let data: RetirementData = serde_json::from_str(json)
406            .map_err(|e| format!("model retirement data is not valid: {e}"))?;
407        if data.schema != DATA_SCHEMA {
408            return Err(format!(
409                "model retirement data has schema {}, this build reads {DATA_SCHEMA}",
410                data.schema
411            ));
412        }
413        let as_of = Date::parse(&data.data_as_of)
414            .ok_or_else(|| format!("bad data_as_of {}", data.data_as_of))?;
415        let mut by_model = HashMap::new();
416        for (index, entry) in data.entries.iter().enumerate() {
417            if by_model
418                .insert((entry.table, entry.model.clone()), index)
419                .is_some()
420            {
421                return Err(format!(
422                    "{} is listed twice for {}",
423                    entry.model, entry.table
424                ));
425            }
426        }
427        let by_fine_tune = data
428            .fine_tunes
429            .iter()
430            .enumerate()
431            .map(|(index, f)| ((f.table, f.base.clone()), index))
432            .collect();
433        let recipes = data
434            .recipes
435            .iter()
436            .enumerate()
437            .map(|(index, r)| (r.id.clone(), index))
438            .collect();
439        let mut rules_by_set: HashMap<String, Vec<usize>> = HashMap::new();
440        for (index, rule) in data.rules.iter().enumerate() {
441            rules_by_set
442                .entry(rule.rule_set.clone())
443                .or_default()
444                .push(index);
445        }
446        Ok(Retirements {
447            data,
448            as_of,
449            by_model,
450            by_fine_tune,
451            recipes,
452            rules_by_set,
453        })
454    }
455
456    /// The entry for `model` on `table`, matched exactly.
457    pub fn entry(&self, table: Table, model: &str) -> Option<&ModelEntry> {
458        self.by_model
459            .get(&(table, model.to_string()))
460            .map(|&i| &self.data.entries[i])
461    }
462
463    /// Fine-tunes of `base` on `table`.
464    pub fn fine_tune(&self, table: Table, base: &str) -> Option<&FineTuneEntry> {
465        self.by_fine_tune
466            .get(&(table, base.to_string()))
467            .map(|&i| &self.data.fine_tunes[i])
468    }
469
470    pub fn recipe(&self, id: &str) -> Option<&RecipeInfo> {
471        self.recipes.get(id).map(|&i| &self.data.recipes[i])
472    }
473
474    /// The parameter rules of a rule set, in data order.
475    pub fn rules(&self, rule_set: &str) -> impl Iterator<Item = &ParamRule> {
476        self.rules_by_set
477            .get(rule_set)
478            .into_iter()
479            .flatten()
480            .map(move |&i| &self.data.rules[i])
481    }
482}
483
484/// The bundled data, parsed once.
485pub fn bundled() -> Result<&'static Retirements, String> {
486    static DATA: OnceLock<Result<Retirements, String>> = OnceLock::new();
487    DATA.get_or_init(|| Retirements::from_json(DATA_JSON))
488        .as_ref()
489        .map_err(Clone::clone)
490}
491
492/// Keys the digest leaves out: the digest itself, and the day the file was
493/// written.
494const UNDIGESTED: [&str; 2] = ["digest", "generated_at"];
495
496/// FNV-1a 64 over the canonical JSON (sorted keys, no whitespace) of every
497/// key except [`UNDIGESTED`], as `fnv1a64:<hex>`. The generator computes the
498/// same.
499pub fn content_digest(json: &str) -> Result<String, String> {
500    let value: serde_json::Value = serde_json::from_str(json).map_err(|e| e.to_string())?;
501    let object = value
502        .as_object()
503        .ok_or_else(|| "the data is not a JSON object".to_string())?;
504    let mut body = serde_json::Map::new();
505    for (key, item) in object {
506        if !UNDIGESTED.contains(&key.as_str()) {
507            body.insert(key.clone(), item.clone());
508        }
509    }
510    let mut canonical = String::new();
511    write_canonical(&serde_json::Value::Object(body), &mut canonical);
512    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
513    for byte in canonical.bytes() {
514        hash ^= u64::from(byte);
515        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
516    }
517    Ok(format!("fnv1a64:{hash:016x}"))
518}
519
520fn write_canonical(value: &serde_json::Value, out: &mut String) {
521    match value {
522        serde_json::Value::Object(map) => {
523            let mut keys: Vec<&String> = map.keys().collect();
524            keys.sort();
525            out.push('{');
526            for (i, key) in keys.into_iter().enumerate() {
527                if i > 0 {
528                    out.push(',');
529                }
530                out.push_str(&serde_json::Value::String(key.clone()).to_string());
531                out.push(':');
532                write_canonical(&map[key], out);
533            }
534            out.push('}');
535        }
536        serde_json::Value::Array(items) => {
537            out.push('[');
538            for (i, item) in items.iter().enumerate() {
539                if i > 0 {
540                    out.push(',');
541                }
542                write_canonical(item, out);
543            }
544            out.push(']');
545        }
546        other => out.push_str(&other.to_string()),
547    }
548}
549
550#[cfg(test)]
551mod data_tests {
552    //! The bundled file must be exactly what the generator writes. These run
553    //! on every `cargo test`, so a hand edit or a half-applied regeneration
554    //! fails CI; `--check` in the generator catches recipes that moved on.
555
556    use super::*;
557    use std::collections::HashSet;
558
559    fn data() -> &'static Retirements {
560        bundled().expect("bundled data parses")
561    }
562
563    #[test]
564    fn digest_matches_the_generator() {
565        let digest = content_digest(DATA_JSON).unwrap();
566        assert_eq!(
567            digest,
568            data().data.digest,
569            "data/model-retirements.json was edited by hand: regenerate it with \
570             scripts/retirements/generate_model_retirements.py"
571        );
572    }
573
574    #[test]
575    fn digest_notices_a_one_character_edit() {
576        let edited = DATA_JSON.replacen("\"2027-01-14\"", "\"2027-01-15\"", 1);
577        assert_ne!(edited, DATA_JSON);
578        assert_ne!(content_digest(&edited).unwrap(), data().data.digest);
579    }
580
581    #[test]
582    fn digest_covers_provenance_but_not_the_write_date() {
583        let original = &data().data.digest;
584        let edit = |key: &str, value: serde_json::Value| {
585            let mut json: serde_json::Value = serde_json::from_str(DATA_JSON).unwrap();
586            json[key] = value;
587            content_digest(&json.to_string()).unwrap()
588        };
589        // Hand edits to the dates, the source, the recipe hashes or the
590        // skipped rules all change the digest.
591        assert_ne!(&edit("data_as_of", "2026-12-31".into()), original);
592        assert_ne!(&edit("source", "someone@else:recipes/".into()), original);
593        let mut recipes = serde_json::to_value(&data().data.recipes).unwrap();
594        recipes[0]["sha256"] = "0".repeat(64).into();
595        assert_ne!(&edit("recipes", recipes), original);
596        assert_ne!(&edit("skipped_rules", serde_json::json!([])), original);
597        // The day the file was written is not content.
598        assert_eq!(&edit("generated_at", "2030-01-01".into()), original);
599    }
600
601    #[test]
602    fn provenance_is_recorded() {
603        let d = &data().data;
604        assert_eq!(d.schema, DATA_SCHEMA);
605        assert!(Date::parse(&d.generated_at).is_some());
606        assert!(data().as_of <= Date::parse(&d.generated_at).unwrap());
607        // The data date is the oldest page date, never a newer one.
608        let oldest = d
609            .recipes
610            .iter()
611            .map(|r| Date::parse(&r.retrieved_on).unwrap())
612            .min()
613            .unwrap();
614        assert_eq!(data().as_of, oldest);
615        assert!(
616            d.source.contains('@'),
617            "source names a commit: {}",
618            d.source
619        );
620        assert!(d.generator.ends_with(".py"));
621        let tables: HashSet<Table> = d.recipes.iter().map(|r| r.table).collect();
622        assert_eq!(
623            tables.len(),
624            Table::ALL.len(),
625            "every provider has a recipe"
626        );
627        for recipe in &d.recipes {
628            assert!(!recipe.version.is_empty(), "{}", recipe.id);
629            assert_eq!(recipe.sha256.len(), 64, "{}", recipe.id);
630            assert!(Date::parse(&recipe.retrieved_on).is_some(), "{}", recipe.id);
631            assert!(!recipe.source_urls.is_empty(), "{}", recipe.id);
632            for url in &recipe.source_urls {
633                assert!(url.starts_with("https://"), "{url}");
634            }
635        }
636    }
637
638    #[test]
639    fn entries_are_consistent() {
640        let r = data();
641        for entry in &r.data.entries {
642            let what = format!("{} ({})", entry.model, entry.table);
643            assert!(r.recipe(&entry.recipe).is_some(), "{what}: unknown recipe");
644            assert_eq!(
645                r.recipe(&entry.recipe).unwrap().table,
646                entry.table,
647                "{what}"
648            );
649            if let Some(date) = &entry.date {
650                assert!(Date::parse(date).is_some(), "{what}: bad date {date}");
651            }
652            if entry.status == EntryStatus::Retiring {
653                assert!(entry.date.is_some(), "{what}: retiring without a date");
654            }
655            assert_ne!(
656                entry.replacement.as_deref(),
657                Some(entry.model.as_str()),
658                "{what}"
659            );
660            if entry.action == Action::Rewrite {
661                assert!(
662                    entry.replacement.is_some(),
663                    "{what}: rewrite needs a replacement"
664                );
665            }
666            if let Some(set) = &entry.rule_set {
667                assert!(r.recipe(set).is_some(), "{what}: unknown rule set {set}");
668            }
669            if entry.verified == Verified::Live {
670                assert!(
671                    entry.verified_on.as_deref().and_then(Date::parse).is_some(),
672                    "{what}"
673                );
674            }
675            assert!(
676                !entry.model.is_empty() && !entry.model.chars().any(char::is_whitespace),
677                "{what}"
678            );
679        }
680        for fine in &r.data.fine_tunes {
681            assert!(Date::parse(&fine.date).is_some(), "{}", fine.base);
682            assert!(r.recipe(&fine.recipe).is_some(), "{}", fine.base);
683        }
684    }
685
686    #[test]
687    fn rules_point_at_real_models() {
688        let r = data();
689        for rule in &r.data.rules {
690            let entries: Vec<&ModelEntry> = r
691                .data
692                .entries
693                .iter()
694                .filter(|e| e.rule_set.as_deref() == Some(rule.rule_set.as_str()))
695                .collect();
696            assert!(!entries.is_empty(), "{}: empty rule set", rule.id);
697            let replacements: HashSet<&str> = entries
698                .iter()
699                .filter_map(|e| e.replacement.as_deref())
700                .collect();
701            for target in rule.targets.iter().chain(&rule.keep_targets) {
702                assert!(
703                    replacements.contains(target.as_str()),
704                    "{}: target {target} is no replacement in {}",
705                    rule.id,
706                    rule.rule_set
707                );
708            }
709            for model in &rule.source_models {
710                assert!(
711                    entries.iter().any(|e| &e.model == model),
712                    "{}: {model} is not in {}",
713                    rule.id,
714                    rule.rule_set
715                );
716            }
717            assert!(!rule.message.trim().is_empty(), "{}", rule.id);
718            match rule.effect {
719                RuleEffect::Add => assert!(!rule.add.is_empty(), "{}", rule.id),
720                RuleEffect::Rename => assert!(rule.rename.is_some(), "{}", rule.id),
721                _ => {}
722            }
723            if rule.verified == Verified::Live {
724                assert!(
725                    rule.verified_on.as_deref().and_then(Date::parse).is_some(),
726                    "{}",
727                    rule.id
728                );
729                // A live label names what the live calls covered.
730                assert!(!rule.live_models.is_empty(), "{}", rule.id);
731                assert_eq!(rule.live_endpoints, ["chat.completions"], "{}", rule.id);
732                assert!(rule.otherwise_verified.is_some(), "{}", rule.id);
733                assert_ne!(rule.otherwise_verified, Some(Verified::Live), "{}", rule.id);
734            }
735        }
736    }
737
738    #[test]
739    fn choices_offer_their_anchors_options() {
740        let r = data();
741        let mut anchors = 0;
742        for rule in &r.data.rules {
743            if let Some(choice) = &rule.choice {
744                assert_eq!(rule.effect, RuleEffect::Choice, "{}", rule.id);
745                let anchor = r
746                    .rules(&rule.rule_set)
747                    .find(|a| &a.id == choice && a.choice.as_deref() == Some(choice))
748                    .unwrap_or_else(|| panic!("{}: no anchor {choice}", rule.id));
749                anchors += usize::from(anchor.id == rule.id);
750                let ids = |rule: &ParamRule| -> Vec<String> {
751                    rule.options.iter().map(|o| o.id.clone()).collect()
752                };
753                assert!(rule.options.len() >= 2, "{}", rule.id);
754                assert_eq!(ids(rule), ids(anchor), "{}", rule.id);
755                for option in &rule.options {
756                    assert!(!option.label.is_empty() && !option.effect.is_empty());
757                }
758            } else {
759                assert_ne!(rule.effect, RuleEffect::Choice, "{}", rule.id);
760                assert!(rule.options.is_empty(), "{}", rule.id);
761            }
762            if let Some(choice) = &rule.see_choice {
763                assert!(rule.choice_note.is_some(), "{}", rule.id);
764                assert!(
765                    r.rules(&rule.rule_set).any(|a| &a.id == choice),
766                    "{}: see_choice {choice}",
767                    rule.id
768                );
769            }
770        }
771        // One reasoning choice per OpenAI dated recipe, and Claude's thinking.
772        assert_eq!(anchors, 3);
773    }
774
775    #[test]
776    fn no_automatic_change_sets_the_reasoning_effort() {
777        // The founder's 18 Oct decision: the reasoning effort is asked per
778        // repository; the lead's 20 Oct decision does the same for Claude's
779        // thinking. Only a choice's options may name them.
780        for rule in &data().data.rules {
781            if !matches!(
782                rule.effect,
783                RuleEffect::Add | RuleEffect::Rename | RuleEffect::Keep
784            ) {
785                continue;
786            }
787            for add in &rule.add {
788                let named = add.name.contains("effort")
789                    || add.name == "thinking"
790                    || (add.name == "reasoning" && add.value.get("effort").is_some());
791                assert!(!named, "{} sets {} automatically", rule.id, add.name);
792            }
793            if let Some(rename) = &rule.rename {
794                assert_ne!(rename.to, "thinking", "{}", rule.id);
795            }
796        }
797        for id in ["ANT-THINKING-DEFAULT", "ANT-THINKING-DISABLED"] {
798            let rule = data().data.rules.iter().find(|r| r.id == id).expect(id);
799            assert_eq!(rule.effect, RuleEffect::Choice, "{id}");
800            assert_eq!(rule.choice.as_deref(), Some("ANT-THINKING-DEFAULT"), "{id}");
801        }
802        for id in [
803            "OAI-REASONING-DEFAULT",
804            "OAI-TOOLS-CC",
805            "OAI-LEGACY-FUNCTIONS",
806            "OAI-SAMPLING",
807            "G6-REASONING-DEFAULT",
808            "G6-TOOLS-CC",
809            "G6-LEGACY-FUNCTIONS",
810            "G6-SAMPLING",
811        ] {
812            let rule = data().data.rules.iter().find(|r| r.id == id).expect(id);
813            assert_eq!(rule.effect, RuleEffect::Choice, "{id}");
814        }
815    }
816
817    #[test]
818    fn fine_tunes_name_a_base_only_when_it_can_be_fine_tuned() {
819        let r = data();
820        for fine in &r.data.fine_tunes {
821            assert!(fine.note.is_some(), "{}", fine.base);
822            assert!(
823                !fine.fine_tunable,
824                "{}: no listed base supports fine-tuning today",
825                fine.base
826            );
827        }
828        // gpt-6-luna does not support fine-tuning: no base is listed.
829        let mini = r
830            .fine_tune(Table::Openai, "gpt-4o-mini-2024-07-18")
831            .expect("fine-tunes of the gpt-4o mini snapshot are matched");
832        assert_eq!(mini.replacement_base, None);
833        assert_eq!(mini.date, "2027-01-14");
834    }
835
836    #[test]
837    fn launch_facts_are_in_the_data() {
838        // The soft-launch check leans on these; if a regeneration drops one,
839        // the README and the launch copy are wrong.
840        let r = data();
841        for alias in ["gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini"] {
842            let entry = r.entry(Table::Openai, alias).expect(alias);
843            assert_eq!(entry.status, EntryStatus::Retiring);
844            assert_eq!(entry.date.as_deref(), Some("2027-01-14"));
845            assert_eq!(entry.replacement.as_deref(), Some("gpt-6-luna"));
846        }
847        let sonnet = r
848            .entry(Table::Anthropic, "claude-3-5-sonnet-20241022")
849            .unwrap();
850        assert_eq!(sonnet.status, EntryStatus::ShutDown);
851        assert!(r
852            .entry(Table::Openai, "claude-3-5-sonnet-20241022")
853            .is_none());
854        assert!(r.entry(Table::Openai, "gpt-6-luna").is_none());
855        let max_tokens = r
856            .rules("openai-2027-01-14")
857            .find(|rule| rule.id == "G6-MAX-TOKENS")
858            .unwrap();
859        assert_eq!(max_tokens.verified, Verified::Live);
860        assert_eq!(
861            max_tokens.rename,
862            Some(RenameParam {
863                from: "max_tokens".into(),
864                to: "max_completion_tokens".into()
865            })
866        );
867        // The rename stays automatic and adds nothing; the reasoning effort
868        // is the per-repo choice it points to.
869        assert!(max_tokens.add.is_empty());
870        assert_eq!(
871            max_tokens.see_choice.as_deref(),
872            Some("G6-REASONING-DEFAULT")
873        );
874    }
875
876    #[test]
877    fn rejects_unknown_fields_and_schemas() {
878        let mut value: serde_json::Value = serde_json::from_str(DATA_JSON).unwrap();
879        value["entries"][0]["surprise"] = serde_json::json!(true);
880        assert!(Retirements::from_json(&value.to_string()).is_err());
881        let mut value: serde_json::Value = serde_json::from_str(DATA_JSON).unwrap();
882        value["schema"] = serde_json::json!(99);
883        assert!(Retirements::from_json(&value.to_string())
884            .unwrap_err()
885            .contains("schema"));
886    }
887}