cpa-server 0.4.4

Part of cliproxy: HTTP routes, client auth, credential selection and the management API
Documentation
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
//! Error classification the Go conductor applies on top of an executor's error
//! (sdk/cliproxy/auth/conductor_cooldown.go, internal/clienterror/client_error.go).
//!
//! Executors report a [`FailureScope`]; Go instead classifies the upstream status and
//! the error text (`err.Error()`, which is the upstream body or `status N`). Both feed
//! retry, failover and cooldown decisions here so they cannot drift apart.

use cpa_core::exec::{ExecError, FailureScope};
use cpa_core::gostr::GoStr;
use serde_json::Value;

/// Go `err.Error()` of an executor status error: the body, or `status N` when empty.
pub fn error_text(e: &ExecError) -> String {
    if e.body.is_empty() {
        format!("status {}", e.status)
    } else {
        String::from_utf8_lossy(&e.body).into_owned()
    }
}

/// Go `extractErrorBody`, what request-scoped error rules match: the error's text,
/// except for the Claude executor's own missing-thread error, whose structured body
/// (`claudeThreadNotFoundError.ResponseBody`, v8.0.27 e7b2226) is Anthropic's JSON
/// while its message stays plain. That error is the local 404 with exactly the
/// executor's message; an upstream answer carries headers.
pub fn rule_text(e: &ExecError) -> String {
    let text = error_text(e);
    if e.status == 404 && explicit_request_scoped(e) && text == cpa_exec::claude::THREAD_NOT_FOUND {
        return format!(r#"{{"type":"error","error":{{"type":"not_found_error","message":"{text}"}}}}"#);
    }
    text
}

/// A local executor error (no upstream response) that the executor marked as a
/// request fault: Go's explicit `RequestScopedError`. Upstream responses always carry
/// headers, so an upstream 404 marked `Request` by a provider is still classified here
/// by status and body like Go does.
fn explicit_request_scoped(e: &ExecError) -> bool {
    e.scope == FailureScope::Request && e.headers.is_empty()
}

/// The Go status of an error: transport faults have none.
pub fn go_status(e: &ExecError) -> u16 {
    if e.scope == FailureScope::Transport {
        0
    } else {
        e.status
    }
}

/// Go's `empty_stream` error: a stream that ended before its first payload. Statusless,
/// so it cools the credential like an unclassified failure and renders as 500.
pub fn empty_stream() -> ExecError {
    ExecError::local(
        0,
        FailureScope::Credential,
        "empty_stream: upstream stream closed before first payload",
    )
}

/// Whether the failure came from an upstream attempt (Go `UpstreamAttempted`): an
/// upstream response, a connection fault, or a stream that ended empty.
pub fn upstream_attempted(e: &ExecError) -> bool {
    !e.headers.is_empty() || e.scope == FailureScope::Transport || e.status == 0
}

/// Go `isUnauthorizedError` for an attempt that was not an explicit request fault.
pub fn is_unauthorized(e: &ExecError) -> bool {
    !explicit_request_scoped(e) && names_unauthorized(e)
}

/// Go `isUnauthorizedError` itself: a 401 status or text, whatever the scope. Result
/// recording uses it with the cooldown policy, which a `*-and-cooldown` rule can force
/// on a request-scoped 401.
pub fn names_unauthorized(e: &ExecError) -> bool {
    let raw = error_text(e).go_lower();
    go_status(e) == 401 || raw.contains("status 401") || raw.contains("401 unauthorized")
}

/// Downstream status for a terminal error. Go answers status-less errors with 500.
pub fn response_status(e: &ExecError) -> u16 {
    match go_status(e) {
        0 => 500,
        s => s,
    }
}

const REQUEST_FAULT_CODES: [&str; 9] = [
    "cyber_policy",
    "context_length_exceeded",
    "message_too_big",
    "string_above_max_length",
    "invalid_prompt",
    "invalid_value",
    "unsupported_value",
    "invalid_request_error",
    "previous_response_not_found",
];
const REQUEST_FAULT_TYPES: [&str; 4] = [
    "invalid_request",
    "invalid_request_error",
    "bad_request_error",
    "invalid_prompt",
];

fn json_body(text: &str) -> Option<Value> {
    serde_json::from_str(text.trim()).ok()
}

fn path_str<'a>(v: &'a Value, path: &str) -> Option<&'a str> {
    path.split('.').try_fold(v, |v, k| v.get(k))?.as_str()
}

