trusty-common 0.53.5

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
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
//! Which provider a bare model id names, judged from its SHAPE (#6114).
//!
//! Why: a model id only means something inside one provider's namespace, but
//! every resolver in this workspace routed on an explicit `bedrock/` /
//! `openrouter/` prefix alone and passed anything else through to whatever the
//! default provider happened to be. On the #6093 mitigation run that sent an
//! OpenRouter slug (`anthropic/claude-opus-4.8`) into a Bedrock-default path:
//! Bedrock rejected the id, and the render that eventually completed ran
//! Bedrock's `us.anthropic.claude-sonnet-4-6` default instead of the model the
//! operator asked for. Two resolvers carried that fall-through
//! (`trusty-review`'s `llm::resolve_provider_and_model` and `trusty-mpm`'s
//! `core::sm::providers::resolve`), so the rule lives here once.
//!
//! What: [`infer_provider_from_model_shape`] answers "whose namespace is this
//! id in", returning `None` when the id is genuinely ambiguous;
//! [`shape_mismatch`] turns that into the reconciliation check a resolver
//! needs — `Some(inferred)` when the id names a DIFFERENT provider than the one
//! about to execute it.
//!
//! Which mismatch function to call depends on where the provider came from. A
//! standing config default loses to any shape; an explicit per-call routing
//! prefix is a human's statement about THIS call and loses only to a catalogue
//! fact, never to the dotted-vendor guess. So: no prefix given →
//! [`shape_mismatch`]; prefix given → [`conclusive_shape_mismatch`]. The two
//! strengths are [`ShapeEvidence`].
//!
//! This is the mirror of [`crate::inference::tier`]: `ModelTier::resolve` maps
//! a provider to a model id, this maps a model id back to its provider.
//!
//! 🔴 **Call this only on an id whose routing prefix you have already
//! stripped.** Slash-form is read as an OpenRouter slug here (a Bedrock model
//! ARN excepted, #9200), while
//! [`ProviderId::from_slug_prefix`] reads the same `anthropic/…` string as the
//! Anthropic first-party family. Both are right for their own question — a
//! routing prefix is what the OPERATOR wrote to pin a provider, an id shape is
//! what the PROVIDER's own catalogue looks like. A consumer strips its own
//! prefix table first, then asks this module about what remains.
//!
//! [`ProviderId::from_slug_prefix`]: crate::inference::registry::ProviderId::from_slug_prefix
//!
//! Test: the inline `tests` module below.

use super::registry::ProviderId;

/// Bedrock cross-region inference-profile prefixes.
///
/// Why: a Bedrock model id that carries one of these is unmistakably Bedrock —
/// no other provider in the registry uses region-scoped dotted ids. Bedrock
/// itself REQUIRES one on Anthropic models, so `trusty-review`'s Bedrock
/// provider validates against this same list rather than keeping a second copy.
/// What: the region scopes AWS publishes inference profiles under.
/// Test: `us_profile_id_is_bedrock`; consumer-side,
/// `trusty_review::llm::bedrock::tests::bedrock_us_prefix_validation`.
pub const BEDROCK_INFERENCE_PROFILE_PREFIXES: &[&str] = &["us.", "eu.", "ap.", "jp.", "global."];

/// Vendor segments that open a Bedrock foundation-model id.
///
/// Why: an un-profiled Bedrock id (`anthropic.claude-sonnet-4-6`) is still
/// unmistakably Bedrock — the dotted `vendor.model` spelling belongs to no
/// other provider here. Matching it lets the resolver name the mismatch
/// instead of handing the id to an aggregator that would 404 on it.
/// What: the vendors AWS publishes foundation models under. A dotted id whose
/// first segment is not in this list stays ambiguous.
/// Test: `dotted_vendor_id_is_bedrock`, `unknown_dotted_prefix_is_ambiguous`.
const BEDROCK_VENDOR_SEGMENTS: &[&str] = &[
    "ai21",
    "amazon",
    "anthropic",
    "cohere",
    "deepseek",
    "luma",
    "meta",
    "mistral",
    "openai",
    "qwen",
    "stability",
    "twelvelabs",
    "writer",
];

