wyrd-spec 0.1.1

Wyrd foundation types: Card envelope, SpecKinds, and pure data contracts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
//! Tenant fallback, governance, and capture policy contracts.

use std::collections::{BTreeSet, HashSet};
use std::num::NonZeroU64;

use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use super::{
    CurrencyCode, GatewayContractError, GatewayDecimal, GatewayOperation, ModelRef, validate_text,
};
use crate::auth::PrincipalId;
use crate::ids::{ProviderDeploymentName, RoleName};

/// Where one fallback rule applies.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum FallbackScope {
    /// Every call without a more specific rule.
    Global,
    /// Calls for one operation.
    Operation {
        /// Operation the rule applies to.
        operation: GatewayOperation,
    },
    /// Calls for one exact requested model.
    Model {
        /// Requested model the rule applies to.
        model: ModelRef,
    },
}

/// Ordered fallback candidates for one scope.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct FallbackRule {
    /// Scope the rule applies to.
    pub scope: FallbackScope,
    /// Non-empty, ordered, duplicate-free candidates.
    pub candidates: Vec<ModelRef>,
}

/// Tenant fallback policy; at most one rule per scope, rules never merge.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct GatewayFallbackPolicy {
    /// Scoped rules.
    pub rules: Vec<FallbackRule>,
}

impl GatewayFallbackPolicy {
    /// Rejects duplicate scopes, empty or duplicated candidate lists, and a
    /// model-scoped rule that lists its own model.
    ///
    /// # Errors
    ///
    /// Returns [`GatewayContractError`] naming `rules[i]` or
    /// `rules[i].candidates` for the first violation.
    pub fn validate(&self) -> Result<(), GatewayContractError> {
        let mut scopes = HashSet::new();
        for (index, rule) in self.rules.iter().enumerate() {
            if !scopes.insert(&rule.scope) {
                return Err(GatewayContractError::new(
                    format!("rules[{index}].scope"),
                    "at most one rule may exist for each scope",
                ));
            }
            let field = format!("rules[{index}].candidates");
            validate_candidates(&field, &rule.candidates)?;
            if let FallbackScope::Model { model } = &rule.scope
                && rule.candidates.contains(model)
            {
                return Err(GatewayContractError::new(
                    field,
                    "a model-scoped rule cannot list its own model",
                ));
            }
        }
        Ok(())
    }
}

/// Per-request ordered fallback override.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct GatewayFallbackOverride {
    /// Non-empty, ordered, duplicate-free candidates.
    pub candidates: Vec<ModelRef>,
}

impl GatewayFallbackOverride {
    /// Rejects an empty or duplicated candidate list.
    ///
    /// This is the model-independent check; the gateway applies
    /// [`Self::validate_for`] once the requested model is known.
    ///
    /// # Errors
    ///
    /// Returns [`GatewayContractError`] for field `fallback.candidates`.
    pub fn validate(&self) -> Result<(), GatewayContractError> {
        validate_candidates("fallback.candidates", &self.candidates)
    }

    /// Rejects an empty or duplicated list, or one containing `requested`.
    ///
    /// # Errors
    ///
    /// Returns [`GatewayContractError`] for field `fallback.candidates`.
    pub fn validate_for(&self, requested: &ModelRef) -> Result<(), GatewayContractError> {
        validate_candidates("fallback.candidates", &self.candidates)?;
        if self.candidates.contains(requested) {
            return Err(GatewayContractError::new(
                "fallback.candidates",
                "an override cannot list the requested model",
            ));
        }
        Ok(())
    }

    /// Encode this override as a [`FALLBACK_HEADER`] value: unpadded
    /// base64url over its JCS UTF-8 serialization.
    ///
    /// Encoding does not check the header limits; the receiving ingress
    /// refuses an oversized value.
    ///
    /// # Errors
    ///
    /// Returns [`GatewayContractError`] for field `fallback` when the
    /// override cannot be serialized.
    pub fn to_header_value(&self) -> Result<String, GatewayContractError> {
        let json = serde_jcs::to_vec(self)
            .map_err(|_| GatewayContractError::new("fallback", "could not be serialized"))?;
        Ok(URL_SAFE_NO_PAD.encode(json))
    }

