ramvamp-core 0.1.1

Runtime for streaming fine-grained MoE experts from NVMe: packed format, io_uring reads, LFU expert cache, CPU kernels, KV cache, generation loop
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
//! Chat message types and the vendored 2507-Instruct ChatML renderer.
//!
//! The Qwen3-30B-A3B-Instruct-2507 chat template (pinned revision
//! `0d7cf23991f47feeb3a57ecb4c9cee8ea4a17bfe`) is replicated here directly
//! in Rust; no Jinja engine runs at inference time. For the supported roles
//! the template reduces to plain ChatML:
//!
//! ```text
//! <|im_start|>{role}\n{content}<|im_end|>\n     per message
//! <|im_start|>assistant\n                        when generation is requested
//! ```
//!
//! with one structural quirk kept for fidelity: a *leading* system message
//! is emitted by a preamble block and skipped by the message loop, while a
//! system message later in the conversation is rendered in place like any
//! other turn. Both paths produce the same ChatML shape, so the observable
//! output is identical to the naive per-message rendering — the fixture
//! snapshots in `fixtures/chat_fixtures.json` (generated by the reference
//! `transformers` implementation) prove it.
//!
//! The tool-calling branches are rendered too, and none of them is plain
//! ChatML:
//!
//! * a **non-empty** `tools` list *replaces* the system turn with a single
//!   `# Tools` turn that folds in a leading system message and lists every
//!   definition as `json.dumps(tool, ensure_ascii=False)` (see
//!   [`pyjson`](super::pyjson)). An *empty* list is falsy in Jinja, so it
//!   takes the plain-chat path instead.
//! * an assistant turn's [`tool_calls`](ChatMessage::tool_calls) are appended
//!   to its content as `<tool_call>` blocks, inside the same turn.
//! * a [`Role::Tool`] message renders as a **`user`** turn wrapping the result
//!   in `<tool_response>`, and consecutive tool messages *merge* into one such
//!   turn.
//!
//! Non-string message content (the template coerces it to `""`) cannot be
//! expressed here: [`ChatMessage::content`] is always a string.

use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::TokenizerError;
use super::pyjson;

/// Chat roles this build renders.
///
/// Serialized in lowercase (`system` / `user` / `assistant` / `tool`),
/// exactly as they appear in the wire format. Deserializing any other role
/// string fails; see [`TokenizerError::UnsupportedRole`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    /// Instructions to the model, normally the first message.
    System,
    /// A human turn.
    User,
    /// A model turn.
    Assistant,
    /// The result of a tool call.
    ///
    /// The one role whose name is *not* what the render emits: the template
    /// wraps tool results in a `user` turn (`<tool_response>` blocks), so
    /// [`as_str`](Self::as_str) is the wire name, not a ChatML marker.
    Tool,
}

impl Role {
    /// The lowercase role string, as it appears on the wire.
    ///
    /// For `system`, `user` and `assistant` this is also the text inside
    /// `<|im_start|>{role}`; [`Role::Tool`] never reaches a marker.
    pub fn as_str(self) -> &'static str {
        match self {
            Role::System => "system",
            Role::User => "user",
            Role::Assistant => "assistant",
            Role::Tool => "tool",
        }
    }
}

impl fmt::Display for Role {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for Role {
    type Err = TokenizerError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "system" => Ok(Role::System),
            "user" => Ok(Role::User),
            "assistant" => Ok(Role::Assistant),
            "tool" => Ok(Role::Tool),
            other => Err(TokenizerError::UnsupportedRole(other.to_owned())),
        }
    }
}

/// One chat turn: a role, its text content, and the calls an assistant turn
/// requested.
///
/// `deny_unknown_fields` makes unsupported inputs a parse error instead of
/// silently dropping template-relevant data. `tool_calls` defaults to empty
/// and is omitted when empty, so JSON written before tool support still
/// parses and tool-free messages still serialize to their old shape.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ChatMessage {
    /// Who is speaking.
    pub role: Role,
    /// The message text, inserted into the template verbatim.
    pub content: String,
    /// Functions this turn asked to call, rendered after its content as
    /// `<tool_call>` blocks.
    ///
    /// Only an assistant turn has a slot for them; the template ignores them
    /// on every other role, and so does the renderer.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tool_calls: Vec<ToolCall>,
}

impl ChatMessage {
    /// A message with the given role and content, requesting no tool calls.
    pub fn new(role: Role, content: impl Into<String>) -> Self {
        ChatMessage {
            role,
            content: content.into(),
            tool_calls: Vec::new(),
        }
    }

    /// A `system` message.
    pub fn system(content: impl Into<String>) -> Self {
        Self::new(Role::System, content)
    }

    /// A `user` message.
    pub fn user(content: impl Into<String>) -> Self {
        Self::new(Role::User, content)
    }

    /// An `assistant` message.
    pub fn assistant(content: impl Into<String>) -> Self {
        Self::new(Role::Assistant, content)
    }

    /// A `tool` message: the result of one call, rendered inside a `user`
    /// turn as a `<tool_response>` block.
    pub fn tool(content: impl Into<String>) -> Self {
        Self::new(Role::Tool, content)
    }

    /// An `assistant` message that requests tool calls. `content` may be
    /// empty, which is the common shape for a pure call turn.
    pub fn assistant_calling(content: impl Into<String>, tool_calls: Vec<ToolCall>) -> Self {
        ChatMessage {
            tool_calls,
            ..Self::new(Role::Assistant, content)
        }
    }
}

