1use super::base_url::{base_url_of, BaseUrl};
39use super::gaps;
40use super::{
41 Action, DateKind, EntryStatus, OptionStatus, ParamRule, RecipeInfo, RetirementData,
42 Retirements, RuleEffect, Table, Verified,
43};
44use super::{Date, ModelEntry};
45use crate::usages::{
46 model_family, CapturedValue, ClientConstruction, GapKind, Routing, Sdk, SdkCall, UsageGap,
47 ValueOrigin, VertexAi,
48};
49use serde::Serialize;
50use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
51
52pub const REPORT_VERSION: u32 = 1;
54
55#[derive(Debug, Clone, Copy)]
57pub struct CheckOptions {
58 pub today: Date,
60 pub fail_within: Option<i64>,
63 pub include_routed: bool,
66 pub count_unconfirmed: bool,
72}
73
74#[derive(Debug, Clone, Copy)]
76pub struct ScanInput<'a> {
77 pub calls: &'a [SdkCall],
78 pub gaps: &'a [UsageGap],
79 pub clients: &'a [ClientConstruction],
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
84#[serde(rename_all = "snake_case")]
85pub enum State {
86 Retired,
89 Retiring,
91 Unconfirmed,
94 Deprecated,
96 AutoRouted,
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
102#[serde(rename_all = "snake_case")]
103pub enum MatchKind {
104 Exact,
106 ResourcePrefix,
108 RouterPrefix,
110 FineTuned,
112}
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
116#[serde(rename_all = "snake_case")]
117pub enum RoutingClass {
118 Direct,
121 Routed,
124 Unknown,
128}
129
130#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
132#[serde(rename_all = "snake_case")]
133pub enum Confidence {
134 Confirmed,
136 ConfirmFirst,
140 Gap,
143}
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
147#[serde(rename_all = "snake_case")]
148pub enum FixKind {
149 Swap,
152 Decide,
155 Manual,
158 None,
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
164#[serde(rename_all = "snake_case")]
165pub enum CallKind {
166 Request,
168 ModelBinding,
172 RequestParam,
176}
177
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
179#[serde(rename_all = "snake_case")]
180pub enum ChangeKind {
181 Rename,
182 Add,
183}
184
185#[derive(Debug, Clone, PartialEq, Serialize)]
187pub struct Change {
188 pub kind: ChangeKind,
189 pub param: String,
191 #[serde(skip_serializing_if = "Option::is_none")]
193 pub to: Option<String>,
194 #[serde(skip_serializing_if = "Option::is_none")]
196 pub value: Option<serde_json::Value>,
197 pub because: Vec<String>,
199 pub rules: Vec<String>,
200 pub verified: Verified,
203}
204
205#[derive(Debug, Clone, PartialEq, Serialize)]
207pub struct ReviewItem {
208 pub rule: Option<String>,
210 pub message: String,
211 pub because: Vec<String>,
212 #[serde(skip_serializing_if = "Option::is_none")]
213 pub verified: Option<Verified>,
214}
215
216#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
218pub struct ChainStep {
219 pub model: String,
220 pub status: Option<State>,
223 pub date: Option<Date>,
224 pub date_kind: Option<DateKind>,
225 #[serde(skip_serializing_if = "Option::is_none")]
227 pub replacement_text: Option<String>,
228}
229
230#[derive(Debug, Clone, PartialEq, Serialize)]
232pub struct ParamValue {
233 pub name: String,
234 pub value: serde_json::Value,
235}
236
237#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
239pub struct OptionEffect {
240 pub rule: String,
241 pub text: String,
242 pub status: OptionStatus,
243}
244
245#[derive(Debug, Clone, PartialEq, Serialize)]
247pub struct DecisionOption {
248 pub id: String,
250 pub label: String,
252 pub add: Vec<ParamValue>,
254 pub remove: Vec<String>,
256 pub keep: Vec<String>,
258 pub effects: Vec<OptionEffect>,
259}
260
261#[derive(Debug, Clone, PartialEq, Serialize)]
264pub struct Decision {
265 pub choice: String,
267 pub reasons: Vec<String>,
269 pub because: Vec<String>,
271 pub rules: Vec<String>,
272 pub options: Vec<DecisionOption>,
273 pub notes: Vec<String>,
275}
276
277#[derive(Debug, Clone, PartialEq, Serialize)]
279pub struct Finding {
280 pub file: String,
281 pub line: u32,
282 pub column: u32,
283 pub end_line: u32,
284 pub symbol: Option<String>,
285 pub chain: Option<String>,
287 pub call_kind: CallKind,
288 pub provider: Table,
289 pub model: String,
291 pub matched: String,
293 pub match_kind: MatchKind,
294 pub key: String,
296 pub status: State,
297 pub listed_status: EntryStatus,
299 pub date: Option<Date>,
300 pub date_kind: DateKind,
301 pub days_left: Option<i64>,
303 pub replacement: Option<String>,
305 pub replacement_text: Option<String>,
308 pub live_replacement: Option<String>,
311 pub replacement_chain: Vec<ChainStep>,
314 pub fix: FixKind,
315 pub changes: Vec<Change>,
316 pub decisions: Vec<Decision>,
318 pub review: Vec<ReviewItem>,
319 pub notes: Vec<String>,
320 pub routing: String,
323 pub routing_class: RoutingClass,
324 pub base_url: Option<BaseUrl>,
326 pub endpoint: Option<&'static str>,
328 pub confidence: Confidence,
329 pub origin: Option<ValueOrigin>,
330 pub value_from: Option<String>,
332 pub value_line: u32,
334 pub gap_reason: Option<String>,
339 pub routing_gap: Option<String>,
344 pub candidate: bool,
347 pub splat: bool,
349 pub in_window: bool,
351 pub fails: bool,
355 pub recipe: String,
356 pub recipe_version: String,
357 pub verified: Verified,
358 pub source_url: Option<String>,
360}
361
362#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
364pub struct Unreadable {
365 pub file: String,
366 pub line: u32,
367 pub chain: Option<String>,
368 pub key: Option<String>,
369 pub sdk: Option<Sdk>,
370 pub reason: String,
372}
373
374#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
375pub struct RecipeRef {
376 pub id: String,
377 pub version: String,
378 pub provider: String,
379 pub retrieved_on: String,
381}
382
383#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
385pub struct ProviderDate {
386 pub provider: String,
387 pub as_of: Date,
389}
390
391#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
392pub struct DataInfo {
393 pub as_of: Date,
395 pub providers: Vec<ProviderDate>,
397 pub source: String,
398 pub recipes: Vec<RecipeRef>,
399}
400
401#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
402pub struct ReportOptions {
403 pub fail_within_days: Option<i64>,
404 pub include_routed: bool,
405 pub count_unconfirmed: bool,
406}
407
408#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
409pub struct NextShutdown {
410 pub date: Date,
411 pub days_left: i64,
412 pub provider: Table,
413 pub calls: usize,
414}
415
416#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
417pub struct Summary {
418 pub files_scanned: usize,
420 pub affected_calls: usize,
422 pub affected_files: usize,
423 pub retired: usize,
424 pub retiring: usize,
425 pub other: usize,
427 pub in_window: usize,
429 pub failing: usize,
431 pub uncounted: usize,
434 pub swap: usize,
435 pub decide: usize,
436 pub manual: usize,
437 pub by_provider: BTreeMap<String, usize>,
438 pub next_shutdown: Option<NextShutdown>,
440 pub routed_calls: usize,
443 pub unreadable_calls: usize,
445 pub no_model_calls: usize,
447 pub response_objects: usize,
450 pub not_analyzed: usize,
454 pub untracked_methods: usize,
457 pub unresolved_clients: usize,
462 pub syntax_error_files: usize,
465 pub skipped_files: usize,
468 pub hidden_calls: usize,
471}
472
473#[derive(Debug, Clone, PartialEq, Serialize)]
475pub struct RetirementReport {
476 pub version: u32,
477 pub today: Date,
478 pub root: String,
480 pub languages: Vec<String>,
481 pub data: DataInfo,
482 pub options: ReportOptions,
483 pub summary: Summary,
484 pub findings: Vec<Finding>,
486 pub routed: Vec<Finding>,
489 pub unreadable: Vec<Unreadable>,
490 pub exit_code: i32,
492}
493
494pub fn check(input: ScanInput<'_>, data: &Retirements, options: &CheckOptions) -> RetirementReport {
496 let mut direct = Vec::new();
497 let mut routed = Vec::new();
498 let mut response_objects = 0;
499
500 let mut gaps_at: HashMap<(&str, u32), Vec<&UsageGap>> = HashMap::new();
502 for gap in input.gaps.iter().filter(|g| !gaps::is_region(g)) {
503 if let Some(span) = gap.span {
504 gaps_at
505 .entry((gap.file.as_str(), span.start_byte))
506 .or_default()
507 .push(gap);
508 }
509 }
510 let calls_at: HashMap<(&str, u32), &SdkCall> = input
511 .calls
512 .iter()
513 .map(|c| ((c.file.as_str(), c.span.start_byte), c))
514 .collect();
515 let at_call = |call: &SdkCall| -> Vec<&UsageGap> {
516 gaps_at
517 .get(&(call.file.as_str(), call.span.start_byte))
518 .cloned()
519 .unwrap_or_default()
520 };
521
522 for call in input.calls {
523 let Some(kind) = call_kind(call) else {
524 response_objects += usize::from(!call.values.is_empty());
525 continue;
526 };
527 let here = at_call(call);
528 let class = call_routing(call, kind, input.clients, &here);
529 for value in &call.values {
530 let value_gap = here.iter().find(|g| gaps::holds_value(g, &value.key));
533 let confidence = match (confidence_of(value.origin), value_gap) {
534 (Confidence::Confirmed, Some(_)) => Confidence::ConfirmFirst,
535 (confidence, _) => confidence,
536 };
537 let Some(mut finding) = finding_for(
538 data,
539 options,
540 Site::Call(call, kind),
541 &class,
542 value,
543 confidence,
544 ) else {
545 continue;
546 };
547 finding.gap_reason = value_gap.map(|g| g.reason.clone());
548 if finding.routing_class == RoutingClass::Routed {
549 routed.push(finding);
550 } else {
551 direct.push(finding);
552 }
553 }
554 }
555 for gap in input.gaps.iter().filter(|g| !g.values.is_empty()) {
556 let call = (gap.kind == GapKind::UnresolvedModel)
561 .then(|| {
562 gap.span
563 .and_then(|s| calls_at.get(&(gap.file.as_str(), s.start_byte)))
564 .copied()
565 })
566 .flatten();
567 let (site, class, confidence) = match call {
568 Some(call) => {
569 let Some(kind) = call_kind(call) else {
570 continue;
571 };
572 (
573 Site::Call(call, kind),
574 call_routing(call, kind, input.clients, &at_call(call)),
575 Confidence::ConfirmFirst,
576 )
577 }
578 None => (
579 Site::Gap(gap),
580 CallRouting {
581 class: RoutingClass::Unknown,
582 routing: "unresolved_client".to_string(),
583 sdk: gap.sdk,
584 schedule: Schedule::Guess,
585 base_url: None,
586 gap: None,
587 },
588 if gap.kind == GapKind::UnresolvedModel {
589 Confidence::ConfirmFirst
590 } else {
591 Confidence::Gap
592 },
593 ),
594 };
595 for value in &gap.values {
596 let Some(mut finding) = finding_for(data, options, site, &class, value, confidence)
597 else {
598 continue;
599 };
600 finding.gap_reason = Some(gap.reason.clone());
601 finding.candidate = gap.kind == GapKind::UnresolvedModel;
602 if finding.routing_class == RoutingClass::Routed {
603 routed.push(finding);
604 } else {
605 direct.push(finding);
606 }
607 }
608 }
609
610 dedupe_findings(&mut direct);
613 dedupe_findings(&mut routed);
614 sort_findings(&mut direct);
615 sort_findings(&mut routed);
616 let routed_calls = routed.len();
617 if !options.include_routed {
618 routed.clear();
619 }
620 let (unreadable, no_model_calls) = unreadable(input);
621
622 let mut summary = summarize(&direct, &routed, routed_calls, unreadable.len());
623 summary.no_model_calls = no_model_calls;
624 summary.response_objects = response_objects;
625 summary.not_analyzed = input.gaps.iter().filter(|g| gaps::is_region(g)).count();
626 summary.untracked_methods = input
627 .gaps
628 .iter()
629 .filter(|g| g.kind == GapKind::DynamicDispatch)
630 .count();
631 summary.unresolved_clients = unresolved_clients(input);
632 let exit_code = i32::from(summary.failing > 0);
633
634 RetirementReport {
635 version: REPORT_VERSION,
636 today: options.today,
637 root: String::new(),
638 languages: crate::usages::USAGE_LANGUAGES
639 .iter()
640 .map(|l| l.to_string())
641 .collect(),
642 data: data_info(&data.data, data.as_of),
643 options: ReportOptions {
644 fail_within_days: options.fail_within,
645 include_routed: options.include_routed,
646 count_unconfirmed: options.count_unconfirmed,
647 },
648 summary,
649 findings: direct,
650 routed,
651 unreadable,
652 exit_code,
653 }
654}
655
656fn data_info(data: &RetirementData, as_of: Date) -> DataInfo {
657 let mut providers: Vec<(Table, ProviderDate)> = Vec::new();
658 for recipe in &data.recipes {
659 let Some(date) = Date::parse(&recipe.retrieved_on) else {
660 continue;
661 };
662 match providers
663 .iter_mut()
664 .find(|(_, p)| p.provider == recipe.provider)
665 {
666 Some((_, existing)) => existing.as_of = existing.as_of.min(date),
667 None => providers.push((
668 recipe.table,
669 ProviderDate {
670 provider: recipe.provider.clone(),
671 as_of: date,
672 },
673 )),
674 }
675 }
676 providers.sort_by_key(|(table, _)| *table);
677 DataInfo {
678 as_of,
679 providers: providers.into_iter().map(|(_, p)| p).collect(),
680 source: data.source.clone(),
681 recipes: data
682 .recipes
683 .iter()
684 .map(|r| RecipeRef {
685 id: r.id.clone(),
686 version: r.version.clone(),
687 provider: r.provider.clone(),
688 retrieved_on: r.retrieved_on.clone(),
689 })
690 .collect(),
691 }
692}
693
694fn confidence_of(origin: ValueOrigin) -> Confidence {
695 match origin {
696 ValueOrigin::Literal
697 | ValueOrigin::ModuleConstant
698 | ValueOrigin::ClassConstant
699 | ValueOrigin::LocalConstant => Confidence::Confirmed,
700 ValueOrigin::EnvDefault | ValueOrigin::ParameterDefault => Confidence::ConfirmFirst,
701 }
702}
703
704const OBJECT_BUILDERS: &[&str] = &[
711 "model_validate",
712 "model_validate_json",
713 "model_validate_strings",
714 "model_construct",
715 "construct",
716 "parse_obj",
717 "parse_raw",
718 "parse_file",
719 "from_orm",
720 "model_copy",
721];
722
723const REQUEST_TYPE_SUFFIXES: &[&str] = &["Param", "Params", "Parameters", "Config", "Request"];
728
729fn call_kind(call: &SdkCall) -> Option<CallKind> {
733 if call.request {
734 return Some(CallKind::Request);
735 }
736 let segments: Vec<&str> = call.member.split('.').collect();
737 let last = segments.last().copied().unwrap_or_default();
738 if OBJECT_BUILDERS.contains(&last) {
739 return None;
740 }
741 if segments.first() == Some(&"types") {
742 let request_module = segments[..segments.len() - 1]
745 .iter()
746 .any(|s| s.ends_with("_param") || s.ends_with("_params"));
747 let request_type = REQUEST_TYPE_SUFFIXES.iter().any(|s| last.ends_with(s));
748 return (request_module || request_type).then_some(CallKind::RequestParam);
749 }
750 Some(CallKind::ModelBinding)
751}
752
753struct CallRouting {
758 class: RoutingClass,
759 routing: String,
760 sdk: Option<Sdk>,
761 schedule: Schedule,
763 base_url: Option<BaseUrl>,
764 gap: Option<String>,
766}
767
768#[derive(Debug, Clone, Copy, PartialEq, Eq)]
770enum Schedule {
771 One(Table),
773 VertexOrGeminiApi,
776 Guess,
779}
780
781fn call_routing(
796 call: &SdkCall,
797 kind: CallKind,
798 clients: &[ClientConstruction],
799 at_call: &[&UsageGap],
800) -> CallRouting {
801 let base_url = base_url_of(call, at_call, clients);
802 let google = || match vertexai_of(call, clients) {
803 Some(VertexAi::On) => Schedule::One(Table::Vertex),
804 Some(VertexAi::Off) => Schedule::One(Table::GeminiApi),
805 Some(VertexAi::Unknown) => Schedule::VertexOrGeminiApi,
806 None => Schedule::Guess,
807 };
808 let (class, schedule) = match call.routing {
809 Routing::OpenaiDirect => (RoutingClass::Direct, Schedule::One(Table::Openai)),
810 Routing::AnthropicDirect => (RoutingClass::Direct, Schedule::One(Table::Anthropic)),
811 Routing::GoogleGenai => match google() {
812 Schedule::Guess => (RoutingClass::Direct, Schedule::One(Table::GeminiApi)),
813 schedule => (RoutingClass::Direct, schedule),
814 },
815 Routing::GoogleGenerativeaiLegacy => {
816 (RoutingClass::Direct, Schedule::One(Table::GeminiApi))
817 }
818 Routing::AzureOpenai
819 | Routing::CustomBaseUrl
820 | Routing::AnthropicBedrock
821 | Routing::AnthropicVertex => (RoutingClass::Routed, Schedule::Guess),
822 Routing::Unknown if call.sdk == Sdk::Google => (RoutingClass::Unknown, google()),
826 Routing::Unknown => (RoutingClass::Unknown, Schedule::Guess),
827 };
828 let gap = at_call.iter().find(|g| gaps::holds_routing(g));
829 CallRouting {
830 class: if gap.is_some() || kind == CallKind::RequestParam {
831 RoutingClass::Unknown
832 } else {
833 class
834 },
835 routing: call.routing.as_str().to_string(),
836 sdk: Some(call.sdk),
837 schedule,
838 base_url,
839 gap: gap.map(|g| g.reason.clone()),
840 }
841}
842
843fn vertexai_of(call: &SdkCall, clients: &[ClientConstruction]) -> Option<VertexAi> {
847 let line = call.client_line?;
848 let mut found = clients
849 .iter()
850 .filter(|c| c.sdk == Sdk::Google && c.file == call.file && c.span.line == line)
851 .filter_map(|c| c.vertexai);
852 let first = found.next()?;
853 Some(if found.all(|v| v == first) {
854 first
855 } else {
856 VertexAi::Unknown
857 })
858}
859
860fn sdk_table(sdk: Sdk) -> Table {
861 match sdk {
862 Sdk::Openai => Table::Openai,
863 Sdk::Anthropic => Table::Anthropic,
864 Sdk::Google => Table::GeminiApi,
865 }
866}
867
868const ROUTER_PREFIXES: &[(&str, Table)] = &[
870 ("openai/", Table::Openai),
871 ("anthropic/", Table::Anthropic),
872 ("google/", Table::GeminiApi),
873 ("gemini/", Table::GeminiApi),
874 ("vertex_ai/", Table::Vertex),
875];
876
877struct Hit<'d> {
883 matched: String,
884 match_kind: MatchKind,
885 table: Table,
886 recipe: &'d RecipeInfo,
887 status: EntryStatus,
888 date: Option<Date>,
889 replacement: Option<String>,
890 replacement_text: Option<String>,
891 action: Action,
892 rule_set: Option<&'d str>,
893 entry: Option<&'d ModelEntry>,
894 verified: Verified,
895 notes: Vec<String>,
896 fine_tune_advice: Option<String>,
898 schedule_unconfirmed: bool,
901}
902
903fn entry_hit<'d>(data: &'d Retirements, entry: &'d ModelEntry, kind: MatchKind) -> Option<Hit<'d>> {
904 let recipe = data.recipe(&entry.recipe)?;
905 Some(Hit {
906 matched: entry.model.clone(),
907 match_kind: kind,
908 table: entry.table,
909 recipe,
910 status: entry.status,
911 date: entry.date.as_deref().and_then(Date::parse),
912 replacement: entry.replacement.clone(),
913 replacement_text: entry.replacement_text.clone(),
914 action: entry.action,
915 rule_set: entry.rule_set.as_deref(),
916 entry: Some(entry),
917 verified: entry.verified,
918 notes: entry.notes.clone(),
919 fine_tune_advice: None,
920 schedule_unconfirmed: false,
921 })
922}
923
924fn lookup<'d>(data: &'d Retirements, table: Table, value: &str) -> Option<Hit<'d>> {
927 if let Some(entry) = data.entry(table, value) {
928 return entry_hit(data, entry, MatchKind::Exact);
929 }
930 if matches!(table, Table::GeminiApi | Table::Vertex) {
931 for prefix in ["models/", "publishers/google/models/"] {
932 if let Some(entry) = value
933 .strip_prefix(prefix)
934 .and_then(|id| data.entry(table, id))
935 {
936 let mut hit = entry_hit(data, entry, MatchKind::ResourcePrefix)?;
937 hit.notes.push(format!(
938 "Matched without the `{prefix}` prefix; Google lists the bare ID."
939 ));
940 return Some(hit);
941 }
942 }
943 }
944 if table == Table::Openai {
945 let base = value.strip_prefix("ft:")?.split(':').next()?;
946 return fine_tune_hit(data, table, base);
947 }
948 None
949}
950
951const NONE_LISTED: &str = "no fine-tunable replacement is listed";
952
953fn fine_tune_advice(
959 fine: &super::FineTuneEntry,
960 base: &str,
961 subject: &str,
962 retrain: &str,
963) -> (String, String) {
964 let note = fine.note.as_deref().unwrap_or_default();
965 let advice = match (&fine.replacement_base, fine.fine_tunable) {
966 (Some(listed), true) => format!(
967 "{subject}: {retrain} {listed}, the base model OpenAI lists for fine-tunes of {base}."
968 ),
969 (Some(listed), false) => format!(
970 "{subject}: OpenAI lists {listed} for fine-tunes of {base}, so {NONE_LISTED}. {note}"
971 ),
972 (None, _) => format!(
973 "{subject}: {} for fine-tunes of {base}. {note}",
974 capitalize(NONE_LISTED)
975 ),
976 };
977 let text = fine
978 .replacement_base
979 .as_ref()
980 .filter(|_| fine.fine_tunable)
981 .map(|b| format!("retrain on {b}"))
982 .unwrap_or_else(|| NONE_LISTED.to_string());
983 (advice.trim_end().to_string(), text)
984}
985
986fn fine_tune_hit<'d>(data: &'d Retirements, table: Table, base: &str) -> Option<Hit<'d>> {
990 if let Some(fine) = data.fine_tune(table, base) {
991 let recipe = data.recipe(&fine.recipe)?;
992 let (advice, text) = fine_tune_advice(fine, base, "Fine-tuned model", "retrain it on");
993 return Some(Hit {
994 matched: base.to_string(),
995 match_kind: MatchKind::FineTuned,
996 table,
997 recipe,
998 status: fine.status,
999 date: Date::parse(&fine.date),
1000 replacement: None,
1001 replacement_text: Some(text),
1002 action: Action::ReportOnly,
1003 rule_set: None,
1004 entry: None,
1005 verified: Verified::Docs,
1006 notes: vec![format!(
1007 "OpenAI retires fine-tunes of {base} with their base model's schedule."
1008 )],
1009 fine_tune_advice: Some(advice),
1010 schedule_unconfirmed: false,
1011 });
1012 }
1013 let entry = data.entry(table, base)?;
1016 let mut hit = entry_hit(data, entry, MatchKind::FineTuned)?;
1017 hit.replacement = None;
1018 hit.replacement_text = Some(NONE_LISTED.to_string());
1019 hit.action = Action::ReportOnly;
1020 hit.rule_set = None;
1021 hit.notes = vec![format!(
1022 "Fine-tuned models follow the schedule of their base model, {base}."
1023 )];
1024 hit.fine_tune_advice = Some(format!(
1025 "Fine-tuned model: OpenAI lists no replacement for fine-tunes of {base}, so {NONE_LISTED}."
1026 ));
1027 Some(hit)
1028}
1029
1030fn fine_tuning_job_hit<'d>(data: &'d Retirements, mut hit: Hit<'d>) -> Hit<'d> {
1036 if hit.match_kind == MatchKind::FineTuned {
1037 return hit;
1040 }
1041 let base = hit.matched.clone();
1042 let provider = hit.table.provider();
1043 let (advice, text) = match data.fine_tune(hit.table, &base) {
1044 Some(fine) => fine_tune_advice(fine, &base, "Fine-tuning job", "start new jobs on"),
1045 None => {
1046 let listed = match &hit.replacement {
1047 Some(listed) => format!(
1048 "{provider} lists {listed} as the replacement for {base}, not as a base for fine-tuning"
1049 ),
1050 None => format!("{provider} lists no replacement for {base}"),
1051 };
1052 (
1053 format!("Fine-tuning job: {listed}, so {NONE_LISTED}."),
1054 NONE_LISTED.to_string(),
1055 )
1056 }
1057 };
1058 hit.replacement = None;
1059 hit.replacement_text = Some(text);
1060 hit.action = Action::ReportOnly;
1061 hit.rule_set = None;
1062 hit.fine_tune_advice = Some(advice);
1063 hit
1064}
1065
1066fn resolve<'d>(
1068 data: &'d Retirements,
1069 routing: &CallRouting,
1070 value: &str,
1071) -> Option<(Hit<'d>, RoutingClass)> {
1072 match routing.schedule {
1073 Schedule::One(table) => return lookup(data, table, value).map(|hit| (hit, routing.class)),
1075 Schedule::VertexOrGeminiApi => {
1076 let mut hit = lookup(data, Table::Vertex, value)
1077 .or_else(|| lookup(data, Table::GeminiApi, value))?;
1078 hit.schedule_unconfirmed = true;
1079 return Some((hit, RoutingClass::Unknown));
1080 }
1081 Schedule::Guess => {}
1082 }
1083 for (prefix, table) in ROUTER_PREFIXES {
1086 if let Some(id) = value.strip_prefix(prefix) {
1087 let mut hit = lookup(data, *table, id)?;
1088 hit.match_kind = MatchKind::RouterPrefix;
1089 return Some((hit, RoutingClass::Routed));
1090 }
1091 }
1092 let table = model_family(value)
1093 .map(sdk_table)
1094 .or(routing.sdk.map(sdk_table))?;
1095 let hit = match lookup(data, table, value) {
1096 Some(hit) => hit,
1097 None if table == Table::GeminiApi && routing.sdk == Some(Sdk::Google) => {
1100 lookup(data, Table::Vertex, value)?
1101 }
1102 None => return None,
1103 };
1104 let table = hit.table;
1105 let crosses = routing.sdk.is_some_and(|sdk| sdk_table(sdk) != table)
1107 && !(routing.sdk == Some(Sdk::Google) && table == Table::Vertex);
1108 let class = if crosses {
1109 RoutingClass::Routed
1110 } else {
1111 routing.class
1112 };
1113 Some((hit, class))
1114}
1115
1116struct Chain<'d> {
1121 steps: Vec<ChainStep>,
1122 live: Option<String>,
1124 last_hop: Option<&'d ModelEntry>,
1127}
1128
1129impl Chain<'_> {
1130 fn chained(&self) -> bool {
1132 self.steps.first().is_some_and(|s| s.status.is_some())
1133 }
1134}
1135
1136fn follow_chain<'d>(data: &'d Retirements, table: Table, first: &str, today: Date) -> Chain<'d> {
1141 let mut steps = Vec::new();
1142 let mut seen = HashSet::new();
1143 let mut current = first.to_string();
1144 let mut last_hop = None;
1145 loop {
1146 if !seen.insert(current.clone()) || steps.len() >= 8 {
1147 return Chain {
1148 steps,
1149 live: None,
1150 last_hop,
1151 };
1152 }
1153 let Some(entry) = data.entry(table, ¤t) else {
1154 steps.push(ChainStep {
1155 model: current.clone(),
1156 status: None,
1157 date: None,
1158 date_kind: None,
1159 replacement_text: None,
1160 });
1161 return Chain {
1162 steps,
1163 live: Some(current),
1164 last_hop,
1165 };
1166 };
1167 let date = entry.date.as_deref().and_then(Date::parse);
1168 let kind = data
1169 .recipe(&entry.recipe)
1170 .map(|r| r.date_kind)
1171 .unwrap_or(DateKind::Hard);
1172 let state = effective_state(entry.status, date, kind, today);
1173 steps.push(ChainStep {
1174 model: entry.model.clone(),
1175 status: Some(state),
1176 date,
1177 date_kind: Some(kind),
1178 replacement_text: entry.replacement_text.clone(),
1179 });
1180 match &entry.replacement {
1181 Some(next) => {
1182 last_hop = Some(entry);
1183 current = next.clone();
1184 }
1185 None => {
1186 let works = matches!(state, State::Deprecated | State::AutoRouted);
1187 return Chain {
1188 steps,
1189 live: works.then(|| entry.model.clone()),
1190 last_hop,
1191 };
1192 }
1193 }
1194 }
1195}
1196
1197fn step_phrase(step: &ChainStep, today: Date) -> String {
1199 match (step.status, step.date) {
1200 (Some(State::Retired), Some(d)) if d <= today => format!("shut down on {}", d.human()),
1201 (Some(State::Retired), _) => "is already shut down".to_string(),
1202 (Some(State::Retiring), Some(d)) => {
1203 let left = days_phrase(today.days_until(d));
1204 match step.date_kind {
1205 Some(DateKind::Earliest) => format!("retires on or after {} ({left})", d.human()),
1206 _ => format!("shuts down on {} ({left})", d.human()),
1207 }
1208 }
1209 (Some(State::Retiring), None) => "is retiring".to_string(),
1210 (Some(State::Unconfirmed), _) => "may already be retired".to_string(),
1211 (Some(State::Deprecated), _) => "is deprecated".to_string(),
1212 (Some(State::AutoRouted), _) => "is routed to a newer model".to_string(),
1213 (None, _) => "is current".to_string(),
1214 }
1215}
1216
1217fn days_phrase(days: i64) -> String {
1218 match days {
1219 0 => "today".to_string(),
1220 1 => "1 day".to_string(),
1221 n => format!("{n} days"),
1222 }
1223}
1224
1225fn chain_message(provider: &str, chain: &Chain<'_>, today: Date, rules_known: bool) -> String {
1229 let dead: Vec<&ChainStep> = chain
1230 .steps
1231 .iter()
1232 .take_while(|s| s.status.is_some() && Some(&s.model) != chain.live.as_ref())
1233 .collect();
1234 let mut text = String::new();
1235 for (index, step) in dead.iter().enumerate() {
1236 if index == 0 {
1237 text.push_str(&format!(
1238 "{provider} lists {} as the replacement, and it {}",
1239 step.model,
1240 step_phrase(step, today)
1241 ));
1242 } else {
1243 text.push_str(&format!(
1244 "; {provider} lists {} for it, and it {}",
1245 step.model,
1246 step_phrase(step, today)
1247 ));
1248 }
1249 }
1250 let last = dead.last().map(|s| s.model.as_str()).unwrap_or_default();
1251 match &chain.live {
1252 Some(live) if rules_known => text.push_str(&format!(
1253 ". {live} is the replacement {provider} lists for {last}; the changes shown are for {live}."
1254 )),
1255 Some(live) => text.push_str(&format!(
1256 ". {live} is the replacement {provider} lists for {last}; the parameters {live} needs have not been checked yet."
1257 )),
1258 None => match dead.last().and_then(|s| s.replacement_text.as_deref()) {
1259 Some(listed) => text.push_str(&format!(
1260 ". For {last}, {provider} lists {listed}: pick one by hand."
1261 )),
1262 None => text.push_str(&format!(
1263 ". {provider} lists no replacement for {last}: pick one by hand."
1264 )),
1265 },
1266 }
1267 text
1268}
1269
1270#[derive(Clone, Copy)]
1275enum Site<'a> {
1276 Call(&'a SdkCall, CallKind),
1277 Gap(&'a UsageGap),
1278}
1279
1280fn finding_for(
1281 data: &Retirements,
1282 options: &CheckOptions,
1283 site: Site<'_>,
1284 routing: &CallRouting,
1285 value: &CapturedValue,
1286 confidence: Confidence,
1287) -> Option<Finding> {
1288 let (hit, class) = resolve(data, routing, &value.value)?;
1289
1290 let (file, span, symbol, chain, kwargs, splat, endpoint, call_kind) = match site {
1291 Site::Call(call, kind) => (
1292 call.file.clone(),
1293 Some(call.span),
1294 call.symbol.clone(),
1295 Some(call.chain.clone()),
1296 call.kwargs.clone(),
1297 call.splat,
1298 (kind != CallKind::RequestParam)
1300 .then(|| endpoint_of(&call.chain, &call.member))
1301 .flatten(),
1302 kind,
1303 ),
1304 Site::Gap(gap) => {
1305 let chain = gap.chain.clone().unwrap_or_default();
1306 (
1307 gap.file.clone(),
1308 gap.span,
1309 gap.symbol.clone(),
1310 gap.chain.clone(),
1311 Vec::new(),
1312 false,
1313 endpoint_of(&chain, &chain),
1314 CallKind::Request,
1315 )
1316 }
1317 };
1318 let gap_reason = match site {
1319 Site::Gap(gap) => Some(gap.reason.clone()),
1320 Site::Call(..) => None,
1321 };
1322 let span = span.unwrap_or(value.span);
1323 let hit = if endpoint == Some(FINE_TUNING) {
1325 fine_tuning_job_hit(data, hit)
1326 } else {
1327 hit
1328 };
1329 let today = options.today;
1330 let date_kind = hit.recipe.date_kind;
1331 let status = effective_state(hit.status, hit.date, date_kind, today);
1332 let days_left = hit.date.map(|d| today.days_until(d));
1333
1334 let replacement_chain = hit
1336 .replacement
1337 .as_deref()
1338 .map(|r| follow_chain(data, hit.table, r, today));
1339 let chained = replacement_chain.as_ref().is_some_and(Chain::chained);
1340 let live = replacement_chain.as_ref().and_then(|c| c.live.clone());
1341
1342 let source = match (&replacement_chain, live.as_deref()) {
1345 (Some(c), Some(target)) if !c.chained() => hit.rule_set.map(|set| {
1346 (
1347 set,
1348 target,
1349 hit.matched.as_str(),
1350 hit.entry.and_then(|e| e.source_family.as_deref()),
1351 )
1352 }),
1353 (Some(c), Some(target)) => c.last_hop.and_then(|hop| {
1354 hop.rule_set.as_deref().map(|set| {
1355 (
1356 set,
1357 target,
1358 hop.model.as_str(),
1359 hop.source_family
1360 .as_deref()
1361 .or(hit.entry.and_then(|e| e.source_family.as_deref())),
1362 )
1363 })
1364 }),
1365 _ => None,
1366 };
1367 let nested = value.key.rsplit_once('.').map(|(container, _)| container);
1372 let mut outcome = Outcome::default();
1373 if call_kind != CallKind::RequestParam {
1374 if let Some((rule_set, target, source_model, source_family)) = source {
1375 let context = RuleContext {
1376 target,
1377 source_model,
1378 source_family,
1379 endpoint: if nested.is_some() { None } else { endpoint },
1380 routing: &routing.routing,
1381 kwargs: if nested.is_some() {
1382 &[]
1383 } else {
1384 kwargs.as_slice()
1385 },
1386 };
1387 let rules = data
1388 .rules(rule_set)
1389 .filter(|rule| nested.is_none() || about_the_model(rule));
1390 outcome = apply_rules(rules, &context);
1391 }
1392 }
1393
1394 let mut reasons = model_reasons(&hit, status, splat, source.is_some(), chained);
1395 if let Some(chain) = replacement_chain.as_ref().filter(|c| c.chained()) {
1396 reasons.push(ReviewItem {
1397 rule: None,
1398 message: chain_message(hit.table.provider(), chain, today, source.is_some()),
1399 because: Vec::new(),
1400 verified: None,
1401 });
1402 }
1403 if hit.schedule_unconfirmed {
1404 let message = match hit.table {
1405 Table::Vertex => format!(
1406 "This client's vertexai= is decided at run time, so Arbor used Google Cloud's (Vertex AI) schedule for {}. If the client uses the Gemini API, Google's schedule applies instead, with its own date and replacement.",
1407 hit.matched
1408 ),
1409 _ => format!(
1410 "This client's vertexai= is decided at run time. Google Cloud (Vertex AI) does not list {}, so this is the Gemini API's schedule: confirm which API the client uses.",
1411 hit.matched
1412 ),
1413 };
1414 reasons.push(ReviewItem {
1415 rule: None,
1416 message,
1417 because: Vec::new(),
1418 verified: None,
1419 });
1420 }
1421 if let Some(container) = nested {
1422 let against = live
1423 .as_deref()
1424 .map(|m| format!(" against {m}"))
1425 .unwrap_or_default();
1426 reasons.push(ReviewItem {
1427 rule: None,
1428 message: format!(
1429 "The model is set in {container}, nested in this call's arguments: Arbor checked only the model there, not the parameters set next to it, so check those{against} by hand."
1430 ),
1431 because: Vec::new(),
1432 verified: None,
1433 });
1434 }
1435 if call_kind == CallKind::RequestParam {
1436 reasons.push(ReviewItem {
1437 rule: None,
1438 message: "The model is set in a request parameter object, not at the request: check the request that sends it."
1439 .to_string(),
1440 because: Vec::new(),
1441 verified: None,
1442 });
1443 }
1444 reasons.append(&mut outcome.review);
1445 let review = dedupe_review(reasons);
1446 let mut notes = hit.notes.clone();
1447 notes.append(&mut outcome.notes);
1448
1449 let manual = !review.is_empty()
1450 || chained
1451 || live.is_none()
1452 || confidence != Confidence::Confirmed
1453 || class != RoutingClass::Direct
1454 || hit.action != Action::Rewrite
1455 || hit.match_kind != MatchKind::Exact;
1456 let fix = if status == State::AutoRouted {
1457 FixKind::None
1458 } else if manual {
1459 FixKind::Manual
1460 } else if !outcome.decisions.is_empty() {
1461 FixKind::Decide
1462 } else {
1463 FixKind::Swap
1464 };
1465
1466 let in_window = match status {
1467 State::Retired => true,
1468 State::Retiring => match (options.fail_within, days_left) {
1469 (Some(window), Some(days)) => days <= window,
1470 _ => false,
1471 },
1472 _ => false,
1473 };
1474 let counted = (confidence == Confidence::Confirmed || options.count_unconfirmed)
1475 && match class {
1476 RoutingClass::Direct => true,
1477 RoutingClass::Routed => options.include_routed,
1478 RoutingClass::Unknown => options.count_unconfirmed,
1479 };
1480
1481 Some(Finding {
1482 file,
1483 line: span.line,
1484 column: span.column,
1485 end_line: span.end_line,
1486 symbol,
1487 chain,
1488 call_kind,
1489 provider: hit.table,
1490 model: value.value.clone(),
1491 matched: hit.matched.clone(),
1492 match_kind: hit.match_kind,
1493 key: value.key.clone(),
1494 status,
1495 listed_status: hit.status,
1496 date: hit.date,
1497 date_kind,
1498 days_left,
1499 replacement: hit.replacement.clone(),
1500 replacement_text: hit.replacement_text.clone(),
1501 live_replacement: live,
1502 replacement_chain: replacement_chain.map(|c| c.steps).unwrap_or_default(),
1503 fix,
1504 changes: outcome.changes,
1505 decisions: outcome.decisions,
1506 review,
1507 notes: dedupe(notes),
1508 routing: routing.routing.clone(),
1509 routing_class: class,
1510 base_url: routing.base_url,
1511 endpoint,
1512 confidence,
1513 origin: (confidence != Confidence::Gap).then_some(value.origin),
1514 value_from: value.name.clone(),
1515 value_line: value.span.line,
1516 gap_reason,
1517 routing_gap: routing.gap.clone(),
1518 candidate: false,
1519 splat,
1520 in_window,
1521 fails: in_window && counted,
1522 recipe: hit.recipe.id.clone(),
1523 recipe_version: hit.recipe.version.clone(),
1524 verified: hit.verified,
1525 source_url: hit.recipe.source_urls.first().cloned(),
1526 })
1527}
1528
1529fn about_the_model(rule: &ParamRule) -> bool {
1534 matches!(rule.effect, RuleEffect::Review | RuleEffect::Note)
1535 && rule.endpoints.is_empty()
1536 && rule.any_kwargs.is_empty()
1537 && rule.all_kwargs.is_empty()
1538 && rule.lacks_kwargs.is_empty()
1539}
1540
1541fn effective_state(status: EntryStatus, date: Option<Date>, kind: DateKind, today: Date) -> State {
1545 match status {
1546 EntryStatus::ShutDown => State::Retired,
1547 EntryStatus::Retiring => match date {
1548 Some(date) if date <= today => match kind {
1549 DateKind::Hard => State::Retired,
1550 DateKind::Earliest => State::Unconfirmed,
1551 },
1552 _ => State::Retiring,
1553 },
1554 EntryStatus::Deprecated => State::Deprecated,
1555 EntryStatus::Unconfirmed => State::Unconfirmed,
1556 EntryStatus::AutoRouted => State::AutoRouted,
1557 }
1558}
1559
1560pub const FINE_TUNING: &str = "fine_tuning";
1563
1564fn endpoint_of(chain: &str, member: &str) -> Option<&'static str> {
1566 let text = if member.contains('.') { member } else { chain };
1567 let has = |needle: &str| text.contains(needle);
1568 let endpoint =
1569 if has("fine_tuning.") || has("fine_tunes.") || has("FineTuningJob.") || has("FineTune.") {
1570 FINE_TUNING
1571 } else if has("chat.completions") || has("ChatCompletion") {
1572 "chat.completions"
1573 } else if has("responses.") {
1574 "responses"
1575 } else if has("assistants.") || has("threads.") {
1576 "assistants"
1577 } else if has("completions.") || has("Completion.") {
1578 "completions_legacy"
1579 } else if has("messages.") {
1580 "messages"
1581 } else if has("generate_content")
1582 || has("GenerativeModel")
1583 || has("chats.")
1584 || has("send_message")
1585 {
1586 "generate_content"
1587 } else if has("interactions.") {
1588 "interactions"
1589 } else if has("embeddings.") || has("embed_content") || has("Embedding.") {
1590 "embeddings"
1591 } else if has("images.") || has("generate_images") {
1592 "images"
1593 } else if has("audio.") {
1594 "audio"
1595 } else {
1596 return None;
1597 };
1598 Some(endpoint)
1599}
1600
1601fn model_reasons(
1603 hit: &Hit<'_>,
1604 status: State,
1605 splat: bool,
1606 rules_known: bool,
1607 chained: bool,
1608) -> Vec<ReviewItem> {
1609 if status == State::AutoRouted {
1610 return Vec::new();
1611 }
1612 let provider = hit.table.provider();
1613 let fine_tuned = hit.match_kind == MatchKind::FineTuned
1614 || hit.entry.and_then(|e| e.kind.as_deref()) == Some("fine_tune_label");
1615 let category = hit.entry.map(|e| e.category.as_str()).unwrap_or("text");
1616 let mut messages = Vec::new();
1617 if let Some(advice) = &hit.fine_tune_advice {
1618 messages.push(advice.clone());
1620 } else if fine_tuned {
1621 messages.push(
1622 "Fine-tuned model: retrain it on a base model that supports fine-tuning.".to_string(),
1623 );
1624 } else if hit.replacement.is_none() {
1625 messages.push(match &hit.replacement_text {
1626 Some(text) => format!("{provider} lists more than one way forward: {text}."),
1627 None => format!("{provider} lists no replacement."),
1628 });
1629 } else if category == "embedding" {
1630 messages.push(
1631 "Embedding model: a new model means re-embedding every stored vector.".to_string(),
1632 );
1633 } else if category != "text" {
1634 messages.push(format!(
1635 "{} model: Arbor checks chat and text parameters only, so review this call by hand.",
1636 capitalize(&category.replace('_', " "))
1637 ));
1638 } else if chained {
1639 } else if !rules_known {
1641 messages.push(format!(
1642 "The parameters {} needs have not been checked yet.",
1643 hit.replacement.as_deref().unwrap_or("the replacement")
1644 ));
1645 } else if hit.action == Action::ReportOnly {
1646 messages.push(
1647 "Arbor does not swap this model automatically yet; review the call by hand."
1648 .to_string(),
1649 );
1650 }
1651 if splat {
1652 messages.push(
1653 "Some arguments come from `**kwargs`, so Arbor could not check them all.".to_string(),
1654 );
1655 }
1656 messages
1657 .into_iter()
1658 .map(|message| ReviewItem {
1659 rule: None,
1660 message,
1661 because: Vec::new(),
1662 verified: None,
1663 })
1664 .collect()
1665}
1666
1667fn capitalize(text: &str) -> String {
1668 let mut chars = text.chars();
1669 match chars.next() {
1670 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
1671 None => String::new(),
1672 }
1673}
1674
1675struct RuleContext<'a> {
1680 target: &'a str,
1681 source_model: &'a str,
1682 source_family: Option<&'a str>,
1683 endpoint: Option<&'static str>,
1684 routing: &'a str,
1685 kwargs: &'a [String],
1686}
1687
1688impl RuleContext<'_> {
1689 fn has(&self, name: &str) -> bool {
1690 self.kwargs.iter().any(|k| k == name)
1691 }
1692
1693 fn applies(&self, rule: &ParamRule, added: &[String]) -> bool {
1696 let listed = |list: &[String], value: Option<&str>| {
1697 list.is_empty() || value.is_some_and(|v| list.iter().any(|x| x == v))
1698 };
1699 listed(&rule.endpoints, self.endpoint)
1700 && listed(&rule.routings, Some(self.routing))
1701 && listed(&rule.source_families, self.source_family)
1702 && listed(&rule.targets, Some(self.target))
1703 && listed(&rule.source_models, Some(self.source_model))
1704 && (rule.any_kwargs.is_empty() || rule.any_kwargs.iter().any(|k| self.has(k)))
1705 && rule.all_kwargs.iter().all(|k| self.has(k))
1706 && !rule
1707 .lacks_kwargs
1708 .iter()
1709 .any(|k| self.has(k) || added.contains(k))
1710 }
1711
1712 fn because(&self, rule: &ParamRule) -> Vec<String> {
1714 let mut out: Vec<String> = Vec::new();
1715 for name in rule.any_kwargs.iter().chain(&rule.all_kwargs) {
1716 if self.has(name) && !out.contains(name) {
1717 out.push(name.clone());
1718 }
1719 }
1720 if let Some(rename) = &rule.rename {
1721 if self.has(&rename.from) && !out.contains(&rename.from) {
1722 out.push(rename.from.clone());
1723 }
1724 }
1725 out
1726 }
1727
1728 fn message(&self, text: &str) -> String {
1732 let text = text.replace("{target}", self.target);
1733 if self.endpoint == Some("responses") {
1734 text.replace("max_completion_tokens", "max_output_tokens")
1735 } else {
1736 text
1737 }
1738 }
1739
1740 fn order(&self, names: &mut [String]) {
1742 names.sort_by_key(|name| self.kwargs.iter().position(|k| k == name));
1743 }
1744
1745 fn endpoint_matches(&self, endpoint: &str) -> bool {
1746 endpoint == "*" || Some(endpoint) == self.endpoint
1747 }
1748
1749 fn verified(&self, rule: &ParamRule) -> Verified {
1752 if rule.verified != Verified::Live {
1753 return rule.verified;
1754 }
1755 let model =
1756 rule.live_models.is_empty() || rule.live_models.iter().any(|m| m == self.target);
1757 let endpoint = rule.live_endpoints.is_empty()
1758 || self
1759 .endpoint
1760 .is_some_and(|e| rule.live_endpoints.iter().any(|x| x == e));
1761 if model && endpoint {
1762 Verified::Live
1763 } else {
1764 rule.otherwise_verified.unwrap_or(Verified::Docs)
1765 }
1766 }
1767}
1768
1769#[derive(Default)]
1770struct Outcome {
1771 changes: Vec<Change>,
1772 review: Vec<ReviewItem>,
1773 notes: Vec<String>,
1774 decisions: Vec<Decision>,
1775}
1776
1777fn apply_rules<'r>(
1778 rules: impl Iterator<Item = &'r ParamRule>,
1779 context: &RuleContext<'_>,
1780) -> Outcome {
1781 let rules: Vec<&ParamRule> = rules.collect();
1782 let mut out = Outcome::default();
1783 let changes_args =
1784 |rule: &&&ParamRule| matches!(rule.effect, RuleEffect::Add | RuleEffect::Rename);
1785 let mut choice_notes: Vec<(String, String)> = Vec::new();
1787
1788 for rule in rules.iter().filter(changes_args) {
1790 if !context.applies(rule, &[]) {
1791 continue;
1792 }
1793 let because = context.because(rule);
1794 if let Some(rename) = rule.rename.as_ref().filter(|r| context.has(&r.from)) {
1795 merge_change(
1796 &mut out.changes,
1797 Change {
1798 kind: ChangeKind::Rename,
1799 param: rename.from.clone(),
1800 to: Some(rename.to.clone()),
1801 value: None,
1802 because: vec![rename.from.clone()],
1803 rules: vec![rule.id.clone()],
1804 verified: context.verified(rule),
1805 },
1806 );
1807 }
1808 apply_adds(rule, context, &because, &mut out.changes, &mut out.review);
1809 if let (Some(choice), Some(note)) = (&rule.see_choice, &rule.choice_note) {
1810 choice_notes.push((choice.clone(), context.message(note)));
1811 }
1812 }
1813 out.changes.sort_by_key(|c| c.kind != ChangeKind::Rename);
1815 let added: Vec<String> = out
1816 .changes
1817 .iter()
1818 .filter(|c| c.kind == ChangeKind::Add)
1819 .map(|c| c.param.clone())
1820 .collect();
1821
1822 for rule in rules.iter().filter(|r| r.effect == RuleEffect::Choice) {
1824 if !context.applies(rule, &added) {
1825 continue;
1826 }
1827 add_choice(rule, context, &mut out);
1828 }
1829
1830 let mut keeps = Vec::new();
1831 for rule in rules.iter().filter(|r| {
1832 !matches!(
1833 r.effect,
1834 RuleEffect::Add | RuleEffect::Rename | RuleEffect::Choice
1835 )
1836 }) {
1837 if !context.applies(rule, &added) {
1838 continue;
1839 }
1840 let because = context.because(rule);
1841 match rule.effect {
1842 RuleEffect::Review => out.review.push(ReviewItem {
1843 rule: Some(rule.id.clone()),
1844 message: context.message(&rule.message),
1845 because,
1846 verified: Some(context.verified(rule)),
1847 }),
1848 RuleEffect::Keep => keeps.push((*rule, because)),
1849 RuleEffect::Note => out.notes.push(context.message(&rule.message)),
1850 RuleEffect::Add | RuleEffect::Rename | RuleEffect::Choice => {}
1851 }
1852 }
1853 for (rule, because) in keeps {
1855 let on_target =
1856 rule.keep_targets.is_empty() || rule.keep_targets.iter().any(|t| t == context.target);
1857 let verb = if because.len() == 1 { "was" } else { "were" };
1858 if !on_target {
1859 let text = rule.else_message.as_deref().unwrap_or(&rule.message);
1860 out.review.push(ReviewItem {
1861 rule: Some(rule.id.clone()),
1862 message: context.message(text),
1863 because,
1864 verified: Some(context.verified(rule)),
1865 });
1866 } else if rule.keep_needs_effort_none && !effort_none(&out.changes) {
1867 if let Some(decision) = out.decisions.first_mut() {
1868 decision.notes.push(format!(
1869 "{} {verb} accepted on {} at reasoning_effort \"none\" ({}); with the model reasoning, untested.",
1870 because.join(", "),
1871 context.target,
1872 decision
1873 .options
1874 .iter()
1875 .find(|o| o.add.iter().any(|a| a.name.contains("reasoning")))
1876 .map(|o| o.label.as_str())
1877 .unwrap_or("reasoning off")
1878 ));
1879 } else {
1880 out.review.push(ReviewItem {
1881 rule: Some(rule.id.clone()),
1882 message: format!(
1883 "{} {verb} checked on {} only at reasoning effort \"none\"; check the effort this call runs at.",
1884 because.join(", "),
1885 context.target
1886 ),
1887 because,
1888 verified: Some(context.verified(rule)),
1889 });
1890 }
1891 } else {
1892 out.notes.push(context.message(&rule.message));
1893 }
1894 }
1895 for (choice, note) in choice_notes {
1896 match out.decisions.iter_mut().find(|d| d.choice == choice) {
1897 Some(decision) => push_unique(&mut decision.notes, note),
1898 None => out.notes.push(note),
1899 }
1900 }
1901 out
1902}
1903
1904fn add_choice(rule: &ParamRule, context: &RuleContext<'_>, out: &mut Outcome) {
1910 let Some(choice) = rule.choice.clone() else {
1911 return;
1912 };
1913 let because = context.because(rule);
1914 let preset = rule
1915 .options
1916 .iter()
1917 .flat_map(|o| o.add.iter().filter(|a| !o.remove.contains(&a.name)))
1918 .filter(|a| context.endpoint_matches(&a.endpoint))
1919 .find(|a| context.has(&a.name));
1920 if let Some(add) = preset {
1921 out.review.push(ReviewItem {
1922 rule: Some(rule.id.clone()),
1923 message: format!(
1924 "{} This call already sets {}; check that it is {}.",
1925 context.message(&rule.message),
1926 add.name,
1927 python_literal(&add.value)
1928 ),
1929 because,
1930 verified: Some(context.verified(rule)),
1931 });
1932 return;
1933 }
1934 let index = match out.decisions.iter().position(|d| d.choice == choice) {
1935 Some(index) => index,
1936 None => {
1937 out.decisions.push(Decision {
1938 choice,
1939 reasons: Vec::new(),
1940 because: Vec::new(),
1941 rules: Vec::new(),
1942 options: rule
1943 .options
1944 .iter()
1945 .map(|o| DecisionOption {
1946 id: o.id.clone(),
1947 label: o.label.clone(),
1948 add: Vec::new(),
1949 remove: Vec::new(),
1950 keep: Vec::new(),
1951 effects: Vec::new(),
1952 })
1953 .collect(),
1954 notes: Vec::new(),
1955 });
1956 out.decisions.len() - 1
1957 }
1958 };
1959 let decision = &mut out.decisions[index];
1960 push_unique(&mut decision.reasons, context.message(&rule.message));
1961 for name in because {
1962 push_unique(&mut decision.because, name);
1963 }
1964 push_unique(&mut decision.rules, rule.id.clone());
1965 for option in &rule.options {
1966 let Some(target) = decision.options.iter_mut().find(|o| o.id == option.id) else {
1967 continue;
1968 };
1969 for add in option
1970 .add
1971 .iter()
1972 .filter(|a| context.endpoint_matches(&a.endpoint))
1973 {
1974 if !target
1975 .add
1976 .iter()
1977 .any(|p| p.name == add.name && p.value == add.value)
1978 {
1979 target.add.push(ParamValue {
1980 name: add.name.clone(),
1981 value: add.value.clone(),
1982 });
1983 }
1984 }
1985 for name in option.remove.iter().filter(|n| context.has(n)) {
1986 push_unique(&mut target.remove, name.clone());
1987 }
1988 for name in option.keep.iter().filter(|n| context.has(n)) {
1989 push_unique(&mut target.keep, name.clone());
1990 }
1991 let text = context.message(&option.effect);
1992 if !target.effects.iter().any(|e| e.text == text) {
1993 target.effects.push(OptionEffect {
1994 rule: rule.id.clone(),
1995 text,
1996 status: option.status,
1997 });
1998 }
1999 context.order(&mut target.remove);
2001 context.order(&mut target.keep);
2002 }
2003 context.order(&mut decision.because);
2004}
2005
2006fn push_unique(list: &mut Vec<String>, item: String) {
2007 if !list.contains(&item) {
2008 list.push(item);
2009 }
2010}
2011
2012fn apply_adds(
2013 rule: &ParamRule,
2014 context: &RuleContext<'_>,
2015 because: &[String],
2016 changes: &mut Vec<Change>,
2017 review: &mut Vec<ReviewItem>,
2018) {
2019 if rule.add.is_empty() {
2020 return;
2021 }
2022 let spec = rule
2023 .add
2024 .iter()
2025 .find(|a| context.endpoint_matches(&a.endpoint));
2026 let Some(spec) = spec else {
2027 let text = rule.else_message.clone().unwrap_or_else(|| {
2028 format!(
2029 "{} Arbor could not tell which API this call uses, so set it by hand.",
2030 rule.message
2031 )
2032 });
2033 review.push(ReviewItem {
2034 rule: Some(rule.id.clone()),
2035 message: context.message(&text),
2036 because: because.to_vec(),
2037 verified: Some(context.verified(rule)),
2038 });
2039 return;
2040 };
2041 if context.has(&spec.name) {
2042 review.push(ReviewItem {
2044 rule: Some(rule.id.clone()),
2045 message: format!(
2046 "This call already sets {}; on {} it must be {}.",
2047 spec.name,
2048 context.target,
2049 python_literal(&spec.value)
2050 ),
2051 because: because.to_vec(),
2052 verified: Some(context.verified(rule)),
2053 });
2054 return;
2055 }
2056 merge_change(
2057 changes,
2058 Change {
2059 kind: ChangeKind::Add,
2060 param: spec.name.clone(),
2061 to: None,
2062 value: Some(spec.value.clone()),
2063 because: because.to_vec(),
2064 rules: vec![rule.id.clone()],
2065 verified: context.verified(rule),
2066 },
2067 );
2068}
2069
2070fn verified_rank(verified: Verified) -> u8 {
2071 match verified {
2072 Verified::Live => 2,
2073 Verified::Docs => 1,
2074 Verified::Unverified => 0,
2075 }
2076}
2077
2078fn merge_change(changes: &mut Vec<Change>, change: Change) {
2080 if let Some(existing) = changes.iter_mut().find(|c| {
2081 c.kind == change.kind
2082 && c.param == change.param
2083 && c.value == change.value
2084 && c.to == change.to
2085 }) {
2086 for name in change.because {
2087 if !existing.because.contains(&name) {
2088 existing.because.push(name);
2089 }
2090 }
2091 for rule in change.rules {
2092 if !existing.rules.contains(&rule) {
2093 existing.rules.push(rule);
2094 }
2095 }
2096 if verified_rank(change.verified) > verified_rank(existing.verified) {
2097 existing.verified = change.verified;
2098 }
2099 return;
2100 }
2101 changes.push(change);
2102}
2103
2104fn effort_none(changes: &[Change]) -> bool {
2106 changes.iter().any(|c| {
2107 c.kind == ChangeKind::Add
2108 && match (c.param.as_str(), &c.value) {
2109 ("reasoning_effort", Some(serde_json::Value::String(v))) => v == "none",
2110 ("reasoning", Some(serde_json::Value::Object(map))) => {
2111 map.get("effort").and_then(|v| v.as_str()) == Some("none")
2112 }
2113 _ => false,
2114 }
2115 })
2116}
2117
2118pub fn python_literal(value: &serde_json::Value) -> String {
2120 match value {
2121 serde_json::Value::Null => "None".to_string(),
2122 serde_json::Value::Bool(true) => "True".to_string(),
2123 serde_json::Value::Bool(false) => "False".to_string(),
2124 serde_json::Value::Number(n) => n.to_string(),
2125 serde_json::Value::String(_) => value.to_string(),
2126 serde_json::Value::Array(items) => format!(
2127 "[{}]",
2128 items
2129 .iter()
2130 .map(python_literal)
2131 .collect::<Vec<_>>()
2132 .join(", ")
2133 ),
2134 serde_json::Value::Object(map) => format!(
2135 "{{{}}}",
2136 map.iter()
2137 .map(|(k, v)| format!(
2138 "{}: {}",
2139 serde_json::Value::String(k.clone()),
2140 python_literal(v)
2141 ))
2142 .collect::<Vec<_>>()
2143 .join(", ")
2144 ),
2145 }
2146}
2147
2148fn dedupe_review(items: Vec<ReviewItem>) -> Vec<ReviewItem> {
2149 let mut seen = HashSet::new();
2150 items
2151 .into_iter()
2152 .filter(|item| seen.insert(item.message.clone()))
2153 .collect()
2154}
2155
2156fn dedupe(items: Vec<String>) -> Vec<String> {
2157 let mut seen = HashSet::new();
2158 items
2159 .into_iter()
2160 .filter(|item| seen.insert(item.clone()))
2161 .collect()
2162}
2163
2164fn unreadable(input: ScanInput<'_>) -> (Vec<Unreadable>, usize) {
2172 let captured: HashSet<(&str, u32, &str)> = input
2173 .calls
2174 .iter()
2175 .flat_map(|call| {
2176 call.values
2177 .iter()
2178 .map(move |v| (call.file.as_str(), call.span.start_byte, v.key.as_str()))
2179 })
2180 .collect();
2181 let mut seen = HashSet::new();
2182 let mut out = Vec::new();
2183 let mut no_model = 0;
2184 for gap in input.gaps {
2185 if gap.kind != GapKind::UnresolvedModel || gap.reason == "truncated" {
2186 continue;
2187 }
2188 if gap.reason == "missing_model" {
2189 no_model += 1;
2190 continue;
2191 }
2192 if !gap.values.is_empty() {
2193 continue;
2194 }
2195 let Some(span) = gap.span else { continue };
2196 let key = gap.key.as_deref().unwrap_or("model");
2197 if captured.contains(&(gap.file.as_str(), span.start_byte, key)) {
2198 continue;
2199 }
2200 if !seen.insert((gap.file.clone(), span.start_byte, key.to_string())) {
2201 continue;
2202 }
2203 out.push(Unreadable {
2204 file: gap.file.clone(),
2205 line: span.line,
2206 chain: gap.chain.clone(),
2207 key: gap.key.clone(),
2208 sdk: gap.sdk,
2209 reason: gap.reason.clone(),
2210 });
2211 }
2212 (out, no_model)
2213}
2214
2215fn unresolved_clients(input: ScanInput<'_>) -> usize {
2220 let shown: HashSet<(&str, u32)> = input
2221 .calls
2222 .iter()
2223 .map(|c| (c.file.as_str(), c.span.start_byte))
2224 .chain(
2225 input
2226 .gaps
2227 .iter()
2228 .filter(|g| {
2229 !gaps::is_region(g)
2230 && (g.kind == GapKind::UnresolvedModel || !g.values.is_empty())
2231 })
2232 .filter_map(|g| g.span.map(|s| (g.file.as_str(), s.start_byte))),
2233 )
2234 .collect();
2235 input
2236 .gaps
2237 .iter()
2238 .filter(|g| {
2241 gaps::holds_routing(g)
2242 && !matches!(g.kind, GapKind::DynamicDispatch | GapKind::VendoredPath)
2243 })
2244 .filter_map(|g| g.span.map(|s| (g.file.as_str(), s.start_byte)))
2245 .filter(|at| !shown.contains(at))
2246 .collect::<HashSet<_>>()
2247 .len()
2248}
2249
2250fn dedupe_findings(findings: &mut Vec<Finding>) {
2251 let mut seen = HashSet::new();
2252 findings.retain(|f| {
2253 seen.insert((
2254 f.file.clone(),
2255 f.line,
2256 f.column,
2257 f.key.clone(),
2258 f.model.clone(),
2259 ))
2260 });
2261}
2262
2263fn state_rank(state: State) -> u8 {
2264 match state {
2265 State::Retired => 0,
2266 State::Retiring => 1,
2267 State::Unconfirmed => 2,
2268 State::Deprecated => 3,
2269 State::AutoRouted => 4,
2270 }
2271}
2272
2273fn sort_findings(findings: &mut [Finding]) {
2274 findings.sort_by(|a, b| {
2275 state_rank(a.status)
2276 .cmp(&state_rank(b.status))
2277 .then(a.date.cmp(&b.date))
2278 .then(a.provider.cmp(&b.provider))
2279 .then(a.file.cmp(&b.file))
2280 .then(a.line.cmp(&b.line))
2281 .then(a.column.cmp(&b.column))
2282 .then(a.key.cmp(&b.key))
2283 });
2284}
2285
2286fn summarize(
2287 findings: &[Finding],
2288 routed: &[Finding],
2289 routed_calls: usize,
2290 unreadable: usize,
2291) -> Summary {
2292 let mut summary = Summary {
2293 affected_calls: findings.len(),
2294 routed_calls,
2295 unreadable_calls: unreadable,
2296 ..Summary::default()
2297 };
2298 let files: BTreeSet<&str> = findings.iter().map(|f| f.file.as_str()).collect();
2299 summary.affected_files = files.len();
2300 for finding in findings {
2301 match finding.status {
2302 State::Retired => summary.retired += 1,
2303 State::Retiring => summary.retiring += 1,
2304 _ => summary.other += 1,
2305 }
2306 match finding.fix {
2307 FixKind::Swap => summary.swap += 1,
2308 FixKind::Decide => summary.decide += 1,
2309 FixKind::Manual => summary.manual += 1,
2310 FixKind::None => {}
2311 }
2312 *summary
2313 .by_provider
2314 .entry(finding.provider.as_str().to_string())
2315 .or_default() += 1;
2316 }
2317 for finding in findings.iter().chain(routed).filter(|f| f.in_window) {
2318 summary.in_window += 1;
2319 if finding.fails {
2320 summary.failing += 1;
2321 } else {
2322 summary.uncounted += 1;
2323 }
2324 }
2325 let next = findings
2326 .iter()
2327 .filter(|f| f.status == State::Retiring)
2328 .filter_map(|f| Some((f.date?, f.days_left?, f.provider)))
2329 .min_by_key(|(date, _, provider)| (*date, *provider));
2330 summary.next_shutdown = next.map(|(date, days_left, provider)| NextShutdown {
2331 date,
2332 days_left,
2333 provider,
2334 calls: findings
2335 .iter()
2336 .filter(|f| {
2337 f.status == State::Retiring && f.date == Some(date) && f.provider == provider
2338 })
2339 .count(),
2340 });
2341 summary
2342}
2343
2344#[cfg(test)]
2345mod tests {
2346 use super::super::bundled;
2347 use super::*;
2348 use crate::usages::{Receiver, Span};
2349
2350 fn span(line: u32) -> Span {
2351 Span {
2352 line,
2353 column: 5,
2354 end_line: line,
2355 end_column: 40,
2356 start_byte: line * 100,
2357 end_byte: line * 100 + 35,
2358 }
2359 }
2360
2361 fn value(model: &str, origin: ValueOrigin, line: u32) -> CapturedValue {
2362 CapturedValue {
2363 key: "model".into(),
2364 value: model.into(),
2365 origin,
2366 name: None,
2367 positional: false,
2368 span: span(line),
2369 model_family: model_family(model),
2370 }
2371 }
2372
2373 fn call(
2374 sdk: Sdk,
2375 routing: Routing,
2376 chain: &str,
2377 model: &str,
2378 kwargs: &[&str],
2379 line: u32,
2380 ) -> SdkCall {
2381 let member = chain.split_once('.').map(|(_, m)| m).unwrap_or(chain);
2382 let mut all: Vec<String> = vec!["model".to_string()];
2383 all.extend(kwargs.iter().map(|k| k.to_string()));
2384 SdkCall {
2385 sdk,
2386 package: sdk.as_str().into(),
2387 chain: chain.into(),
2388 member: member.into(),
2389 request: true,
2390 receiver: Receiver::Client,
2391 routing,
2392 client_line: Some(1),
2393 file: "app.py".into(),
2394 span: span(line),
2395 symbol: Some("ask".into()),
2396 kwargs: all,
2397 positional: 0,
2398 splat: false,
2399 values: vec![value(model, ValueOrigin::Literal, line)],
2400 }
2401 }
2402
2403 fn openai(model: &str, kwargs: &[&str]) -> SdkCall {
2404 call(
2405 Sdk::Openai,
2406 Routing::OpenaiDirect,
2407 "client.chat.completions.create",
2408 model,
2409 kwargs,
2410 10,
2411 )
2412 }
2413
2414 fn object(sdk: Sdk, chain: &str, member: &str, model: &str, line: u32) -> SdkCall {
2417 let mut object = call(sdk, Routing::OpenaiDirect, chain, model, &[], line);
2418 object.member = member.into();
2419 object.request = false;
2420 object.receiver = Receiver::Symbol;
2421 object.client_line = None;
2422 object
2423 }
2424
2425 fn options(today: &str) -> CheckOptions {
2426 CheckOptions {
2427 today: Date::parse(today).unwrap(),
2428 fail_within: None,
2429 include_routed: false,
2430 count_unconfirmed: false,
2431 }
2432 }
2433
2434 fn run(calls: &[SdkCall], gaps: &[UsageGap], opts: &CheckOptions) -> RetirementReport {
2435 let input = ScanInput {
2436 calls,
2437 gaps,
2438 clients: &[],
2439 };
2440 check(input, bundled().unwrap(), opts)
2441 }
2442
2443 fn one(calls: &[SdkCall]) -> Finding {
2444 let report = run(calls, &[], &options("2026-10-18"));
2445 assert_eq!(report.findings.len(), 1, "{:#?}", report.findings);
2446 report.findings[0].clone()
2447 }
2448
2449 fn change(finding: &Finding, param: &str) -> Option<Change> {
2450 finding.changes.iter().find(|c| c.param == param).cloned()
2451 }
2452
2453 fn option<'a>(finding: &'a Finding, id: &str) -> &'a DecisionOption {
2454 finding.decisions[0]
2455 .options
2456 .iter()
2457 .find(|o| o.id == id)
2458 .unwrap_or_else(|| panic!("no option {id}: {:#?}", finding.decisions))
2459 }
2460
2461 #[test]
2462 fn retiring_model_counts_days_from_a_fixed_clock() {
2463 let finding = one(&[openai("gpt-4o", &["messages"])]);
2464 assert_eq!(finding.status, State::Retiring);
2465 assert_eq!(finding.date.unwrap().iso(), "2027-01-14");
2466 assert_eq!(finding.days_left, Some(88));
2467 assert_eq!(finding.replacement.as_deref(), Some("gpt-6-luna"));
2468 assert_eq!(finding.live_replacement.as_deref(), Some("gpt-6-luna"));
2469 assert_eq!(finding.routing_class, RoutingClass::Direct);
2470 assert_eq!(finding.confidence, Confidence::Confirmed);
2471 assert_eq!(finding.call_kind, CallKind::Request);
2472 assert_eq!(finding.endpoint, Some("chat.completions"));
2473 assert!(!finding.in_window, "retiring is not failing by default");
2474 assert!(finding.notes.iter().any(|n| n.contains("efficient tier")));
2475
2476 let report = run(&[openai("gpt-4o", &[])], &[], &options("2027-01-15"));
2478 let later = &report.findings[0];
2479 assert_eq!(later.status, State::Retired);
2480 assert_eq!(later.days_left, Some(-1));
2481 assert!(later.in_window && later.fails);
2482 assert_eq!(report.exit_code, 1);
2483
2484 let report = run(&[openai("gpt-4o", &[])], &[], &options("2027-01-14"));
2487 assert_eq!(report.findings[0].status, State::Retired);
2488 assert_eq!(report.findings[0].days_left, Some(0));
2489 assert_eq!(report.exit_code, 1);
2490 let report = run(&[openai("gpt-4o", &[])], &[], &options("2027-01-13"));
2491 assert_eq!(report.findings[0].status, State::Retiring);
2492 assert_eq!(report.findings[0].days_left, Some(1));
2493 assert_eq!(report.exit_code, 0);
2494 }
2495
2496 #[test]
2497 fn fail_within_counts_retiring_calls_inside_the_window() {
2498 let calls = [openai("gpt-4o", &[])];
2499 let mut opts = options("2026-10-18");
2500 assert_eq!(run(&calls, &[], &opts).exit_code, 0);
2501 opts.fail_within = Some(87);
2502 assert_eq!(run(&calls, &[], &opts).exit_code, 0);
2503 opts.fail_within = Some(88);
2504 let report = run(&calls, &[], &opts);
2505 assert_eq!(report.exit_code, 1);
2506 assert_eq!(report.summary.in_window, 1);
2507 assert_eq!(report.summary.failing, 1);
2508 }
2509
2510 #[test]
2511 fn retired_model_fails_by_default() {
2512 let claude = call(
2513 Sdk::Anthropic,
2514 Routing::AnthropicDirect,
2515 "claude.messages.create",
2516 "claude-3-5-sonnet-20241022",
2517 &["max_tokens", "messages"],
2518 20,
2519 );
2520 let report = run(&[claude], &[], &options("2026-10-18"));
2521 let finding = &report.findings[0];
2522 assert_eq!(finding.status, State::Retired);
2523 assert_eq!(finding.provider, Table::Anthropic);
2524 assert_eq!(finding.date.unwrap().iso(), "2025-10-28");
2525 assert_eq!(finding.replacement.as_deref(), Some("claude-sonnet-5-5"));
2526 assert!(finding.in_window && finding.fails);
2527 assert_eq!(report.exit_code, 1);
2528 assert_eq!(report.summary.retired, 1);
2529 assert!(
2532 change(finding, "thinking").is_none(),
2533 "{:#?}",
2534 finding.changes
2535 );
2536 assert_eq!(finding.fix, FixKind::Decide);
2537 assert_eq!(finding.decisions.len(), 1);
2538 assert_eq!(finding.decisions[0].choice, "ANT-THINKING-DEFAULT");
2539 let between = option(finding, "thinking_between_tools");
2540 assert_eq!(between.label, "think only between tools");
2541 assert_eq!(between.add.len(), 1);
2542 assert_eq!(between.add[0].name, "thinking");
2543 assert_eq!(
2544 python_literal(&between.add[0].value),
2545 "{\"type\": \"between_tools\"}"
2546 );
2547 let default = option(finding, "model_default");
2548 assert!(default.add.is_empty() && default.remove.is_empty());
2549 assert!(default
2550 .effects
2551 .iter()
2552 .any(|e| e.text.contains("thinks adaptively")));
2553 }
2554
2555 #[test]
2556 fn claude_thinking_is_a_decision_never_a_change() {
2557 let claude = |kwargs: &[&str]| {
2558 call(
2559 Sdk::Anthropic,
2560 Routing::AnthropicDirect,
2561 "claude.messages.create",
2562 "claude-3-7-sonnet-20250219",
2563 kwargs,
2564 20,
2565 )
2566 };
2567 let finding = one(&[claude(&["max_tokens", "messages", "tools"])]);
2569 assert!(finding.changes.is_empty(), "{:#?}", finding.changes);
2570 assert_eq!(finding.decisions[0].choice, "ANT-THINKING-DEFAULT");
2571 assert!(finding
2572 .review
2573 .iter()
2574 .all(|r| r.rule.as_deref() != Some("ANT-THINKING-DEFAULT")));
2575
2576 let finding = one(&[claude(&["max_tokens", "messages", "thinking"])]);
2580 assert!(finding.changes.is_empty(), "{:#?}", finding.changes);
2581 assert_eq!(finding.decisions.len(), 1, "{:#?}", finding.review);
2582 let decision = &finding.decisions[0];
2583 assert_eq!(decision.choice, "ANT-THINKING-DEFAULT");
2584 assert_eq!(decision.rules, ["ANT-THINKING-DISABLED"]);
2585 assert_eq!(decision.because, ["thinking"]);
2586 assert!(decision.reasons[0].contains("if it is {\"type\": \"disabled\"}"));
2587 let between = option(&finding, "thinking_between_tools");
2588 assert_eq!(between.remove, ["thinking"]);
2589 assert_eq!(between.add[0].name, "thinking");
2590 assert_eq!(option(&finding, "model_default").remove, ["thinking"]);
2591 assert!(finding
2593 .review
2594 .iter()
2595 .any(|r| r.rule.as_deref() == Some("ANT-THINKING-BUDGET")));
2596 assert_eq!(finding.fix, FixKind::Manual);
2597 }
2598
2599 #[test]
2600 fn the_reasoning_effort_is_a_decision_never_a_change() {
2601 let finding = one(&[openai(
2602 "gpt-4o-mini",
2603 &["messages", "max_tokens", "temperature", "tools"],
2604 )]);
2605 let rename = change(&finding, "max_tokens").expect("rename");
2607 assert_eq!(rename.kind, ChangeKind::Rename);
2608 assert_eq!(rename.to.as_deref(), Some("max_completion_tokens"));
2609 assert_eq!(rename.verified, Verified::Live);
2610 assert_eq!(finding.changes.len(), 1, "{:#?}", finding.changes);
2612 assert_eq!(finding.fix, FixKind::Decide);
2613
2614 assert_eq!(finding.decisions.len(), 1);
2616 let decision = &finding.decisions[0];
2617 assert_eq!(decision.choice, "G6-REASONING-DEFAULT");
2618 for rule in ["G6-REASONING-DEFAULT", "G6-SAMPLING", "G6-TOOLS-CC"] {
2619 assert!(decision.rules.iter().any(|r| r == rule), "{rule}");
2620 }
2621 assert_eq!(decision.because, ["temperature", "tools"]);
2622 let off = option(&finding, "reasoning_none");
2623 assert_eq!(off.label, "keep reasoning off");
2624 assert_eq!(off.add.len(), 1);
2625 assert_eq!(off.add[0].name, "reasoning_effort");
2626 assert_eq!(off.add[0].value, serde_json::json!("none"));
2627 assert_eq!(off.keep, ["temperature", "tools"]);
2628 let reason = option(&finding, "model_default");
2629 assert!(reason.add.is_empty());
2630 assert_eq!(reason.remove, ["temperature", "tools"]);
2631 assert!(reason
2632 .effects
2633 .iter()
2634 .any(|e| e.text.contains("tool calls stop")));
2635 assert!(decision
2637 .notes
2638 .iter()
2639 .any(|n| n.contains("max_completion_tokens also bounds its reasoning")));
2640 assert!(off
2642 .effects
2643 .iter()
2644 .any(|e| e.rule == "G6-REASONING-DEFAULT" && e.status == OptionStatus::Unverified));
2645 }
2646
2647 #[test]
2648 fn the_responses_api_names_its_own_output_limit() {
2649 let effects = |chain: &str| -> Vec<String> {
2652 let mut call = openai("gpt-4o", &["input"]);
2653 call.chain = chain.into();
2654 call.member = chain.split_once('.').unwrap().1.into();
2655 let finding = one(&[call]);
2656 option(&finding, "model_default")
2657 .effects
2658 .iter()
2659 .map(|e| e.text.clone())
2660 .collect()
2661 };
2662 let responses = effects("client.responses.create");
2663 assert!(
2664 responses
2665 .iter()
2666 .any(|t| t.contains("max_output_tokens also has to cover them")),
2667 "{responses:#?}"
2668 );
2669 assert!(responses
2670 .iter()
2671 .all(|t| !t.contains("max_completion_tokens")));
2672 let chat = effects("client.chat.completions.create");
2673 assert!(chat
2674 .iter()
2675 .any(|t| t.contains("max_completion_tokens also has to cover them")));
2676 }
2677
2678 #[test]
2679 fn a_plain_call_is_a_decision_and_nothing_else() {
2680 let finding = one(&[openai("gpt-4o", &["messages"])]);
2681 assert!(finding.changes.is_empty());
2682 assert!(finding.review.is_empty());
2683 assert_eq!(finding.fix, FixKind::Decide);
2684 let off = option(&finding, "reasoning_none");
2685 assert_eq!(off.add[0].name, "reasoning_effort");
2686 assert!(option(&finding, "model_default").remove.is_empty());
2687 let report = run(&[openai("gpt-4o", &[])], &[], &options("2026-10-18"));
2688 assert_eq!(report.summary.decide, 1);
2689 assert_eq!(report.summary.swap, 0);
2690 }
2691
2692 #[test]
2693 fn unsupported_parameters_need_a_person() {
2694 let finding = one(&[openai("gpt-4o", &["messages", "stop", "logit_bias"])]);
2695 assert_eq!(finding.fix, FixKind::Manual);
2696 assert!(finding
2697 .review
2698 .iter()
2699 .any(|r| r.rule.as_deref() == Some("G6-STOP-LOGIT-BIAS")
2700 && r.message.contains("gpt-6-luna")
2701 && r.verified == Some(Verified::Live)));
2702
2703 let finding = one(&[openai("gpt-4o", &["presence_penalty", "seed"])]);
2705 assert!(finding
2706 .review
2707 .iter()
2708 .any(|r| r.rule.as_deref() == Some("G6-PENALTIES")));
2709 assert!(
2711 finding.decisions[0]
2712 .notes
2713 .iter()
2714 .any(|n| n
2715 .starts_with("seed was accepted on gpt-6-luna at reasoning_effort \"none\""))
2716 );
2717
2718 let finding = one(&[openai("gpt-4o", &["seed", "reasoning_effort"])]);
2720 assert!(finding.decisions.is_empty());
2721 assert!(finding
2722 .review
2723 .iter()
2724 .any(|r| r.rule.as_deref() == Some("G6-N-SEED")));
2725 }
2726
2727 #[test]
2728 fn reasoning_sources_and_endpoints_pick_the_right_rules() {
2729 let finding = one(&[openai("o3-mini", &["temperature"])]);
2731 assert!(finding
2732 .review
2733 .iter()
2734 .any(|r| r.rule.as_deref() == Some("OAI-SAMPLING-REASONING-SOURCE")));
2735 assert!(finding.decisions.is_empty());
2736 assert!(change(&finding, "reasoning_effort").is_none());
2737
2738 let responses = call(
2741 Sdk::Openai,
2742 Routing::OpenaiDirect,
2743 "client.responses.create",
2744 "gpt-3.5-turbo",
2745 &["input", "temperature"],
2746 12,
2747 );
2748 let finding = one(&[responses]);
2749 assert!(finding.changes.is_empty());
2750 let off = option(&finding, "reasoning_none");
2751 assert_eq!(off.add[0].name, "reasoning");
2752 assert_eq!(off.add[0].value, serde_json::json!({"effort": "none"}));
2753 assert!(finding
2754 .review
2755 .iter()
2756 .any(|r| r.rule.as_deref() == Some("OAI-SAMPLING-RESPONSES")
2757 && r.verified == Some(Verified::Unverified)));
2758
2759 let finding = one(&[openai("gpt-4", &["tools", "reasoning_effort"])]);
2761 assert!(finding.decisions.is_empty());
2762 assert!(change(&finding, "reasoning_effort").is_none());
2763 assert!(finding
2764 .review
2765 .iter()
2766 .any(|r| r.rule.as_deref() == Some("OAI-TOOLS-CC")
2767 && r.message
2768 .contains("already sets reasoning_effort; check that it is \"none\"")));
2769
2770 let legacy = call(
2772 Sdk::Openai,
2773 Routing::OpenaiDirect,
2774 "openai.Completion.create",
2775 "gpt-3.5-turbo",
2776 &["prompt"],
2777 14,
2778 );
2779 let finding = one(&[legacy]);
2780 assert_eq!(finding.endpoint, Some("completions_legacy"));
2781 assert!(finding
2782 .review
2783 .iter()
2784 .any(|r| r.rule.as_deref() == Some("OAI-LEGACY-COMPLETIONS-ENDPOINT")));
2785 }
2786
2787 #[test]
2788 fn live_labels_hold_only_for_the_models_and_api_called() {
2789 let label = |model: &str| {
2792 let finding = one(&[openai(model, &["tools", "reasoning_effort"])]);
2793 finding
2794 .review
2795 .iter()
2796 .find(|r| r.rule.as_deref() == Some("OAI-TOOLS-CC"))
2797 .and_then(|r| r.verified)
2798 .unwrap()
2799 };
2800 assert_eq!(label("gpt-3.5-turbo"), Verified::Live);
2801 assert_eq!(label("gpt-4"), Verified::Docs);
2802
2803 let rename = |model: &str| change(&one(&[openai(model, &["max_tokens"])]), "max_tokens");
2805 assert_eq!(rename("gpt-3.5-turbo").unwrap().verified, Verified::Live);
2806 assert_eq!(
2807 rename("gpt-4o-2024-05-13").unwrap().verified,
2808 Verified::Docs
2809 );
2810
2811 let assistants = call(
2813 Sdk::Openai,
2814 Routing::OpenaiDirect,
2815 "client.beta.assistants.create",
2816 "gpt-4o",
2817 &["stop"],
2818 16,
2819 );
2820 let finding = one(&[assistants]);
2821 let stop = finding
2822 .review
2823 .iter()
2824 .find(|r| r.rule.as_deref() == Some("G6-STOP-LOGIT-BIAS"))
2825 .unwrap();
2826 assert_eq!(stop.verified, Some(Verified::Unverified));
2827 }
2828
2829 #[test]
2830 fn response_and_type_objects_are_not_requests() {
2831 let calls = [
2833 object(
2834 Sdk::Openai,
2835 "ChatCompletion",
2836 "types.chat.ChatCompletion",
2837 "gpt-3.5-turbo-0613",
2838 5,
2839 ),
2840 object(
2841 Sdk::Anthropic,
2842 "Message",
2843 "types.Message",
2844 "claude-3-5-sonnet-20241022",
2845 9,
2846 ),
2847 ];
2848 let report = run(&calls, &[], &options("2026-10-18"));
2849 assert!(report.findings.is_empty(), "{:#?}", report.findings);
2850 assert_eq!(report.exit_code, 0);
2851 assert_eq!(report.summary.response_objects, 2);
2852
2853 for (chain, member) in [
2855 (
2856 "ChatCompletion.model_validate",
2857 "types.chat.ChatCompletion.model_validate",
2858 ),
2859 (
2860 "ChatCompletion.construct",
2861 "types.chat.ChatCompletion.construct",
2862 ),
2863 (
2864 "openai.types.chat.ChatCompletion",
2865 "types.chat.ChatCompletion",
2866 ),
2867 ("Choice", "types.chat.chat_completion.Choice"),
2868 ] {
2869 let report = run(
2870 &[object(Sdk::Openai, chain, member, "gpt-3.5-turbo-0613", 5)],
2871 &[],
2872 &options("2026-10-18"),
2873 );
2874 assert!(report.findings.is_empty(), "{chain}");
2875 }
2876
2877 let tool = object(
2879 Sdk::Openai,
2880 "ImageGeneration",
2881 "types.responses.tool_param.ImageGeneration",
2882 "dall-e-2",
2883 7,
2884 );
2885 let finding = one(&[tool]);
2886 assert_eq!(finding.call_kind, CallKind::RequestParam);
2887 assert_eq!(finding.endpoint, None);
2888 assert_eq!(finding.fix, FixKind::Manual);
2889 assert_eq!(finding.routing_class, RoutingClass::Unknown);
2892 assert!(!finding.fails);
2893 assert!(finding
2894 .review
2895 .iter()
2896 .any(|r| r.message.contains("request parameter object")));
2897
2898 let session = object(
2901 Sdk::Openai,
2902 "RealtimeSessionCreateRequest",
2903 "types.realtime.realtime_session_create_request.RealtimeSessionCreateRequest",
2904 "gpt-4o-realtime-preview",
2905 11,
2906 );
2907 let finding = one(&[session]);
2908 assert_eq!(finding.call_kind, CallKind::RequestParam);
2909 assert_eq!(finding.status, State::Retired);
2910
2911 let mut binding = call(
2913 Sdk::Google,
2914 Routing::GoogleGenerativeaiLegacy,
2915 "genai.GenerativeModel",
2916 "gemini-2.0-flash",
2917 &[],
2918 8,
2919 );
2920 binding.request = false;
2921 binding.member = "GenerativeModel".into();
2922 let finding = one(&[binding]);
2923 assert_eq!(finding.call_kind, CallKind::ModelBinding);
2924 assert_eq!(finding.endpoint, Some("generate_content"));
2925 assert_eq!(finding.status, State::Retired);
2926 }
2927
2928 #[test]
2929 fn replacement_chains_end_at_a_model_that_still_works() {
2930 let finding = one(&[openai("gpt-4-vision-preview", &["max_tokens"])]);
2932 assert_eq!(finding.replacement.as_deref(), Some("gpt-4o"));
2933 assert_eq!(finding.live_replacement.as_deref(), Some("gpt-6-luna"));
2934 let steps: Vec<(&str, Option<State>)> = finding
2935 .replacement_chain
2936 .iter()
2937 .map(|s| (s.model.as_str(), s.status))
2938 .collect();
2939 assert_eq!(
2940 steps,
2941 [("gpt-4o", Some(State::Retiring)), ("gpt-6-luna", None)]
2942 );
2943 assert_eq!(finding.fix, FixKind::Manual);
2944 assert!(finding.review.iter().any(|r| r.message
2945 == "OpenAI lists gpt-4o as the replacement, and it shuts down on 14 Jan 2027 (88 days). \
2946 gpt-6-luna is the replacement OpenAI lists for gpt-4o; the changes shown are for gpt-6-luna."));
2947 assert_eq!(
2949 change(&finding, "max_tokens").unwrap().to.as_deref(),
2950 Some("max_completion_tokens")
2951 );
2952
2953 let finding = one(&[openai("text-davinci-003", &[])]);
2955 assert_eq!(
2956 finding.replacement.as_deref(),
2957 Some("gpt-3.5-turbo-instruct")
2958 );
2959 assert_eq!(finding.live_replacement.as_deref(), Some("gpt-5.6-terra"));
2960 assert_eq!(finding.replacement_chain[0].status, Some(State::Retired));
2961 assert!(finding.changes.is_empty());
2965 assert!(
2966 finding.review.iter().any(|r| r.message
2967 == "OpenAI lists gpt-3.5-turbo-instruct as the replacement, and it shut down on \
2968 28 Sep 2026. gpt-5.6-terra is the replacement OpenAI lists for \
2969 gpt-3.5-turbo-instruct; the parameters gpt-5.6-terra needs have not been \
2970 checked yet."),
2971 "{:#?}",
2972 finding.review
2973 );
2974 assert!(!finding
2975 .review
2976 .iter()
2977 .any(|r| r.message.contains("the changes shown are for")));
2978
2979 let bison = call(
2983 Sdk::Google,
2984 Routing::Unknown,
2985 "client.models.generate_content",
2986 "text-bison",
2987 &["contents"],
2988 30,
2989 );
2990 let vertex = ClientConstruction {
2991 sdk: Sdk::Google,
2992 package: "google.genai".into(),
2993 constructor: "google.genai.Client".into(),
2994 chain: "genai.Client".into(),
2995 binding: Some("client".into()),
2996 scope: crate::usages::ClientScope::Module,
2997 routing: Routing::Unknown,
2998 is_async: false,
2999 kwargs: vec!["vertexai".into()],
3000 splat: false,
3001 file: "app.py".into(),
3002 span: span(1),
3003 symbol: None,
3004 vertexai: Some(VertexAi::On),
3005 };
3006 let input = ScanInput {
3007 calls: std::slice::from_ref(&bison),
3008 gaps: &[],
3009 clients: std::slice::from_ref(&vertex),
3010 };
3011 let report = check(input, bundled().unwrap(), &options("2026-10-18"));
3012 let finding = &report.findings[0];
3013 assert_eq!(
3014 finding.replacement.as_deref(),
3015 Some("gemini-2.5-flash-lite")
3016 );
3017 assert_eq!(finding.live_replacement, None);
3018 assert_eq!(finding.fix, FixKind::Manual);
3019 assert!(finding
3020 .review
3021 .iter()
3022 .any(|r| r.message.contains("pick one by hand")));
3023 }
3024
3025 #[test]
3026 fn fine_tunes_never_get_a_base_that_cannot_be_fine_tuned() {
3027 let finding = one(&[openai("ft:gpt-4o-mini-2024-07-18:acme::abc123", &[])]);
3029 assert_eq!(finding.match_kind, MatchKind::FineTuned);
3030 assert_eq!(finding.matched, "gpt-4o-mini-2024-07-18");
3031 assert_eq!(finding.replacement, None);
3032 assert_eq!(
3033 finding.replacement_text.as_deref(),
3034 Some("no fine-tunable replacement is listed")
3035 );
3036 assert_eq!(finding.fix, FixKind::Manual);
3037 let advice = &finding.review[0].message;
3038 assert!(advice.starts_with("Fine-tuned model:"), "{advice}");
3039 assert!(advice.contains("does not support fine-tuning"), "{advice}");
3040 assert!(!advice.contains("retrain on gpt-6-luna"), "{advice}");
3041
3042 let finding = one(&[openai("ft:gpt-3.5-turbo:acme::abc123", &[])]);
3044 assert_eq!(
3045 finding.replacement_text.as_deref(),
3046 Some("no fine-tunable replacement is listed")
3047 );
3048 assert!(finding.review[0]
3049 .message
3050 .contains("OpenAI lists gpt-5.6-terra for fine-tunes of gpt-3.5-turbo"));
3051 }
3052
3053 #[test]
3054 fn fine_tuning_jobs_never_get_a_base_that_cannot_be_fine_tuned() {
3055 let job = |model: &str| {
3058 call(
3059 Sdk::Openai,
3060 Routing::OpenaiDirect,
3061 "client.fine_tuning.jobs.create",
3062 model,
3063 &["training_file", "hyperparameters"],
3064 30,
3065 )
3066 };
3067 for model in ["gpt-4o-mini-2024-07-18", "gpt-4o-mini", "gpt-3.5-turbo"] {
3068 let finding = one(&[job(model)]);
3069 assert_eq!(finding.endpoint, Some(FINE_TUNING), "{model}");
3070 assert_eq!(finding.status, State::Retiring, "{model}");
3071 assert_eq!(finding.replacement, None, "{model}");
3072 assert_eq!(finding.live_replacement, None, "{model}");
3073 assert!(finding.replacement_chain.is_empty(), "{model}");
3074 assert_eq!(
3075 finding.replacement_text.as_deref(),
3076 Some("no fine-tunable replacement is listed"),
3077 "{model}"
3078 );
3079 assert_eq!(finding.fix, FixKind::Manual, "{model}");
3080 assert!(
3082 finding.changes.is_empty() && finding.decisions.is_empty(),
3083 "{model}: {finding:#?}"
3084 );
3085 let advice = &finding.review[0].message;
3086 assert!(advice.starts_with("Fine-tuning job:"), "{advice}");
3087 assert!(!advice.contains("start new jobs on"), "{advice}");
3088 }
3089 let finding = one(&[job("gpt-4o-mini-2024-07-18")]);
3091 assert_eq!(finding.date.unwrap().iso(), "2027-01-14");
3092 assert!(
3093 finding.review[0]
3094 .message
3095 .contains("gpt-6-luna, the replacement OpenAI lists for these models, does not support fine-tuning"),
3096 "{:#?}",
3097 finding.review
3098 );
3099 let finding = one(&[job("gpt-4o-mini")]);
3102 assert!(
3103 finding.review[0].message.contains(
3104 "OpenAI lists gpt-6-luna as the replacement for gpt-4o-mini, not as a base for fine-tuning"
3105 ),
3106 "{:#?}",
3107 finding.review
3108 );
3109 let finding = one(&[job("gpt-3.5-turbo")]);
3112 assert!(finding.review[0]
3113 .message
3114 .contains("OpenAI lists gpt-5.6-terra for fine-tunes of gpt-3.5-turbo"));
3115 let finding = one(&[job("ft:gpt-4o-mini-2024-07-18:acme::abc123")]);
3117 assert_eq!(finding.match_kind, MatchKind::FineTuned);
3118 assert!(finding.review[0].message.starts_with("Fine-tuned model:"));
3119 assert_eq!(
3121 endpoint_of("openai.FineTuningJob.create", "FineTuningJob.create"),
3122 Some(FINE_TUNING)
3123 );
3124 assert_eq!(
3125 endpoint_of("openai.FineTune.create", "FineTune.create"),
3126 Some(FINE_TUNING)
3127 );
3128 let report = run(&[job("gpt-4o-mini")], &[], &options("2026-10-18"));
3129 assert_eq!((report.summary.swap, report.summary.manual), (0, 1));
3130 }
3131
3132 #[test]
3133 fn nested_models_get_only_the_rules_about_the_model() {
3134 let source = r#"from anthropic import Anthropic
3139from openai import OpenAI
3140
3141claude = Anthropic()
3142client = OpenAI()
3143
3144
3145def batch():
3146 return claude.messages.batches.create(
3147 requests=[{"custom_id": "a", "params": {"model": "claude-3-5-sonnet-20241022", "max_tokens": 10, "messages": [], "temperature": 0.2}}]
3148 )
3149
3150
3151def plain():
3152 return claude.messages.create(model="claude-3-5-sonnet-20241022", max_tokens=10, messages=[], temperature=0.2)
3153
3154
3155def tool_model(tools):
3156 return client.chat.completions.create(model="gpt-4o", messages=[], max_tokens=10, tools=[{"type": "x", "model": "gpt-4o-mini"}])
3157"#;
3158 let report = check_source(source, &options("2026-10-20"));
3159 let at = |needle: &str, key: &str| -> Finding {
3160 let line = line_of(source, needle);
3161 let found: Vec<&Finding> = report
3162 .findings
3163 .iter()
3164 .filter(|f| f.line == line && f.key == key)
3165 .collect();
3166 assert_eq!(found.len(), 1, "{needle} {key}: {:#?}", report.findings);
3167 found[0].clone()
3168 };
3169 let nested = at("batches.create", "requests.params.model");
3170 assert!(nested.changes.is_empty(), "{:#?}", nested.changes);
3171 assert!(nested.decisions.is_empty(), "{:#?}", nested.decisions);
3172 assert_eq!(nested.fix, FixKind::Manual);
3173 let check = nested
3174 .review
3175 .iter()
3176 .find(|r| r.message.contains("requests.params"))
3177 .expect("a check naming the nested request");
3178 assert!(
3179 check
3180 .message
3181 .contains("check those against claude-sonnet-5-5 by hand"),
3182 "{}",
3183 check.message
3184 );
3185 let data = bundled().unwrap();
3187 for item in &nested.review {
3188 if let Some(id) = &item.rule {
3189 let rule = data.data.rules.iter().find(|r| &r.id == id).unwrap();
3190 assert!(about_the_model(rule), "{id} is about the request");
3191 }
3192 }
3193 assert!(nested
3194 .review
3195 .iter()
3196 .map(|r| r.message.as_str())
3197 .chain(nested.notes.iter().map(String::as_str))
3198 .all(|m| !m.contains("temperature")));
3199 let plain = at("claude.messages.create(", "model");
3201 assert!(plain
3202 .review
3203 .iter()
3204 .any(|r| r.rule.as_deref() == Some("ANT-SAMPLING")));
3205
3206 if let Some(tool) = report.findings.iter().find(|f| f.key == "tools.model") {
3209 assert!(
3210 tool.changes.is_empty() && tool.decisions.is_empty(),
3211 "{tool:#?}"
3212 );
3213 assert_eq!(tool.fix, FixKind::Manual);
3214 assert!(tool.review.iter().any(|r| r.message.contains("in tools,")));
3215 }
3216 let call = at("client.chat.completions.create(", "model");
3217 assert!(change(&call, "max_tokens").is_some(), "{call:#?}");
3218 assert_eq!(call.decisions.len(), 1);
3219 }
3220
3221 #[test]
3222 fn calls_through_unresolved_clients_with_unread_models_are_counted() {
3223 let source = r#"from openai import OpenAI
3227
3228client = OpenAI()
3229
3230
3231def helper(api, model, messages):
3232 return api.chat.completions.create(model=model, messages=messages)
3233
3234
3235def helper_dict(api, messages, model="gpt-4-0125-preview"):
3236 params = {"model": model, "messages": messages}
3237 return api.chat.completions.create(**params)
3238
3239
3240def factory(make):
3241 return make().chat.completions.create(messages=[])
3242
3243
3244def factory_literal(make):
3245 return make().chat.completions.create(model="gpt-4-0125-preview", messages=[])
3246
3247
3248def known(model):
3249 return client.chat.completions.create(model=model, messages=[])
3250"#;
3251 let report = check_source(source, &options("2026-10-20"));
3252 assert_eq!(
3254 report.summary.unresolved_clients, 3,
3255 "{:#?}",
3256 report.summary
3257 );
3258 let line = line_of(source, "make().chat.completions.create(model=");
3261 assert!(report
3262 .findings
3263 .iter()
3264 .any(|f| f.line == line && f.confidence == Confidence::Gap));
3265 assert_eq!(report.summary.unreadable_calls, 1);
3266 let found = scan(source);
3268 let shown = report.findings.len()
3269 + report.summary.unreadable_calls
3270 + report.summary.no_model_calls
3271 + report.summary.untracked_methods
3272 + report.summary.unresolved_clients;
3273 let sdk_calls: HashSet<u32> = found
3274 .calls
3275 .iter()
3276 .map(|c| c.span.start_byte)
3277 .chain(
3278 found
3279 .gaps
3280 .iter()
3281 .filter_map(|g| g.span.map(|s| s.start_byte)),
3282 )
3283 .collect();
3284 assert!(shown >= sdk_calls.len(), "{shown} < {}", sdk_calls.len());
3285 }
3286
3287 #[test]
3288 fn routed_calls_are_kept_apart() {
3289 let azure = call(
3290 Sdk::Openai,
3291 Routing::AzureOpenai,
3292 "azure.chat.completions.create",
3293 "gpt-4o",
3294 &[],
3295 30,
3296 );
3297 let proxy = call(
3298 Sdk::Openai,
3299 Routing::CustomBaseUrl,
3300 "router.chat.completions.create",
3301 "anthropic/claude-3-opus-20240229",
3302 &[],
3303 31,
3304 );
3305 let calls = [azure, proxy];
3306 let report = run(&calls, &[], &options("2026-10-18"));
3307 assert!(report.findings.is_empty());
3308 assert!(report.routed.is_empty());
3309 assert_eq!(report.summary.routed_calls, 2);
3310 assert_eq!(report.exit_code, 0, "routed calls do not fail by default");
3311
3312 let mut opts = options("2026-10-18");
3313 opts.include_routed = true;
3314 let report = run(&calls, &[], &opts);
3315 assert_eq!(report.routed.len(), 2);
3316 let claude = report
3317 .routed
3318 .iter()
3319 .find(|f| f.provider == Table::Anthropic)
3320 .unwrap();
3321 assert_eq!(claude.match_kind, MatchKind::RouterPrefix);
3322 assert_eq!(claude.matched, "claude-3-opus-20240229");
3323 assert_eq!(claude.routing, "custom_base_url");
3324 assert_eq!(
3325 report.exit_code, 1,
3326 "with --include-routed a retired model fails"
3327 );
3328 }
3329
3330 #[test]
3331 fn base_url_routing_follows_the_usage_scan() {
3332 let model = "gpt-3.5-turbo-0613";
3338 let at = |line: u32, routing: Routing| {
3339 let mut c = call(
3340 Sdk::Openai,
3341 routing,
3342 "client.chat.completions.create",
3343 model,
3344 &[],
3345 line,
3346 );
3347 c.client_line = Some(line - 20);
3348 c
3349 };
3350 let calls = [
3351 at(21, Routing::OpenaiDirect),
3352 at(22, Routing::OpenaiDirect),
3353 at(23, Routing::Unknown),
3354 at(24, Routing::Unknown),
3355 at(25, Routing::CustomBaseUrl),
3356 at(26, Routing::OpenaiDirect),
3357 ];
3358 let client = |line: u32| ClientConstruction {
3359 sdk: Sdk::Openai,
3360 package: "openai".into(),
3361 constructor: "openai.OpenAI".into(),
3362 chain: "OpenAI".into(),
3363 binding: Some("client".into()),
3364 scope: crate::usages::ClientScope::Module,
3365 routing: Routing::OpenaiDirect,
3366 is_async: false,
3367 kwargs: if line == 6 {
3368 Vec::new()
3369 } else {
3370 vec!["base_url".into()]
3371 },
3372 splat: false,
3373 file: "app.py".into(),
3374 span: span(line),
3375 symbol: None,
3376 vertexai: None,
3377 };
3378 let clients: Vec<ClientConstruction> = (1..=6).map(client).collect();
3379 let gap = |line: u32, reason: &str| UsageGap {
3380 kind: GapKind::AmbiguousClient,
3381 sdk: Some(Sdk::Openai),
3382 file: "app.py".into(),
3383 span: Some(span(line)),
3384 symbol: None,
3385 chain: Some("client.chat.completions.create".into()),
3386 key: None,
3387 reason: reason.into(),
3388 detail: String::new(),
3389 values: Vec::new(),
3390 values_complete: false,
3391 };
3392 let gaps = [
3393 gap(22, "base_url_env"),
3394 gap(23, "base_url_env"),
3395 gap(24, "base_url_unresolved"),
3396 ];
3397 let run_with = |opts: &CheckOptions| {
3398 let input = ScanInput {
3399 calls: &calls,
3400 gaps: &gaps,
3401 clients: &clients,
3402 };
3403 check(input, bundled().unwrap(), opts)
3404 };
3405 let report = run_with(&options("2026-10-18"));
3406 let class = |line: u32| {
3407 report
3408 .findings
3409 .iter()
3410 .find(|f| f.line == line)
3411 .map(|f| (f.routing_class, f.base_url, f.fails))
3412 };
3413 assert_eq!(
3414 class(21),
3415 Some((RoutingClass::Direct, Some(BaseUrl::ProviderHost), true))
3416 );
3417 assert_eq!(
3419 class(22),
3420 Some((
3421 RoutingClass::Unknown,
3422 Some(BaseUrl::EnvProviderDefault),
3423 false
3424 ))
3425 );
3426 assert_eq!(
3427 class(23),
3428 Some((RoutingClass::Unknown, Some(BaseUrl::EnvOnly), false))
3429 );
3430 assert_eq!(
3431 class(24),
3432 Some((RoutingClass::Unknown, Some(BaseUrl::Unreadable), false))
3433 );
3434 assert_eq!(class(25), None, "another host stays routed");
3435 assert_eq!(class(26), Some((RoutingClass::Direct, None, true)));
3436 assert_eq!(report.summary.routed_calls, 1);
3437 assert_eq!(report.summary.uncounted, 3);
3438 let gap_of = |line: u32| {
3439 report
3440 .findings
3441 .iter()
3442 .find(|f| f.line == line)
3443 .and_then(|f| f.routing_gap.clone())
3444 };
3445 assert_eq!(gap_of(22).as_deref(), Some("base_url_env"));
3446 assert_eq!(gap_of(24).as_deref(), Some("base_url_unresolved"));
3447 assert_eq!(gap_of(21), None);
3448
3449 let mut opts = options("2026-10-18");
3450 opts.count_unconfirmed = true;
3451 assert_eq!(run_with(&opts).summary.failing, 5);
3452 opts.include_routed = true;
3453 let report = run_with(&opts);
3454 assert_eq!(report.summary.failing, 6);
3455 assert_eq!(report.routed[0].base_url, Some(BaseUrl::OtherHost));
3456 }
3457
3458 #[test]
3459 fn unconfirmed_values_are_listed_but_count_only_when_asked() {
3460 let mut env = openai("gpt-3.5-turbo-0613", &[]);
3461 env.values[0].origin = ValueOrigin::EnvDefault;
3462 env.values[0].name = Some("os.getenv(\"MODEL\")".into());
3463 let report = run(std::slice::from_ref(&env), &[], &options("2026-10-18"));
3464 let finding = &report.findings[0];
3465 assert_eq!(finding.confidence, Confidence::ConfirmFirst);
3466 assert_eq!(finding.origin, Some(ValueOrigin::EnvDefault));
3467 assert_eq!(
3468 finding.fix,
3469 FixKind::Manual,
3470 "confirm-first is never a swap"
3471 );
3472 assert!(finding.in_window && !finding.fails);
3473 assert_eq!(report.exit_code, 0);
3474 assert_eq!(report.summary.uncounted, 1);
3475
3476 let mut opts = options("2026-10-18");
3477 opts.count_unconfirmed = true;
3478 assert_eq!(run(&[env], &[], &opts).exit_code, 1);
3479
3480 let gap = UsageGap {
3481 kind: GapKind::UnknownClientFactory,
3482 sdk: Some(Sdk::Openai),
3483 file: "svc.py".into(),
3484 span: Some(span(40)),
3485 symbol: None,
3486 chain: Some("self.client.chat.completions.create".into()),
3487 key: None,
3488 reason: "factory_call".into(),
3489 detail: String::new(),
3490 values: vec![value("gpt-4o-2024-08-06", ValueOrigin::Literal, 40)],
3491 values_complete: false,
3492 };
3493 let report = run(&[], &[gap], &options("2026-10-18"));
3494 let finding = &report.findings[0];
3495 assert_eq!(finding.confidence, Confidence::Gap);
3496 assert_eq!(finding.routing_class, RoutingClass::Unknown);
3497 assert_eq!(finding.gap_reason.as_deref(), Some("factory_call"));
3498 assert_eq!(finding.origin, None);
3499 assert_eq!(finding.replacement.as_deref(), Some("gpt-6-luna"));
3500 assert_eq!(finding.fix, FixKind::Manual, "a gap is never a swap");
3501 }
3502
3503 #[test]
3504 fn unreadable_models_are_counted_once_and_fallbacks_are_not() {
3505 let mut env = openai("gpt-4.1", &[]);
3506 env.values[0].origin = ValueOrigin::EnvDefault;
3507 let gap = |line: u32| UsageGap {
3508 kind: GapKind::UnresolvedModel,
3509 sdk: Some(Sdk::Openai),
3510 file: "app.py".into(),
3511 span: Some(span(line)),
3512 symbol: None,
3513 chain: Some("client.chat.completions.create".into()),
3514 key: Some("model".into()),
3515 reason: "env_var".into(),
3516 detail: String::new(),
3517 values: Vec::new(),
3518 values_complete: false,
3519 };
3520 let report = run(&[env], &[gap(10), gap(50), gap(50)], &options("2026-10-18"));
3522 assert_eq!(report.unreadable.len(), 1);
3523 assert_eq!(report.unreadable[0].line, 50);
3524 assert_eq!(report.summary.unreadable_calls, 1);
3525 }
3526
3527 #[test]
3528 fn matching_is_exact() {
3529 for not_listed in [
3530 "GPT-4O",
3531 "gpt-4o ",
3532 "gpt-4o-2099-01-01",
3533 "my-gpt-4o",
3534 "gpt-6-luna",
3535 ] {
3536 let report = run(&[openai(not_listed, &[])], &[], &options("2026-10-18"));
3537 assert!(report.findings.is_empty(), "{not_listed}");
3538 }
3539 let report = run(
3542 &[openai("claude-3-opus-20240229", &[])],
3543 &[],
3544 &options("2026-10-18"),
3545 );
3546 assert!(report.findings.is_empty());
3547 }
3548
3549 #[test]
3550 fn resource_prefixes_are_matched_and_never_swapped() {
3551 let gemini = call(
3552 Sdk::Google,
3553 Routing::GoogleGenai,
3554 "client.models.generate_content",
3555 "models/gemini-2.0-flash",
3556 &["contents"],
3557 60,
3558 );
3559 let finding = one(&[gemini]);
3560 assert_eq!(finding.provider, Table::GeminiApi);
3561 assert_eq!(finding.match_kind, MatchKind::ResourcePrefix);
3562 assert_eq!(finding.status, State::Retired);
3563 assert_eq!(
3564 finding.fix,
3565 FixKind::Manual,
3566 "a prefixed match is never a plain swap"
3567 );
3568 }
3569
3570 fn scan(source: &str) -> crate::usages::FileUsages {
3572 let mut parser = tree_sitter::Parser::new();
3573 parser
3574 .set_language(&tree_sitter_python::language())
3575 .unwrap();
3576 let tree = parser.parse(source, None).unwrap();
3577 crate::usages::python::extract(&tree, source, "app.py")
3578 }
3579
3580 fn check_source(source: &str, opts: &CheckOptions) -> RetirementReport {
3582 let found = scan(source);
3583 let input = ScanInput {
3584 calls: &found.calls,
3585 gaps: &found.gaps,
3586 clients: &found.clients,
3587 };
3588 check(input, bundled().unwrap(), opts)
3589 }
3590
3591 fn line_of(source: &str, needle: &str) -> u32 {
3593 let lines: Vec<usize> = source
3594 .lines()
3595 .enumerate()
3596 .filter(|(_, l)| l.contains(needle))
3597 .map(|(i, _)| i + 1)
3598 .collect();
3599 assert_eq!(lines.len(), 1, "{needle}");
3600 lines[0] as u32
3601 }
3602
3603 #[test]
3604 fn the_vertexai_flag_picks_the_schedule() {
3605 let source = r#"import os
3609
3610from google import genai
3611
3612api = genai.Client(vertexai=False, api_key=os.environ["GEMINI_API_KEY"])
3613nothing = genai.Client(vertexai=None)
3614cloud = genai.Client(vertexai=True, project="p", location="us-central1")
3615toggle = genai.Client(vertexai=os.getenv("USE_VERTEX", "false") == "true")
3616plain = genai.Client()
3617
3618
3619def run():
3620 api.models.generate_content(model="gemini-1.5-flash", contents="api-retired")
3621 api.models.generate_content(model="gemini-2.5-flash", contents="api-vertex-only")
3622 api.models.generate_content(model="gemini-2.0-flash", contents="api-both")
3623 nothing.models.generate_content(model="gemini-2.0-flash", contents="none-both")
3624 cloud.models.generate_content(model="gemini-2.0-flash", contents="cloud-both")
3625 cloud.models.generate_content(model="gemini-1.5-flash", contents="cloud-api-only")
3626 cloud.models.generate_content(model="gemini-2.5-flash", contents="cloud-vertex-only")
3627 toggle.models.generate_content(model="gemini-1.5-flash", contents="toggle-api-only")
3628 toggle.models.generate_content(model="gemini-2.0-flash", contents="toggle-both")
3629 plain.models.generate_content(model="gemini-2.5-flash", contents="plain-vertex-only")
3630"#;
3631 let found = scan(source);
3633 let flags: Vec<(Option<&str>, Option<VertexAi>)> = found
3634 .clients
3635 .iter()
3636 .map(|c| (c.binding.as_deref(), c.vertexai))
3637 .collect();
3638 assert_eq!(
3639 flags,
3640 [
3641 (Some("api"), Some(VertexAi::Off)),
3642 (Some("nothing"), Some(VertexAi::Off)),
3643 (Some("cloud"), Some(VertexAi::On)),
3644 (Some("toggle"), Some(VertexAi::Unknown)),
3645 (Some("plain"), None),
3646 ]
3647 );
3648 let plain = serde_json::to_value(&found.clients[4]).unwrap();
3649 assert!(plain.get("vertexai").is_none(), "{plain}");
3650
3651 let data = bundled().unwrap();
3652 let report = check_source(source, &options("2026-10-20"));
3653 let at = |needle: &str| -> Vec<&Finding> {
3654 let line = line_of(source, needle);
3655 report.findings.iter().filter(|f| f.line == line).collect()
3656 };
3657 let one = |needle: &str| -> &Finding {
3658 let found = at(needle);
3659 assert_eq!(found.len(), 1, "{needle}: {found:#?}");
3660 found[0]
3661 };
3662 let listed = |table: Table, model: &str| data.entry(table, model).unwrap();
3663
3664 let retired = one("api-retired");
3666 assert_eq!(retired.provider, Table::GeminiApi);
3667 assert_eq!(retired.status, State::Retired);
3668 assert_eq!(retired.routing_class, RoutingClass::Direct);
3669 assert_eq!(retired.confidence, Confidence::Confirmed);
3670 assert!(retired.fails);
3671 assert_eq!(report.exit_code, 1);
3672 assert!(at("api-vertex-only")
3674 .iter()
3675 .all(|f| f.provider == Table::GeminiApi));
3676 for needle in ["api-both", "none-both"] {
3677 let both = one(needle);
3678 assert_eq!(both.provider, Table::GeminiApi, "{needle}");
3679 assert_eq!(
3680 both.replacement,
3681 listed(Table::GeminiApi, "gemini-2.0-flash").replacement,
3682 "{needle}"
3683 );
3684 assert!(both.review.iter().all(|r| !r.message.contains("run time")));
3685 }
3686
3687 let cloud = one("cloud-both");
3690 assert_eq!(cloud.provider, Table::Vertex);
3691 assert_eq!(
3692 cloud.replacement,
3693 listed(Table::Vertex, "gemini-2.0-flash").replacement
3694 );
3695 assert_eq!(cloud.routing_class, RoutingClass::Unknown);
3696 assert_eq!(cloud.routing_gap.as_deref(), Some("endpoint_option"));
3697 assert!(!cloud.fails);
3698 assert!(at("cloud-api-only").is_empty(), "a Gemini API-only model");
3699 let earliest = one("cloud-vertex-only");
3701 let entry = listed(Table::Vertex, "gemini-2.5-flash");
3702 assert_eq!(earliest.date_kind, DateKind::Earliest);
3703 assert_eq!(earliest.date.map(|d| d.iso()), entry.date.clone());
3704
3705 let toggled = one("toggle-api-only");
3708 assert_eq!(toggled.provider, Table::GeminiApi);
3709 assert_eq!(toggled.status, State::Retired);
3710 assert_eq!(toggled.routing_class, RoutingClass::Unknown);
3711 assert!(!toggled.fails);
3712 assert_eq!(toggled.fix, FixKind::Manual);
3713 assert!(toggled
3714 .review
3715 .iter()
3716 .any(|r| r.message.contains("decided at run time")
3717 && r.message.contains("Gemini API's schedule")));
3718 let toggled = one("toggle-both");
3719 assert_eq!(toggled.provider, Table::Vertex);
3720 assert!(toggled
3721 .review
3722 .iter()
3723 .any(|r| r.message.contains("decided at run time")
3724 && r.message.contains("Google's schedule applies instead")));
3725 let mut opts = options("2026-10-20");
3726 opts.count_unconfirmed = true;
3727 let counted = check_source(source, &opts);
3728 let line = line_of(source, "toggle-api-only");
3729 assert!(counted.findings.iter().any(|f| f.line == line && f.fails));
3730
3731 assert!(at("plain-vertex-only")
3733 .iter()
3734 .all(|f| f.provider == Table::GeminiApi));
3735 }
3736
3737 #[test]
3738 fn an_unrouted_google_client_still_finds_vertex_models() {
3739 let mut gemini = call(
3743 Sdk::Google,
3744 Routing::Unknown,
3745 "client.models.generate_content",
3746 "gemini-2.5-flash",
3747 &["contents"],
3748 70,
3749 );
3750 let vertex = ClientConstruction {
3751 sdk: Sdk::Google,
3752 package: "google.genai".into(),
3753 constructor: "google.genai.Client".into(),
3754 chain: "genai.Client".into(),
3755 binding: Some("client".into()),
3756 scope: crate::usages::ClientScope::Module,
3757 routing: Routing::Unknown,
3758 is_async: false,
3759 kwargs: vec!["vertexai".into(), "project".into()],
3760 splat: false,
3761 file: "app.py".into(),
3762 span: span(1),
3763 symbol: None,
3764 vertexai: Some(VertexAi::On),
3765 };
3766 let mut option = gap_at(GapKind::AmbiguousClient, "endpoint_option", 70, None);
3767 option.sdk = Some(Sdk::Google);
3768 let report = check(
3769 ScanInput {
3770 calls: std::slice::from_ref(&gemini),
3771 gaps: std::slice::from_ref(&option),
3772 clients: std::slice::from_ref(&vertex),
3773 },
3774 bundled().unwrap(),
3775 &options("2026-10-18"),
3776 );
3777 let finding = &report.findings[0];
3778 assert_eq!(finding.provider, Table::Vertex);
3779 assert_eq!(finding.routing_class, RoutingClass::Unknown);
3780 assert_eq!(finding.routing_gap.as_deref(), Some("endpoint_option"));
3781 assert!(!finding.fails);
3782
3783 gemini.values[0] = value("text-bison", ValueOrigin::Literal, 70);
3786 let report = run(
3787 std::slice::from_ref(&gemini),
3788 std::slice::from_ref(&option),
3789 &options("2026-10-18"),
3790 );
3791 let finding = &report.findings[0];
3792 assert_eq!(finding.provider, Table::Vertex);
3793 assert_eq!(finding.routing_class, RoutingClass::Unknown);
3794 }
3795
3796 #[test]
3797 fn summary_and_provider_dates() {
3798 let calls = [
3799 openai("gpt-4-0314", &[]),
3800 openai("gpt-4o", &[]),
3801 call(
3802 Sdk::Openai,
3803 Routing::OpenaiDirect,
3804 "client.chat.completions.create",
3805 "gpt-4o-mini",
3806 &[],
3807 11,
3808 ),
3809 ];
3810 let report = run(&calls, &[], &options("2026-10-18"));
3811 assert_eq!(report.summary.affected_calls, 3);
3812 assert_eq!(report.summary.retired, 1);
3813 assert_eq!(report.summary.retiring, 2);
3814 let next = report.summary.next_shutdown.as_ref().unwrap();
3815 assert_eq!(next.date.iso(), "2027-01-14");
3816 assert_eq!(next.days_left, 88);
3817 assert_eq!(next.calls, 2);
3818 assert_eq!(
3819 report.findings[0].status,
3820 State::Retired,
3821 "retired sorts first"
3822 );
3823 assert_eq!(report.findings[0].fix, FixKind::Manual);
3824
3825 let dates: Vec<(&str, String)> = report
3827 .data
3828 .providers
3829 .iter()
3830 .map(|p| (p.provider.as_str(), p.as_of.iso()))
3831 .collect();
3832 assert_eq!(dates[0], ("OpenAI", "2026-10-18".to_string()));
3833 assert_eq!(dates[1], ("Anthropic", "2026-10-16".to_string()));
3834 assert_eq!(report.data.as_of.iso(), "2026-10-16");
3835
3836 let json = serde_json::to_value(&report).unwrap();
3837 assert_eq!(json["version"], 1);
3838 assert_eq!(json["findings"][1]["status"], "retiring");
3839 assert_eq!(json["findings"][1]["date"], "2027-01-14");
3840 }
3841
3842 #[test]
3843 fn candidate_values_of_a_known_call_are_confirm_first() {
3844 let mut lookup = openai("gpt-4o", &["temperature"]);
3847 lookup.values.clear();
3848 let gap = UsageGap {
3849 kind: GapKind::UnresolvedModel,
3850 sdk: Some(Sdk::Openai),
3851 file: "app.py".into(),
3852 span: Some(span(10)),
3853 symbol: Some("ask".into()),
3854 chain: Some("client.chat.completions.create".into()),
3855 key: Some("model".into()),
3856 reason: "dict_lookup".into(),
3857 detail: String::new(),
3858 values: vec![
3859 value("gpt-4o-mini", ValueOrigin::Literal, 3),
3860 value("gpt-6-luna", ValueOrigin::Literal, 3),
3861 ],
3862 values_complete: true,
3863 };
3864 let missing = UsageGap {
3865 kind: GapKind::UnresolvedModel,
3866 span: Some(span(20)),
3867 key: Some("model".into()),
3868 reason: "missing_model".into(),
3869 values: Vec::new(),
3870 ..gap.clone()
3871 };
3872 let report = run(&[lookup], &[gap, missing], &options("2026-10-18"));
3873 assert_eq!(report.findings.len(), 1, "only the retiring entry matches");
3874 let finding = &report.findings[0];
3875 assert_eq!(finding.model, "gpt-4o-mini");
3876 assert!(finding.candidate);
3877 assert_eq!(finding.confidence, Confidence::ConfirmFirst);
3878 assert_eq!(
3879 finding.routing_class,
3880 RoutingClass::Direct,
3881 "the call's own routing"
3882 );
3883 assert_eq!(finding.gap_reason.as_deref(), Some("dict_lookup"));
3884 assert!(finding.decisions[0]
3886 .because
3887 .iter()
3888 .any(|b| b == "temperature"));
3889 assert_eq!(report.summary.unreadable_calls, 0);
3892 assert_eq!(report.summary.no_model_calls, 1);
3893 }
3894
3895 fn gap_at(kind: GapKind, reason: &str, line: u32, key: Option<&str>) -> UsageGap {
3897 UsageGap {
3898 kind,
3899 sdk: Some(Sdk::Openai),
3900 file: "app.py".into(),
3901 span: Some(span(line)),
3902 symbol: None,
3903 chain: Some("client.chat.completions.create".into()),
3904 key: key.map(str::to_string),
3905 reason: reason.into(),
3906 detail: String::new(),
3907 values: Vec::new(),
3908 values_complete: false,
3909 }
3910 }
3911
3912 #[test]
3913 fn every_gap_at_a_call_keeps_it_from_reading_as_confirmed() {
3914 let call = openai("gpt-3.5-turbo-0613", &[]);
3916 let clean = run(std::slice::from_ref(&call), &[], &options("2026-10-18"));
3917 assert_eq!(clean.findings[0].confidence, Confidence::Confirmed);
3918 assert_eq!(clean.exit_code, 1);
3919
3920 let mut cases: Vec<(GapKind, String)> = gaps::GAP_REASONS
3923 .iter()
3924 .map(|(kind, reason, _)| (*kind, reason.to_string()))
3925 .collect();
3926 for kind in [
3927 GapKind::UnresolvedModel,
3928 GapKind::AmbiguousClient,
3929 GapKind::UnknownClientFactory,
3930 GapKind::DynamicDispatch,
3931 GapKind::VendoredPath,
3932 ] {
3933 cases.push((kind, "a_reason_added_later".to_string()));
3934 }
3935 for (kind, reason) in &cases {
3936 let key = (*kind == GapKind::UnresolvedModel).then_some("model");
3937 let gap = gap_at(*kind, reason, 10, key);
3938 let report = run(
3939 std::slice::from_ref(&call),
3940 std::slice::from_ref(&gap),
3941 &options("2026-10-18"),
3942 );
3943 let finding = &report.findings[0];
3944 let label = format!("{kind}/{reason}");
3945 assert!(
3946 finding.confidence != Confidence::Confirmed
3947 || finding.routing_class != RoutingClass::Direct,
3948 "{label} reads as confirmed"
3949 );
3950 assert!(!finding.fails, "{label} counts toward the exit code");
3951 assert_eq!(report.exit_code, 0, "{label}");
3952 assert_eq!(finding.fix, FixKind::Manual, "{label} is never a swap");
3953 if *kind == GapKind::UnresolvedModel {
3954 assert_eq!(finding.confidence, Confidence::ConfirmFirst, "{label}");
3955 assert_eq!(finding.routing_class, RoutingClass::Direct, "{label}");
3956 assert_eq!(finding.gap_reason.as_deref(), Some(reason.as_str()));
3957 } else {
3958 assert_eq!(finding.routing_class, RoutingClass::Unknown, "{label}");
3959 assert_eq!(finding.routing_gap.as_deref(), Some(reason.as_str()));
3960 }
3961 let mut opts = options("2026-10-18");
3963 opts.count_unconfirmed = true;
3964 let counted = run(
3965 std::slice::from_ref(&call),
3966 std::slice::from_ref(&gap),
3967 &opts,
3968 );
3969 assert_eq!(counted.exit_code, 1, "{label} with --count-unconfirmed");
3970 }
3971 }
3972
3973 #[test]
3974 fn a_value_gap_holds_its_own_key_or_every_key() {
3975 let mut call = openai("gpt-3.5-turbo-0613", &["extra_body"]);
3976 let mut fallback = value("gpt-3.5-turbo-0613", ValueOrigin::Literal, 10);
3977 fallback.key = "extra_body.fallbacks.model".into();
3978 call.values.push(fallback);
3979 let confidence = |gaps: &[UsageGap]| -> Vec<(String, Confidence)> {
3980 run(std::slice::from_ref(&call), gaps, &options("2026-10-18"))
3981 .findings
3982 .iter()
3983 .map(|f| (f.key.clone(), f.confidence))
3984 .collect()
3985 };
3986 let other = gap_at(
3988 GapKind::UnresolvedModel,
3989 "env_var",
3990 10,
3991 Some("extra_body.fallbacks.model"),
3992 );
3993 let found = confidence(std::slice::from_ref(&other));
3994 assert!(found.contains(&("model".into(), Confidence::Confirmed)));
3995 assert!(found.contains(&(
3996 "extra_body.fallbacks.model".into(),
3997 Confidence::ConfirmFirst
3998 )));
3999 let truncated = gap_at(GapKind::UnresolvedModel, "truncated", 10, None);
4002 assert!(confidence(&[truncated])
4003 .iter()
4004 .all(|(_, c)| *c == Confidence::ConfirmFirst));
4005 }
4006
4007 #[test]
4008 fn unanalyzed_parts_and_untracked_methods_are_counted() {
4009 let region = UsageGap {
4012 sdk: None,
4013 chain: None,
4014 ..gap_at(GapKind::UnresolvedModel, "truncated", 30, None)
4015 };
4016 let dispatch = gap_at(GapKind::DynamicDispatch, "getattr", 40, None);
4017 let report = run(&[], &[region, dispatch], &options("2026-10-18"));
4018 assert_eq!(report.summary.not_analyzed, 1);
4019 assert_eq!(report.summary.untracked_methods, 1);
4020 assert!(report.unreadable.is_empty());
4021 assert_eq!(report.exit_code, 0);
4022 }
4023
4024 const GAP_FIXTURES: &[(&str, &str)] = &[
4027 (
4028 "value_gaps.py",
4029 r#"import functools
4030import os
4031
4032from openai import OpenAI
4033
4034client = OpenAI()
4035
4036
4037class Bot:
4038 MODEL = "gpt-4o"
4039
4040 def run(self):
4041 return client.chat.completions.create(model=self.MODEL, messages=[])
4042
4043
4044def ask(model="gpt-4o"):
4045 return client.chat.completions.create(model=model, messages=[])
4046
4047
4048@functools.lru_cache
4049def cached(model="gpt-4o"):
4050 return client.chat.completions.create(model=model, messages=[])
4051
4052
4053def _private(model="gpt-4o"):
4054 return client.chat.completions.create(model=model, messages=[])
4055
4056
4057_private("gpt-4o-mini")
4058
4059
4060def env_fallback():
4061 return client.chat.completions.create(model=os.getenv("MODEL", "gpt-4o"), messages=[])
4062
4063
4064def splatted(overrides):
4065 return client.chat.completions.create(**{"model": "gpt-4o", **overrides}, messages=[])
4066
4067
4068def no_model():
4069 return client.chat.completions.create(messages=[])
4070"#,
4071 ),
4072 (
4073 "dynamic_value.py",
4074 r#"from openai import OpenAI
4075
4076MODEL = "gpt-4o"
4077client = OpenAI()
4078exec("MODEL = 'gpt-6-luna'")
4079
4080
4081def run():
4082 return client.chat.completions.create(model=MODEL, messages=[])
4083
4084
4085def literal():
4086 return client.chat.completions.create(model="gpt-4o", messages=[])
4087"#,
4088 ),
4089 (
4090 "module_config.py",
4091 r#"import openai
4092
4093
4094def legacy():
4095 return openai.ChatCompletion.create(engine="gpt-4o", messages=[])
4096"#,
4097 ),
4098 (
4099 "endpoint_env.py",
4100 r#"import os
4101
4102from openai import OpenAI
4103
4104os.environ["OPENAI_BASE_URL"] = "http://localhost:4000"
4105client = OpenAI()
4106
4107
4108def run():
4109 return client.chat.completions.create(model="gpt-4o", messages=[])
4110"#,
4111 ),
4112 (
4113 "base_url_env.py",
4114 r#"import os
4115
4116from openai import OpenAI
4117
4118client = OpenAI(base_url=os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1"))
4119other = OpenAI(base_url=os.environ.get("OPENAI_BASE_URL"))
4120
4121
4122def run():
4123 return client.chat.completions.create(model="gpt-4o", messages=[])
4124
4125
4126def run_env_only():
4127 return other.chat.completions.create(model="gpt-4o", messages=[])
4128"#,
4129 ),
4130 (
4131 "endpoint_option.py",
4132 r#"from google import genai
4133
4134client = genai.Client(http_options={"base_url": "https://example.invalid"})
4135
4136
4137def run():
4138 return client.models.generate_content(model="gemini-2.0-flash", contents="hi")
4139"#,
4140 ),
4141 (
4142 "routing_gaps.py",
4143 r#"import random
4144
4145from openai import AzureOpenAI, OpenAI
4146
4147
4148def make():
4149 return OpenAI()
4150
4151
4152plain = OpenAI()
4153either = OpenAI() if random.random() > 0.5 else AzureOpenAI()
4154moved = OpenAI()
4155moved.base_url = "http://localhost:4000"
4156unread = OpenAI(base_url=random.choice(["a", "b"]))
4157made = make()
4158
4159
4160def branch():
4161 return either.chat.completions.create(model="gpt-4o", messages=[])
4162
4163
4164def assigned():
4165 return moved.chat.completions.create(model="gpt-4o", messages=[])
4166
4167
4168def unresolved():
4169 return unread.chat.completions.create(model="gpt-4o", messages=[])
4170
4171
4172def factory():
4173 return made.chat.completions.create(model="gpt-4o", messages=[])
4174
4175
4176def dispatch():
4177 return getattr(plain.chat.completions, "create")(model="gpt-4o", messages=[])
4178
4179
4180def send(c=plain):
4181 return c.chat.completions.create(model="gpt-4o", messages=[])
4182
4183
4184def _helper(c):
4185 return c.chat.completions.create(model="gpt-4o", messages=[])
4186
4187
4188_helper(plain)
4189"#,
4190 ),
4191 ];
4192
4193 fn python_files(
4195 root: &std::path::Path,
4196 dir: &std::path::Path,
4197 out: &mut Vec<(String, String)>,
4198 ) {
4199 let mut entries: Vec<_> = std::fs::read_dir(dir)
4200 .unwrap_or_else(|e| panic!("cannot read {}: {e}", dir.display()))
4201 .map(|e| e.unwrap().path())
4202 .collect();
4203 entries.sort();
4204 for path in entries {
4205 if path.is_dir() {
4206 python_files(root, &path, out);
4207 } else if path.extension().is_some_and(|e| e == "py") {
4208 let name = path
4209 .strip_prefix(root)
4210 .unwrap()
4211 .to_string_lossy()
4212 .replace('\\', "/");
4213 out.push((name, std::fs::read_to_string(&path).unwrap()));
4214 }
4215 }
4216 }
4217
4218 #[test]
4219 fn no_gap_from_the_usage_scan_reads_as_confirmed() {
4220 let mut files: Vec<(String, String)> = GAP_FIXTURES
4224 .iter()
4225 .map(|(name, source)| (name.to_string(), source.to_string()))
4226 .collect();
4227 let mut deep = r#"client.chat.completions.create(model="gpt-4o", messages=[])"#.to_string();
4228 for _ in 0..70 {
4229 deep = format!("(lambda: {deep})");
4230 }
4231 files.push((
4232 "truncated_scopes.py".into(),
4233 format!(
4234 "from openai import OpenAI\n\nclient = OpenAI()\n\ndeep = {deep}\n\n\ndef shallow():\n return client.chat.completions.create(model=\"gpt-4o\", messages=[])\n"
4235 ),
4236 ));
4237 let fallbacks = vec![r#"{"model": "gpt-4o"}"#; 40].join(", ");
4238 files.push((
4239 "truncated_values.py".into(),
4240 format!(
4241 "from openai import OpenAI\n\nclient = OpenAI()\n\n\ndef run():\n return client.chat.completions.create(model=\"gpt-4o\", messages=[], extra_body={{\"fallbacks\": [{fallbacks}]}})\n"
4242 ),
4243 ));
4244 let corpus = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../eval/corpus");
4245 let mut corpora = 0;
4246 for entry in std::fs::read_dir(&corpus).expect("the eval corpus is in the workspace") {
4247 let path = entry.unwrap().path();
4248 if path
4249 .file_name()
4250 .is_some_and(|n| n.to_string_lossy().starts_with("py-sdk-"))
4251 {
4252 corpora += 1;
4253 python_files(&corpus, &path, &mut files);
4254 }
4255 }
4256 assert!(corpora >= 4, "the SDK eval corpora moved");
4257
4258 let mut parser = tree_sitter::Parser::new();
4259 parser
4260 .set_language(&tree_sitter_python::language())
4261 .unwrap();
4262 let (mut calls, mut gaps_found, mut clients) = (Vec::new(), Vec::new(), Vec::new());
4263 for (name, source) in &files {
4264 let tree = parser.parse(source, None).unwrap();
4265 let found = crate::usages::python::extract(&tree, source, name);
4266 calls.extend(found.calls);
4267 gaps_found.extend(found.gaps);
4268 clients.extend(found.clients);
4269 }
4270
4271 let seen: BTreeSet<(GapKind, &str)> = gaps_found
4273 .iter()
4274 .map(|g| (g.kind, g.reason.as_str()))
4275 .collect();
4276 for (kind, reason) in &seen {
4277 assert!(
4278 gaps::gap_text(*kind, reason).is_some(),
4279 "the usage scan gave a {kind} gap with reason `{reason}`, which GAP_REASONS does not name"
4280 );
4281 }
4282 let reasons: BTreeSet<&str> = seen.iter().map(|(_, r)| *r).collect();
4284 for needed in [
4285 "dynamic_feature",
4286 "subclass_override",
4287 "module_config",
4288 "endpoint_option",
4289 "endpoint_env",
4290 "base_url_env",
4291 "base_url_unresolved",
4292 "base_url_assigned",
4293 "multiple_assignments",
4294 "in_file_callers",
4295 "splat",
4296 "unseen_callers",
4297 "parameter_default",
4298 "parameter_overridden",
4299 "missing_model",
4300 "truncated",
4301 "env_var",
4302 "factory_call",
4303 "getattr",
4304 ] {
4305 assert!(reasons.contains(needed), "no fixture gives `{needed}`");
4306 }
4307
4308 let opts = CheckOptions {
4309 today: Date::parse("2026-10-20").unwrap(),
4310 fail_within: Some(36_500),
4311 include_routed: true,
4312 count_unconfirmed: false,
4313 };
4314 let input = ScanInput {
4315 calls: &calls,
4316 gaps: &gaps_found,
4317 clients: &clients,
4318 };
4319 let report = check(input, bundled().unwrap(), &opts);
4320 assert!(report.findings.len() > 50, "{}", report.findings.len());
4321 let mut held = 0;
4322 for finding in report.findings.iter().chain(&report.routed) {
4323 let here: Vec<&UsageGap> = gaps_found
4324 .iter()
4325 .filter(|g| {
4326 g.file == finding.file
4327 && g.chain.is_some()
4328 && g.span
4329 .is_some_and(|s| s.line == finding.line && s.column == finding.column)
4330 })
4331 .collect();
4332 let value_gap = here.iter().any(|g| gaps::holds_value(g, &finding.key));
4333 let routing_gap = here.iter().any(|g| gaps::holds_routing(g));
4334 let at = format!("{}:{} {}", finding.file, finding.line, finding.model);
4335 if value_gap {
4336 assert_ne!(finding.confidence, Confidence::Confirmed, "{at}");
4337 }
4338 if routing_gap {
4339 assert_ne!(finding.routing_class, RoutingClass::Direct, "{at}");
4340 }
4341 if value_gap || routing_gap {
4342 held += 1;
4343 assert!(!finding.fails, "{at} counts toward the exit code");
4344 assert_ne!(finding.fix, FixKind::Swap, "{at}");
4345 assert_ne!(finding.fix, FixKind::Decide, "{at}");
4346 }
4347 }
4348 assert!(held >= 30, "only {held} findings had a gap at their call");
4349 assert_eq!(report.summary.not_analyzed, 1, "the nested scopes");
4350 assert!(report.summary.untracked_methods >= 1, "the getattr call");
4351 }
4352
4353 #[test]
4354 fn python_literals() {
4355 assert_eq!(python_literal(&serde_json::json!("none")), "\"none\"");
4356 assert_eq!(
4357 python_literal(&serde_json::json!({"type": "between_tools"})),
4358 "{\"type\": \"between_tools\"}"
4359 );
4360 assert_eq!(
4361 python_literal(&serde_json::json!([true, null, 2])),
4362 "[True, None, 2]"
4363 );
4364 }
4365}