xchecker 1.2.0

Spec pipeline with receipts and gateable JSON contracts
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
//! JCS emission performance benchmarks (NFR1)
//!
//! **WHITE-BOX TEST**: This test uses internal module APIs (`doctor::{...}`, `types::{...}`)
//! and may break with internal refactors. These tests are intentionally white-box to validate
//! internal implementation details. See FR-TEST-4 for white-box test policy.
//!
//! Tests that JCS canonicalization meets the ≤ 50ms target for typical payloads

use anyhow::Result;
use chrono::Utc;
use serde_json::json;
use std::collections::BTreeMap;
use std::time::Instant;
use xchecker::doctor::{CheckStatus, DoctorCheck, DoctorOutput};
use xchecker::types::{ArtifactInfo, ConfigSource, ConfigValue, StatusOutput};

/// Helper to serialize using JCS
fn to_jcs_string<T: serde::Serialize>(value: &T) -> Result<String> {
    let json_value = serde_json::to_value(value)?;
    let canonical_bytes = serde_json_canonicalizer::to_vec(&json_value)?;
    Ok(String::from_utf8(canonical_bytes)?)
}

/// Create a typical receipt-like structure for benchmarking
/// Note: We use a simplified structure since Receipt has many required fields
fn create_typical_receipt_json() -> serde_json::Value {
    json!({
        "schema_version": "1",
        "emitted_at": Utc::now().to_rfc3339(),
        "spec_id": "test-spec",
        "phase": "requirements",
        "xchecker_version": "0.1.0",
        "claude_cli_version": "0.8.5",
        "model_full_name": "haiku",
        "model_alias": null,
        "canonicalization_version": "yaml-v1,md-v1",
        "canonicalization_backend": "jcs-rfc8785",
        "flags": {
            "packet_max_bytes": "65536",
            "packet_max_lines": "1200"
        },
        "runner": "native",
        "runner_distro": null,
        "packet": {
            "files": [],
            "total_bytes": 1024,
            "total_lines": 50
        },
        "outputs": [
            {"path": "00-requirements.md", "blake3_first8": "abcd1234"},
            {"path": "00-requirements.core.yaml", "blake3_first8": "ef567890"}
        ],
        "exit_code": 0,
        "error_kind": null,
        "error_reason": null,
        "stderr_tail": null,
        "stderr_redacted": "Some stderr output",
        "warnings": ["Warning 1", "Warning 2"],
        "fallback_used": false,
        "diff_context": null
    })
}

/// Create a typical status output for benchmarking
fn create_typical_status() -> StatusOutput {
    let mut effective_config = BTreeMap::new();
    effective_config.insert(
        "packet_max_bytes".to_string(),
        ConfigValue {
            value: json!(65536),
            source: ConfigSource::Default,
        },
    );
    effective_config.insert(
        "packet_max_lines".to_string(),
        ConfigValue {
            value: json!(1200),
            source: ConfigSource::Config,
        },
    );
    effective_config.insert(
        "phase_timeout".to_string(),
        ConfigValue {
            value: json!(600),
            source: ConfigSource::Cli,
        },
    );

    let mut artifacts = Vec::new();
    for i in 0..20 {
        artifacts.push(ArtifactInfo {
            path: format!("artifact-{i:03}.md"),
            blake3_first8: format!("{:08x}", i * 12345),
        });
    }

    StatusOutput {
        schema_version: "1".to_string(),
        emitted_at: Utc::now(),
        runner: "native".to_string(),
        runner_distro: None,
        fallback_used: false,
        canonicalization_version: "yaml-v1,md-v1".to_string(),
        canonicalization_backend: "jcs-rfc8785".to_string(),
        artifacts,
        last_receipt_path: "receipts/requirements-20241124_120000.json".to_string(),
        effective_config,
        lock_drift: None,
        pending_fixups: None,
    }
}

