nemo-relay 0.7.2

Core Rust SDK for NeMo Relay observability, scope management, and runtime instrumentation.
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
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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Cross-provider codec parity tests for the NeMo Relay core crate.
//!
//! Each test builds the same logical scenario in all three built-in provider
//! schemas (OpenAI Chat Completions, Anthropic Messages, OpenAI Responses) and
//! asserts that detection plus normalization produce agreeing output. Where
//! the schemas legitimately diverge, the divergence is asserted explicitly:
//! the asymmetry is part of the parity contract, and a change here means one
//! codec drifted from the others.

use serde_json::json;

use super::model_pricing::pricing_test_mutex;
use super::request::{GenerationParams, Message, MessageContent};
use super::resolve::{normalize_request, normalize_request_with_hint, normalize_response};
use super::response::{
    AnnotatedLlmResponse, ApiSpecificResponse, CostEstimate, CostSource, FinishReason,
    PricingCatalog, PricingResolver, Usage, reset_active_pricing_resolver,
    set_active_pricing_resolver,
};
use crate::api::llm::LlmRequest;
use crate::json::Json;

// -------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------

struct ResetPricingResolverGuard;

impl Drop for ResetPricingResolverGuard {
    fn drop(&mut self) {
        let _ = reset_active_pricing_resolver();
    }
}

fn install_parity_pricing(model_id: &str) {
    let catalog = PricingCatalog::from_json_str(
        &json!({
            "version": 1,
            "entries": [
                {
                    "provider": "test",
                    "model_id": model_id,
                    "pricing_as_of": "2026-06-05",
                    "pricing_source": "test",
                    "rates": {
                        "input_per_million": 0.15,
                        "output_per_million": 0.60,
                        "cache_read_per_million": 0.075
                    },
                    "prompt_cache": {
                        "read_accounting": "included_in_prompt_tokens"
                    }
                }
            ]
        })
        .to_string(),
    )
    .unwrap();
    set_active_pricing_resolver(PricingResolver::from_catalogs(vec![catalog])).unwrap();
}

fn req(content: Json) -> LlmRequest {
    LlmRequest {
        headers: serde_json::Map::new(),
        content,
    }
}

fn decode(raw: &Json) -> AnnotatedLlmResponse {
    normalize_response(raw).unwrap_or_else(|| panic!("response should detect and decode: {raw}"))
}

/// The same logical response (one assistant text message) in each schema.
fn chat_text_response(model: &str) -> Json {
    json!({
        "id": "chatcmpl-parity",
        "object": "chat.completion",
        "model": model,
        "choices": [{
            "index": 0,
            "message": {"role": "assistant", "content": "hello"},
            "finish_reason": "stop"
        }]
    })
}

fn anthropic_text_response(model: &str) -> Json {
    json!({
        "id": "msg_parity",
        "type": "message",
        "role": "assistant",
        "model": model,
        "content": [{"type": "text", "text": "hello"}],
        "stop_reason": "end_turn"
    })
}

fn responses_text_response(model: &str) -> Json {
    json!({
        "id": "resp_parity",
        "model": model,
        "status": "completed",
        "output": [{
            "type": "message",
            "role": "assistant",
            "content": [{"type": "output_text", "text": "hello"}]
        }]
    })
}

/// The same logical usage (1000 prompt / 500 completion / 200 cache-read)
/// expressed in each schema's native usage shape. `extra_usage` merges extra
/// schema-specific usage keys into the payload.
fn chat_response_with_usage(model: &str, extra_usage: Json) -> Json {
    let mut raw = chat_text_response(model);
    let mut usage = json!({
        "prompt_tokens": 1000,
        "completion_tokens": 500,
        "total_tokens": 1500,
        "prompt_tokens_details": {"cached_tokens": 200}
    });
    merge_object(&mut usage, extra_usage);
    raw.as_object_mut().unwrap().insert("usage".into(), usage);
    raw
}

