qubit-json 0.6.0

Lenient JSON decoder for non-fully-trusted JSON text inputs
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
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Criterion benchmarks for public JSON decoding entry points.

mod internal;

use criterion::{
    BenchmarkId,
    Criterion,
    Throughput,
    black_box,
    criterion_group,
    criterion_main,
};
use qubit_json::{
    JsonDecodeOptions,
    LenientJsonDecoder,
};

use internal::BenchmarkRecord;

/// Runs the public decoder benchmarks over representative input normalization
/// paths.
///
/// # Parameters
///
/// * `c` - Criterion context used to register public decoder benchmarks.
///
/// # Panics
///
/// Panics when a fixed benchmark fixture no longer satisfies its documented
/// decoding contract.
fn benchmark_decoder(c: &mut Criterion) {
    let default_decoder = LenientJsonDecoder::default();
    let strict_decoder = LenientJsonDecoder::new(JsonDecodeOptions::strict());
    let plain_input = r#"{"id":7,"text":"plain"}"#;
    consume_record(
        serde_json::from_str::<BenchmarkRecord>(plain_input)
            .expect("strict benchmark input must decode"),
    );
    consume_record(
        strict_decoder
            .decode::<BenchmarkRecord>(plain_input)
            .expect("strict decoder benchmark input must decode"),
    );
    consume_record(
        default_decoder
            .decode::<BenchmarkRecord>(plain_input)
            .expect("default decoder benchmark input must decode"),
    );
    let mut comparison = c.benchmark_group("plain-comparison");
    comparison.bench_function("serde_json", |bencher| {
        bencher.iter(|| {
            black_box(serde_json::from_str::<BenchmarkRecord>(black_box(
                plain_input,
            )))
        });
    });
    comparison.bench_function("strict_decoder", |bencher| {
        bencher.iter(|| {
            black_box(
                strict_decoder
                    .decode::<BenchmarkRecord>(black_box(plain_input)),
            )
        });
    });
    comparison.bench_function("default_decoder", |bencher| {
        bencher.iter(|| {
            black_box(
                default_decoder
                    .decode::<BenchmarkRecord>(black_box(plain_input)),
            )
        });
    });
    comparison.finish();

    let plain_bytes = plain_input.as_bytes();
    consume_record(
        serde_json::from_slice::<BenchmarkRecord>(plain_bytes)
            .expect("strict benchmark input must decode"),
    );
    consume_record(
        strict_decoder
            .decode_slice::<BenchmarkRecord>(plain_bytes)
            .expect("strict decoder benchmark input must decode"),
    );
    consume_record(
        default_decoder
            .decode_slice::<BenchmarkRecord>(plain_bytes)
            .expect("default decoder benchmark input must decode"),
    );
    let mut bytes_comparison = c.benchmark_group("plain-bytes-comparison");
    bytes_comparison.bench_function("serde_json_from_slice", |bencher| {
        bencher.iter(|| {
            black_box(serde_json::from_slice::<BenchmarkRecord>(black_box(
                plain_bytes,
            )))
        });
    });
    bytes_comparison.bench_function("strict_decoder_decode_slice", |bencher| {
        bencher.iter(|| {
            black_box(
                strict_decoder
                    .decode_slice::<BenchmarkRecord>(black_box(plain_bytes)),
            )
        });
    });
    bytes_comparison.bench_function(
        "default_decoder_decode_slice",
        |bencher| {
            bencher.iter(|| {
                black_box(
                    default_decoder.decode_slice::<BenchmarkRecord>(black_box(
                        plain_bytes,
                    )),
                )
            });
        },
    );
    bytes_comparison.finish();

    let cases = [
        ("plain", plain_input),
        ("fenced", "```json\n{\"id\":7,\"text\":\"fenced\"}\n```"),
        ("raw-control", "{\"id\":7,\"text\":\"line one\nline two\"}"),
    ];

    for (name, input) in cases {
        consume_record(
            default_decoder
                .decode::<BenchmarkRecord>(input)
                .expect("benchmark input must decode"),
        );
        consume_record(
            default_decoder
                .decode_object::<BenchmarkRecord>(input)
                .expect("benchmark input must decode as an object"),
        );
        default_decoder
            .decode_value(input)
            .expect("benchmark input must decode as a value");
        let mut group = c.benchmark_group(name);
        group.bench_function("decode", |bencher| {
            bencher.iter(|| {
                black_box(
                    default_decoder.decode::<BenchmarkRecord>(black_box(input)),
                )
            });
        });
        group.bench_function("decode_object", |bencher| {
            bencher.iter(|| {
                black_box(
                    default_decoder
                        .decode_object::<BenchmarkRecord>(black_box(input)),
                )
            });
        });
        group.bench_function("decode_value", |bencher| {
            bencher.iter(|| {
                black_box(default_decoder.decode_value(black_box(input)))
            });
        });
        group.finish();
    }

    let array_input = r#"[{"id":7,"text":"array"}]"#;
    for record in default_decoder
        .decode_array::<BenchmarkRecord>(array_input)
        .expect("benchmark input must decode as an array")
    {
        consume_record(record);
    }
    c.bench_function("array/decode_array", |bencher| {
        bencher.iter(|| {
            black_box(
                default_decoder
                    .decode_array::<BenchmarkRecord>(black_box(array_input)),
            )
        });
    });
}

