返回 CodeWhale
corrections.rs
根目录 / crates / config / src / catalog / corrections.rs
1 //! Codewhale's corrections to Models.dev rows (#6396).
2 //!
3 //! Some Models.dev facts are true but misleading for a Codewhale route: a flat
4 //! price for a plan that bills quota, a base rate that doubles past a prompt
5 //! size, an output limit the provider publishes differently. These used to be
6 //! hand edits to the offline seed, so they held only until the first live
7 //! refresh replaced the row. Here they are field patches applied to every
8 //! Models.dev row as it is hydrated, bundled seed and live refresh alike, so a
9 //! correction means the same thing on every install.
10 //!
11 //! Corrections rank above bundled and live Models.dev and below signed cloud
12 //! facts (which may correct a correction) and provider rosters. A corrected
13 //! row keeps its own source, so layer code that sorts rows by source still
14 //! places it correctly; a price the correction owns (set or withheld) is
15 //! attributed to [`CatalogSource::CodewhaleBundled`] through `cost_source`.
16 //! It reuses the signed layer's [`ModelFact`] shape and patch code, so there
17 //! is one way to correct a catalog row. Corrections never add a row and never
18 //! hide one.
19
20 use std::collections::BTreeMap;
21 use std::sync::OnceLock;
22
23 use serde::Deserialize;
24
25 use super::{CatalogOffering, CatalogSource};
26 use crate::cloud_facts::catalog_patch::apply_patches;
27 use crate::cloud_facts::{ModelFact, ModelOp};
28
29 /// The committed corrections asset.
30 pub const CATALOG_CORRECTIONS_JSON: &str = include_str!("../../assets/catalog_corrections.json");
31
32 /// Parsed corrections.
33 #[derive(Debug, Clone, PartialEq, Deserialize)]
34 #[serde(deny_unknown_fields)]
35 pub struct CatalogCorrections {
36 #[serde(default, rename = "_about")]
37 pub about: String,
38 /// Stamped as [`CatalogSource::CodewhaleBundled`] on prices it owns.
39 pub revision: String,
40 /// Pure reviewed model/transport data. This file is its only owner; the
41 /// bundled seed carries no copy.
42 #[serde(default)]
43 pub reviewed: super::reviewed::ReviewedCatalog,
44 /// Rules for every row a provider serves.
45 #[serde(default)]
46 pub providers: Vec<ProviderCorrection>,
47 /// Rules for one `(provider, wire id)` row.
48 #[serde(default)]
49 pub models: Vec<ModelCorrection>,
50 }
51
52 /// A rule for every row of one provider.
53 #[derive(Debug, Clone, PartialEq, Deserialize)]
54 #[serde(deny_unknown_fields)]
55 pub struct ProviderCorrection {
56 pub provider: String,
57 /// Why no price is shown for any of this provider's rows.
58 pub pricing_withheld: String,
59 }
60
61 /// A field patch for one row, with the reason it exists.
62 #[derive(Debug, Clone, PartialEq, Deserialize)]
63 pub struct ModelCorrection {
64 /// Why the patch exists. Required unless the patch only withholds pricing
65 /// (whose text is its own reason).
66 #[serde(default)]
67 pub reason: Option<String>,
68 #[serde(flatten)]
69 pub fact: ModelFact,
70 }
71
72 impl CatalogCorrections {
73 /// Parse and validate a corrections document.
74 ///
75 /// # Errors
76 /// Returns a message naming the first entry that is malformed or does more
77 /// than a correction may (hide, deprecate, annotate, or add a row).
78 pub fn parse(json: &str) -> Result<Self, String> {
79 let corrections: Self = serde_json::from_str(json).map_err(|err| err.to_string())?;
80 corrections.validate()?;
81 Ok(corrections)
82 }
83
84 fn validate(&self) -> Result<(), String> {
85 if self.revision.trim().is_empty() {
86 return Err("revision must be set".into());
87 }
88 self.reviewed.validate()?;
89 for rule in &self.providers {
90 if rule.provider.trim().is_empty() || rule.pricing_withheld.trim().is_empty() {
91 return Err("provider rules need a provider and a reason".into());
92 }
93 }
94 for correction in &self.models {
95 let fact = &correction.fact;
96 let name = format!("{}/{}", fact.provider, fact.id);
97 if fact.provider.trim().is_empty() || fact.id.trim().is_empty() {
98 return Err(format!("{name}: provider and id are required"));
99 }
100 if fact.op != ModelOp::Upsert || fact.allow_unlisted {
101 return Err(format!("{name}: a correction may only patch a listed row"));
102 }
103 if fact.display_name.is_some()
104 || fact.note.is_some()
105 || fact.deprecated_at.is_some()
106 || fact.replacement.is_some()
107 || fact.applies_to.is_some()
108 {
109 return Err(format!("{name}: a correction changes facts, not labels"));
110 }
111 if fact.pricing.is_some() && fact.pricing_withheld.is_some() {
112 return Err(format!("{name}: sets a price and withholds it"));
113 }
114 let patches_more_than_price = fact.context_window.is_some()
115 || fact.max_output.is_some()
116 || fact.pricing.is_some()
117 || fact.reasoning.is_some()
118 || fact.reasoning_options.is_some();
119 if !patches_more_than_price && fact.pricing_withheld.is_none() {
120 return Err(format!("{name}: changes nothing"));
121 }
122 if patches_more_than_price
123 && correction
124 .reason
125 .as_deref()
126 .is_none_or(|reason| reason.trim().is_empty())
127 {
128 return Err(format!("{name}: needs a reason"));
129 }
130 }
131 Ok(())
132 }
133
134 /// Validate committed referents against the seed, not a partial live refresh.
135 fn validate_targets(&self, seed: &[CatalogOffering]) -> Result<(), String> {
136 for rule in &self.providers {
137 if !seed.iter().any(|row| row.provider == rule.provider) {
138 return Err(format!(
139 "{}: correction provider missing from bundled seed",
140 rule.provider
141 ));
142 }
143 }
144 for correction in &self.models {
145 let fact = &correction.fact;
146 if !seed
147 .iter()
148 .any(|row| row.provider == fact.provider && row.wire_model_id == fact.id)
149 {
150 return Err(format!(
151 "{}/{}: correction model missing from bundled seed",
152 fact.provider, fact.id
153 ));
154 }
155 }
156 Ok(())
157 }
158
159 /// Apply every correction to the rows it names, in place.
160 ///
161 /// Provider rules run first, then per-row patches, so a row patch can add
162 /// to a provider rule (a DeepSeek output limit on top of its withheld
163 /// price). Rows no rule names are untouched. Live refreshes may omit
164 /// correction targets; only the committed seed must contain every target.
165 pub fn apply_to(&self, rows: &mut [CatalogOffering]) {
166 let mut patches: BTreeMap<(String, String), Vec<ModelFact>> = BTreeMap::new();
167 for rule in &self.providers {
168 for row in rows.iter().filter(|row| row.provider == rule.provider) {
169 patches
170 .entry((row.provider.clone(), row.wire_model_id.clone()))
171 .or_default()
172 .push(ModelFact {
173 provider: row.provider.clone(),
174 id: row.wire_model_id.clone(),
175 pricing_withheld: Some(rule.pricing_withheld.clone()),
176 ..ModelFact::default()
177 });
178 }
179 }
180 for correction in &self.models {
181 patches
182 .entry((correction.fact.provider.clone(), correction.fact.id.clone()))
183 .or_default()
184 .push(correction.fact.clone());
185 }
186 if patches.is_empty() {
187 return;
188 }
189 let source = CatalogSource::CodewhaleBundled {
190 revision: self.revision.clone(),
191 };
192 for row in rows.iter_mut() {
193 let key = (row.provider.clone(), row.wire_model_id.clone());
194 let Some(row_patches) = patches.get(&key) else {
195 continue;
196 };
197 // The row stays on its own layer: a hydrated row is classified by
198 // its source (a live Models.dev row must stay below signed facts),
199 // so only the price a correction owns is attributed to it.
200 let origin = row.source.clone();
201 let modalities_source = row.modalities_source.clone();
202 let cost_source = row.cost_source.clone();
203 let mut single = BTreeMap::from([(key.clone(), std::mem::take(row))]);
204 apply_patches(&mut single, row_patches, &source, false);
205 if let Some(mut patched) = single.remove(&key) {
206 patched.source = origin;
207 patched.modalities_source = modalities_source;
208 if !row_patches.iter().any(owns_price) {
209 patched.cost_source = cost_source;
210 }
211 *row = patched;
212 }
213 }
214 }
215 }
216
217 fn owns_price(fact: &ModelFact) -> bool {
218 fact.pricing.is_some() || fact.pricing_withheld.is_some()
219 }
220
221 /// The committed corrections, parsed once.
222 ///
223 /// # Panics
224 /// Panics if the committed asset is invalid or names a missing seed target.
225 #[must_use]
226 pub fn bundled_corrections() -> &'static CatalogCorrections {
227 static CORRECTIONS: OnceLock<CatalogCorrections> = OnceLock::new();
228 CORRECTIONS.get_or_init(|| {
229 let corrections = CatalogCorrections::parse(CATALOG_CORRECTIONS_JSON)
230 .expect("committed catalog corrections must be valid");
231 let seed = super::bundled_offerings_from_models_dev(super::bundled_models_dev_catalog());
232 corrections
233 .validate_targets(&seed)
234 .expect("committed catalog correction targets must exist");
235 corrections
236 })
237 }
238
239 #[cfg(test)]
240 mod tests {
241 use super::*;
242
243 #[test]
244 fn missing_seed_targets_fail_validation_but_partial_live_refreshes_are_allowed() {
245 let corrections = bundled_corrections();
246 let seed = super::super::bundled_offerings_from_models_dev(
247 super::super::bundled_models_dev_catalog(),
248 );
249 let provider = &corrections.providers[0].provider;
250 let without_provider: Vec<_> = seed
251 .iter()
252 .filter(|row| &row.provider != provider)
253 .cloned()
254 .collect();
255 let error = corrections.validate_targets(&without_provider).unwrap_err();
256 assert!(error.contains(provider), "{error}");
257
258 let target = &corrections.models[0].fact;
259 let mut without_model = seed;
260 without_model
261 .retain(|row| row.provider != target.provider || row.wire_model_id != target.id);
262 let error = corrections.validate_targets(&without_model).unwrap_err();
263 assert!(
264 error.contains(&format!("{}/{}", target.provider, target.id)),
265 "{error}"
266 );
267
268 // Absence from a live refresh does not invalidate committed corrections
269 // or invent a row to patch.
270 corrections.apply_to(&mut without_model);
271 assert!(
272 !without_model
273 .iter()
274 .any(|row| row.provider == target.provider && row.wire_model_id == target.id)
275 );
276 corrections.apply_to(&mut []);
277 }
278 }
279
279 lines RUST