    /// Decode a [`FALLBACK_HEADER`] value and validate it for `requested`.
    ///
    /// The value must be at most [`MAX_FALLBACK_HEADER_BYTES`] of unpadded
    /// base64url decoding to at most [`MAX_FALLBACK_JSON_BYTES`] of JSON that
    /// deserializes as an override and passes [`Self::validate_for`].
    ///
    /// # Errors
    ///
    /// Returns [`GatewayContractError`] for field `fallback` when the value is
    /// oversized, not unpadded base64url, not an override document, or lists
    /// no, a repeated, or the requested model.
    pub fn from_header_value(
        value: &[u8],
        requested: &ModelRef,
    ) -> Result<Self, GatewayContractError> {
        let refuse = |reason| GatewayContractError::new("fallback", reason);
        if value.len() > MAX_FALLBACK_HEADER_BYTES {
            return Err(refuse("must be at most 8 KiB encoded"));
        }
        let json = URL_SAFE_NO_PAD
            .decode(value)
            .map_err(|_| refuse("must be unpadded base64url"))?;
        if json.len() > MAX_FALLBACK_JSON_BYTES {
            return Err(refuse("must decode to at most 4 KiB"));
        }
        let fallback: Self = serde_json::from_slice(&json)
            .map_err(|_| refuse("must be a JSON fallback override"))?;
        fallback
            .validate_for(requested)
            .map_err(|error| refuse(error.reason))?;
        Ok(fallback)
    }
}

/// Request header carrying one call's [`GatewayFallbackOverride`] to the
/// public gateway ingress; absent means tenant fallback policy applies.
pub const FALLBACK_HEADER: &str = "wyrd-gateway-fallback";

/// Largest accepted encoded [`FALLBACK_HEADER`] value, in bytes.
pub const MAX_FALLBACK_HEADER_BYTES: usize = 8 * 1024;

/// Largest accepted decoded [`FALLBACK_HEADER`] JSON, in bytes.
pub const MAX_FALLBACK_JSON_BYTES: usize = 4 * 1024;

/// Rejects an empty or duplicated fallback candidate list.
///
/// # Errors
///
/// Returns [`GatewayContractError`] naming `field`.
fn validate_candidates(field: &str, candidates: &[ModelRef]) -> Result<(), GatewayContractError> {
    if candidates.is_empty() {
        return Err(GatewayContractError::new(field, "must not be empty"));
    }
    let mut seen = HashSet::new();
    if candidates.iter().any(|candidate| !seen.insert(candidate)) {
        return Err(GatewayContractError::new(field, "must not repeat a model"));
    }
    Ok(())
}

/// Principal set a budget applies to.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum GatewayPolicySubject {
    /// The whole tenant.
    Tenant,
    /// One principal.
    Principal {
        /// Principal identity.
        principal_id: PrincipalId,
    },
    /// Every principal holding one role.
    Role {
        /// Role name.
        role_name: RoleName,
    },
}

/// Principal set a limit applies to; limits have no role subject.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum GatewayLimitSubject {
    /// The whole tenant.
    Tenant,
    /// One principal.
    Principal {
        /// Principal identity.
        principal_id: PrincipalId,
    },
}

/// Calls a limit applies to.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum GatewayPolicyTarget {
    /// Every deployment and model.
    All,
    /// Every model of one deployment.
    Deployment {
        /// Deployment name.
        deployment: ProviderDeploymentName,
    },
    /// One exact model.
    Model {
        /// Model identity.
        model: ModelRef,
    },
}

/// Rate and concurrency limit for one subject and target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct GatewayLimit {
    /// Limited principal set.
    pub subject: GatewayLimitSubject,
    /// Limited calls.
    pub target: GatewayPolicyTarget,
    /// Maximum admitted requests per minute.
    #[cfg_attr(feature = "server", schema(value_type = Option<u64>, minimum = 1))]
    pub requests_per_minute: Option<NonZeroU64>,
    /// Maximum tokens per minute.
    #[cfg_attr(feature = "server", schema(value_type = Option<u64>, minimum = 1))]
    pub tokens_per_minute: Option<NonZeroU64>,
    /// Maximum concurrently admitted calls.
    #[cfg_attr(feature = "server", schema(value_type = Option<u64>, minimum = 1))]
    pub concurrent_calls: Option<NonZeroU64>,
}