fn any_path(v: &Value, paths: &[&str], pred: impl Fn(&str) -> bool) -> bool {
    paths
        .iter()
        .filter_map(|p| path_str(v, p))
        .any(|s| pred(&s.trim().go_lower()))
}

const CODE_PATHS: [&str; 4] = ["error.code", "code", "response.error.code", "body.error.code"];
const TYPE_PATHS: [&str; 4] = ["error.type", "type", "response.error.type", "body.error.type"];

/// `clienterror.IsClaudeThreadNotFound` (v8.0.27, 5c959cb, e7b2226): Claude's 404 for
/// a stale `previous_message_id` continuation, as a JSON error or plain text. Only a
/// replay of the whole conversation helps, so no credential is cooled or rotated.
pub fn is_claude_thread_not_found(status: u16, text: &str) -> bool {
    let body = text.trim();
    if status != 404 || body.is_empty() {
        return false;
    }
    let names_thread = |message: &str| {
        let lower = message.go_lower();
        lower.contains("thread state") && lower.contains("previous_message_id")
    };
    match json_body(body) {
        Some(value) => {
            path_str(&value, "error.type").is_some_and(|t| t.trim().eq_ignore_ascii_case("not_found_error"))
                && names_thread(path_str(&value, "error.message").unwrap_or_default())
        }
        None => names_thread(body),
    }
}

/// `clienterror.IsRequestFault`.
pub fn is_request_fault(status: u16, text: &str) -> bool {
    if status == 402 || status == 429 {
        return false;
    }
    let body = json_body(text);
    if let Some(body) = &body
        && status == 401
        && any_path(body, &TYPE_PATHS, |t| t == "authentication_error")
    {
        return false;
    }
    if is_claude_thread_not_found(status, text) {
        return true;
    }
    if let Some(body) = &body {
        if any_path(body, &CODE_PATHS, |c| {
            c == "model_not_found" || c == "model_not_found_error"
        }) {
            return false;
        }
        if any_path(body, &CODE_PATHS, |c| REQUEST_FAULT_CODES.contains(&c))
            || any_path(body, &TYPE_PATHS, |t| REQUEST_FAULT_TYPES.contains(&t))
        {
            return true;
        }
    }
    let lower = text.go_lower();
    if lower.contains("item with id")
        && lower.contains("not found")
        && lower.contains("items are not persisted when `store` is set to false")
    {
        return true;
    }
    matches!(status, 400 | 409 | 413 | 422)
}

fn model_support_message(text: &str) -> bool {
    let lower = text.trim().go_lower();
    !lower.is_empty()
        && [
            "model_not_supported",
            "requested model is not supported",
            "requested model is unsupported",
            "requested model is unavailable",
            "model is not supported",
            "model not supported",
            "unsupported model",
            "model unavailable",
            "not available for your plan",
            "not available for your account",
        ]
        .iter()
        .any(|p| lower.contains(p))
}

/// `isModelSupportError`.
pub fn is_model_support(status: u16, text: &str) -> bool {
    explicit_model_not_found(text, "") || (matches!(status, 400 | 404 | 422) && model_support_message(text))
}

/// `isInvalidGrantError`.
pub fn is_invalid_grant(status: u16, text: &str) -> bool {
    text.go_lower().contains("invalid_grant") && matches!(status, 0 | 400 | 401)
}

/// `isCloudflareChallengeError`.
pub fn is_cloudflare(status: u16, text: &str) -> bool {
    let lower = text.trim().go_lower();
    status < 500
        && (lower.contains("challenge-platform")
            || lower.contains("cf-mitigated")
            || lower.contains("cloudflare challenge")
            || (lower.contains("just a moment") && lower.contains("cloudflare")))
}