/// One function call requested by an assistant turn.
///
/// The template accepts two input shapes and flattens both to this pair:
///
/// ```text
/// {"name": …, "arguments": …}                                  bare
/// {"id": …, "type": "function", "function": {"name", "arguments"}}  OpenAI
/// ```
///
/// via `{%- if tool_call.function %}{%- set tool_call = tool_call.function
/// %}{%- endif %}`. Deserialization accepts either; `id` and `type` are
/// dropped because the template has no slot for them, and serialization
/// writes the bare shape.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "ToolCallRepr")]
pub struct ToolCall {
    /// The function name.
    ///
    /// Written into the render **unescaped**, exactly as the reference does
    /// (`{{- tool_call.name }}` inside a JSON string literal the template
    /// assembles by hand). A name containing a quote therefore produces
    /// malformed JSON in the prompt — that is the reference's behavior, and
    /// [`render_chatml`] is bug-compatible with it on purpose, just like
    /// `encode_chat` is about added-token literals. Validating the charset
    /// is the caller's job; [`ContentSanitizer::sanitize_tool_call`] is the
    /// renderer-side backstop for untrusted names.
    pub name: String,
    /// The call arguments.
    pub arguments: ToolArguments,
}

impl ToolCall {
    /// A call whose arguments are already serialized, spliced into the
    /// render verbatim.
    pub fn raw(name: impl Into<String>, arguments: impl Into<String>) -> Self {
        ToolCall {
            name: name.into(),
            arguments: ToolArguments::Raw(arguments.into()),
        }
    }

    /// A call whose arguments are a JSON value, serialized by [`pyjson`].
    pub fn json(name: impl Into<String>, arguments: Value) -> Self {
        ToolCall {
            name: name.into(),
            arguments: ToolArguments::Value(arguments),
        }
    }
}

/// A tool call's `arguments`, in the two forms the template distinguishes.
///
/// ```jinja
/// {%- if tool_call.arguments is string %}
///     {{- tool_call.arguments }}
/// {%- else %}
///     {{- tool_call.arguments | tojson }}
/// {%- endif %}
/// ```
///
/// A string is emitted **verbatim** — its spacing, key order and even its
/// malformedness reach the prompt unchanged — while any other value goes
/// through `json.dumps(..., ensure_ascii=False)`. Parsing a [`Raw`] payload
/// and re-serializing it would silently rewrite the prompt, so the two forms
/// stay distinct all the way to the output.
///
/// [`Raw`]: Self::Raw
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ToolArguments {
    /// Pre-serialized arguments, spliced in as text.
    ///
    /// First variant on purpose: `untagged` tries variants in order, and a
    /// JSON string must land here rather than in [`Value`](Self::Value),
    /// which would also accept it.
    Raw(String),
    /// Structured arguments, serialized by [`pyjson::to_string`].
    Value(Value),
}

// `serde_json::Value` withholds `Eq` because it can hold an `f64`, but
// `serde_json::Number` refuses every non-finite value, so no `Value` can
// contain a NaN and `PartialEq` on the tree is reflexive. Asserting it here
// keeps `ChatMessage: Eq` for the crates that build sets and comparisons out
// of whole conversations.
impl Eq for ToolArguments {}

impl ToolArguments {
    /// The exact bytes this payload contributes to the render.
    fn render(&self) -> Cow<'_, str> {
        match self {
            ToolArguments::Raw(raw) => Cow::Borrowed(raw.as_str()),
            ToolArguments::Value(value) => Cow::Owned(tojson(value)),
        }
    }
}

/// Deserialization shim for [`ToolCall`]: the two accepted input shapes.
#[derive(Deserialize)]
#[serde(untagged)]
enum ToolCallRepr {
    /// `{"id": …, "type": "function", "function": {…}}`. Tried first: it is
    /// the only shape with a `function` key, and the template's `if
    /// tool_call.function` prefers it too.
    Wrapped(WrappedToolCall),
    /// `{"name": …, "arguments": …}`.
    Bare(BareToolCall),
}

/// The OpenAI wrapper. `id` and `type` are accepted and ignored.
#[derive(Deserialize)]
struct WrappedToolCall {
    function: BareToolCall,
}

/// The pair the template actually reads.
#[derive(Deserialize)]
struct BareToolCall {
    name: String,
    arguments: ToolArguments,
}

impl From<ToolCallRepr> for ToolCall {
    fn from(repr: ToolCallRepr) -> Self {
        let bare = match repr {
            ToolCallRepr::Wrapped(wrapped) => wrapped.function,
            ToolCallRepr::Bare(bare) => bare,
        };
        ToolCall {
            name: bare.name,
            arguments: bare.arguments,
        }
    }
}

/// The template's `| tojson`: `json.dumps(value, ensure_ascii=False)`.
fn tojson(value: &Value) -> String {
    // `pyjson::to_string` is fallible only through a UTF-8 check on bytes
    // `serde_json` has just written into memory, which cannot fail for a
    // `Value`. `Value`'s own `Display` is infallible and differs from
    // `json.dumps` only in separators, so even that unreachable branch emits
    // the right JSON shape rather than a panic or a hole in the prompt.
    pyjson::to_string(value).unwrap_or_else(|_| value.to_string())
}

/// ChatML turn opener, `<|im_start|>`. A single added token (id 151644) in
/// the pinned vocabulary.
pub(crate) const IM_START: &str = "<|im_start|>";

/// ChatML turn closer, `<|im_end|>`. A single added token (id 151645); also
/// the primary stop token.
pub(crate) const IM_END: &str = "<|im_end|>";

/// Everything the tools system block emits before the definitions.
const TOOLS_PREAMBLE: &str = "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>";

/// Everything it emits after them, up to (but not including) `<|im_end|>`.
const TOOLS_FOOTER: &str = "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call>";