/// Runs size-scaling benchmarks that mirror the HTTP and LLM SDK consumers.
///
/// The strict byte benchmarks include both a reused decoder and a decoder
/// constructed inside the measured iteration. The latter mirrors the current
/// `rs-http` call sites, which configure strict decoding immediately before
/// each response or SSE payload is decoded.
///
/// # Parameters
///
/// * `c` - Criterion context used to register downstream-shaped benchmarks.
///
/// # Panics
///
/// Panics when a generated benchmark payload no longer satisfies its expected
/// decoding contract.
fn benchmark_downstream_scaling(c: &mut Criterion) {
    let strict_decoder = LenientJsonDecoder::new(JsonDecodeOptions::strict());
    let default_decoder = LenientJsonDecoder::default();
    let mut plain_group = c.benchmark_group("downstream-plain-bytes");

    for payload_bytes in [1_024_usize, 65_536, 1_048_576] {
        let input = benchmark_record_input(payload_bytes, None);
        consume_record(
            serde_json::from_slice::<BenchmarkRecord>(input.as_bytes())
                .expect("strict byte benchmark input must decode"),
        );
        consume_record(
            strict_decoder
                .decode_slice::<BenchmarkRecord>(input.as_bytes())
                .expect("strict decoder byte benchmark input must decode"),
        );
        consume_record(
            LenientJsonDecoder::new(JsonDecodeOptions::strict())
                .decode_slice::<BenchmarkRecord>(input.as_bytes())
                .expect(
                    "constructed strict decoder benchmark input must decode",
                ),
        );
        consume_record(
            default_decoder
                .decode_slice::<BenchmarkRecord>(input.as_bytes())
                .expect("default decoder byte benchmark input must decode"),
        );
        plain_group.throughput(Throughput::Bytes(input.len() as u64));
        plain_group.bench_with_input(
            BenchmarkId::new("serde_json_from_slice", payload_bytes),
            &input,
            |bencher, input| {
                bencher.iter(|| {
                    black_box(serde_json::from_slice::<BenchmarkRecord>(
                        black_box(input.as_bytes()),
                    ))
                });
            },
        );
        plain_group.bench_with_input(
            BenchmarkId::new("strict_decoder_decode_slice", payload_bytes),
            &input,
            |bencher, input| {
                bencher.iter(|| {
                    black_box(strict_decoder.decode_slice::<BenchmarkRecord>(
                        black_box(input.as_bytes()),
                    ))
                });
            },
        );
        plain_group.bench_with_input(
            BenchmarkId::new(
                "strict_decoder_construct_and_decode_slice",
                payload_bytes,
            ),
            &input,
            |bencher, input| {
                bencher.iter(|| {
                    let decoder =
                        LenientJsonDecoder::new(JsonDecodeOptions::strict());
                    black_box(decoder.decode_slice::<BenchmarkRecord>(
                        black_box(input.as_bytes()),
                    ))
                });
            },
        );
        plain_group.bench_with_input(
            BenchmarkId::new("default_decoder_decode_slice", payload_bytes),
            &input,
            |bencher, input| {
                bencher.iter(|| {
                    black_box(default_decoder.decode_slice::<BenchmarkRecord>(
                        black_box(input.as_bytes()),
                    ))
                });
            },
        );
    }
    plain_group.finish();

    let mut lenient_group = c.benchmark_group("downstream-lenient-typed");
    for payload_bytes in [1_024_usize, 65_536, 1_048_576] {
        let plain = benchmark_record_input(payload_bytes, None);
        let unicode = benchmark_unicode_record_input(payload_bytes);
        let fenced = format!("```json\n{plain}\n```");
        let pretty = format!(
            "{{\n  \"id\": 7,\n  \"text\": \"{}\"\n}}",
            "a".repeat(payload_bytes),
        );
        let sparse_control = benchmark_record_input(payload_bytes, Some(1_024));
        for (name, input) in [
            ("plain", plain),
            ("unicode-no-control", unicode),
            ("fenced", fenced),
            ("pretty", pretty),
            ("sparse-control", sparse_control),
        ] {
            consume_record(
                default_decoder
                    .decode_object::<BenchmarkRecord>(&input)
                    .expect("lenient typed benchmark input must decode"),
            );
            lenient_group.throughput(Throughput::Bytes(input.len() as u64));
            lenient_group.bench_with_input(
                BenchmarkId::new(name, payload_bytes),
                &input,
                |bencher, input| {
                    bencher.iter(|| {
                        black_box(
                            default_decoder.decode_object::<BenchmarkRecord>(
                                black_box(input.as_str()),
                            ),
                        )
                    });
                },
            );
        }
    }
    lenient_group.finish();

    let failure_payload_bytes = 65_536;
    let plain = benchmark_record_input(failure_payload_bytes, None);
    let malformed = &plain[..plain.len() - 1];
    let wrong_top_level = format!("[{plain}]");
    let bounded_decoder = LenientJsonDecoder::new(
        JsonDecodeOptions::strict().with_max_input_bytes(Some(plain.len() - 1)),
    );
    assert!(
        default_decoder
            .decode_object::<BenchmarkRecord>(malformed)
            .is_err(),
        "malformed benchmark input must fail",
    );
    assert!(
        default_decoder
            .decode_object::<BenchmarkRecord>(&wrong_top_level)
            .is_err(),
        "array benchmark input must fail object decoding",
    );
    assert!(
        bounded_decoder
            .decode_slice::<BenchmarkRecord>(plain.as_bytes())
            .is_err(),
        "oversized benchmark input must fail",
    );
    let mut failure_group = c.benchmark_group("downstream-failures");
    failure_group.throughput(Throughput::Bytes(plain.len() as u64));
    failure_group.bench_function("invalid-json", |bencher| {
        bencher.iter(|| {
            black_box(
                default_decoder
                    .decode_object::<BenchmarkRecord>(black_box(malformed)),
            )
        });
    });
    failure_group.bench_function("top-level-mismatch", |bencher| {
        bencher.iter(|| {
            black_box(default_decoder.decode_object::<BenchmarkRecord>(
                black_box(wrong_top_level.as_str()),
            ))
        });
    });
    failure_group.bench_function("size-limit-rejection", |bencher| {
        bencher.iter(|| {
            black_box(
                bounded_decoder.decode_slice::<BenchmarkRecord>(black_box(
                    plain.as_bytes(),
                )),
            )
        });
    });
    for payload_bytes in [65_536_usize, 1_048_576] {
        let plain = benchmark_record_input(payload_bytes, None);
        let first_field_type_error =
            plain.replacen("\"id\":7", "\"id\":\"wrong\"", 1);
        let last_field_type_error = format!(
            "{{\"text\":\"{}\",\"id\":\"wrong\"}}",
            "a".repeat(payload_bytes),
        );

        for (name, input) in [
            ("first-field-type-error", first_field_type_error),
            ("last-field-type-error", last_field_type_error),
        ] {
            assert!(
                strict_decoder
                    .decode_slice::<BenchmarkRecord>(input.as_bytes())
                    .is_err(),
                "type-mismatched benchmark input must fail",
            );
            failure_group.throughput(Throughput::Bytes(input.len() as u64));
            failure_group.bench_with_input(
                BenchmarkId::new(name, payload_bytes),
                &input,
                |bencher, input| {
                    bencher.iter(|| {
                        black_box(
                            strict_decoder.decode_slice::<BenchmarkRecord>(
                                black_box(input.as_bytes()),
                            ),
                        )
                    });
                },
            );
        }
    }
    failure_group.finish();
}