fn anthropic_response_with_usage(model: &str, extra_usage: Json) -> Json {
    let mut raw = anthropic_text_response(model);
    // Anthropic reports no total_tokens; the codec computes prompt + completion.
    let mut usage = json!({
        "input_tokens": 1000,
        "output_tokens": 500,
        "cache_read_input_tokens": 200
    });
    merge_object(&mut usage, extra_usage);
    raw.as_object_mut().unwrap().insert("usage".into(), usage);
    raw
}

fn responses_response_with_usage(model: &str, extra_usage: Json) -> Json {
    let mut raw = responses_text_response(model);
    let mut usage = json!({
        "input_tokens": 1000,
        "output_tokens": 500,
        "total_tokens": 1500,
        "input_tokens_details": {"cached_tokens": 200}
    });
    merge_object(&mut usage, extra_usage);
    raw.as_object_mut().unwrap().insert("usage".into(), usage);
    raw
}

fn merge_object(target: &mut Json, extra: Json) {
    if let (Some(target), Json::Object(extra)) = (target.as_object_mut(), extra) {
        target.extend(extra);
    }
}

// ===================================================================
// Response parity: model name and message text
// ===================================================================

#[test]
fn test_response_model_name_and_text_parity() {
    let chat = decode(&chat_text_response("parity-shared-model"));
    let anthropic = decode(&anthropic_text_response("parity-shared-model"));
    let responses = decode(&responses_text_response("parity-shared-model"));

    for decoded in [&chat, &anthropic, &responses] {
        assert_eq!(decoded.model.as_deref(), Some("parity-shared-model"));
        assert_eq!(decoded.response_text(), Some("hello"));
        assert_eq!(decoded.finish_reason, Some(FinishReason::Complete));
    }

    // Response IDs keep the provider-native value because IDs are
    // provider-scoped identifiers; only the field mapping is normalized.
    assert_eq!(chat.id.as_deref(), Some("chatcmpl-parity"));
    assert_eq!(anthropic.id.as_deref(), Some("msg_parity"));
    assert_eq!(responses.id.as_deref(), Some("resp_parity"));
}

// ===================================================================
// Response parity: finish reasons
// ===================================================================

#[test]
fn test_finish_reason_complete_parity() {
    let raws = [
        json!({"choices": [{"message": {"role": "assistant", "content": "x"}, "finish_reason": "stop"}]}),
        json!({"type": "message", "content": [{"type": "text", "text": "x"}], "stop_reason": "end_turn"}),
        json!({"status": "completed", "output": [{"type": "message", "content": [{"type": "output_text", "text": "x"}]}]}),
    ];
    for raw in &raws {
        assert_eq!(
            decode(raw).finish_reason,
            Some(FinishReason::Complete),
            "expected Complete for {raw}",
        );
    }
}

#[test]
fn test_finish_reason_length_parity() {
    let raws = [
        json!({"choices": [{"message": {"role": "assistant", "content": "x"}, "finish_reason": "length"}]}),
        json!({"type": "message", "content": [{"type": "text", "text": "x"}], "stop_reason": "max_tokens"}),
        json!({
            "status": "incomplete",
            "incomplete_details": {"reason": "max_output_tokens"},
            "output": []
        }),
    ];
    for raw in &raws {
        assert_eq!(
            decode(raw).finish_reason,
            Some(FinishReason::Length),
            "expected Length for {raw}",
        );
    }
}