/// Create a typical doctor output for benchmarking
fn create_typical_doctor() -> DoctorOutput {
    let checks = vec![
        DoctorCheck {
            name: "atomic_rename".to_string(),
            status: CheckStatus::Pass,
            details: "Atomic rename test passed".to_string(),
        },
        DoctorCheck {
            name: "claude_path".to_string(),
            status: CheckStatus::Pass,
            details: "Found claude at /usr/local/bin/claude".to_string(),
        },
        DoctorCheck {
            name: "claude_version".to_string(),
            status: CheckStatus::Pass,
            details: "Claude CLI version 0.8.5".to_string(),
        },
        DoctorCheck {
            name: "config_parse".to_string(),
            status: CheckStatus::Pass,
            details: "Configuration parsed successfully".to_string(),
        },
        DoctorCheck {
            name: "runner_selection".to_string(),
            status: CheckStatus::Pass,
            details: "Runner mode: native".to_string(),
        },
        DoctorCheck {
            name: "write_permissions".to_string(),
            status: CheckStatus::Pass,
            details: "Write permissions OK".to_string(),
        },
        DoctorCheck {
            name: "wsl_availability".to_string(),
            status: CheckStatus::Warn,
            details: "WSL not available (not on Windows)".to_string(),
        },
    ];

    DoctorOutput {
        schema_version: "1".to_string(),
        emitted_at: Utc::now(),
        ok: true,
        checks,
        cache_stats: None,
    }
}

#[test]
fn test_receipt_jcs_performance() -> Result<()> {
    let receipt = create_typical_receipt_json();

    // Warm-up run
    let _ = to_jcs_string(&receipt)?;

    // Measure 10 runs
    let mut timings = Vec::new();
    for _ in 0..10 {
        let start = Instant::now();
        let _ = to_jcs_string(&receipt)?;
        let elapsed = start.elapsed();
        timings.push(elapsed.as_micros() as f64 / 1000.0); // Convert to ms
    }

    // Calculate median
    timings.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let median = timings[timings.len() / 2];

    println!("Receipt JCS emission:");
    println!("  Median: {median:.3} ms");
    println!(
        "  Min: {:.3} ms",
        timings.iter().copied().fold(f64::INFINITY, f64::min)
    );
    println!(
        "  Max: {:.3} ms",
        timings.iter().copied().fold(f64::NEG_INFINITY, f64::max)
    );

    // NFR1 target: ≤ 50ms for JCS emission
    // Receipt is the smallest payload, should be well under target
    assert!(
        median < 50.0,
        "Receipt JCS emission took {median:.3} ms, exceeds 50ms target"
    );

    Ok(())
}

#[test]
fn test_status_jcs_performance() -> Result<()> {
    let status = create_typical_status();

    // Warm-up run
    let _ = to_jcs_string(&status)?;

    // Measure 10 runs
    let mut timings = Vec::new();
    for _ in 0..10 {
        let start = Instant::now();
        let _ = to_jcs_string(&status)?;
        let elapsed = start.elapsed();
        timings.push(elapsed.as_micros() as f64 / 1000.0); // Convert to ms
    }

    // Calculate median
    timings.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let median = timings[timings.len() / 2];

    println!("Status JCS emission:");
    println!("  Median: {median:.3} ms");
    println!(
        "  Min: {:.3} ms",
        timings.iter().copied().fold(f64::INFINITY, f64::min)
    );
    println!(
        "  Max: {:.3} ms",
        timings.iter().copied().fold(f64::NEG_INFINITY, f64::max)
    );

    // NFR1 target: ≤ 50ms for JCS emission
    assert!(
        median < 50.0,
        "Status JCS emission took {median:.3} ms, exceeds 50ms target"
    );

    Ok(())
}

#[test]
fn test_doctor_jcs_performance() -> Result<()> {
    let doctor = create_typical_doctor();

    // Warm-up run
    let _ = to_jcs_string(&doctor)?;

    // Measure 10 runs
    let mut timings = Vec::new();
    for _ in 0..10 {
        let start = Instant::now();
        let _ = to_jcs_string(&doctor)?;
        let elapsed = start.elapsed();
        timings.push(elapsed.as_micros() as f64 / 1000.0); // Convert to ms
    }

    // Calculate median
    timings.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let median = timings[timings.len() / 2];

    println!("Doctor JCS emission:");
    println!("  Median: {median:.3} ms");
    println!(
        "  Min: {:.3} ms",
        timings.iter().copied().fold(f64::INFINITY, f64::min)
    );
    println!(
        "  Max: {:.3} ms",
        timings.iter().copied().fold(f64::NEG_INFINITY, f64::max)
    );

    // NFR1 target: ≤ 50ms for JCS emission
    assert!(
        median < 50.0,
        "Doctor JCS emission took {median:.3} ms, exceeds 50ms target"
    );

    Ok(())
}