/// `isRequestInvalidError`: never failed over, never cooled.
pub fn is_request_invalid(e: &ExecError) -> bool {
    if explicit_request_scoped(e) {
        return true;
    }
    let status = go_status(e);
    let text = error_text(e);
    if is_cloudflare(status, &text) || is_invalid_grant(status, &text) || is_model_support(status, &text) {
        return false;
    }
    is_request_fault(status, &text)
}

/// Faults that stop a `responses/compact` request without failover.
pub fn is_compact_fault(e: &ExecError) -> bool {
    let status = go_status(e);
    let text = error_text(e);
    if credential_scoped(e) || is_cloudflare(status, &text) || is_invalid_grant(status, &text) {
        return false;
    }
    is_request_fault(status, &text) || matches!(status, 400 | 404 | 405 | 409 | 413 | 422 | 501)
}

/// Compact failures that must not change credential availability.
pub fn is_compact_neutral(e: &ExecError) -> bool {
    let status = go_status(e);
    let text = error_text(e);
    !(credential_scoped(e)
        || is_cloudflare(status, &text)
        || is_invalid_grant(status, &text)
        || matches!(status, 401 | 402 | 403 | 429))
}

/// A count_tokens 404 that names no model: the endpoint is missing, not the model.
pub fn is_count_endpoint_missing(e: &ExecError, requested_model: &str) -> bool {
    let base = crate::scheduler::canonical_model(requested_model);
    go_status(e) == 404 && !explicit_model_not_found(&error_text(e), base)
}

/// Executor-reported credential-wide quota (`IsCredentialScoped`).
pub fn credential_scoped(e: &ExecError) -> bool {
    e.scope == FailureScope::Credential && e.status == 429
}

/// A statusless model-scoped error: a plugin executor's `rpcError` without a status or
/// plain error, or a built-in executor's Go `fmt.Errorf` that is no connection fault (the
/// Claude and Antigravity compaction summary extraction and seal). Built-in executors
/// report connection faults as transport. Go classifies such an error by its message, in three separate decisions
/// (sdk/cliproxy/auth/conductor_cooldown.go): the result code (`resultErrorFromError`),
/// the cooldown skip on that result (`shouldSkipCredentialCooldown`) and the retry round
/// on the error (`isRequestRetryRoundError`).
fn statusless(e: &ExecError) -> Option<(String, String)> {
    (e.status == 0 && e.scope == FailureScope::Model).then(|| {
        let text = error_text(e);
        let lower = text.trim().go_lower();
        (text, lower)
    })
}

/// Go `shouldSkipCredentialCooldown`: request faults and transport or connection
/// lifecycle faults never cool a credential. For a statusless error, the code
/// `resultErrorFromError` assigns (model-not-found first, then lifecycle, then
/// transient) and the result's message fallbacks decide; a model-not-found code leaves
/// both fallbacks to the message, where the transient one ignores a message naming a
/// TLS handshake timeout.
pub fn skips_cooldown(e: &ExecError) -> bool {
    if is_request_invalid(e) || is_transport(e) {
        return true;
    }
    let Some((text, lower)) = statusless(e) else {
        return false;
    };
    let (lifecycle, transient) = (lifecycle_message(&lower), transient_message(&lower));
    if explicit_model_not_found(&text, "") {
        lifecycle || (transient && !lower.contains("tls handshake timeout"))
    } else {
        lifecycle || transient
    }
}

/// Go `isConnectionLifecycleMessage` on a trimmed, lowercased message.
fn lifecycle_message(lower: &str) -> bool {
    matches!(
        lower,
        "context canceled" | "context deadline exceeded" | "eof" | "unexpected eof"
    ) || [
        "websocket: close 1000",
        "websocket: close 1001",
        "websocket: close 1006",
        "unexpected eof",
    ]
    .iter()
    .any(|needle| lower.contains(needle))
        || http2_closed(lower)
}

/// Go `isTransientTransportMessage` on a trimmed, lowercased message.
fn transient_message(lower: &str) -> bool {
    const NEEDLES: [&str; 16] = [
        "tls: tls handshake",
        "tls handshake timeout",
        "wsarecv",
        "wsasend",
        "a connection attempt failed",
        "connection refused",
        "connection reset",
        "i/o timeout",
        "no such host",
        "server misbehaving",
        "network is unreachable",
        "no route to host",
        "broken pipe",
        "connection aborted",
        "use of closed network connection",
        "unexpected eof",
    ];
    NEEDLES.iter().any(|needle| lower.contains(needle)) || http2_closed(lower)
}