#[test]
fn test_finish_reason_tool_use_parity_and_responses_divergence() {
    let chat = decode(&json!({
        "choices": [{
            "message": {
                "role": "assistant",
                "content": null,
                "tool_calls": [{
                    "id": "call_parity_1",
                    "type": "function",
                    "function": {"name": "get_weather", "arguments": "{\"city\":\"NYC\"}"}
                }]
            },
            "finish_reason": "tool_calls"
        }]
    }));
    let anthropic = decode(&json!({
        "type": "message",
        "content": [{
            "type": "tool_use",
            "id": "call_parity_1",
            "name": "get_weather",
            "input": {"city": "NYC"}
        }],
        "stop_reason": "tool_use"
    }));
    let responses = decode(&json!({
        "status": "completed",
        "output": [{
            "type": "function_call",
            "call_id": "call_parity_1",
            "name": "get_weather",
            "arguments": "{\"city\":\"NYC\"}"
        }]
    }));

    assert_eq!(chat.finish_reason, Some(FinishReason::ToolUse));
    assert_eq!(anthropic.finish_reason, Some(FinishReason::ToolUse));
    // The Responses API has no distinct tool-use terminal status: a
    // function_call turn still ends with status "completed", so the
    // normalized finish reason is Complete and tool-call presence must be
    // read from `tool_calls` instead.
    assert_eq!(responses.finish_reason, Some(FinishReason::Complete));
    assert!(responses.has_tool_calls());
}

// ===================================================================
// Response parity: tool calls
// ===================================================================

#[test]
fn test_response_tool_call_parity() {
    // One logical tool invocation. The id lives in a schema-specific field
    // (chat `tool_calls[].id`, Anthropic `tool_use.id`, Responses `call_id`),
    // and arguments arrive as a JSON string in the OpenAI schemas but as
    // parsed JSON in Anthropic's `input`. Normalization erases all of that.
    let chat = decode(&json!({
        "choices": [{
            "message": {
                "role": "assistant",
                "content": null,
                "tool_calls": [{
                    "id": "call_parity_1",
                    "type": "function",
                    "function": {
                        "name": "get_weather",
                        "arguments": "{\"city\":\"NYC\",\"units\":\"c\"}"
                    }
                }]
            },
            "finish_reason": "tool_calls"
        }]
    }));
    let anthropic = decode(&json!({
        "type": "message",
        "content": [{
            "type": "tool_use",
            "id": "call_parity_1",
            "name": "get_weather",
            "input": {"city": "NYC", "units": "c"}
        }],
        "stop_reason": "tool_use"
    }));
    // The Responses item-level `id` is ignored; the cross-provider
    // correlation id is `call_id`.
    let responses = decode(&json!({
        "status": "completed",
        "output": [{
            "type": "function_call",
            "id": "fc_item_1",
            "call_id": "call_parity_1",
            "name": "get_weather",
            "arguments": "{\"city\":\"NYC\",\"units\":\"c\"}"
        }]
    }));

    let chat_calls = chat.tool_calls.expect("chat tool calls");
    let anthropic_calls = anthropic.tool_calls.expect("anthropic tool calls");
    let responses_calls = responses.tool_calls.expect("responses tool calls");

    assert_eq!(chat_calls, anthropic_calls);
    assert_eq!(chat_calls, responses_calls);
    assert_eq!(chat_calls.len(), 1);
    assert_eq!(chat_calls[0].id, "call_parity_1");
    assert_eq!(chat_calls[0].name, "get_weather");
    assert_eq!(
        chat_calls[0].arguments,
        json!({"city": "NYC", "units": "c"})
    );
    assert!(chat_calls[0].arguments.is_object());
}

// ===================================================================
// Response parity: usage
// ===================================================================

#[test]
fn test_response_usage_parity() {
    // The model name is unique to this test and never appears in any pricing
    // catalog, so estimation deterministically yields no cost.
    let chat = decode(&chat_response_with_usage("parity-usage-model", json!({})));
    let anthropic = decode(&anthropic_response_with_usage(
        "parity-usage-model",
        json!({}),
    ));
    let responses = decode(&responses_response_with_usage(
        "parity-usage-model",
        json!({}),
    ));

    let expected = Usage {
        prompt_tokens: Some(1000),
        completion_tokens: Some(500),
        total_tokens: Some(1500),
        cache_read_tokens: Some(200),
        cache_write_tokens: None,
        cost: None,
    };
    assert_eq!(chat.usage, Some(expected.clone()));
    // Anthropic supplies no total_tokens on the wire; the codec computes
    // prompt + completion so the normalized usage still matches the others.
    assert_eq!(anthropic.usage, Some(expected.clone()));
    assert_eq!(responses.usage, Some(expected));
}

