tool_parser_edge_cases.rs 10.6 KB
Newer Older
1
2
3
4
5
//! Edge Cases and Error Handling Tests
//!
//! Tests for malformed input, edge cases, and error recovery

use sglang_router_rs::tool_parser::{
6
    JsonParser, MistralParser, PythonicParser, QwenParser, ToolParser,
7
8
};

9
10
11
mod common;
use common::create_test_tools;

12
13
#[tokio::test]
async fn test_empty_input() {
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
    // Test that all parsers handle empty input correctly
    let json_parser = JsonParser::new();
    let (_normal_text, tools) = json_parser.parse_complete("").await.unwrap();
    assert_eq!(
        tools.len(),
        0,
        "JSON parser should return empty for empty input"
    );

    let mistral_parser = MistralParser::new();
    let (_normal_text, tools) = mistral_parser.parse_complete("").await.unwrap();
    assert_eq!(
        tools.len(),
        0,
        "Mistral parser should return empty for empty input"
    );

    let qwen_parser = QwenParser::new();
    let (_normal_text, tools) = qwen_parser.parse_complete("").await.unwrap();
    assert_eq!(
        tools.len(),
        0,
        "Qwen parser should return empty for empty input"
    );

    let pythonic_parser = PythonicParser::new();
    let (_normal_text, tools) = pythonic_parser.parse_complete("").await.unwrap();
    assert_eq!(
        tools.len(),
        0,
        "Pythonic parser should return empty for empty input"
    );
46
47
48
49
50
51
52
53
}

#[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!(
54
55
56
57
58
59
        json_parser
            .parse_complete(plain_text)
            .await
            .unwrap()
            .1
            .len(),
60
61
62
63
64
65
66
67
68
        0
    );

    let mistral_parser = MistralParser::new();
    assert_eq!(
        mistral_parser
            .parse_complete(plain_text)
            .await
            .unwrap()
69
            .1
70
71
72
73
74
75
            .len(),
        0
    );

    let qwen_parser = QwenParser::new();
    assert_eq!(
76
77
78
79
80
81
        qwen_parser
            .parse_complete(plain_text)
            .await
            .unwrap()
            .1
            .len(),
82
83
84
85
86
87
88
89
90
        0
    );

    let pythonic_parser = PythonicParser::new();
    assert_eq!(
        pythonic_parser
            .parse_complete(plain_text)
            .await
            .unwrap()
91
            .1
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
            .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 {
108
        let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
109
        assert_eq!(
110
            tools.len(),
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
            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
140
        if let Ok((_normal_text, tools)) = parser.parse_complete(input).await {
141
            assert_eq!(
142
                tools.len(),
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
                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}}"#;
158
159
    let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 0, "Should not parse without name field");
160
161
162

    // Name is not a string
    let input = r#"{"name": 123, "arguments": {}}"#;
163
164
    let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 0, "Should not parse with non-string name");
165
166
167
168
169
170
171
172
173
174
175
176
}

#[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
    );

177
178
179
    let (_normal_text, tools) = json_parser.parse_complete(&input).await.unwrap();
    assert_eq!(tools.len(), 1);
    assert_eq!(tools[0].function.name, "test");
180

181
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
182
183
184
185
186
187
188
189
190
191
    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 世界 🌍 مرحبا עולם"}}"#;

192
193
    let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 1);
194

195
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
196
197
198
199
200
201
202
    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]"}}]"#;
203
204
205
    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();
206
207
208
209
    assert_eq!(args["text"], "Array: [1, 2, 3]");

    let pythonic_parser = PythonicParser::new();
    let input = r#"[echo(text="List: [a, b, c]")]"#;
210
211
212
    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();
213
214
215
216
217
218
219
220
221
222
223
224
    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.
    "#;

225
226
227
    let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 1);
    assert_eq!(tools[0].function.name, "actual_tool");
228
229
230
231
232
233
234
235
}

#[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"}}"#;

236
237
    let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 1);
238

239
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
    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
        }
    }"#;

263
264
    let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 1);
265

266
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
    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
        }
    }"#;

288
289
    let (_normal_text, tools) = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(tools.len(), 1);
290

291
    let args: serde_json::Value = serde_json::from_str(&tools[0].function.arguments).unwrap();
292
293
294
295
296
297
298
    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() {
299
300
301
    let mut parser = QwenParser::new();

    let tools = create_test_tools();
302
303

    // Send exactly "<tool" which is a 5-character prefix of "<tool_call>\n"
304
305
306
307
308
    let result = parser.parse_incremental("<tool", &tools).await.unwrap();
    assert!(
        result.calls.is_empty(),
        "Should be incomplete for partial tag"
    );
309
310
311
312
313

    // Complete the token
    let result = parser
        .parse_incremental(
            "_call>\n{\"name\": \"test\", \"arguments\": {}}\n</tool_call>",
314
            &tools,
315
316
317
318
319
        )
        .await
        .unwrap();

    // Should successfully parse after completing
320
321
322
    if !result.calls.is_empty() {
        if let Some(name) = &result.calls[0].name {
            assert_eq!(name, "test");
323
324
325
326
327
328
        }
    }
}

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

    let tools = create_test_tools();
332
333
334
335
336
337
338
339
340
341

    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 {
342
        let result = parser.parse_incremental(prefix, &tools).await.unwrap();
343
        assert!(
344
            result.calls.is_empty(),
345
346
347
348
            "Prefix '{}' (len {}) should be incomplete",
            prefix,
            expected_len
        );
349
        // Buffer is now internal to parser - can't assert on it
350
351
    }
}