/// Go `isHTTP2ClosedConnectionMessage`.
fn http2_closed(lower: &str) -> bool {
    lower.contains("http2: client connection force closed via clientconn.close")
        || lower.contains("http2: client conn is closed")
}

/// Transport, timeout and connection-lifecycle faults: no cooldown, retry-round eligible.
pub fn is_transport(e: &ExecError) -> bool {
    if e.scope == FailureScope::Transport {
        return true;
    }
    let lower = error_text(e).trim().go_lower();
    // ponytail: compatibility for executors that report transport faults untyped.
    e.headers.is_empty() && lower.starts_with("upstream request failed")
}

/// `isCredentialRetryRoundStatus` or a transport fault (`isRequestRetryRoundError`).
/// A statusless error counts when its message is Go's transient transport text
/// (`isTransientTransportError`), which leaves out the lifecycle-only texts.
pub fn is_retry_round(e: &ExecError) -> bool {
    is_transport(e)
        || matches!(e.status, 403 | 408 | 429 | 500 | 502 | 503 | 504)
        || statusless(e).is_some_and(|(_, lower)| transient_message(&lower))
}

/// `isExplicitModelNotFoundError` on an error text.
pub fn explicit_model_not_found(text: &str, requested: &str) -> bool {
    json_body(text).is_some_and(|v| structured_not_found(&v, requested))
}

fn structured_not_found(v: &Value, requested: &str) -> bool {
    match v {
        Value::Object(map) => {
            let mut not_found_type = false;
            let mut exact_reference = false;
            for (key, item) in map {
                if let Value::String(text) = item {
                    match key.trim().go_lower().as_str() {
                        "code" if model_not_found_identifier(text) => return true,
                        "type" => {
                            if model_not_found_identifier(text) {
                                return true;
                            }
                            not_found_type |= not_found_identifier(text);
                        }
                        "error" | "message" | "detail" | "error_description" | "title" => {
                            if explicit_not_found_message(text, requested) {
                                return true;
                            }
                            exact_reference |= exact_model_reference(text, requested);
                        }
                        _ => {}
                    }
                }
                if matches!(item, Value::Object(_) | Value::Array(_)) && structured_not_found(item, requested) {
                    return true;
                }
            }
            not_found_type && exact_reference
        }
        Value::Array(items) => items.iter().any(|item| {
            item.as_str().is_some_and(|t| explicit_not_found_message(t, requested))
                || structured_not_found(item, requested)
        }),
        _ => false,
    }
}

fn normalize_identifier(s: &str) -> String {
    s.replace(['-', ' '], "_")
}

fn model_not_found_identifier(value: &str) -> bool {
    let mut candidate = value.trim().go_lower();
    match candidate.rfind('#') {
        Some(i) if i + 1 < candidate.len() => candidate = candidate[i + 1..].to_owned(),
        _ => {
            if let Some(q) = candidate.find('?') {
                candidate.truncate(q);
            }
            let trimmed = candidate.trim_end_matches('/');
            candidate = match trimmed.rfind(['/', ':']) {
                Some(i) => trimmed[i + 1..].to_owned(),
                None => trimmed.to_owned(),
            };
        }
    }
    matches!(
        normalize_identifier(&candidate).as_str(),
        "model_not_found" | "model_not_found_error" | "unknown_model" | "model_does_not_exist" | "model_not_exist"
    )
}

fn not_found_identifier(value: &str) -> bool {
    matches!(
        normalize_identifier(&value.trim().go_lower()).as_str(),
        "not_found" | "not_found_error"
    )
}

fn trim_sentence(s: &str) -> String {
    s.trim()
        .go_lower()
        .trim_matches(|c| " .!;\t\r\n".contains(c))
        .to_owned()
}

fn strip_prefix<'a>(lower: &'a str, prefix: &str) -> Option<&'a str> {
    if lower == prefix {
        return Some("");
    }
    let rest = lower
        .strip_prefix(&format!("{prefix} "))
        .or_else(|| lower.strip_prefix(&format!("{prefix}:")))?;
    let rest = rest.trim();
    Some(rest.strip_prefix(':').unwrap_or(rest).trim())
}