/// The provider-native prefix every Fireworks model id carries.
const FIREWORKS_NATIVE_PREFIX: &str = "accounts/fireworks/models/";

/// The partition and service every Bedrock model ARN opens with. Commercial
/// `aws` partition only: nothing here resolves GovCloud or China regions.
const BEDROCK_ARN_HEAD: &str = "arn:aws:bedrock:";

/// Bedrock ARN resource types that name a runnable model, each with whether
/// its ARN carries a 12-digit account id (`foundation-model` ARNs leave it
/// empty). Another resource type (`agent/…`, `knowledge-base/…`) is not a model.
const BEDROCK_ARN_MODEL_RESOURCES: &[(&str, bool)] = &[
    ("application-inference-profile", true),
    ("inference-profile", true),
    ("foundation-model", false),
];

/// Whether `id` is a well-formed Bedrock model ARN.
///
/// Why: an ARN contains `/`, which every other rule here reads as an
/// OpenRouter slug, so a tagged application inference profile routed to
/// OpenRouter (#9200).
/// What: `arn:aws:bedrock:<region>:<account>:<type>/<name>` anchored at the
/// start of `id`, with `<type>` in [`BEDROCK_ARN_MODEL_RESOURCES`], a
/// lowercase region, the account its type requires, and a non-empty `<name>`
/// with no whitespace or `/`. Anything else is `false`, so a malformed ARN
/// falls through to the rules it met before #9200 and never becomes Bedrock.
/// Test: `every_bedrock_model_arn_is_conclusive_in_both_checks`,
/// `malformed_bedrock_arn_keeps_its_pre_9200_classification`.
fn is_bedrock_model_arn(id: &str) -> bool {
    let Some(rest) = id.strip_prefix(BEDROCK_ARN_HEAD) else {
        return false;
    };
    // `<name>` may itself hold `:` (`amazon.nova-pro-v1:0`), so split twice only.
    let mut fields = rest.splitn(3, ':');
    let (Some(region), Some(account), Some(resource)) =
        (fields.next(), fields.next(), fields.next())
    else {
        return false;
    };
    let Some((kind, name)) = resource.split_once('/') else {
        return false;
    };
    let Some(&(_, has_account)) = BEDROCK_ARN_MODEL_RESOURCES.iter().find(|(k, _)| *k == kind)
    else {
        return false;
    };
    let region_ok = !region.is_empty()
        && region
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
    let account_ok = if has_account {
        account.len() == 12 && account.bytes().all(|b| b.is_ascii_digit())
    } else {
        account.is_empty()
    };
    let name_ok = !name.is_empty() && !name.contains('/') && !name.contains(char::is_whitespace);
    region_ok && account_ok && name_ok
}

/// How strongly a model id's spelling names its provider.
///
/// Why: not every signal here is equally good, and the difference decides
/// whether inference may overrule a human. A slash-form slug or a region-scoped
/// inference profile belongs to exactly one provider's catalogue. A dotted
/// `vendor.model` id is a guess from a vendor-name list, and a guess must not
/// veto an operator who typed a routing prefix on this very call.
/// What: the two strengths [`classify_model_shape`] reports.
/// Test: `dotted_vendor_evidence_is_probable`,
/// `slug_and_profile_evidence_is_conclusive`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShapeEvidence {
    /// The spelling belongs to exactly one provider's catalogue: a
    /// `vendor/model` slug, the Fireworks-native path, a region-scoped
    /// Bedrock inference profile, or a Bedrock model ARN.
    Conclusive,
    /// A dotted `vendor.model` id whose first segment is a known Bedrock
    /// vendor. Strong enough to outrank a standing config default, not strong
    /// enough to outrank an explicit per-call routing prefix.
    Probable,
}

