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
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
//! 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();
        let result = parser.parse_complete("").await.unwrap();
        assert_eq!(
            result.len(),
            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!(
        json_parser.parse_complete(plain_text).await.unwrap().len(),
        0
    );

    let mistral_parser = MistralParser::new();
    assert_eq!(
        mistral_parser
            .parse_complete(plain_text)
            .await
            .unwrap()
            .len(),
        0
    );

    let qwen_parser = QwenParser::new();
    assert_eq!(
        qwen_parser.parse_complete(plain_text).await.unwrap().len(),
        0
    );

    let pythonic_parser = PythonicParser::new();
    assert_eq!(
        pythonic_parser
            .parse_complete(plain_text)
            .await
            .unwrap()
            .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 {
        let result = json_parser.parse_complete(input).await.unwrap();
        assert_eq!(
            result.len(),
            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
        if let Ok(result) = parser.parse_complete(input).await {
            assert_eq!(
                result.len(),
                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}}"#;
    let result = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(result.len(), 0, "Should not parse without name field");

    // Name is not a string
    let input = r#"{"name": 123, "arguments": {}}"#;
    let result = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(result.len(), 0, "Should not parse with non-string name");
}

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

    let result = json_parser.parse_complete(&input).await.unwrap();
    assert_eq!(result.len(), 1);
    assert_eq!(result[0].function.name, "test");

    let args: serde_json::Value = serde_json::from_str(&result[0].function.arguments).unwrap();
    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 世界 🌍 مرحبا עולם"}}"#;

    let result = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(result.len(), 1);

    let args: serde_json::Value = serde_json::from_str(&result[0].function.arguments).unwrap();
    assert_eq!(args["text"], "Hello 世界 🌍 مرحبا עולם");
}

#[tokio::test]
async fn test_nested_brackets_in_strings() {
    // Test that parsers correctly handle brackets within string literals

    let mistral_parser = MistralParser::new();
    let input = r#"[TOOL_CALLS] [{"name": "echo", "arguments": {"text": "Array: [1, 2, 3]"}}]"#;
    let result = mistral_parser.parse_complete(input).await.unwrap();
    assert_eq!(result.len(), 1);
    let args: serde_json::Value = serde_json::from_str(&result[0].function.arguments).unwrap();
    assert_eq!(args["text"], "Array: [1, 2, 3]");

    let pythonic_parser = PythonicParser::new();
    let input = r#"[echo(text="List: [a, b, c]")]"#;
    let result = pythonic_parser.parse_complete(input).await.unwrap();
    assert_eq!(result.len(), 1);
    let args: serde_json::Value = serde_json::from_str(&result[0].function.arguments).unwrap();
    assert_eq!(args["text"], "List: [a, b, c]");
}

#[tokio::test]
async fn test_multiple_formats_in_text() {
    // Test that parsers don't get confused by other formats in the 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.
    "#;

    let result = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(result.len(), 1);
    assert_eq!(result[0].function.name, "actual_tool");
}

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

    let result = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(result.len(), 1);

    let args: serde_json::Value = serde_json::from_str(&result[0].function.arguments).unwrap();
    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
        }
    }"#;

    let result = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(result.len(), 1);

    let args: serde_json::Value = serde_json::from_str(&result[0].function.arguments).unwrap();
    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
        }
    }"#;

    let result = json_parser.parse_complete(input).await.unwrap();
    assert_eq!(result.len(), 1);

    let args: serde_json::Value = serde_json::from_str(&result[0].function.arguments).unwrap();
    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();

    // Test case that would fail with the bug:
    // 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();

    // Test various exact prefix lengths that would be missed by exclusive range
    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
        );
    }
}