fn explicit_not_found_message(message: &str, requested: &str) -> bool {
    let lower = trim_sentence(message);
    if lower.is_empty() || lower.contains("in request") || lower.contains("in body") || lower.contains("request body") {
        return false;
    }
    let normalized = lower.replace('-', "_");
    if normalized.contains("model_not_found") || normalized.contains("unknown_model") {
        return true;
    }
    for prefix in ["no such model", "unknown model"] {
        if let Some(rest) = strip_prefix(&lower, prefix) {
            if rest.is_empty() {
                return true;
            }
            return trim_model_reference(rest, requested).is_some_and(|s| s.is_empty());
        }
    }
    for prefix in ["the requested model", "requested model", "the model", "model"] {
        if let Some(rest) = strip_prefix(&lower, prefix) {
            if missing_phrase(rest) {
                return true;
            }
            return trim_model_reference(rest, requested).is_some_and(missing_phrase);
        }
    }
    false
}

fn exact_model_reference(message: &str, requested: &str) -> bool {
    let lower = trim_sentence(message);
    for prefix in ["the requested model", "requested model", "the model", "model"] {
        if let Some(rest) = strip_prefix(&lower, prefix) {
            return trim_model_reference(rest, requested).is_some_and(|s| s.is_empty());
        }
    }
    false
}

fn trim_model_reference<'a>(value: &'a str, requested: &str) -> Option<&'a str> {
    let model = requested.trim().go_lower();
    if model.is_empty() {
        return None;
    }
    for candidate in [
        model.clone(),
        format!("'{model}'"),
        format!("\"{model}\""),
        format!("`{model}`"),
    ] {
        if value == candidate {
            return Some("");
        }
        if let Some(rest) = value.strip_prefix(&candidate)
            && (rest.is_empty() || rest.starts_with([' ', ':', ',']))
        {
            return Some(rest.trim_start_matches([' ', ':', ',']));
        }
    }
    None
}