/// UTC calendar accounting period for a budget.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum GatewayBudgetPeriod {
    /// One UTC calendar day.
    CalendarDayUtc,
    /// One UTC calendar month.
    CalendarMonthUtc,
}

/// Admission of a call whose cost cannot be bounded.
#[derive(
    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema,
)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum UnknownCostPolicy {
    /// Reject the call.
    Reject,
    /// Admit it with an explicit unpriced outcome when no budget applies.
    #[default]
    AllowUnpriced,
}

/// Spending budget for one subject and period.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct GatewayBudget {
    /// Budgeted principal set.
    pub subject: GatewayPolicySubject,
    /// Accounting period.
    pub period: GatewayBudgetPeriod,
    /// Positive budget amount.
    pub amount: GatewayDecimal,
    /// Budget currency.
    pub currency: CurrencyCode,
}

/// Price for one provider billing dimension.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct GatewayPriceRate {
    /// Open provider billing dimension, such as `input_tokens`.
    pub dimension: String,
    /// Billing unit, such as `1m_tokens`.
    pub unit: String,
    /// Non-negative price per unit.
    pub price: GatewayDecimal,
}

/// One immutable pricing version for a model.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct GatewayModelPricing {
    /// Priced model.
    pub model: ModelRef,
    /// Immutable version label.
    pub version: String,
    /// Pricing currency.
    pub currency: CurrencyCode,
    /// Admission time from which this entry applies.
    pub effective_at: DateTime<Utc>,
    /// Whether the entry is eligible for newly admitted calls.
    pub active: bool,
    /// Non-empty rates.
    pub rates: Vec<GatewayPriceRate>,
}

impl GatewayModelPricing {
    /// True when `other` is the same immutable version with identical content
    /// apart from the `active` flag, which replacement may retire.
    #[must_use]
    pub fn same_version_content(&self, other: &Self) -> bool {
        self.model == other.model
            && self.version == other.version
            && self.currency == other.currency
            && self.effective_at == other.effective_at
            && self.rates == other.rates
    }
}

/// The tenant's single gateway governance policy.
///
/// The default is the empty policy: no limits or budgets, no active pricing,
/// and `unknown_cost: allow_unpriced`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct GatewayGovernancePolicy {
    /// Rate and concurrency limits.
    pub limits: Vec<GatewayLimit>,
    /// Spending budgets.
    pub budgets: Vec<GatewayBudget>,
    /// Versioned model pricing.
    pub pricing: Vec<GatewayModelPricing>,
    /// Unknown-cost admission.
    pub unknown_cost: UnknownCostPolicy,
}