#[test]
fn test_response_usage_schema_specific_extras() {
    let chat = decode(&chat_response_with_usage("parity-usage-model", json!({})));
    let anthropic = decode(&anthropic_response_with_usage(
        "parity-usage-model",
        json!({"cache_creation_input_tokens": 64}),
    ));
    let responses = decode(&responses_response_with_usage(
        "parity-usage-model",
        json!({"output_tokens_details": {"reasoning_tokens": 128}}),
    ));

    // Only Anthropic reports prompt-cache writes, so cache_write_tokens is
    // populated for Anthropic alone.
    assert_eq!(
        anthropic.usage.as_ref().unwrap().cache_write_tokens,
        Some(64)
    );
    assert_eq!(chat.usage.as_ref().unwrap().cache_write_tokens, None);
    assert_eq!(responses.usage.as_ref().unwrap().cache_write_tokens, None);

    // Only the Responses schema reports reasoning tokens; the normalized
    // Usage has no reasoning slot, so the value is preserved in the
    // schema-specific api_specific payload.
    match responses.api_specific.as_ref().unwrap() {
        ApiSpecificResponse::OpenAIResponses {
            output_tokens_details,
            ..
        } => {
            assert_eq!(
                output_tokens_details,
                &Some(json!({"reasoning_tokens": 128}))
            );
        }
        other => panic!("expected OpenAIResponses api_specific, got {other:?}"),
    }
    assert!(matches!(
        chat.api_specific,
        Some(ApiSpecificResponse::OpenAIChat { .. })
    ));
    assert!(matches!(
        anthropic.api_specific,
        Some(ApiSpecificResponse::AnthropicMessages { .. })
    ));

    // The shared usage facts still agree despite the schema-specific extras.
    for decoded in [&chat, &anthropic, &responses] {
        let usage = decoded.usage.as_ref().unwrap();
        assert_eq!(usage.prompt_tokens, Some(1000));
        assert_eq!(usage.completion_tokens, Some(500));
        assert_eq!(usage.total_tokens, Some(1500));
        assert_eq!(usage.cache_read_tokens, Some(200));
    }
}

// ===================================================================
// Response parity: cost
// ===================================================================

#[test]
fn test_provider_reported_cost_object_parity() {
    // Provider-reported cost always wins over estimation, so this test does
    // not depend on the active pricing resolver.
    let cost = json!({"cost": {
        "total": 0.0123,
        "input": 0.004,
        "output": 0.0083,
        "currency": "USD"
    }});
    let chat = decode(&chat_response_with_usage(
        "parity-reported-model",
        cost.clone(),
    ));
    let anthropic = decode(&anthropic_response_with_usage(
        "parity-reported-model",
        cost.clone(),
    ));
    let responses = decode(&responses_response_with_usage(
        "parity-reported-model",
        cost,
    ));

    let expected = CostEstimate {
        total: Some(0.0123),
        currency: "USD".to_string(),
        input: Some(0.004),
        output: Some(0.0083),
        cache_read: None,
        cache_write: None,
        source: CostSource::ProviderReported,
        pricing_provider: None,
        pricing_model: None,
        pricing_as_of: None,
        pricing_source: None,
    };
    assert_eq!(chat.usage.unwrap().cost, Some(expected.clone()));
    assert_eq!(anthropic.usage.unwrap().cost, Some(expected.clone()));
    assert_eq!(responses.usage.unwrap().cost, Some(expected));
}

#[test]
fn test_provider_reported_scalar_cost_parity() {
    // The legacy scalar `cost_usd` is accepted by all three schemas and is
    // always interpreted as a USD total.
    let cost = json!({"cost_usd": 0.5});
    let decoded = [
        decode(&chat_response_with_usage(
            "parity-reported-model",
            cost.clone(),
        )),
        decode(&anthropic_response_with_usage(
            "parity-reported-model",
            cost.clone(),
        )),
        decode(&responses_response_with_usage(
            "parity-reported-model",
            cost,
        )),
    ];
    for response in decoded {
        let cost = response.usage.unwrap().cost.expect("scalar reported cost");
        assert_eq!(cost.total, Some(0.5));
        assert_eq!(cost.currency, "USD");
        assert_eq!(cost.source, CostSource::ProviderReported);
        assert_eq!(cost.input, None);
        assert_eq!(cost.output, None);
    }
}