fn missing_phrase(value: &str) -> bool {
    matches!(
        value.trim_matches(|c| " .!;\t\r\n".contains(c)),
        "not found"
            | "was not found"
            | "could not be found"
            | "does not exist"
            | "doesn't exist"
            | "not exist"
            | "is unknown"
            | "does not exist or you do not have access to it"
    )
}

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

    /// The Claude and Antigravity compaction summary failures (Go `fmt.Errorf`, v8.0.35
    /// 2bc236d2): a normal model failure on the trigger path, availability-neutral on the
    /// compact alt, and never a retry round.
    #[test]
    fn compaction_summary_failures_follow_go() {
        for message in [
            "extract summary: no summary text found in upstream response",
            "seal compaction capsule: generate nonce: x",
        ] {
            let e = ExecError::local(0, FailureScope::Model, message);
            assert!(!skips_cooldown(&e), "{message}");
            assert!(!is_retry_round(&e), "{message}");
            assert!(!is_transport(&e), "{message}");
            assert!(is_compact_neutral(&e) && !is_compact_fault(&e), "{message}");
            assert!(!is_request_invalid(&e), "{message}");
        }
    }

    /// Go 56eee6a4 (TestManager_MarkResult_ConnectionLifecycleDoesNotCooldown and the
    /// shouldRetryAfterError table): a statusless HTTP/2 closed-connection error, bare or
    /// wrapped as a `url.Error`, is a connection drop: no cooldown, and a retry round.
    #[test]
    fn http2_closed_connections_are_transient_like_go() {
        for message in [
            "http2: client connection force closed via ClientConn.Close",
            "http2: client conn is closed",
            "Post \"https://example.com\": http2: client conn is closed",
        ] {
            let e = ExecError::local(0, FailureScope::Model, message);
            assert!(skips_cooldown(&e), "{message}");
            assert!(is_retry_round(&e), "{message}");
        }
        let other = ExecError::local(0, FailureScope::Model, "http2: server sent GOAWAY");
        assert!(!skips_cooldown(&other) && !is_retry_round(&other));
    }

    fn upstream(status: u16, body: &str) -> ExecError {
        let mut e = ExecError::local(status, FailureScope::Request, body.to_owned());
        e.headers.insert("content-type", "application/json".parse().unwrap());
        e
    }

    #[test]
    fn request_faults_follow_go_status_and_body_rules() {
        // Anthropic's invalid_request_error envelope is a request fault even on 500.
        assert!(is_request_invalid(&upstream(
            500,
            r#"{"type":"error","error":{"type":"invalid_request_error"}}"#
        )));
        // 429/402 stay credential failures whatever the body says.
        assert!(!is_request_invalid(&upstream(
            429,
            r#"{"error":{"type":"invalid_request_error"}}"#
        )));
        // 401 authentication_error is a credential failure.
        assert!(!is_request_invalid(&upstream(
            401,
            r#"{"error":{"type":"authentication_error"}}"#
        )));
        // An upstream 404 marked Request by the executor is not a request fault in Go.
        assert!(!is_request_invalid(&upstream(404, "not found")));
        // Except Claude's missing thread state (v8.0.27 TestIsRequestFault cases): only
        // the client can recover, by replaying the conversation.
        const THREAD: &str = "No thread state was found for the requested previous_message_id. Replay the full conversation with thread create to start a new Thread.";
        let json = format!(r#"{{"type":"error","error":{{"type":"not_found_error","message":"{THREAD}"}}}}"#);
        assert!(is_request_invalid(&upstream(404, &json)));
        assert!(is_request_invalid(&upstream(404, THREAD)));
        assert!(!is_request_invalid(&upstream(
            404,
            r#"{"error":{"type":"not_found_error","message":"Not Found"}}"#
        )));
        assert!(!is_request_fault(500, &json));
        assert!(is_request_invalid(&upstream(422, "bad")));
        // Model-not-found is a capability mismatch, even on 400.
        assert!(!is_request_invalid(&upstream(
            400,
            r#"{"error":{"code":"model_not_found"}}"#
        )));
        assert!(!is_request_invalid(&upstream(400, "invalid_grant")));
        // A local Request error (no upstream headers) is explicit.
        assert!(is_request_invalid(&ExecError::local(
            501,
            FailureScope::Request,
            "not supported"
        )));
        let transport = ExecError::local(502, FailureScope::Transport, "reset");
        assert!(!is_request_invalid(&transport) && is_retry_round(&transport));
        assert_eq!(response_status(&transport), 500);
    }

    #[test]
    fn special_classifiers_match_go() {
        assert!(is_model_support(404, "The model is not supported for this account"));
        assert!(!is_model_support(500, "model not supported"));
        assert!(!is_model_support(
            500,
            r#"{"error":{"type":"not_found_error","message":"model: claude-x"}}"#
        ));
        assert!(explicit_model_not_found(
            r#"{"type":"error","error":{"type":"not_found_error","message":"model: claude-x"}}"#,
            "claude-x"
        ));
        assert!(explicit_model_not_found(
            r#"{"error":{"message":"The model `gpt-9` does not exist"}}"#,
            "gpt-9"
        ));
        assert!(!explicit_model_not_found(
            r#"{"error":{"message":"model field missing in request body"}}"#,
            ""
        ));
        assert!(is_invalid_grant(400, r#"{"error":"invalid_grant"}"#));
        assert!(!is_invalid_grant(403, "invalid_grant"));
        assert!(is_cloudflare(403, "<title>Just a moment...</title> cloudflare"));
        assert!(!is_cloudflare(503, "challenge-platform"));
        let count_404 = upstream(404, "Not Found");
        assert!(is_count_endpoint_missing(&count_404, "claude-x(high)"));
        assert!(!is_count_endpoint_missing(
            &upstream(404, r#"{"error":{"code":"model_not_found"}}"#),
            "claude-x"
        ));
        assert!(is_compact_fault(&upstream(404, "nope")) && is_compact_neutral(&upstream(404, "nope")));
        assert!(!is_compact_neutral(&upstream(429, "quota")));
        let mut empty = upstream(500, "");
        empty.body = Bytes::new();
        assert_eq!(error_text(&empty), "status 500");
    }
}