impl GatewayGovernancePolicy {
    /// Rejects duplicate keys, empty limits or rates, non-positive budgets,
    /// invalid text, and mixed budget/active-pricing currencies.
    ///
    /// # Errors
    ///
    /// Returns [`GatewayContractError`] naming the first offending entry.
    pub fn validate(&self) -> Result<(), GatewayContractError> {
        let mut limits = HashSet::new();
        for (index, limit) in self.limits.iter().enumerate() {
            if !limits.insert((&limit.subject, &limit.target)) {
                return Err(GatewayContractError::new(
                    format!("limits[{index}]"),
                    "duplicate subject and target",
                ));
            }
            if limit.requests_per_minute.is_none()
                && limit.tokens_per_minute.is_none()
                && limit.concurrent_calls.is_none()
            {
                return Err(GatewayContractError::new(
                    format!("limits[{index}]"),
                    "at least one limit must be set",
                ));
            }
        }
        let mut currency: Option<&CurrencyCode> = None;
        let mut budgets = HashSet::new();
        for (index, budget) in self.budgets.iter().enumerate() {
            if !budgets.insert((&budget.subject, budget.period)) {
                return Err(GatewayContractError::new(
                    format!("budgets[{index}]"),
                    "duplicate subject and period",
                ));
            }
            if budget.amount.is_zero() {
                return Err(GatewayContractError::new(
                    format!("budgets[{index}].amount"),
                    "must be positive",
                ));
            }
            require_one_currency(
                &mut currency,
                &budget.currency,
                format!("budgets[{index}].currency"),
            )?;
        }
        let mut versions = HashSet::new();
        let mut effective = HashSet::new();
        for (index, entry) in self.pricing.iter().enumerate() {
            validate_text(&format!("pricing[{index}].version"), &entry.version)?;
            if !versions.insert((&entry.model, entry.version.as_str())) {
                return Err(GatewayContractError::new(
                    format!("pricing[{index}]"),
                    "duplicate model and version",
                ));
            }
            if !effective.insert((&entry.model, entry.effective_at)) {
                return Err(GatewayContractError::new(
                    format!("pricing[{index}]"),
                    "duplicate model and effective_at",
                ));
            }
            if entry.rates.is_empty() {
                return Err(GatewayContractError::new(
                    format!("pricing[{index}].rates"),
                    "must not be empty",
                ));
            }
            for (rate_index, rate) in entry.rates.iter().enumerate() {
                let field = format!("pricing[{index}].rates[{rate_index}]");
                validate_text(&format!("{field}.dimension"), &rate.dimension)?;
                validate_text(&format!("{field}.unit"), &rate.unit)?;
            }
            if entry.active {
                require_one_currency(
                    &mut currency,
                    &entry.currency,
                    format!("pricing[{index}].currency"),
                )?;
            }
        }
        Ok(())
    }
}

/// Records the first currency seen and rejects any later different one.
///
/// # Errors
///
/// Returns [`GatewayContractError`] naming `field` when `code` differs from
/// the currency already recorded in `seen`.
fn require_one_currency<'a>(
    seen: &mut Option<&'a CurrencyCode>,
    code: &'a CurrencyCode,
    field: String,
) -> Result<(), GatewayContractError> {
    match seen {
        Some(existing) if *existing != code => Err(GatewayContractError::new(
            field,
            "budgets and active pricing must use one currency",
        )),
        _ => {
            seen.get_or_insert(code);
            Ok(())
        }
    }
}

/// Gateway-call capture mode.
#[derive(
    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema,
)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum GatewayCaptureMode {
    /// Publish nothing to Bifrost.
    #[default]
    Disabled,
    /// Publish call metadata without request or response content.
    Metadata,
    /// Publish metadata plus the selected redacted payload fields.
    Payload,
}

/// Payload column selected for capture.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Serialize,
    Deserialize,
    schemars::JsonSchema,
)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum GatewayPayloadField {
    /// Redacted request payload.
    Request,
    /// Redacted response payload.
    Response,
}

/// `PUT /v1/admin/gateway/capture-policy` body.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct GatewayCapturePolicyWrite {
    /// Capture mode.
    pub mode: GatewayCaptureMode,
    /// Payload fields; empty unless `mode` is `payload`.
    pub payload_fields: BTreeSet<GatewayPayloadField>,
}

impl GatewayCapturePolicyWrite {
    /// Rejects payload fields outside `payload` mode and an empty `payload` set.
    ///
    /// # Errors
    ///
    /// Returns [`GatewayContractError`] for field `payload_fields`.
    pub fn validate(&self) -> Result<(), GatewayContractError> {
        match (self.mode, self.payload_fields.is_empty()) {
            (GatewayCaptureMode::Payload, true) => Err(GatewayContractError::new(
                "payload_fields",
                "payload mode requires at least one field",
            )),
            (GatewayCaptureMode::Disabled | GatewayCaptureMode::Metadata, false) => Err(
                GatewayContractError::new("payload_fields", "must be empty unless mode is payload"),
            ),
            _ => Ok(()),
        }
    }
}

/// Persisted capture policy with its server-assigned version.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct GatewayCapturePolicy {
    /// Capture mode.
    pub mode: GatewayCaptureMode,
    /// Selected payload fields.
    pub payload_fields: BTreeSet<GatewayPayloadField>,
    /// Version that increases only when effective content changes.
    #[cfg_attr(feature = "server", schema(value_type = u64, minimum = 1))]
    pub version: NonZeroU64,
}

