返回 CodeWhale
candidate.rs
根目录 / crates / config / src / route / candidate.rs
1 //! The runtime-resolved executable route (#3384).
2 //!
3 //! A [`ReadyRouteCandidate`] is the concrete form of the #2608 contract:
4 //!
5 //! > Execution requires a `ReadyRouteCandidate`.
6 //! > A `ReadyRouteCandidate` can only be produced by `RouteResolver`.
7 //!
8 //! Fields are private and exposed only through read-only getters, so the type
9 //! can neither be *constructed* nor *mutated* outside this crate, and it
10 //! deliberately does not derive `Deserialize` (so it cannot be fabricated from
11 //! JSON either). The only constructor is `ReadyRouteCandidate::new`
12 //! (`pub(super)`), and [`super::resolver::RouteResolver::resolve`] is its sole
13 //! caller. A candidate's existence is therefore proof it passed the resolver,
14 //! and a candidate's limits are therefore exactly what the resolver produced
15 //! (including any [`SourcedLimitOverride`]s recorded on it).
16 //!
17 //! The route-owned, three-state capability profile lives in this crate and is
18 //! carried on the candidate. A full `config_snapshot: Config` remains deferred
19 //! because embedding it would couple the candidate to the full config model.
20
21 use serde::{Deserialize, Serialize};
22
23 use super::RequestProtocol;
24 use super::capabilities::RouteCapabilities;
25 use super::ids::{LogicalModelRef, ModelId, ProviderId, WireModelId};
26 use super::offering::RouteLimits;
27 use crate::ProviderKind;
28 use crate::responses_dialect::ResponsesProfileId;
29
30 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
31 pub struct CatalogConnection {
32 pub binding: String,
33 pub identity: String,
34 pub base_url: String,
35 }
36
37 /// A concrete, resolved endpoint the route will talk to.
38 #[derive(Debug, Clone, Serialize, Deserialize)]
39 pub struct ResolvedEndpoint {
40 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub catalog_connection: Option<CatalogConnection>,
42 /// Resolved base URL (after any override).
43 pub base_url: String,
44 /// Endpoint key (e.g. `"chat"`, `"responses"`).
45 pub endpoint_key: String,
46 /// Wire protocol spoken at this endpoint.
47 pub protocol: RequestProtocol,
48 }
49
50 /// The CLASS of auth source resolved for the route.
51 ///
52 /// This records only *where* a credential comes from, never the credential
53 /// value itself. There is intentionally no field that could hold a secret.
54 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
55 #[serde(rename_all = "snake_case")]
56 pub enum ResolvedAuthSource {
57 /// Supplied via CLI flag/argument.
58 Cli,
59 /// Read from a config file.
60 ConfigFile,
61 /// Read from the OS keyring.
62 Keyring,
63 /// Read from an environment variable.
64 Env,
65 /// Produced by running a command.
66 Command,
67 /// Resolved from a named secret.
68 Secret,
69 /// No credential resolved.
70 Missing,
71 /// Auth resolution has not been performed for this candidate.
72 ///
73 /// The route resolver never inspects credentials, so a freshly resolved
74 /// candidate honestly reports `Unresolved` rather than claiming `Missing`
75 /// (which would assert a lookup that never happened).
76 Unresolved,
77 }
78
79 /// Which token limit a [`SourcedLimitOverride`] targets.
80 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
81 #[serde(rename_all = "snake_case")]
82 pub enum LimitField {
83 /// [`RouteLimits::context_tokens`](super::offering::RouteLimits).
84 ContextTokens,
85 /// [`RouteLimits::input_tokens`](super::offering::RouteLimits).
86 InputTokens,
87 /// [`RouteLimits::output_tokens`](super::offering::RouteLimits).
88 OutputTokens,
89 }
90
91 /// Why a limit override was requested.
92 ///
93 /// This is provenance, not policy: the resolver applies whatever the caller
94 /// requested and records the source on the candidate so every consumer can see
95 /// where an effective limit came from.
96 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
97 #[serde(rename_all = "snake_case")]
98 pub enum OverrideSource {
99 /// Operator-configured context window.
100 UserContextWindow,
101 /// Operator-configured context window for one exact wire model id
102 /// (`[providers.<id>.model_context_windows]`, #6108).
103 UserModelContextWindow,
104 /// Limits declared by the operator for an exact model and endpoint.
105 UserModelMetadata,
106 /// Catalog limits describe the public API offering, not the account-scoped
107 /// Codex route; the API-only limits are stripped.
108 CodexPublicApiLimitStrip,
109 /// Per-model context from the fresh Codex account roster.
110 CodexRosterCorrection,
111 /// Fresh, route-scoped provider-reported context metadata.
112 ProviderReportedContextWindow,
113 /// Conservative all-plan safe floor for a membership-plan route.
114 MembershipPlanSafeFloor,
115 /// Maximum output documented for one exact provider endpoint/model route.
116 DocumentedRouteOutputMaximum,
117 }
118
119 /// One sourced limit override, applied by the resolver BEFORE the candidate is
120 /// constructed and recorded on the candidate as provenance.
121 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
122 pub struct SourcedLimitOverride {
123 /// The limit field to override.
124 pub field: LimitField,
125 /// The value to set (`None` clears the limit to "unknown").
126 pub value: Option<u64>,
127 /// Why the override was requested.
128 pub source: OverrideSource,
129 }
130
131 /// Pricing/quota class for the resolved route.
132 ///
133 /// Carries only coarse, non-sensitive shape; never secrets or account ids.
134 ///
135 /// `PartialEq` (but not `Eq`: the `Token` rates are `f64`) lets offerings and
136 /// candidates be compared in tests and lets
137 /// [`super::offering::ProviderModelOffering`] carry a pricing meter.
138 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
139 #[serde(rename_all = "snake_case")]
140 pub enum PricingSku {
141 /// Per-token pricing.
142 Token {
143 /// Input price per million tokens, if known.
144 input_per_mtok: Option<f64>,
145 /// Output price per million tokens, if known.
146 output_per_mtok: Option<f64>,
147 },
148 /// Subscription quota usage.
149 SubscriptionQuota {
150 /// Percent of quota used, if known.
151 used_pct: Option<f32>,
152 /// When the quota resets, if known.
153 resets_at: Option<String>,
154 },
155 /// Prepaid account credits.
156 AccountCredits {
157 /// Remaining balance, if known.
158 balance: Option<f64>,
159 },
160 /// Local or otherwise not billed.
161 LocalOrNotApplicable,
162 /// Pricing unknown or stale.
163 UnknownOrStale,
164 }
165
166 /// Outcome of route validation.
167 #[derive(Debug, Clone, Serialize, Deserialize)]
168 pub struct ValidationReport {
169 /// Whether the route passed validation.
170 pub ok: bool,
171 /// Human-readable diagnostics (advisory; secret-free).
172 pub messages: Vec<String>,
173 }
174
175 /// A runtime-resolved, executable route.
176 ///
177 /// The candidate is IMMUTABLE once minted: every field is private and exposed
178 /// only through read-only getters, the type cannot be constructed outside this
179 /// crate (private fields + no `Deserialize`), and there are no setters. The
180 /// only constructor is `Self::new`, which is `pub(super)`; see module docs.
181 /// Post-resolution limit adjustments must instead be requested up front via
182 /// [`super::resolver::RouteRequest::limit_overrides`], which the resolver
183 /// applies BEFORE construction and records in [`Self::applied_limit_overrides`].
184 ///
185 /// Immutability is compile-time enforced — this does not build:
186 ///
187 /// ```compile_fail
188 /// use codewhale_config::route::{RouteRequest, RouteResolver};
189 ///
190 /// let mut candidate = RouteResolver::new()
191 /// .resolve(&RouteRequest::default())
192 /// .unwrap();
193 /// // ERROR: field `limits` of `ReadyRouteCandidate` is private
194 /// candidate.limits.context_tokens = Some(1);
195 /// ```
196 #[derive(Debug, Clone, Serialize)]
197 #[non_exhaustive]
198 pub struct ReadyRouteCandidate {
199 /// Resolved provider id.
200 provider_id: ProviderId,
201 /// Resolved provider kind.
202 provider_kind: ProviderKind,
203 /// The selector the user/route requested.
204 logical_model: LogicalModelRef,
205 /// Canonical model identity, if one was resolved.
206 canonical_model: Option<ModelId>,
207 /// Provider-owned wire id put on the request.
208 wire_model_id: WireModelId,
209 /// Resolved endpoint transport facts.
210 endpoint: ResolvedEndpoint,
211 /// Resolved auth source CLASS (never a secret value).
212 auth: ResolvedAuthSource,
213 /// Selected wire protocol.
214 protocol: RequestProtocol,
215 /// Responses dialect selected after the protocol is known.
216 /// Absent for every non-Responses route.
217 #[serde(skip_serializing_if = "Option::is_none")]
218 responses_profile_id: Option<ResponsesProfileId>,
219 /// Route/offering-scoped token limits, when known (overrides applied).
220 limits: RouteLimits,
221 /// Capability facts for the exact provider/model offering.
222 capabilities: RouteCapabilities,
223 /// Pricing/quota class, if known.
224 pricing: Option<PricingSku>,
225 /// Validation outcome.
226 validation: ValidationReport,
227 /// Provenance of every limit override applied at resolution time.
228 #[serde(skip_serializing_if = "Vec::is_empty")]
229 applied_limit_overrides: Vec<SourcedLimitOverride>,
230 }
231
232 impl ReadyRouteCandidate {
233 /// Mint a candidate. Restricted to [`super::resolver`] so the resolver is
234 /// the sole producer of executable routes (the #2608 mutation gate).
235 #[allow(clippy::too_many_arguments)]
236 pub(super) fn new(
237 provider_id: ProviderId,
238 provider_kind: ProviderKind,
239 logical_model: LogicalModelRef,
240 canonical_model: Option<ModelId>,
241 wire_model_id: WireModelId,
242 endpoint: ResolvedEndpoint,
243 auth: ResolvedAuthSource,
244 protocol: RequestProtocol,
245 responses_profile_id: Option<ResponsesProfileId>,
246 limits: RouteLimits,
247 capabilities: RouteCapabilities,
248 pricing: Option<PricingSku>,
249 validation: ValidationReport,
250 applied_limit_overrides: Vec<SourcedLimitOverride>,
251 ) -> Self {
252 assert_eq!(
253 protocol == RequestProtocol::Responses,
254 responses_profile_id.is_some(),
255 "a responses route carries a profile id and other routes do not"
256 );
257 Self {
258 provider_id,
259 provider_kind,
260 logical_model,
261 canonical_model,
262 wire_model_id,
263 endpoint,
264 auth,
265 protocol,
266 responses_profile_id,
267 limits,
268 capabilities,
269 pricing,
270 validation,
271 applied_limit_overrides,
272 }
273 }
274
275 /// Resolved provider id.
276 #[must_use]
277 pub fn provider_id(&self) -> &ProviderId {
278 &self.provider_id
279 }
280
281 /// Resolved provider kind.
282 #[must_use]
283 pub fn provider_kind(&self) -> ProviderKind {
284 self.provider_kind
285 }
286
287 /// The selector the user/route requested.
288 #[must_use]
289 pub fn logical_model(&self) -> &LogicalModelRef {
290 &self.logical_model
291 }
292
293 /// Canonical model identity, if one was resolved.
294 #[must_use]
295 pub fn canonical_model(&self) -> Option<&ModelId> {
296 self.canonical_model.as_ref()
297 }
298
299 /// Provider-owned wire id put on the request.
300 #[must_use]
301 pub fn wire_model_id(&self) -> &WireModelId {
302 &self.wire_model_id
303 }
304
305 /// Resolved endpoint transport facts.
306 #[must_use]
307 pub fn endpoint(&self) -> &ResolvedEndpoint {
308 &self.endpoint
309 }
310
311 /// Resolved auth source CLASS (never a secret value).
312 #[must_use]
313 pub fn auth(&self) -> &ResolvedAuthSource {
314 &self.auth
315 }
316
317 /// Selected wire protocol.
318 #[must_use]
319 pub fn protocol(&self) -> RequestProtocol {
320 self.protocol
321 }
322
323 /// Responses dialect id, present exactly when the protocol is Responses.
324 #[must_use]
325 pub fn responses_profile_id(&self) -> Option<ResponsesProfileId> {
326 self.responses_profile_id
327 }
328
329 /// Route/offering-scoped token limits, when known (overrides applied).
330 #[must_use]
331 pub fn limits(&self) -> RouteLimits {
332 self.limits
333 }
334
335 /// Capability facts for the exact provider/model offering.
336 #[must_use]
337 pub fn capabilities(&self) -> RouteCapabilities {
338 self.capabilities
339 }
340
341 /// Pricing/quota class, if known.
342 #[must_use]
343 pub fn pricing(&self) -> Option<&PricingSku> {
344 self.pricing.as_ref()
345 }
346
347 /// Validation outcome.
348 #[must_use]
349 pub fn validation(&self) -> &ValidationReport {
350 &self.validation
351 }
352
353 /// Provenance of every limit override applied at resolution time.
354 #[must_use]
355 pub fn applied_limit_overrides(&self) -> &[SourcedLimitOverride] {
356 &self.applied_limit_overrides
357 }
358 }
359
359 lines RUST