/// Runs scaling benchmarks for control-character normalization.
///
/// # Parameters
///
/// * `c` - Criterion context used to register normalization benchmarks.
///
/// # Panics
///
/// Panics when a generated control-character payload cannot be decoded.
fn benchmark_control_character_scaling(c: &mut Criterion) {
    let decoder = LenientJsonDecoder::default();
    let mut group = c.benchmark_group("control-characters");

    for payload_bytes in [1_024_usize, 65_536, 1_048_576] {
        for (name, control_stride) in
            [("plain", None), ("sparse", Some(1_024)), ("dense", Some(2))]
        {
            let input = control_character_input(payload_bytes, control_stride);
            let normalized_limit = normalized_control_character_input_bytes(
                input.len(),
                payload_bytes,
                control_stride,
            );
            let bounded_decoder = LenientJsonDecoder::new(
                JsonDecodeOptions::default()
                    .with_max_normalized_bytes(Some(normalized_limit)),
            );
            decoder
                .decode_value(&input)
                .expect("benchmark input must decode as a value");
            bounded_decoder
                .decode_value(&input)
                .expect("bounded benchmark input must decode as a value");
            group.throughput(Throughput::Bytes(input.len() as u64));
            group.bench_with_input(
                BenchmarkId::new(name, payload_bytes),
                &input,
                |bencher, input| {
                    bencher.iter(|| {
                        black_box(
                            decoder.decode_value(black_box(input.as_str())),
                        )
                    });
                },
            );
            group.bench_with_input(
                BenchmarkId::new(
                    format!("{name}-normalized-limit"),
                    payload_bytes,
                ),
                &input,
                |bencher, input| {
                    bencher.iter(|| {
                        black_box(
                            bounded_decoder
                                .decode_value(black_box(input.as_str())),
                        )
                    });
                },
            );
        }
    }
    group.finish();
}