/// Render a conversation exactly as the pinned 2507-Instruct template does.
///
/// Mirrors the template's structure: the preamble emits either the tools
/// system block (when `tools` is non-empty) or a *leading* system message;
/// the loop emits user turns, non-leading system turns, assistant turns with
/// their `<tool_call>` blocks, and tool results folded into `user` turns; the
/// trailing `<|im_start|>assistant\n` is appended when
/// `add_generation_prompt` is set. An empty `messages` slice renders only the
/// generation prompt, matching Jinja's undefined-lookup semantics for
/// `messages[0]`.
///
/// An empty `tools` slice is not the same as "no tools branch by fiat": Jinja
/// treats an empty list as falsy, so the reference takes the plain-chat
/// branch for it too.
pub(crate) fn render_chatml(
    messages: &[ChatMessage],
    tools: &[Value],
    add_generation_prompt: bool,
) -> String {
    render_turns(messages, tools, add_generation_prompt, None)
}

/// Render a conversation exactly as [`render_chatml`] does, but with every
/// attacker-reachable string passed through `sanitizer` first: message
/// content, tool definitions, and each call's name and arguments.
///
/// Structurally identical to the faithful render — same turns, same markers,
/// same order — so the only difference is that none of that input can
/// contribute added-token ids.
pub(crate) fn render_chatml_sanitized(
    messages: &[ChatMessage],
    tools: &[Value],
    add_generation_prompt: bool,
    sanitizer: &ContentSanitizer,
) -> String {
    render_turns(messages, tools, add_generation_prompt, Some(sanitizer))
}

/// Shared body of [`render_chatml`] and [`render_chatml_sanitized`].
///
/// With `sanitizer` unset the output is byte-identical to the reference
/// template render; the two entry points cannot drift apart because there is
/// only one copy of the structure.
fn render_turns(
    messages: &[ChatMessage],
    tools: &[Value],
    add_generation_prompt: bool,
    sanitizer: Option<&ContentSanitizer>,
) -> String {
    let content_len: usize = messages.iter().map(|m| m.content.len()).sum();
    // Per-turn markers cost at most ~34 bytes ("<|im_start|>assistant\n" +
    // "<|im_end|>\n"); one more for the generation prompt.
    let mut out = String::with_capacity(content_len + 34 * (messages.len() + 1));

    let leading_system = messages.first().filter(|m| m.role == Role::System);
    if tools.is_empty() {
        if let Some(system) = leading_system {
            push_turn(&mut out, Role::System, &turn_content(system, sanitizer));
        }
    } else {
        // One turn, not two: the tools block *is* the system turn, and it
        // swallows the leading system message rather than following it.
        push_tools_system_block(&mut out, leading_system, tools, sanitizer);
    }

    for (index, message) in messages.iter().enumerate() {
        if index == 0 && message.role == Role::System {
            // Already emitted by the preamble; the template's loop skips it
            // via `message.role == "system" and not loop.first`.
            continue;
        }
        match message.role {
            Role::Assistant => push_assistant_turn(&mut out, message, sanitizer),
            Role::Tool => {
                // Non-local by construction: the template opens the turn only
                // when the previous message is not a tool result and closes it
                // only when the next one is not, so a run of results stacks
                // into a single user turn. `index - 1` is taken through
                // `checked_sub`, which is also the `loop.first` case.
                let previous = index
                    .checked_sub(1)
                    .and_then(|i| messages.get(i))
                    .map(|m| m.role);
                let next = messages.get(index + 1).map(|m| m.role);
                push_tool_response(
                    &mut out,
                    message,
                    previous != Some(Role::Tool),
                    next != Some(Role::Tool),
                    sanitizer,
                );
            }
            Role::System | Role::User => {
                push_turn(&mut out, message.role, &turn_content(message, sanitizer));
            }
        }
    }
    if add_generation_prompt {
        out.push_str(IM_START);
        out.push_str(Role::Assistant.as_str());
        out.push('\n');
    }
    out
}

/// Append the `tools` branch's system turn: the leading system message (if
/// any), the fixed preamble, one line per definition, and the fixed footer.
fn push_tools_system_block(
    out: &mut String,
    leading_system: Option<&ChatMessage>,
    tools: &[Value],
    sanitizer: Option<&ContentSanitizer>,
) {
    out.push_str(IM_START);
    out.push_str(Role::System.as_str());
    out.push('\n');
    if let Some(system) = leading_system {
        out.push_str(&turn_content(system, sanitizer));
        out.push_str("\n\n");
    }
    out.push_str(TOOLS_PREAMBLE);
    for tool in tools {
        out.push('\n');
        match sanitizer {
            // Sanitize the *tree*, then serialize: rewriting the serialized
            // blob could put a marker anywhere, while rewriting strings in
            // place cannot change the JSON's structure at all.
            Some(sanitizer) => out.push_str(&tojson(&sanitizer.sanitize_json(tool))),
            None => out.push_str(&tojson(tool)),
        }
    }
    out.push_str(TOOLS_FOOTER);
    out.push_str(IM_END);
    out.push('\n');
}

/// Append an assistant turn: its content, then one `<tool_call>` block per
/// requested call, then the closing marker.
fn push_assistant_turn(
    out: &mut String,
    message: &ChatMessage,
    sanitizer: Option<&ContentSanitizer>,
) {
    let content = turn_content(message, sanitizer);
    out.push_str(IM_START);
    out.push_str(Role::Assistant.as_str());
    out.push('\n');
    out.push_str(&content);
    for (index, call) in message.tool_calls.iter().enumerate() {
        // The template's `(loop.first and content) or (not loop.first)`: the
        // separator is skipped only before the first block of a turn with no
        // content. Whitespace-only content is truthy in Jinja, so " " still
        // gets its newline — `is_empty`, not `trim().is_empty()`.
        if index > 0 || !content.is_empty() {
            out.push('\n');
        }
        push_tool_call(out, call, sanitizer);
    }
    out.push_str(IM_END);
    out.push('\n');
}