#[test]
fn test_estimated_cost_parity_for_identical_model_and_usage() {
    let _pricing_guard = pricing_test_mutex()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    install_parity_pricing("parity-priced-model");
    let _reset_guard = ResetPricingResolverGuard;

    // Each codec infers its own default provider ("openai" vs "anthropic"),
    // but pricing lookup falls back to the model-only key, so an identical
    // model + normalized usage must estimate identically everywhere.
    let chat = decode(&chat_response_with_usage("parity-priced-model", json!({})));
    let anthropic = decode(&anthropic_response_with_usage(
        "parity-priced-model",
        json!({}),
    ));
    let responses = decode(&responses_response_with_usage(
        "parity-priced-model",
        json!({}),
    ));

    let chat_cost = chat.usage.unwrap().cost.expect("chat estimated cost");
    let anthropic_cost = anthropic
        .usage
        .unwrap()
        .cost
        .expect("anthropic estimated cost");
    let responses_cost = responses
        .usage
        .unwrap()
        .cost
        .expect("responses estimated cost");

    assert_eq!(chat_cost, anthropic_cost);
    assert_eq!(chat_cost, responses_cost);
    // 800 billable prompt (1000 - 200 cached) * 0.15/M
    //   + 500 completion * 0.60/M + 200 cache-read * 0.075/M
    let total = chat_cost.total.expect("estimated total");
    assert!(
        (total - 0.000_435).abs() < 1e-9,
        "unexpected estimated total: {total}"
    );
    assert_eq!(chat_cost.currency, "USD");
    assert_eq!(chat_cost.source, CostSource::ModelPricing);
    assert_eq!(chat_cost.pricing_provider.as_deref(), Some("test"));
    assert_eq!(
        chat_cost.pricing_model.as_deref(),
        Some("parity-priced-model")
    );
}

// ===================================================================
// Request parity: detection and hint hardening
// ===================================================================

#[test]
fn test_request_hint_never_overrides_strong_signals() {
    // A wrong hint must not reroute a body whose shape is unambiguous.
    let responses_request = req(json!({
        "model": "gpt-parity",
        "instructions": "You are terse.",
        "input": "Summarize the docs.",
        "max_output_tokens": 64
    }));
    let hinted = normalize_request_with_hint(&responses_request, Some("anthropic"))
        .expect("responses request decodes despite wrong hint");
    assert_eq!(
        hinted,
        normalize_request(&responses_request).expect("responses request decodes"),
    );
    // Responses-only field proves the Responses codec handled the body.
    assert_eq!(hinted.max_output_tokens, Some(64));

    let anthropic_request = req(json!({
        "model": "claude-parity",
        "system": "You are terse.",
        "messages": [{"role": "user", "content": "Summarize the docs."}],
        "stop_sequences": ["END"]
    }));
    let hinted = normalize_request_with_hint(&anthropic_request, Some("openai.chat"))
        .expect("anthropic request decodes despite wrong hint");
    assert_eq!(
        hinted,
        normalize_request(&anthropic_request).expect("anthropic request decodes"),
    );
    // stop_sequences normalized into params (not left in extra) proves the
    // Anthropic codec handled the body.
    let stop = hinted
        .params
        .as_ref()
        .and_then(|params| params.stop.as_ref())
        .expect("anthropic stop_sequences normalized");
    assert_eq!(stop, &vec!["END".to_string()]);
    assert!(!hinted.extra.contains_key("stop_sequences"));
}