#[cfg(test)]
mod tests {
    use base64::Engine as _;
    use base64::engine::general_purpose::{URL_SAFE, URL_SAFE_NO_PAD};

    use super::{
        GatewayCapturePolicyWrite, GatewayFallbackOverride, GatewayFallbackPolicy,
        GatewayGovernancePolicy, MAX_FALLBACK_HEADER_BYTES,
    };
    use crate::gateway::ModelRef;
    use serde_json::{Value, json};

    /// Builds a `ModelRef` JSON document.
    fn model(deployment: &str, name: &str) -> serde_json::Value {
        json!({"deployment": deployment, "model": name})
    }

    /// Proves fallback duplicates, empties, and self-reference fail, while the
    /// exact shape round-trips.
    #[test]
    fn fallback_policy_rules_validate() {
        let valid = json!({"rules": [
            {"scope": "global", "candidates": [model("openai", "gpt-4o")]},
            {"scope": {"operation": {"operation": "embeddings"}}, "candidates": [model("gemini", "e")]},
            {"scope": {"model": {"model": model("openai", "gpt-4o")}}, "candidates": [model("anthropic", "claude")]},
        ]});
        let policy: GatewayFallbackPolicy = serde_json::from_value(valid.clone()).expect("decodes");
        policy.validate().expect("valid");
        assert_eq!(serde_json::to_value(&policy).expect("encodes"), valid);

        for rules in [
            json!([{"scope": "global", "candidates": []}]),
            json!([{"scope": "global", "candidates": [model("a-a", "x"), model("a-a", "x")]}]),
            json!([
                {"scope": "global", "candidates": [model("a-a", "x")]},
                {"scope": "global", "candidates": [model("b-b", "y")]}
            ]),
            json!([{"scope": {"model": {"model": model("a-a", "x")}}, "candidates": [model("a-a", "x")]}]),
        ] {
            let policy: GatewayFallbackPolicy =
                serde_json::from_value(json!({"rules": rules})).expect("decodes");
            assert!(policy.validate().is_err(), "{rules}");
        }

        let requested = ModelRef::from_projection("openai/gpt-4o").expect("model");
        let override_self: GatewayFallbackOverride =
            serde_json::from_value(json!({"candidates": [model("openai", "gpt-4o")]}))
                .expect("decodes");
        assert!(override_self.validate_for(&requested).is_err());
    }