/// Append one `<tool_call>` block.
///
/// The JSON is assembled by hand, exactly as the template does: the name is
/// interpolated into a string literal without escaping, and the arguments are
/// either spliced verbatim or serialized by `tojson`.
fn push_tool_call(out: &mut String, call: &ToolCall, sanitizer: Option<&ContentSanitizer>) {
    out.push_str("<tool_call>\n{\"name\": \"");
    match sanitizer {
        Some(sanitizer) => out.push_str(&sanitizer.sanitize(&call.name)),
        None => out.push_str(&call.name),
    }
    out.push_str("\", \"arguments\": ");
    match sanitizer {
        Some(sanitizer) => out.push_str(&sanitizer.sanitize_arguments(&call.arguments).render()),
        None => out.push_str(&call.arguments.render()),
    }
    out.push_str("}\n</tool_call>");
}

/// Append one tool result as a `<tool_response>` block, opening and closing
/// the surrounding `user` turn only at the ends of a run of results.
fn push_tool_response(
    out: &mut String,
    message: &ChatMessage,
    opens: bool,
    closes: bool,
    sanitizer: Option<&ContentSanitizer>,
) {
    if opens {
        out.push_str(IM_START);
        // The turn is a *user* turn: the template hardcodes the role rather
        // than writing `message.role`.
        out.push_str(Role::User.as_str());
    }
    out.push_str("\n<tool_response>\n");
    out.push_str(&turn_content(message, sanitizer));
    out.push_str("\n</tool_response>");
    if closes {
        out.push_str(IM_END);
        out.push('\n');
    }
}

/// The zero-width character inserted to break an added-token literal:
/// U+200B ZERO WIDTH SPACE.
///
/// Chosen because it is invisible (a human reading the transcript still sees
/// `<|im_start|>`), it is not produced or removed by NFC normalization, and
/// it never appears inside an added-token literal — so inserting it can only
/// destroy matches, never create them.
pub const SANITIZE_MARKER: char = '\u{200B}';

/// Neutralizes added-token literals in attacker-controlled message content.
///
/// # Why this exists
///
/// [`render_chatml`] inserts content verbatim and the `tokenizers` backend
/// runs its added-token trie over the raw string before the pre-tokenizer, so
/// a literal `<|im_start|>` typed by a user encodes to the *real* control id
/// 151644 — a fabricated turn the model obeys. That behavior is
/// reference-faithful (`transformers` and `llama.cpp` do the same) and is
/// deliberately preserved by [`render_chatml`] / `encode_chat`; this type is
/// the opt-in path for content that is not trusted.
///
/// # Strategy: break, do not delete
///
/// Each literal is broken by inserting [`SANITIZE_MARKER`] after its first
/// character (`<` + marker + `|im_start|>`). Two properties follow:
///
/// * **Readable.** The marker is zero-width, so a user who legitimately asks
///   "what does `<|im_start|>` mean?" still sees the literal in the
///   transcript, the model still reads it as ordinary text, and stripping the
///   marker restores the original byte-for-byte.
/// * **Safe under composition.** Deleting a literal can *create* a new one by
///   joining its neighbours — `<|im_<|im_start|>start|>` collapses to
///   `<|im_start|>` under naive stripping. Insertion never joins anything, so
///   this class of bug cannot exist here.
///
/// The accepted trade-off is that sanitized content is no longer
/// byte-identical: pasted text that contained one of these literals comes back
/// with an invisible character inside it.
///
/// # Guarantee
///
/// [`sanitize`](Self::sanitize) output contains no added-token literal at any
/// offset. The scan resumes one character past each break rather than past the
/// whole literal, so overlapping and nested occurrences are all caught; the
/// output is the input with markers inserted, so any literal in the output
/// would have to be marker-free and therefore map back to an unbroken literal
/// in the input, which the scan cannot have missed.
#[derive(Debug, Clone)]
pub struct ContentSanitizer {
    /// Added-token literals, shortest first (see
    /// [`literal_at`](Self::literal_at)), deduplicated, non-empty.
    literals: Vec<String>,
    /// Which bytes can begin a literal. The scan only does prefix work at
    /// those offsets, which keeps megabyte-sized content a linear byte walk.
    first_bytes: [bool; 256],
}

impl ContentSanitizer {
    /// Build a sanitizer for the given added-token literals.
    ///
    /// The caller passes the *whole* added vocabulary of the loaded
    /// tokenizer — not just the tokens flagged `special`, since every added
    /// token encodes to a single id regardless of that flag.
    pub(crate) fn from_literals<I>(literals: I) -> Self
    where
        I: IntoIterator<Item = String>,
    {
        let mut literals: Vec<String> = literals.into_iter().filter(|l| !l.is_empty()).collect();
        // Shortest first so `literal_at` reports the shortest literal starting
        // at an offset; that is the one that decides whether a marker can land
        // strictly inside the match.
        literals.sort_by(|a, b| {
            a.len()
                .cmp(&b.len())
                .then_with(|| a.as_str().cmp(b.as_str()))
        });
        literals.dedup();

        let mut first_bytes = [false; 256];
        for literal in &literals {
            if let Some(&byte) = literal.as_bytes().first() {
                first_bytes[byte as usize] = true;
            }
        }
        ContentSanitizer {
            literals,
            first_bytes,
        }
    }