#[test]
fn test_request_unknown_hint_matches_hintless_normalization() {
    // Unrecognized hint strings are ignored: full decoded output (not just
    // surface detection) must match the hintless path for every schema.
    let bodies = [
        json!({"model": "m", "instructions": "sys", "input": "hi"}),
        json!({"model": "m", "system": "sys", "messages": [{"role": "user", "content": "hi"}]}),
        json!({"model": "m", "messages": [{"role": "user", "content": "hi"}]}),
    ];
    for body in &bodies {
        let request = req(body.clone());
        let baseline = normalize_request(&request).expect("canonical body decodes");
        for hint in ["gemini", "not-a-provider", "anthropic.count_tokens"] {
            assert_eq!(
                normalize_request_with_hint(&request, Some(hint)).as_ref(),
                Some(&baseline),
                "hint {hint:?} must not change normalization for {body}",
            );
        }
    }
}

#[test]
fn test_request_hint_none_equals_normalize_request() {
    // normalize_request_with_hint(None) is the same full decode as
    // normalize_request, for every canonical body shape.
    let bodies = [
        json!({"model": "m", "instructions": "sys", "input": "hi"}),
        json!({"model": "m", "system": "sys", "messages": [{"role": "user", "content": "hi"}]}),
        json!({"model": "m", "messages": [{"role": "user", "content": "hi"}]}),
    ];
    for body in &bodies {
        let request = req(body.clone());
        assert_eq!(
            normalize_request_with_hint(&request, None),
            normalize_request(&request),
            "hint=None must equal normalize_request for {body}",
        );
    }
}

// ===================================================================
// Request parity: normalization of an equivalent request
// ===================================================================

#[test]
fn test_request_normalization_parity() {
    let chat = normalize_request(&req(json!({
        "model": "parity-request-model",
        "messages": [
            {"role": "system", "content": "You are terse."},
            {"role": "user", "content": "Summarize the docs."}
        ],
        "temperature": 0.5,
        "max_tokens": 256,
        "stop": ["END"]
    })))
    .expect("chat request decodes");

    let anthropic = normalize_request(&req(json!({
        "model": "parity-request-model",
        "system": "You are terse.",
        "messages": [{"role": "user", "content": "Summarize the docs."}],
        "temperature": 0.5,
        "max_tokens": 256,
        "stop_sequences": ["END"]
    })))
    .expect("anthropic request decodes");

    let responses = normalize_request(&req(json!({
        "model": "parity-request-model",
        "instructions": "You are terse.",
        "input": "Summarize the docs.",
        "temperature": 0.5,
        "max_output_tokens": 256
    })))
    .expect("responses request decodes");

    let expected_messages = vec![
        Message::System {
            content: MessageContent::Text("You are terse.".to_string()),
            name: None,
        },
        Message::User {
            content: MessageContent::Text("Summarize the docs.".to_string()),
            name: None,
        },
    ];
    assert_eq!(chat.messages, expected_messages);
    let expected_user_messages = vec![Message::User {
        content: MessageContent::Text("Summarize the docs.".to_string()),
        name: None,
    }];
    assert_eq!(anthropic.messages, expected_user_messages);
    assert_eq!(responses.messages, expected_user_messages);
    assert_eq!(
        anthropic.instructions,
        Some(MessageContent::Text("You are terse.".to_string()))
    );
    assert_eq!(anthropic.instructions, responses.instructions);
    for decoded in [&chat, &anthropic, &responses] {
        assert_eq!(decoded.model.as_deref(), Some("parity-request-model"));
        assert_eq!(decoded.system_prompt(), Some("You are terse."));
        assert_eq!(decoded.last_user_message(), Some("Summarize the docs."));
    }

    // Chat `max_tokens`/`stop` and Anthropic `max_tokens`/`stop_sequences`
    // normalize into identical GenerationParams.
    let expected_params = GenerationParams {
        temperature: Some(0.5),
        max_tokens: Some(256),
        top_p: None,
        stop: Some(vec!["END".to_string()]),
    };
    assert_eq!(chat.params, Some(expected_params.clone()));
    assert_eq!(anthropic.params, Some(expected_params));

    // Responses schema deviations: `max_output_tokens` maps into
    // params.max_tokens like the other schemas but is also preserved on the
    // Responses-only field, and the schema has no stop sequences, so
    // params.stop stays None.
    assert_eq!(
        responses.params,
        Some(GenerationParams {
            temperature: Some(0.5),
            max_tokens: Some(256),
            top_p: None,
            stop: None,
        })
    );
    assert_eq!(responses.max_output_tokens, Some(256));
    assert_eq!(chat.max_output_tokens, None);
    assert_eq!(anthropic.max_output_tokens, None);
}