/// Returns the exact normalized byte size for a generated control input.
///
/// # Parameters
///
/// * `input_bytes` - Raw byte size of the generated JSON object.
/// * `payload_bytes` - Number of bytes in its JSON string payload.
/// * `control_stride` - Optional spacing between raw NUL characters.
///
/// # Returns
///
/// The repaired JSON byte size, where every raw NUL expands from one byte to
/// the six-byte `\\u0000` escape.
///
/// # Panics
///
/// Panics when `control_stride` is `Some(0)`.
fn normalized_control_character_input_bytes(
    input_bytes: usize,
    payload_bytes: usize,
    control_stride: Option<usize>,
) -> usize {
    let control_count = control_stride.map_or(0, |stride| {
        assert_ne!(stride, 0, "control stride must be nonzero");
        payload_bytes.div_ceil(stride)
    });
    input_bytes + (control_count * 5)
}

/// Builds a JSON object whose string payload has the requested control density.
///
/// # Parameters
///
/// * `payload_bytes` - Number of bytes to place in the object's string field.
/// * `control_stride` - Optional distance between raw NUL characters.
///
/// # Returns
///
/// A JSON-like object accepted by the lenient value decoder.
///
/// # Panics
///
/// Panics when `control_stride` is `Some(0)`.
fn control_character_input(
    payload_bytes: usize,
    control_stride: Option<usize>,
) -> String {
    let mut input = String::with_capacity(payload_bytes + 11);
    input.push_str("{\"text\":\"");
    for index in 0..payload_bytes {
        if control_stride.is_some_and(|stride| index % stride == 0) {
            input.push('\u{0000}');
        } else {
            input.push('a');
        }
    }
    input.push_str("\"}");
    input
}

/// Builds a typed JSON object with a requested string payload size and optional
/// raw-control-character density.
///
/// # Parameters
///
/// * `payload_bytes` - Number of bytes to place in the record's text field.
/// * `control_stride` - Optional distance between raw NUL characters.
///
/// # Returns
///
/// A JSON-like object accepted by the lenient typed decoder.
///
/// # Panics
///
/// Panics when `control_stride` is `Some(0)`.
fn benchmark_record_input(
    payload_bytes: usize,
    control_stride: Option<usize>,
) -> String {
    let mut input = String::with_capacity(payload_bytes + 18);
    input.push_str("{\"id\":7,\"text\":\"");
    for index in 0..payload_bytes {
        if control_stride.is_some_and(|stride| index % stride == 0) {
            input.push('\u{0000}');
        } else {
            input.push('a');
        }
    }
    input.push_str("\"}");
    input
}

/// Builds a JSON record whose text contains valid multibyte UTF-8 only.
///
/// # Parameters
///
/// * `payload_bytes` - Approximate UTF-8 payload size in bytes.
///
/// # Returns
///
/// A valid JSON object containing no ASCII C0 control bytes.
#[must_use]
fn benchmark_unicode_record_input(payload_bytes: usize) -> String {
    const CHARACTER: &str = "δΈ€";

    let repetitions = payload_bytes.div_ceil(CHARACTER.len());
    format!(
        "{{\"id\":7,\"text\":\"{}\"}}",
        CHARACTER.repeat(repetitions),
    )
}

/// Consumes deserialized fields so the benchmark exercises the complete result.
///
/// # Parameters
///
/// * `record` - Deserialized benchmark value whose fields are consumed.
fn consume_record(record: BenchmarkRecord) {
    black_box(record.id);
    black_box(record.text);
}

criterion_group!(
    benches,
    benchmark_decoder,
    benchmark_control_character_scaling,
    benchmark_downstream_scaling
);
criterion_main!(benches);