/// Classify `model`'s provider and how strongly its spelling says so.
///
/// Why: [`infer_provider_from_model_shape`] answers "whose is this", but a
/// resolver deciding whether to REJECT an operator's explicit prefix needs to
/// know whether the answer is a catalogue fact or a vendor-name guess (#6114).
/// What: `Some((provider, evidence))`, or `None` when the id could belong to
/// several providers (`claude-opus-4-5-20260101`, `gpt-5.4-mini`) — the case
/// where a caller's configured default legitimately decides.
///
/// The input must already have had the caller's own routing prefix stripped —
/// see the module docs.
/// Test: `slug_and_profile_evidence_is_conclusive`,
/// `dotted_vendor_evidence_is_probable`, `shape_classification_table`,
/// `application_inference_profile_arn_is_conclusive_bedrock`,
/// `non_bedrock_arns_and_look_alikes_keep_their_classification`.
pub fn classify_model_shape(model: &str) -> Option<(ProviderId, ShapeEvidence)> {
    let id = model.trim();
    if id.is_empty() {
        return None;
    }
    if id.starts_with(FIREWORKS_NATIVE_PREFIX) {
        return Some((ProviderId::Fireworks, ShapeEvidence::Conclusive));
    }
    // #9200: before the `/` rule — a Bedrock ARN's `/` is not a slug separator.
    if is_bedrock_model_arn(id) {
        return Some((ProviderId::Bedrock, ShapeEvidence::Conclusive));
    }
    if id.contains('/') {
        return Some((ProviderId::OpenRouter, ShapeEvidence::Conclusive));
    }
    if BEDROCK_INFERENCE_PROFILE_PREFIXES
        .iter()
        .any(|pfx| id.starts_with(pfx))
    {
        return Some((ProviderId::Bedrock, ShapeEvidence::Conclusive));
    }
    let vendor = id.split('.').next().unwrap_or(id);
    if vendor.len() < id.len() && BEDROCK_VENDOR_SEGMENTS.contains(&vendor) {
        return Some((ProviderId::Bedrock, ShapeEvidence::Probable));
    }
    None
}

/// Infer the provider whose namespace `model` belongs to, from its shape alone.
///
/// Why: a resolver that cannot tell `anthropic/claude-opus-4.8` from
/// `us.anthropic.claude-opus-4-8` has no way to notice that the id and the
/// provider about to run it disagree, so it runs the wrong model silently
/// (#6114). This is the form to use when NO explicit routing prefix was given —
/// there is no human choice to overrule, so both evidence strengths count.
/// What: [`classify_model_shape`] with the evidence discarded.
///
/// The input must already have had the caller's own routing prefix stripped —
/// see the module docs.
/// Test: `openrouter_slug_is_openrouter`, `us_profile_id_is_bedrock`,
/// `dotted_vendor_id_is_bedrock`, `fireworks_native_id_is_fireworks`,
/// `bare_ids_are_ambiguous`.
pub fn infer_provider_from_model_shape(model: &str) -> Option<ProviderId> {
    classify_model_shape(model).map(|(provider, _)| provider)
}

/// Report the provider `model`'s shape names, when that is not `provider`.
///
/// Why: this is the reconciliation a resolver owes its caller — the run must
/// fail naming both the id and the provider rather than execute a different
/// model than the one requested (#6114).
/// What: `Some(inferred)` when [`infer_provider_from_model_shape`] names a
/// provider other than `provider`; `None` when they agree or the id is
/// ambiguous. Both evidence strengths count, so use this only where `provider`
/// came from a config default — see [`conclusive_shape_mismatch`] for the
/// explicit-prefix case.
/// Test: `mismatch_flags_openrouter_slug_on_bedrock`,
/// `mismatch_is_none_when_shape_agrees`, `mismatch_is_none_for_ambiguous_id`.
pub fn shape_mismatch(provider: ProviderId, model: &str) -> Option<ProviderId> {
    match infer_provider_from_model_shape(model) {
        Some(inferred) if inferred != provider => Some(inferred),
        _ => None,
    }
}