#[test]
fn test_combined_jcs_performance() -> Result<()> {
    // Test all three together to simulate a typical workflow
    let receipt = create_typical_receipt_json();
    let status = create_typical_status();
    let doctor = create_typical_doctor();

    // Warm-up run
    let _ = to_jcs_string(&receipt)?;
    let _ = to_jcs_string(&status)?;
    let _ = to_jcs_string(&doctor)?;

    // Measure 10 runs of all three
    let mut timings = Vec::new();
    for _ in 0..10 {
        let start = Instant::now();
        let _ = to_jcs_string(&receipt)?;
        let _ = to_jcs_string(&status)?;
        let _ = to_jcs_string(&doctor)?;
        let elapsed = start.elapsed();
        timings.push(elapsed.as_micros() as f64 / 1000.0); // Convert to ms
    }

    // Calculate median
    timings.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let median = timings[timings.len() / 2];

    println!("Combined JCS emission (receipt + status + doctor):");
    println!("  Median: {median:.3} ms");
    println!(
        "  Min: {:.3} ms",
        timings.iter().copied().fold(f64::INFINITY, f64::min)
    );
    println!(
        "  Max: {:.3} ms",
        timings.iter().copied().fold(f64::NEG_INFINITY, f64::max)
    );

    // NFR1 target: ≤ 50ms for JCS emission
    // Combined should still be under target since individual operations are fast
    assert!(
        median < 50.0,
        "Combined JCS emission took {median:.3} ms, exceeds 50ms target"
    );

    Ok(())
}

#[test]
fn test_large_status_jcs_performance() -> Result<()> {
    // Create a larger status output with 100 artifacts
    let mut effective_config = BTreeMap::new();
    for i in 0..20 {
        effective_config.insert(
            format!("config_key_{i}"),
            ConfigValue {
                value: json!(format!("value_{}", i)),
                source: ConfigSource::Default,
            },
        );
    }

    let mut artifacts = Vec::new();
    for i in 0..100 {
        artifacts.push(ArtifactInfo {
            path: format!("artifact-{i:03}.md"),
            blake3_first8: format!("{:08x}", i * 12345),
        });
    }

    let status = StatusOutput {
        schema_version: "1".to_string(),
        emitted_at: Utc::now(),
        runner: "native".to_string(),
        runner_distro: None,
        fallback_used: false,
        canonicalization_version: "yaml-v1,md-v1".to_string(),
        canonicalization_backend: "jcs-rfc8785".to_string(),
        artifacts,
        last_receipt_path: "receipts/requirements-20241124_120000.json".to_string(),
        effective_config,
        lock_drift: None,
        pending_fixups: None,
    };

    // Warm-up run
    let _ = to_jcs_string(&status)?;

    // Measure 10 runs
    let mut timings = Vec::new();
    for _ in 0..10 {
        let start = Instant::now();
        let _ = to_jcs_string(&status)?;
        let elapsed = start.elapsed();
        timings.push(elapsed.as_micros() as f64 / 1000.0); // Convert to ms
    }

    // Calculate median
    timings.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let median = timings[timings.len() / 2];

    println!("Large Status JCS emission (100 artifacts, 20 config keys):");
    println!("  Median: {median:.3} ms");
    println!(
        "  Min: {:.3} ms",
        timings.iter().copied().fold(f64::INFINITY, f64::min)
    );
    println!(
        "  Max: {:.3} ms",
        timings.iter().copied().fold(f64::NEG_INFINITY, f64::max)
    );

    // NFR1 target: ≤ 50ms for JCS emission
    // Even with larger payload, should be under target
    assert!(
        median < 50.0,
        "Large Status JCS emission took {median:.3} ms, exceeds 50ms target"
    );

    Ok(())
}