    /// The literals this sanitizer neutralizes, shortest first.
    ///
    /// Derived from the loaded vocabulary, so it tracks the pin instead of a
    /// hardcoded list.
    pub fn literals(&self) -> impl ExactSizeIterator<Item = &str> {
        self.literals.iter().map(String::as_str)
    }

    /// Whether `content` contains no added-token literal, i.e. sanitizing it
    /// would change nothing.
    pub fn is_clean(&self, content: &str) -> bool {
        self.find_literal(content, 0).is_none()
    }

    /// Neutralize every added-token literal in `content`.
    ///
    /// Borrows when there is nothing to do, which is the overwhelmingly common
    /// case. Never fails and never panics: any `&str` is valid input,
    /// including empty and multi-megabyte content.
    pub fn sanitize<'a>(&self, content: &'a str) -> Cow<'a, str> {
        let Some((first, _)) = self.find_literal(content, 0) else {
            return Cow::Borrowed(content);
        };

        let mut out = String::with_capacity(content.len() + SANITIZE_MARKER.len_utf8() * 8);
        // Bytes of `content` already appended to `out`.
        let mut copied = 0;
        let mut cursor = first;
        while let Some((at, literal)) = self.find_literal(content, cursor) {
            let Some(head) = content[at..].chars().next() else {
                // Unreachable: a literal matched at `at`, so `at` is not the
                // end of the string. Bail out rather than panic.
                break;
            };
            out.push_str(&content[copied..at]);
            // A literal of two or more characters is broken from the inside,
            // keeping every original character. A one-character literal has no
            // inside, so the marker replaces it; that still never joins its
            // neighbours, because the marker sits where the character was.
            if literal.len() > head.len_utf8() {
                out.push(head);
            }
            out.push(SANITIZE_MARKER);
            // Resume one character in, not past the literal: a longer or
            // differently-aligned literal may start inside this one.
            cursor = at + head.len_utf8();
            copied = cursor;
        }
        out.push_str(&content[copied..]);
        Cow::Owned(out)
    }

    /// A copy of `value` with every string inside it sanitized, object keys
    /// included.
    ///
    /// Tool definitions go through this *before* they are serialized, never
    /// after: a marker inserted into the finished blob could land anywhere,
    /// while rewriting strings in the tree cannot change the JSON's structure
    /// at all. Keys are covered as well as values because both are emitted as
    /// JSON strings, and a key is just as good a place to hide
    /// `<|im_start|>`.
    ///
    /// Numbers, booleans and nulls are copied unchanged. Recursion depth is
    /// bounded by the depth of `value`, which for anything parsed from JSON
    /// text is bounded by `serde_json`'s own nesting limit.
    pub fn sanitize_json(&self, value: &Value) -> Value {
        match value {
            Value::String(string) => Value::String(self.sanitize(string).into_owned()),
            Value::Array(items) => {
                Value::Array(items.iter().map(|item| self.sanitize_json(item)).collect())
            }
            Value::Object(members) => Value::Object(
                members
                    .iter()
                    .map(|(key, value)| {
                        (self.sanitize(key).into_owned(), self.sanitize_json(value))
                    })
                    .collect(),
            ),
            scalar => scalar.clone(),
        }
    }

    /// A copy of `arguments` with every string inside it sanitized.
    ///
    /// A [`ToolArguments::Raw`] payload reaches the prompt as text, so it is
    /// sanitized as text — which cannot corrupt it either, since the renderer
    /// never parses it. A structured one is rewritten like a tool definition.
    pub fn sanitize_arguments(&self, arguments: &ToolArguments) -> ToolArguments {
        match arguments {
            ToolArguments::Raw(raw) => ToolArguments::Raw(self.sanitize(raw).into_owned()),
            ToolArguments::Value(value) => ToolArguments::Value(self.sanitize_json(value)),
        }
    }

    /// A copy of `call` with its name and arguments sanitized.
    ///
    /// The name matters because the renderer interpolates it unescaped, so a
    /// name carrying `</tool_call><|im_end|>` would otherwise close the block
    /// and the turn. A legitimate name contains no added-token literal and is
    /// returned unchanged.
    pub fn sanitize_tool_call(&self, call: &ToolCall) -> ToolCall {
        ToolCall {
            name: self.sanitize(&call.name).into_owned(),
            arguments: self.sanitize_arguments(&call.arguments),
        }
    }

    /// A copy of `message` with sanitized content and tool calls.
    pub fn sanitize_message(&self, message: &ChatMessage) -> ChatMessage {
        ChatMessage {
            role: message.role,
            content: self.sanitize(&message.content).into_owned(),
            tool_calls: message
                .tool_calls
                .iter()
                .map(|call| self.sanitize_tool_call(call))
                .collect(),
        }
    }

    /// A copy of `messages` with every content string sanitized.
    ///
    /// Applies to assistant turns too: the model can emit any added token
    /// outside the stop set, and a decoded reply is re-encoded as context on
    /// the next turn.
    pub fn sanitize_messages(&self, messages: &[ChatMessage]) -> Vec<ChatMessage> {
        messages.iter().map(|m| self.sanitize_message(m)).collect()
    }

    /// The byte offset of the first literal starting at or after `from`, and
    /// the shortest literal that starts there.
    fn find_literal<'s>(&'s self, content: &str, from: usize) -> Option<(usize, &'s str)> {
        let bytes = content.as_bytes();
        let mut at = from;
        while at < bytes.len() {
            // A literal is valid UTF-8, so its first byte is never a
            // continuation byte and a candidate offset is always a character
            // boundary. The explicit check keeps the slice below infallible
            // even if that ever stops holding.
            if self.first_bytes[bytes[at] as usize]
                && content.is_char_boundary(at)
                && let Some(literal) = self.literal_at(&content[at..])
            {
                return Some((at, literal));
            }
            at += 1;
        }
        None
    }

    /// The shortest literal that prefixes `rest`, if any.
    fn literal_at<'s>(&'s self, rest: &str) -> Option<&'s str> {
        self.literals
            .iter()
            .find(|literal| rest.starts_with(literal.as_str()))
            .map(String::as_str)
    }
}

