tool_parser_edge_cases.rs 10.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//! Edge Cases and Error Handling Tests
//!
//! Tests for malformed input, edge cases, and error recovery

use sglang_router_rs::tool_parser::{
    JsonParser, MistralParser, ParseState, ParserRegistry, PythonicParser, QwenParser,
    StreamResult, ToolParser,
};

#[tokio::test]
async fn test_empty_input() {
    let registry = ParserRegistry::new();
    let parsers = vec!["json", "mistral", "qwen", "pythonic", "llama"];

    for parser_name in parsers {
        let parser = registry
            .get_parser(&format!("test-{}", parser_name))
            .unwrap();
19
        let (_normal_text, tools) = parser.parse_complete("").await.unwrap();
20
        assert_eq!(
21
            tools.len(),
22
23
24
25
26
27
28
29
30
31
32
33
34
            0,
            "Parser {} should return empty for empty input",
            parser_name
        );
    }
}

#[tokio::test]
async fn test_plain_text_no_tools() {
    let plain_text = "This is just a regular response with no tool calls whatsoever.";

    let json_parser = JsonParser::new();
    assert_eq!(
35
36
37
38
39
40
        json_parser
            .parse_complete(plain_text)
            .await
            .unwrap()
            .1
            .len(),
41
42
43
44
45
46
47
48
49
        0
    );

    let mistral_parser = MistralParser::new();
    assert_eq!(
        mistral_parser
            .parse_complete(plain_text)
            .await
            .unwrap()
50
            .1
51
52
53
54
55
56
            .len(),
        0
    );

    let qwen_parser = QwenParser::new();
    assert_eq!(
57
58
59
60
61
62
        qwen_parser
            .parse_complete(plain_text)
            .await
            .unwrap()
            .1
            .len(),
63
64
65
66
67
68
69
70
71
        0
    );

    let pythonic_parser = PythonicParser::new();
    assert_eq!(
        pythonic_parser
            .parse_complete(plain_text)
            .await
            .unwrap()
72
            .1
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
            .len(),
        0
    );
}

#[tokio::test]
async fn test_incomplete_json() {
    let json_parser = JsonParser::new();

    let incomplete_cases = vec![
        r#"{"name": "test""#,                 // Missing closing brace
        r#"{"name": "test", "arguments":"#,   // Incomplete arguments
        r#"{"name": "test", "arguments": {"#, // Incomplete nested object
    ];

    for input in incomplete_cases {
89
        let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
90
        assert_eq!(
91
            tools.len(),
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
            0,
            "Should not parse incomplete JSON: {}",
            input
        );
    }

    // This case might actually parse because [{"name": "test"}] is complete
    // The trailing comma suggests more items but the first item is valid
    let _result = json_parser
        .parse_complete(r#"[{"name": "test"},"#)
        .await
        .unwrap();
    // This could parse the first element or return empty - implementation dependent
}

#[tokio::test]
async fn test_malformed_mistral() {
    let parser = MistralParser::new();

    let malformed_cases = vec![
        "[TOOL_CALLS]",                // Missing array
        "[TOOL_CALLS] {",              // Not an array
        "[TOOL_CALLS] [",              // Incomplete array
        "[TOOL_CALLS] [{]",            // Invalid JSON in array
        "[TOOL_CALLS] [{\"name\": }]", // Invalid value
    ];

    for input in malformed_cases {
        // Parser might return error or empty vec for malformed input
121
        if let Ok((_normal_text, tools)) = parser.parse_complete(input).await {
122
            assert_eq!(
123
                tools.len(),
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
                0,
                "Should not parse malformed Mistral: {}",
                input
            );
        }
        // Error is also acceptable for malformed input
    }
}

#[tokio::test]
async fn test_missing_required_fields() {
    let json_parser = JsonParser::new();

    // Missing name field
    let input = r#"{"arguments": {"x": 1}}"#;
139
140
    let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 0, "Should not parse without name field");
141
142
143

    // Name is not a string
    let input = r#"{"name": 123, "arguments": {}}"#;
144
145
    let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 0, "Should not parse with non-string name");
146
147
148
149
150
151
152
153
154
155
156
157
}

#[tokio::test]
async fn test_very_long_strings() {
    let json_parser = JsonParser::new();

    let long_string = "x".repeat(10000);
    let input = format!(
        r#"{{"name": "test", "arguments": {{"data": "{}"}}}}"#,
        long_string
    );

158
159
160
    let (_normal_text, tools) = json_parser.parse_complete(&input).await.unwrap();
    assert_eq!(tools.len(), 1);
    assert_eq!(tools[0].function.name, "test");
161

162
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
163
164
165
166
167
168
169
170
171
172
    assert_eq!(args["data"].as_str().unwrap().len(), 10000);
}

#[tokio::test]
async fn test_unicode_edge_cases() {
    let json_parser = JsonParser::new();

    // Various Unicode characters including emojis, CJK, RTL text
    let input = r#"{"name": "translate", "arguments": {"text": "Hello 世界 🌍 مرحبا עולם"}}"#;

173
174
    let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 1);