#[test]
fn baseline_patching_keeps_raw_array_fields_with_reordered_logical_items() {
    let original = json!([
        {"type": "text", "text": "a", "provider_marker": "A"},
        {"type": "text", "text": "b", "provider_marker": "B"},
        {"type": "text", "text": "c", "provider_marker": "C"}
    ]);
    let baseline = json!([
        {"type": "text", "text": "a"},
        {"type": "text", "text": "b"},
        {"type": "text", "text": "c"}
    ]);
    let edited = json!([
        {"type": "text", "text": "b"},
        {"type": "text", "text": "a"},
        {"type": "text", "text": "c"}
    ]);

    assert_eq!(
        super::patch_changed_json(&original, &baseline, &edited).unwrap(),
        json!([
            {"type": "text", "text": "b", "provider_marker": "B"},
            {"type": "text", "text": "a", "provider_marker": "A"},
            {"type": "text", "text": "c", "provider_marker": "C"}
        ])
    );
}

#[test]
fn baseline_patching_does_not_pair_reordered_deletion_with_unrelated_insertion() {
    let original = json!([
        {"type": "text", "text": "a", "provider_marker": "A"},
        {"type": "text", "text": "b", "provider_marker": "B"}
    ]);
    let baseline = json!([
        {"type": "text", "text": "a"},
        {"type": "text", "text": "b"}
    ]);
    let edited = json!([
        {"type": "text", "text": "new"},
        {"type": "text", "text": "a"}
    ]);

    assert_eq!(
        super::patch_changed_json(&original, &baseline, &edited).unwrap(),
        json!([
            {"type": "text", "text": "new"},
            {"type": "text", "text": "a", "provider_marker": "A"}
        ])
    );
}

#[test]
fn baseline_patching_handles_insert_delete_and_duplicate_reorders() {
    let duplicate_a = json!({"type": "text", "text": "a"});
    let b = json!({"type": "text", "text": "b"});
    let original = json!([
        {"type": "text", "text": "a", "provider_marker": "A1"},
        {"type": "text", "text": "a", "provider_marker": "A2"},
        {"type": "text", "text": "b", "provider_marker": "B"}
    ]);
    let baseline = Json::Array(vec![duplicate_a.clone(), duplicate_a.clone(), b.clone()]);
    let edited = Json::Array(vec![
        duplicate_a.clone(),
        b,
        duplicate_a,
        json!({"type": "text", "text": "new"}),
    ]);

    assert_eq!(
        super::patch_changed_json(&original, &baseline, &edited).unwrap(),
        json!([
            {"type": "text", "text": "a", "provider_marker": "A1"},
            {"type": "text", "text": "b", "provider_marker": "B"},
            {"type": "text", "text": "a", "provider_marker": "A2"},
            {"type": "text", "text": "new"}
        ])
    );
}

#[test]
fn baseline_patching_rejects_multiple_reordered_and_edited_items_without_provenance() {
    let original = json!([
        {"type": "text", "text": "a", "provider_marker": "A"},
        {"type": "text", "text": "b", "provider_marker": "B"}
    ]);
    let baseline = json!([
        {"type": "text", "text": "a"},
        {"type": "text", "text": "b"}
    ]);
    let edited = json!([
        {"type": "text", "text": "b-edited"},
        {"type": "text", "text": "a-edited"}
    ]);

    let error = super::patch_changed_json(&original, &baseline, &edited).unwrap_err();
    assert!(
        error
            .to_string()
            .contains("multiple edited array items without stable identities")
    );
}