/// The text a turn contributes: the content itself, or its sanitized form.
fn turn_content<'m>(
    message: &'m ChatMessage,
    sanitizer: Option<&ContentSanitizer>,
) -> Cow<'m, str> {
    match sanitizer {
        Some(sanitizer) => sanitizer.sanitize(&message.content),
        None => Cow::Borrowed(message.content.as_str()),
    }
}

/// Append one `<|im_start|>{role}\n{content}<|im_end|>\n` turn.
fn push_turn(out: &mut String, role: Role, content: &str) {
    out.push_str(IM_START);
    out.push_str(role.as_str());
    out.push('\n');
    out.push_str(content);
    out.push_str(IM_END);
    out.push('\n');
}

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

    #[test]
    fn role_round_trips_through_str() {
        for role in [Role::System, Role::User, Role::Assistant, Role::Tool] {
            assert_eq!(role.as_str().parse::<Role>().unwrap(), role);
        }
    }

    #[test]
    fn unknown_role_is_a_typed_error() {
        assert!(matches!(
            "function".parse::<Role>().unwrap_err(),
            TokenizerError::UnsupportedRole(r) if r == "function"
        ));
        assert!(matches!(
            "System".parse::<Role>().unwrap_err(),
            TokenizerError::UnsupportedRole(_)
        ));
    }

    #[test]
    fn message_json_rejects_unknown_roles_and_fields() {
        assert!(
            serde_json::from_str::<ChatMessage>(r#"{"role":"developer","content":"x"}"#).is_err()
        );
        assert!(
            serde_json::from_str::<ChatMessage>(r#"{"role":"user","content":"x","name":"bob"}"#)
                .is_err()
        );
        let ok: ChatMessage = serde_json::from_str(r#"{"role":"user","content":"hi"}"#).unwrap();
        assert_eq!(ok, ChatMessage::user("hi"));
        // The fields the tool branches added parse, and an empty `tool_calls`
        // is the tool-free message it renders as.
        let tool: ChatMessage = serde_json::from_str(r#"{"role":"tool","content":"31C"}"#).unwrap();
        assert_eq!(tool, ChatMessage::tool("31C"));
        let empty: ChatMessage =
            serde_json::from_str(r#"{"role":"assistant","content":"","tool_calls":[]}"#).unwrap();
        assert_eq!(empty, ChatMessage::assistant(""));
    }

    #[test]
    fn tool_calls_parse_from_both_template_shapes() {
        let bare: ChatMessage = serde_json::from_str(
            r#"{"role":"assistant","content":"","tool_calls":[{"name":"f","arguments":{"a":1}}]}"#,
        )
        .unwrap();
        let wrapped: ChatMessage = serde_json::from_str(
            r#"{"role":"assistant","content":"","tool_calls":[
                {"id":"call_1","type":"function","function":{"name":"f","arguments":{"a":1}}}]}"#,
        )
        .unwrap();
        // `id` and `type` are dropped, so both inputs are the same call.
        assert_eq!(bare, wrapped);
        assert_eq!(
            bare.tool_calls,
            [ToolCall::json("f", serde_json::json!({"a": 1}))]
        );

        // A string payload stays a string, and everything else stays a value.
        let raw: ChatMessage = serde_json::from_str(
            r#"{"role":"assistant","content":"","tool_calls":[{"name":"f","arguments":"{ nonsense"}]}"#,
        )
        .unwrap();
        assert_eq!(raw.tool_calls, [ToolCall::raw("f", "{ nonsense")]);

        // Serializing writes the bare shape, which parses back unchanged.
        for message in [&bare, &raw] {
            let json = serde_json::to_string(message).unwrap();
            assert_eq!(
                &serde_json::from_str::<ChatMessage>(&json).unwrap(),
                message
            );
        }
        // A tool-free message serializes exactly as it did before the field
        // existed.
        assert_eq!(
            serde_json::to_string(&ChatMessage::user("hi")).unwrap(),
            r#"{"role":"user","content":"hi"}"#
        );
    }

    #[test]
    fn empty_conversation_renders_only_the_generation_prompt() {
        assert_eq!(render_chatml(&[], &[], true), "<|im_start|>assistant\n");
        assert_eq!(render_chatml(&[], &[], false), "");
    }

    #[test]
    fn leading_system_is_rendered_once() {
        let rendered = render_chatml(
            &[ChatMessage::system("sys"), ChatMessage::user("hi")],
            &[],
            true,
        );
        assert_eq!(
            rendered,
            "<|im_start|>system\nsys<|im_end|>\n\
             <|im_start|>user\nhi<|im_end|>\n\
             <|im_start|>assistant\n"
        );
    }

    #[test]
    fn whitespace_only_assistant_content_still_gets_its_separator() {
        // `" "` is truthy in Jinja, so the first `<tool_call>` is preceded by
        // a newline; `""` is falsy and is not. The fixtures cover the empty
        // and non-empty cases, not this one in between.
        let call = ToolCall::json("f", serde_json::json!({}));
        let blank = render_chatml(
            &[ChatMessage::assistant_calling(" ", vec![call.clone()])],
            &[],
            false,
        );
        assert_eq!(
            blank,
            "<|im_start|>assistant\n \n<tool_call>\n{\"name\": \"f\", \"arguments\": {}}\n</tool_call><|im_end|>\n"
        );
        let empty = render_chatml(
            &[ChatMessage::assistant_calling("", vec![call])],
            &[],
            false,
        );
        assert_eq!(
            empty,
            "<|im_start|>assistant\n<tool_call>\n{\"name\": \"f\", \"arguments\": {}}\n</tool_call><|im_end|>\n"
        );
    }

    #[test]
    fn a_run_of_tool_results_opens_and_closes_exactly_one_turn() {
        let rendered = render_chatml(
            &[
                ChatMessage::tool("a"),
                ChatMessage::tool("b"),
                ChatMessage::user("and?"),
                ChatMessage::tool("c"),
            ],
            &[],
            false,
        );
        assert_eq!(
            rendered,
            "<|im_start|>user\n<tool_response>\na\n</tool_response>\n\
             <tool_response>\nb\n</tool_response><|im_end|>\n\
             <|im_start|>user\nand?<|im_end|>\n\
             <|im_start|>user\n<tool_response>\nc\n</tool_response><|im_end|>\n"
        );
        assert_eq!(rendered.matches(IM_START).count(), 3);
        assert_eq!(rendered.matches(IM_END).count(), 3);
    }

    #[test]
    fn a_leading_system_message_still_counts_as_the_previous_role() {
        // The template skips the leading system message with an `if`, not by
        // dropping it from the loop, so the tool result that follows it is
        // *not* `loop.first` — but the previous role is `system`, not `tool`,
        // so the turn opens anyway. Indexing over the original slice is what
        // keeps those two facts from being conflated.
        let rendered = render_chatml(
            &[ChatMessage::system("s"), ChatMessage::tool("r")],
            &[],
            false,
        );
        assert_eq!(
            rendered,
            "<|im_start|>system\ns<|im_end|>\n\
             <|im_start|>user\n<tool_response>\nr\n</tool_response><|im_end|>\n"
        );
    }

    #[test]
    fn an_empty_tools_slice_is_the_plain_chat_branch() {
        // Jinja's `{%- if tools %}` is false for `[]`, so an empty list must
        // not produce a `# Tools` block.
        let messages = [ChatMessage::system("s"), ChatMessage::user("hi")];
        assert_eq!(
            render_chatml(&messages, &[], true),
            "<|im_start|>system\ns<|im_end|>\n\
             <|im_start|>user\nhi<|im_end|>\n\
             <|im_start|>assistant\n"
        );
        let with_tools = render_chatml(&messages, &[serde_json::json!({"type": "function"})], true);
        assert!(with_tools.contains("# Tools"));
        // ...and the system message is folded into that one turn, not left as
        // a turn of its own.
        assert_eq!(with_tools.matches("<|im_start|>system").count(), 1);
    }

    /// A stand-in vocabulary. Deliberately not the pinned one: it has a
    /// literal that is a prefix of another, a literal sharing a first byte
    /// with a different shape, and a one-character literal — shapes the real
    /// Qwen vocabulary does not contain but the algorithm must still handle.
    fn test_sanitizer() -> ContentSanitizer {
        ContentSanitizer::from_literals(
            ["<|a|>", "<a>", "<|abc|>", "@", "\u{4e2d}x"]
                .into_iter()
                .map(String::from),
        )
    }

    fn strip_markers(s: &str) -> String {
        s.replace(SANITIZE_MARKER, "")
    }

    #[test]
    fn sanitizer_literals_are_deduplicated_and_shortest_first() {
        let sanitizer = ContentSanitizer::from_literals(
            ["bb", "a", "bb", "", "ccc"].into_iter().map(String::from),
        );
        let literals: Vec<&str> = sanitizer.literals().collect();
        // Empty literals are dropped (they would match everywhere and cannot
        // be broken), duplicates collapse, and the order is shortest first.
        assert_eq!(literals, ["a", "bb", "ccc"]);
    }

    #[test]
    fn clean_content_is_borrowed_unchanged() {
        let sanitizer = test_sanitizer();
        for content in [
            "",
            "   \n\t  ",
            "system",
            "<|a",
            "a|>",
            "< | a | >",
            "<b>",
            "\u{4e2d}",
        ] {
            assert!(sanitizer.is_clean(content), "{content:?}");
            assert!(
                matches!(sanitizer.sanitize(content), Cow::Borrowed(_)),
                "{content:?} should not allocate"
            );
            assert_eq!(sanitizer.sanitize(content), content);
        }
    }

    #[test]
    fn a_broken_literal_keeps_every_original_character() {
        let sanitizer = test_sanitizer();
        let sanitized = sanitizer.sanitize("what does <|a|> mean?").into_owned();
        assert_ne!(sanitized, "what does <|a|> mean?");
        assert!(sanitizer.is_clean(&sanitized));
        // Zero-width marker only: strip it and the text is byte-identical.
        assert_eq!(strip_markers(&sanitized), "what does <|a|> mean?");
    }

    #[test]
    fn one_character_literals_are_replaced_not_split() {
        let sanitizer = test_sanitizer();
        // "@" has no inside, so it cannot be broken from within; it is
        // replaced by the marker, which still cannot join its neighbours.
        let sanitized = sanitizer.sanitize("a@b").into_owned();
        assert!(sanitizer.is_clean(&sanitized));
        assert_eq!(sanitized, format!("a{SANITIZE_MARKER}b"));
    }

    #[test]
    fn nested_and_overlapping_literals_are_all_broken() {
        let sanitizer = test_sanitizer();
        for content in [
            "<|<|a|>a|>",        // a literal hiding inside a longer near-literal
            "<|a<|a|>|>",        // overlapping starts
            "<|abc|>",           // longer literal sharing a prefix with "<|a"
            "<|a|><|abc|><a>",   // adjacent, different literals
            "<a<a>>",            // nested angle brackets
            "<|a|><|a|><|a|>",   // repeated
            "<|a|>tail",         // at the very start
            "head<|a|>",         // at the very end
            "<|a|>",             // the whole content
            "x<|a|>y",           // no surrounding whitespace
            "\u{4e2d}\u{4e2d}x", // multi-byte literal
        ] {
            let sanitized = sanitizer.sanitize(content).into_owned();
            assert!(
                sanitizer.is_clean(&sanitized),
                "{content:?} -> {sanitized:?}"
            );
            assert!(sanitizer.is_clean(&sanitizer.sanitize(&sanitized)));
        }
    }

    #[test]
    fn sanitizing_never_leaves_a_literal_for_any_short_string() {
        // Exhaustive over every string up to length 6 drawn from the alphabet
        // the literals are built from. That covers every nesting, overlap,
        // truncation and adjacency shape those literals can form, so the
        // "output contains no literal" guarantee is proved rather than
        // spot-checked.
        let sanitizer =
            ContentSanitizer::from_literals(["<|a|>", "<a>", "@"].into_iter().map(String::from));
        let alphabet = ['<', '>', '|', 'a', '@'];
        let base = alphabet.len();
        let mut content = String::new();
        let mut checked = 0usize;
        for len in 0..=6u32 {
            for mut word in 0..base.pow(len) {
                content.clear();
                for _ in 0..len {
                    content.push(alphabet[word % base]);
                    word /= base;
                }
                let sanitized = sanitizer.sanitize(&content).into_owned();
                assert!(
                    sanitizer.is_clean(&sanitized),
                    "{content:?} -> {sanitized:?}"
                );
                // Insertion-only, except for the one-character literal, which
                // has no inside and is replaced by the marker.
                assert_eq!(
                    strip_markers(&sanitized),
                    content.replace('@', ""),
                    "{content:?}"
                );
                checked += 1;
            }
        }
        assert_eq!(checked, 19_531, "expected the full sweep");
    }

    #[test]
    fn sanitizing_huge_content_neither_panics_nor_misses() {
        let sanitizer = test_sanitizer();
        let mut content = String::new();
        while content.len() < 1 << 20 {
            content.push_str("lorem ipsum <|a|> dolor @ sit \u{4e2d}x amet ");
        }
        let sanitized = sanitizer.sanitize(&content).into_owned();
        assert!(sanitizer.is_clean(&sanitized));
    }

    #[test]
    fn sanitized_render_keeps_the_chatml_structure() {
        let sanitizer = test_sanitizer();
        let messages = [ChatMessage::system("s"), ChatMessage::user("<|a|>")];
        let rendered = render_chatml_sanitized(&messages, &[], true, &sanitizer);
        assert_eq!(
            strip_markers(&rendered),
            render_chatml(&messages, &[], true),
            "sanitizing must only insert markers, never change the structure"
        );
    }

    #[test]
    fn sanitizing_messages_covers_every_role() {
        let sanitizer = test_sanitizer();
        let messages = [
            ChatMessage::system("<|a|>"),
            ChatMessage::user("<a>"),
            ChatMessage::assistant("<|abc|>"),
            ChatMessage::tool("<|a|>"),
        ];
        for message in sanitizer.sanitize_messages(&messages) {
            assert!(sanitizer.is_clean(&message.content), "{message:?}");
        }
    }

    #[test]
    fn sanitizing_a_json_tree_rewrites_strings_and_keys_only() {
        let sanitizer = test_sanitizer();
        let tool = serde_json::json!({
            "<|a|>key": "<a>value",
            "nested": {"list": ["<|abc|>", 1, 2.5, null, true]},
            "clean": "nothing to do",
        });
        let sanitized = sanitizer.sanitize_json(&tool);

        // Structure and scalars survive; every string in the render is clean.
        let rendered = tojson(&sanitized);
        assert!(sanitizer.is_clean(&rendered), "{rendered}");
        assert_eq!(strip_markers(&rendered), tojson(&tool));
        assert!(rendered.contains("2.5") && rendered.contains("null"));
        // ...and the result is still parseable JSON, which is the whole point
        // of rewriting the tree instead of the serialized blob.
        assert_eq!(
            serde_json::from_str::<Value>(&rendered).unwrap()["clean"],
            serde_json::json!("nothing to do")
        );
    }

    #[test]
    fn sanitizing_a_tool_call_covers_the_name_and_both_argument_forms() {
        let sanitizer = test_sanitizer();
        let raw = sanitizer.sanitize_tool_call(&ToolCall::raw("<|a|>rm", "{\"x\":\"<a>\"}"));
        assert!(sanitizer.is_clean(&raw.name));
        assert!(sanitizer.is_clean(&raw.arguments.render()));
        // A raw payload is rewritten as text and stays valid JSON here only
        // because the marker lands inside a string; the renderer never parses
        // it either way.
        assert_eq!(strip_markers(&raw.arguments.render()), "{\"x\":\"<a>\"}");

        let value = sanitizer.sanitize_tool_call(&ToolCall::json(
            "<|a|>rm",
            serde_json::json!({"p": "<|abc|>"}),
        ));
        assert!(sanitizer.is_clean(&value.name));
        assert!(sanitizer.is_clean(&value.arguments.render()));

        // A legitimate call is returned untouched.
        let benign = ToolCall::json("get_weather", serde_json::json!({"city": "Cairo"}));
        assert_eq!(sanitizer.sanitize_tool_call(&benign), benign);
    }
}