175

176
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
177
178
179
180
181
182
183
    assert_eq!(args["text"], "Hello 世界 🌍 مرحبا עולם");
}

#[tokio::test]
async fn test_nested_brackets_in_strings() {
    let mistral_parser = MistralParser::new();
    let input = r#"[TOOL_CALLS] [{"name": "echo", "arguments": {"text": "Array: [1, 2, 3]"}}]"#;
184
185
186
    let (_normal_text, tools) = mistral_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 1);
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
187
188
189
190
    assert_eq!(args["text"], "Array: [1, 2, 3]");

    let pythonic_parser = PythonicParser::new();
    let input = r#"[echo(text="List: [a, b, c]")]"#;
191
192
193
    let (_normal_text, tools) = pythonic_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 1);
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
194
195
196
197
198
199
200
201
202
203
204
205
    assert_eq!(args["text"], "List: [a, b, c]");
}

#[tokio::test]
async fn test_multiple_formats_in_text() {
    let json_parser = JsonParser::new();
    let input = r#"
    Here's some text with [TOOL_CALLS] that shouldn't trigger.
    {"name": "actual_tool", "arguments": {}}
    And some more text with <tool_call> tags.
    "#;

206
207
208
    let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 1);
    assert_eq!(tools[0].function.name, "actual_tool");
209
210
211
212
213
214
215
216
}

#[tokio::test]
async fn test_escaped_characters() {
    let json_parser = JsonParser::new();

    let input = r#"{"name": "write", "arguments": {"content": "Line 1\nLine 2\r\nLine 3\tTabbed\\Backslash\"Quote"}}"#;

217
218
    let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 1);
219

220
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
    let content = args["content"].as_str().unwrap();
    assert!(content.contains('\n'));
    assert!(content.contains('\t'));
    assert!(content.contains('\\'));
    assert!(content.contains('"'));
}

#[tokio::test]
async fn test_numeric_edge_cases() {
    let json_parser = JsonParser::new();

    let input = r#"{
        "name": "calculate",
        "arguments": {
            "int": 42,
            "float": 123.456,
            "scientific": 1.23e-4,
            "negative": -999,
            "zero": 0,
            "large": 9007199254740991
        }
    }"#;

244
245
    let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 1);
246

247
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
    assert_eq!(args["int"], 42);
    assert_eq!(args["float"], 123.456);
    assert_eq!(args["scientific"], 0.000123);
    assert_eq!(args["negative"], -999);
    assert_eq!(args["zero"], 0);
    assert_eq!(args["large"], 9007199254740991i64);
}

#[tokio::test]
async fn test_null_and_boolean_values() {
    let json_parser = JsonParser::new();

    let input = r#"{
        "name": "configure",
        "arguments": {
            "enabled": true,
            "disabled": false,
            "optional": null
        }
    }"#;

269
270
    let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 1);
271

272
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
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
    assert_eq!(args["enabled"], true);
    assert_eq!(args["disabled"], false);
    assert_eq!(args["optional"], serde_json::Value::Null);
}

#[tokio::test]
async fn test_partial_token_at_buffer_boundary() {
    let parser = QwenParser::new();
    let mut state = ParseState::new();

    // Send exactly "<tool" which is a 5-character prefix of "<tool_call>\n"
    let result = parser.parse_incremental("<tool", &mut state).await.unwrap();
    assert!(matches!(result, StreamResult::Incomplete));
    assert_eq!(state.buffer, "<tool");

    // Complete the token
    let result = parser
        .parse_incremental(
            "_call>\n{\"name\": \"test\", \"arguments\": {}}\n</tool_call>",
            &mut state,
        )
        .await
        .unwrap();

    // Should successfully parse after completing
    match result {
        StreamResult::ToolComplete(tool) => {
            assert_eq!(tool.function.name, "test");
        }
        _ => {
            // In Phase 2 simplified streaming, might get Incomplete
            // The important thing is it didn't fail to recognize the partial token
        }
    }
}

#[tokio::test]
async fn test_exact_prefix_lengths() {
    let parser = QwenParser::new();

    let test_cases = vec![
        ("<", 1),            // 1-char prefix
        ("<t", 2),           // 2-char prefix
        ("<tool", 5),        // 5-char prefix (the main bug case)
        ("<tool_call", 10),  // 10-char prefix
        ("<tool_call>", 11), // 11-char prefix (full start without \n)
    ];

    for (prefix, expected_len) in test_cases {
        let mut state = ParseState::new();
        let result = parser.parse_incremental(prefix, &mut state).await.unwrap();
        assert!(
            matches!(result, StreamResult::Incomplete),
            "Prefix '{}' (len {}) should be incomplete",
            prefix,
            expected_len
        );
        assert_eq!(
            state.buffer, prefix,
            "Buffer should contain the prefix '{}'",
            prefix
        );
    }
}