/// The same reconciliation, but only on evidence strong enough to overrule a
/// human.
///
/// Why: an operator who writes `openrouter/anthropic.claude-x` has stated the
/// provider for this call. Rejecting that because a dotted first segment
/// happens to match a Bedrock vendor name would turn a working configuration
/// into a hard error on a guess. The catalogue-fact shapes still win: nothing
/// makes `bedrock/anthropic/claude-opus-4.8` runnable, and refusing it is the
/// whole point of #6114.
/// What: `Some(inferred)` only when the shape disagrees with `provider` AND the
/// evidence is [`ShapeEvidence::Conclusive`].
/// Test: `conclusive_mismatch_ignores_a_probable_shape`,
/// `conclusive_mismatch_still_flags_a_slug_on_bedrock`.
pub fn conclusive_shape_mismatch(provider: ProviderId, model: &str) -> Option<ProviderId> {
    match classify_model_shape(model) {
        Some((inferred, ShapeEvidence::Conclusive)) if inferred != provider => Some(inferred),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn openrouter_slug_is_openrouter() {
        // The #6114 id itself: an OpenRouter slug that used to fall through to
        // whatever default provider the path carried.
        assert_eq!(
            infer_provider_from_model_shape("anthropic/claude-opus-4.8"),
            Some(ProviderId::OpenRouter)
        );
        assert_eq!(
            infer_provider_from_model_shape("openai/gpt-5.4-mini-20260317"),
            Some(ProviderId::OpenRouter)
        );
    }

    #[test]
    fn us_profile_id_is_bedrock() {
        for id in [
            "us.anthropic.claude-sonnet-4-6",
            "eu.anthropic.claude-haiku-4-5",
            "global.anthropic.claude-opus-4-8",
        ] {
            assert_eq!(
                infer_provider_from_model_shape(id),
                Some(ProviderId::Bedrock),
                "{id} must read as Bedrock"
            );
        }
    }

    #[test]
    fn dotted_vendor_id_is_bedrock() {
        assert_eq!(
            infer_provider_from_model_shape("anthropic.claude-sonnet-4-6"),
            Some(ProviderId::Bedrock)
        );
        assert_eq!(
            infer_provider_from_model_shape("amazon.nova-pro-v1:0"),
            Some(ProviderId::Bedrock)
        );
    }

    #[test]
    fn fireworks_native_id_is_fireworks() {
        assert_eq!(
            infer_provider_from_model_shape("accounts/fireworks/models/llama-v3p1-70b-instruct"),
            Some(ProviderId::Fireworks),
            "the fireworks-native id must not be read as an OpenRouter slug"
        );
    }

    #[test]
    fn bare_ids_are_ambiguous() {
        for id in ["", "   ", "claude-opus-4-5-20260101", "gpt-5.4-mini"] {
            assert_eq!(
                infer_provider_from_model_shape(id),
                None,
                "{id:?} must stay ambiguous so the configured default decides"
            );
        }
    }

    #[test]
    fn unknown_dotted_prefix_is_ambiguous() {
        // A dot alone is not a Bedrock signal — version-dotted slugs are common.
        assert_eq!(infer_provider_from_model_shape("llama-3.1-70b"), None);
    }

    #[test]
    fn mismatch_flags_openrouter_slug_on_bedrock() {
        assert_eq!(
            shape_mismatch(ProviderId::Bedrock, "anthropic/claude-opus-4.8"),
            Some(ProviderId::OpenRouter),
            "#6114: this pair must be reportable, not silently run on Bedrock"
        );
        assert_eq!(
            shape_mismatch(ProviderId::OpenRouter, "us.anthropic.claude-sonnet-4-6"),
            Some(ProviderId::Bedrock)
        );
    }

    #[test]
    fn mismatch_is_none_when_shape_agrees() {
        assert_eq!(
            shape_mismatch(ProviderId::Bedrock, "us.anthropic.claude-sonnet-4-6"),
            None
        );
        assert_eq!(
            shape_mismatch(
                ProviderId::Fireworks,
                "accounts/fireworks/models/llama-v3p1-70b-instruct"
            ),
            None
        );
    }

    #[test]
    fn mismatch_is_none_for_ambiguous_id() {
        assert_eq!(shape_mismatch(ProviderId::Bedrock, "claude-opus-4-8"), None);
        assert_eq!(shape_mismatch(ProviderId::Anthropic, ""), None);
    }

    #[test]
    fn slug_and_profile_evidence_is_conclusive() {
        for id in [
            "anthropic/claude-opus-4.8",
            "us.anthropic.claude-sonnet-4-6",
            "accounts/fireworks/models/llama-v3p1-70b-instruct",
        ] {
            let (_, evidence) = classify_model_shape(id).expect("{id} must classify");
            assert_eq!(
                evidence,
                ShapeEvidence::Conclusive,
                "{id} belongs to exactly one catalogue"
            );
        }
    }

    #[test]
    fn dotted_vendor_evidence_is_probable() {
        let (provider, evidence) =
            classify_model_shape("anthropic.claude-sonnet-4-6").expect("must classify");
        assert_eq!(provider, ProviderId::Bedrock);
        assert_eq!(
            evidence,
            ShapeEvidence::Probable,
            "a vendor-name match is a guess, not a catalogue fact"
        );
    }

    /// #6114 (code-critic MEDIUM 2): the dotted-vendor guess must not veto an
    /// operator's explicit routing prefix.
    ///
    /// Why: `openrouter/anthropic.claude-x` states the provider for this call.
    /// Turning it into a hard error because `anthropic` appears in a Bedrock
    /// vendor list would break a working configuration on a guess.
    /// What: asserts the conclusive-only check stays silent on a `Probable`
    /// shape, in both directions.
    /// Test: this test itself; the resolver-level proof lives in both consumer
    /// crates' `*_prefix_survives_a_probable_*` tests.
    #[test]
    fn conclusive_mismatch_ignores_a_probable_shape() {
        assert_eq!(
            conclusive_shape_mismatch(ProviderId::OpenRouter, "anthropic.claude-sonnet-4-6"),
            None,
            "an explicit prefix outranks the dotted-vendor guess"
        );
        assert_eq!(
            conclusive_shape_mismatch(ProviderId::Anthropic, "amazon.nova-pro-v1:0"),
            None
        );
        // The plain form still reports it — a config default does NOT outrank it.
        assert_eq!(
            shape_mismatch(ProviderId::OpenRouter, "anthropic.claude-sonnet-4-6"),
            Some(ProviderId::Bedrock)
        );
    }

    #[test]
    fn conclusive_mismatch_still_flags_a_slug_on_bedrock() {
        assert_eq!(
            conclusive_shape_mismatch(ProviderId::Bedrock, "anthropic/claude-opus-4.8"),
            Some(ProviderId::OpenRouter),
            "nothing makes an OpenRouter slug runnable on Bedrock"
        );
        assert_eq!(
            conclusive_shape_mismatch(ProviderId::OpenRouter, "us.anthropic.claude-sonnet-4-6"),
            Some(ProviderId::Bedrock)
        );
        assert_eq!(
            conclusive_shape_mismatch(
                ProviderId::OpenRouter,
                "accounts/fireworks/models/llama-v3p1-70b-instruct"
            ),
            Some(ProviderId::Fireworks)
        );
    }

    /// Shaped like the owner-ruling-59 pilot profile; the account id is AWS's
    /// documentation placeholder, not a real account.
    const PILOT_SHAPED_ARN: &str =
        "arn:aws:bedrock:us-west-2:111122223333:application-inference-profile/9iatxd8u1751";

    /// #9200 regression: the `/` in an application-inference-profile ARN read
    /// as an OpenRouter slug, so a tagged Bedrock profile routed to OpenRouter.
    #[test]
    fn application_inference_profile_arn_is_conclusive_bedrock() {
        assert_eq!(
            classify_model_shape(PILOT_SHAPED_ARN),
            Some((ProviderId::Bedrock, ShapeEvidence::Conclusive)),
            "#9200: a Bedrock application-inference-profile ARN is Bedrock's catalogue"
        );
    }

    #[test]
    fn every_bedrock_model_arn_is_conclusive_in_both_checks() {
        for arn in [
            PILOT_SHAPED_ARN,
            "arn:aws:bedrock:us-east-1:111122223333:inference-profile/us.anthropic.claude-sonnet-4-6",
            "arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-pro-v1:0",
            "  arn:aws:bedrock:eu-central-1::foundation-model/anthropic.claude-haiku-4-5  ",
        ] {
            assert_eq!(
                classify_model_shape(arn),
                Some((ProviderId::Bedrock, ShapeEvidence::Conclusive)),
                "{arn}"
            );
            assert_eq!(
                conclusive_shape_mismatch(ProviderId::OpenRouter, arn),
                Some(ProviderId::Bedrock),
                "{arn}: no aggregator can run a Bedrock ARN"
            );
            assert_eq!(
                conclusive_shape_mismatch(ProviderId::Bedrock, arn),
                None,
                "{arn}: a Bedrock ARN on Bedrock is no mismatch"
            );
        }
    }

    /// Every classification, before and after #9200. Only the rows marked
    /// `#9200` changed; each was `Some((OpenRouter, Conclusive))` before.
    #[test]
    fn shape_classification_table() {
        use ProviderId::{Bedrock, Fireworks, OpenRouter};
        use ShapeEvidence::{Conclusive, Probable};
        let table: &[(&str, Option<(ProviderId, ShapeEvidence)>)] = &[
            ("", None),
            ("   ", None),
            ("claude-opus-4-5-20260101", None),
            ("claude-opus-4-8", None),
            ("gpt-5.4-mini", None),
            ("llama-3.1-70b", None),
            ("anthropic/claude-opus-4.8", Some((OpenRouter, Conclusive))),
            (
                "anthropic/claude-sonnet-4.6",
                Some((OpenRouter, Conclusive)),
            ),
            (
                "openai/gpt-5.4-mini-20260317",
                Some((OpenRouter, Conclusive)),
            ),
            (
                "us.anthropic.claude-sonnet-4-6",
                Some((Bedrock, Conclusive)),
            ),
            ("eu.anthropic.claude-haiku-4-5", Some((Bedrock, Conclusive))),
            ("ap.anthropic.claude-haiku-4-5", Some((Bedrock, Conclusive))),
            ("jp.anthropic.claude-haiku-4-5", Some((Bedrock, Conclusive))),
            (
                "global.anthropic.claude-opus-4-8",
                Some((Bedrock, Conclusive)),
            ),
            ("anthropic.claude-sonnet-4-6", Some((Bedrock, Probable))),
            ("amazon.nova-pro-v1:0", Some((Bedrock, Probable))),
            (
                "accounts/fireworks/models/llama-v3p1-70b-instruct",
                Some((Fireworks, Conclusive)),
            ),
            // #9200
            (PILOT_SHAPED_ARN, Some((Bedrock, Conclusive))),
            // #9200
            (
                "arn:aws:bedrock:us-east-1:111122223333:inference-profile/us.anthropic.claude-sonnet-4-6",
                Some((Bedrock, Conclusive)),
            ),
            // #9200
            (
                "arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-pro-v1:0",
                Some((Bedrock, Conclusive)),
            ),
        ];
        for (id, expected) in table {
            assert_eq!(classify_model_shape(id), *expected, "{id:?}");
        }
    }

    /// #9200: the ARN rule anchors on `arn:aws:bedrock:` at the start of the
    /// id and on a model resource type. Everything else keeps its pre-#9200
    /// classification — and none of it becomes Bedrock.
    #[test]
    fn non_bedrock_arns_and_look_alikes_keep_their_classification() {
        let slug = Some((ProviderId::OpenRouter, ShapeEvidence::Conclusive));
        for (id, expected) in [
            (
                "arn:aws:sagemaker:us-west-2:111122223333:endpoint/my-endpoint",
                slug,
            ),
            (
                "arn:aws:bedrock-agent:us-west-2:111122223333:agent/AGENT12345",
                slug,
            ),
            // Service `bedrock`, but an agent is not a model Converse runs.
            (
                "arn:aws:bedrock:us-west-2:111122223333:agent/AGENT12345",
                slug,
            ),
            (format!("x{PILOT_SHAPED_ARN}").as_str(), slug),
            (format!("profile={PILOT_SHAPED_ARN}").as_str(), slug),
            // The module never strips a routing prefix; a consumer does.
            (format!("openrouter/{PILOT_SHAPED_ARN}").as_str(), slug),
            // Partition choice: only the commercial `aws` partition.
            (
                "arn:aws-us-gov:bedrock:us-gov-west-1:111122223333:application-inference-profile/abc",
                slug,
            ),
            (
                "ARN:AWS:BEDROCK:US-WEST-2:111122223333:APPLICATION-INFERENCE-PROFILE/ABC",
                slug,
            ),
            ("anthropic/claude-sonnet-4.6", slug),
        ] {
            assert_eq!(classify_model_shape(id), expected, "{id:?}");
            assert_ne!(
                conclusive_shape_mismatch(ProviderId::OpenRouter, id),
                Some(ProviderId::Bedrock),
                "{id:?} must not be claimed for Bedrock"
            );
        }
    }

    /// #9200 fail-open check: a malformed `arn:aws:bedrock:` string is never
    /// Bedrock — it keeps exactly the classification it had before #9200.
    #[test]
    fn malformed_bedrock_arn_keeps_its_pre_9200_classification() {
        let slug = Some((ProviderId::OpenRouter, ShapeEvidence::Conclusive));
        for (id, expected) in [
            // Missing resource segment entirely.
            ("arn:aws:bedrock:us-west-2:111122223333", None),
            ("arn:aws:bedrock:", None),
            // Resource type with no `/<id>`.
            (
                "arn:aws:bedrock:us-west-2:111122223333:application-inference-profile",
                None,
            ),
            // Empty resource id.
            (
                "arn:aws:bedrock:us-west-2:111122223333:application-inference-profile/",
                slug,
            ),
            ("arn:aws:bedrock:us-east-1::foundation-model/", slug),
            // Empty resource type.
            ("arn:aws:bedrock:us-west-2:111122223333:/9iatxd8u1751", slug),
            // Empty or malformed region.
            (
                "arn:aws:bedrock::111122223333:application-inference-profile/abc",
                slug,
            ),
            (
                "arn:aws:bedrock:US_WEST:111122223333:application-inference-profile/abc",
                slug,
            ),
            // Account id wrong for the resource type.
            (
                "arn:aws:bedrock:us-west-2:12345:application-inference-profile/abc",
                slug,
            ),
            (
                "arn:aws:bedrock:us-west-2::application-inference-profile/abc",
                slug,
            ),
            (
                "arn:aws:bedrock:us-east-1:111122223333:foundation-model/amazon.nova-pro-v1:0",
                slug,
            ),
            // Whitespace or a further `/` inside the resource id.
            (
                "arn:aws:bedrock:us-west-2:111122223333:application-inference-profile/ab cd",
                slug,
            ),
            (
                "arn:aws:bedrock:us-west-2:111122223333:application-inference-profile/a/b",
                slug,
            ),
        ] {
            assert_eq!(classify_model_shape(id), expected, "{id:?}");
        }
    }
}