    /// Proves the fallback header round-trips through its exact encoding and
    /// refuses every malformed, oversized, or invalid value as `fallback`.
    ///
    /// # Panics
    /// Panics when the fixed requested model or override fixture stops
    /// parsing or encoding, the encoding is not the exact unpadded base64url
    /// JCS document, or any malformed value is accepted or refused under a
    /// field other than `fallback`.
    #[test]
    fn fallback_header_round_trips_and_refuses() {
        let requested = ModelRef::from_projection("openai/gpt-4o").expect("model");
        let fallback: GatewayFallbackOverride =
            serde_json::from_value(json!({"candidates": [model("anthropic", "claude")]}))
                .expect("decodes");
        let value = fallback.to_header_value().expect("encodes");
        assert_eq!(
            URL_SAFE_NO_PAD.decode(&value).expect("base64url"),
            br#"{"candidates":[{"deployment":"anthropic","model":"claude"}]}"#
        );
        assert_eq!(
            GatewayFallbackOverride::from_header_value(value.as_bytes(), &requested),
            Ok(fallback)
        );

        let encode = |document: Value| URL_SAFE_NO_PAD.encode(document.to_string());
        let oversized_json = encode(json!({"candidates": [model("a-a", &"x".repeat(5000))]}));
        for value in [
            String::new(),
            "not base64!".to_owned(),
            URL_SAFE.encode(r#"{"candidates":[]}"#),
            "A".repeat(MAX_FALLBACK_HEADER_BYTES + 1),
            oversized_json,
            encode(json!({"candidates": [model("a-a", "x")], "extra": true})),
            encode(json!({"candidates": []})),
            encode(json!({"candidates": [model("a-a", "x"), model("a-a", "x")]})),
            encode(json!({"candidates": [model("openai", "gpt-4o")]})),
        ] {
            let error = GatewayFallbackOverride::from_header_value(value.as_bytes(), &requested)
                .expect_err("refused");
            assert_eq!(error.field, "fallback", "{value}");
        }
    }

    /// Proves governance duplicates, mixed currencies, zero budgets, and empty
    /// limits fail, and the default is the empty allow-unpriced policy.
    #[test]
    fn governance_policy_rules_validate() {
        assert_eq!(
            serde_json::to_value(GatewayGovernancePolicy::default()).expect("encodes"),
            json!({"limits": [], "budgets": [], "pricing": [], "unknown_cost": "allow_unpriced"})
        );
        let pricing = |version: &str, at: &str, currency: &str, active: bool| {
            json!({
                "model": model("openai", "gpt-4o"), "version": version, "currency": currency,
                "effective_at": at, "active": active,
                "rates": [{"dimension": "input_tokens", "unit": "1m_tokens", "price": "2.50"}],
            })
        };
        let budget = |subject: serde_json::Value, currency: &str, amount: &str| json!({"subject": subject, "period": "calendar_month_utc", "amount": amount, "currency": currency});
        let valid = json!({
            "limits": [{"subject": "tenant", "target": "all", "requests_per_minute": 60, "tokens_per_minute": null, "concurrent_calls": null}],
            "budgets": [budget(json!("tenant"), "USD", "100")],
            "pricing": [pricing("v1", "2026-01-01T00:00:00Z", "USD", true), pricing("v0", "2025-01-01T00:00:00Z", "EUR", false)],
            "unknown_cost": "reject",
        });
        let policy: GatewayGovernancePolicy = serde_json::from_value(valid).expect("decodes");
        policy
            .validate()
            .expect("valid; retired pricing may keep an old currency");

        let invalid = [
            json!({"budgets": [budget(json!("tenant"), "USD", "1"), budget(json!("tenant"), "USD", "2")]}),
            json!({"budgets": [budget(json!("tenant"), "USD", "0")]}),
            json!({"budgets": [budget(json!("tenant"), "USD", "1")], "pricing": [pricing("v1", "2026-01-01T00:00:00Z", "EUR", true)]}),
            json!({"pricing": [pricing("v1", "2026-01-01T00:00:00Z", "USD", true), pricing("v1", "2026-02-01T00:00:00Z", "USD", true)]}),
            json!({"pricing": [pricing("v1", "2026-01-01T00:00:00Z", "USD", true), pricing("v2", "2026-01-01T00:00:00Z", "USD", true)]}),
            json!({"limits": [{"subject": "tenant", "target": "all", "requests_per_minute": null, "tokens_per_minute": null, "concurrent_calls": null}]}),
        ];
        for mut case in invalid {
            for key in ["limits", "budgets", "pricing"] {
                case.as_object_mut()
                    .expect("object")
                    .entry(key)
                    .or_insert(json!([]));
            }
            case["unknown_cost"] = json!("allow_unpriced");
            let policy: GatewayGovernancePolicy =
                serde_json::from_value(case.clone()).expect("decodes");
            assert!(policy.validate().is_err(), "{case}");
        }
        assert!(
            serde_json::from_value::<GatewayGovernancePolicy>(json!({
                "limits": [{"subject": {"role": {"role_name": "viewer"}}, "target": "all", "requests_per_minute": 1, "tokens_per_minute": null, "concurrent_calls": null}],
                "budgets": [], "pricing": [], "unknown_cost": "reject",
            }))
            .is_err(),
            "limits have no role subject"
        );
    }

    /// Proves capture mode and payload-field combinations validate.
    #[test]
    fn capture_policy_field_combinations_validate() {
        for (mode, fields, ok) in [
            ("disabled", json!([]), true),
            ("metadata", json!([]), true),
            ("payload", json!(["response", "request"]), true),
            ("payload", json!([]), false),
            ("metadata", json!(["request"]), false),
        ] {
            let write: GatewayCapturePolicyWrite =
                serde_json::from_value(json!({"mode": mode, "payload_fields": fields}))
                    .expect("decodes");
            assert_eq!(write.validate().is_ok(), ok, "{mode} {fields}");
        }
    }
}