moonlight-core 0.1.2

Shared comparison, diffing, classification, and JSONL storage primitives for Moonlight.
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
use super::*;
use crate::{
    Adapter, BodyCapture, Classification, ComparisonRun, ComparisonSummary, RunInput,
    TargetObservation,
};
use chrono::{TimeZone, Utc};
use std::collections::BTreeMap;
use tempfile::tempdir;

fn body() -> BodyCapture {
    BodyCapture {
        size_bytes: 0,
        sha256: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".to_string(),
        preview: String::new(),
        truncated: false,
    }
}

fn target(latency_ms: u128) -> TargetObservation {
    TargetObservation {
        status: Some(0),
        headers: BTreeMap::new(),
        body: body(),
        stderr: None,
        latency_ms,
        error: None,
    }
}

fn run(
    path: impl Into<String>,
    timestamp_seconds: i64,
    classification: Classification,
    secondary: bool,
) -> ComparisonRun {
    let path = path.into();
    ComparisonRun {
        id: Uuid::new_v4(),
        timestamp: Utc.timestamp_opt(timestamp_seconds, 0).unwrap(),
        adapter: Adapter::Http,
        input: RunInput::Http {
            method: "GET".to_string(),
            path,
            query: None,
        },
        request_headers: BTreeMap::new(),
        request_body: body(),
        primary: target(10),
        candidate: target(20),
        secondary: secondary.then(|| target(30)),
        comparison: ComparisonSummary {
            classification,
            ..Default::default()
        },
    }
}

fn write_runs(path: &std::path::Path, runs: &[ComparisonRun]) {
    let lines = runs
        .iter()
        .map(|run| serde_json::to_string(run).unwrap())
        .collect::<Vec<_>>()
        .join("\n");
    std::fs::write(path, format!("{lines}\n")).unwrap();
}

#[tokio::test]
async fn load_creates_parent_directory() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("nested").join("http-runs.jsonl");

    let _storage = Storage::load(path.clone()).await.unwrap();

    assert!(path.parent().unwrap().exists());
}

#[tokio::test]
async fn run_writer_creates_parent_directory() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("nested").join("cli-runs.jsonl");

    let writer = RunWriter::open(path.clone()).await.unwrap();
    writer
        .append(&run("writer", 1, Classification::Match, false))
        .await
        .unwrap();
    writer.flush().await.unwrap();

    assert!(path.exists());
}

#[tokio::test]
async fn run_writer_appends_without_loading_existing_files() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("cli-runs.jsonl");
    std::fs::write(dir.path().join("corrupt.jsonl"), "not-json\n").unwrap();

    let writer = RunWriter::open(path.clone()).await.unwrap();
    writer
        .append(&run("writer", 1, Classification::Match, false))
        .await
        .unwrap();
    writer.flush().await.unwrap();

    let lines = std::fs::read_to_string(path).unwrap();
    assert_eq!(lines.lines().count(), 1);
}

#[tokio::test]
async fn load_skips_empty_and_corrupt_jsonl_lines() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("http-runs.jsonl");
    let valid = serde_json::to_string(&run("valid", 1, Classification::Match, false)).unwrap();
    std::fs::write(&path, format!("\n{valid}\nnot-json\n\n")).unwrap();

    let storage = Storage::load(path).await.unwrap();
    let runs = storage.list().await;

    assert_eq!(runs.len(), 1);
    assert!(matches!(
        runs[0].input,
        RunInput::Http { ref path, .. } if path == "valid"
    ));
}

#[tokio::test]
async fn list_returns_newest_first() {
    let dir = tempdir().unwrap();
    let storage = Storage::load(dir.path().join("http-runs.jsonl"))
        .await
        .unwrap();
    let first = run("first", 1, Classification::Match, false);
    let second = run("second", 2, Classification::SuspiciousDifference, false);
    storage.insert(first).await.unwrap();
    storage.insert(second).await.unwrap();

    let runs = storage.list().await;

    assert!(matches!(
        runs[0].input,
        RunInput::Http { ref path, .. } if path == "second"
    ));
    assert!(matches!(
        runs[1].input,
        RunInput::Http { ref path, .. } if path == "first"
    ));
}

#[tokio::test]
async fn list_page_returns_newest_first_window() {
    let dir = tempdir().unwrap();
    let storage = Storage::load(dir.path().join("http-runs.jsonl"))
        .await
        .unwrap();
    for index in 0..5 {
        storage
            .insert(run(
                format!("run-{index}"),
                index,
                Classification::Match,
                false,
            ))
            .await
            .unwrap();
    }

    let runs = storage.list_page(2, 1).await;

    assert_eq!(runs.len(), 2);
    assert!(matches!(
        runs[0].input,
        RunInput::Http { ref path, .. } if path == "run-3"
    ));
    assert!(matches!(
        runs[1].input,
        RunInput::Http { ref path, .. } if path == "run-2"
    ));
}

#[tokio::test]
async fn retention_by_max_runs_keeps_newest_active_runs() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("http-runs.jsonl");
    let storage = Storage::load_with_options(
        path.clone(),
        StorageOptions {
            retention_max_runs: Some(2),
            retention_max_bytes: None,
        },
    )
    .await
    .unwrap();
    for index in 0..4 {
        storage
            .insert(run(
                format!("run-{index}"),
                index,
                Classification::Match,
                false,
            ))
            .await
            .unwrap();
    }

    let lines = std::fs::read_to_string(path).unwrap();
    let stored = storage.list().await;

    assert_eq!(lines.lines().count(), 2);
    assert_eq!(stored.len(), 2);
    assert!(matches!(
        stored[0].input,
        RunInput::Http { ref path, .. } if path == "run-3"
    ));
    assert!(matches!(
        stored[1].input,
        RunInput::Http { ref path, .. } if path == "run-2"
    ));
}

#[tokio::test]
async fn concurrent_inserts_are_serialized() {
    let dir = tempdir().unwrap();
    let storage = Storage::load(dir.path().join("http-runs.jsonl"))
        .await
        .unwrap();
    let first = storage.clone();
    let second = storage.clone();

    let (first_result, second_result) = tokio::join!(
        async move {
            first
                .insert(run("first", 1, Classification::Match, false))
                .await
        },
        async move {
            second
                .insert(run("second", 2, Classification::Match, false))
                .await
        }
    );

    first_result.unwrap();
    second_result.unwrap();
    assert_eq!(storage.list().await.len(), 2);
}

#[tokio::test]
async fn load_merges_jsonl_files_in_same_directory() {
    let dir = tempdir().unwrap();
    let http_path = dir.path().join("http-runs.jsonl");
    let cli_path = dir.path().join("cli-runs.jsonl");
    std::fs::write(
        &http_path,
        format!(
            "{}\n",
            serde_json::to_string(&run("http", 1, Classification::Match, false)).unwrap()
        ),
    )
    .unwrap();
    std::fs::write(
        &cli_path,
        format!(
            "{}\n",
            serde_json::to_string(&run("cli", 2, Classification::ReferenceNoise, true)).unwrap()
        ),
    )
    .unwrap();

    let storage = Storage::load(http_path).await.unwrap();
    let stats = storage.stats().await;

    assert_eq!(stats.total_runs, 2);
    assert_eq!(stats.matches, 1);
    assert_eq!(stats.reference_noise, 1);
}

#[tokio::test]
async fn jsonl_reader_reads_only_requested_file() {
    let dir = tempdir().unwrap();
    let requested_path = dir.path().join("cli-runs.jsonl");
    let sibling_path = dir.path().join("http-runs.jsonl");
    write_runs(
        &requested_path,
        &[
            run("cli-1", 1, Classification::Match, false),
            run("cli-2", 2, Classification::SuspiciousDifference, false),
        ],
    );
    write_runs(
        &sibling_path,
        &[run("http", 3, Classification::ReferenceNoise, true)],
    );

    let reader = JsonlStorageReader::new(requested_path);
    let stats = reader.stats().await.unwrap();
    let runs = reader.list_page(None, 0).await.unwrap();

    assert_eq!(stats.total_runs, 2);
    assert_eq!(stats.matches, 1);
    assert_eq!(stats.suspicious_differences, 1);
    assert_eq!(stats.reference_noise, 0);
    assert_eq!(runs.len(), 2);
    assert!(matches!(
        runs[0].input,
        RunInput::Http { ref path, .. } if path == "cli-2"
    ));
}

#[tokio::test]
async fn jsonl_reader_missing_file_is_empty() {
    let dir = tempdir().unwrap();
    let reader = JsonlStorageReader::new(dir.path().join("missing.jsonl"));

    let stats = reader.stats().await.unwrap();
    let list = reader.list_page(Some(10), 0).await.unwrap();
    let found = reader.get(Uuid::new_v4()).await.unwrap();

    assert_eq!(stats.total_runs, 0);
    assert!(stats.latest_runs.is_empty());
    assert!(list.is_empty());
    assert!(found.is_none());
}

#[tokio::test]
async fn jsonl_reader_skips_corrupt_lines() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("cli-runs.jsonl");
    let valid = run("valid", 1, Classification::Match, false);
    std::fs::write(
        &path,
        format!("not-json\n{}\n", serde_json::to_string(&valid).unwrap()),
    )
    .unwrap();

    let reader = JsonlStorageReader::new(path);
    let stats = reader.stats().await.unwrap();

    assert_eq!(stats.total_runs, 1);
    assert_eq!(stats.matches, 1);
}

#[tokio::test]
async fn jsonl_reader_pages_newest_first() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("cli-runs.jsonl");
    let runs = (0..5)
        .map(|index| run(format!("run-{index}"), index, Classification::Match, false))
        .collect::<Vec<_>>();
    write_runs(&path, &runs);

    let reader = JsonlStorageReader::new(path);
    let page = reader.list_page(Some(2), 1).await.unwrap();

    assert_eq!(page.len(), 2);
    assert!(matches!(
        page[0].input,
        RunInput::Http { ref path, .. } if path == "run-3"
    ));
    assert!(matches!(
        page[1].input,
        RunInput::Http { ref path, .. } if path == "run-2"
    ));
}

#[tokio::test]
async fn jsonl_reader_get_returns_matching_run() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("cli-runs.jsonl");
    let first = run("first", 1, Classification::Match, false);
    let second = run("second", 2, Classification::SuspiciousDifference, false);
    let second_id = second.id;
    write_runs(&path, &[first, second]);

    let reader = JsonlStorageReader::new(path);
    let found = reader.get(second_id).await.unwrap().unwrap();

    assert_eq!(found.id, second_id);
    assert!(matches!(
        found.input,
        RunInput::Http { ref path, .. } if path == "second"
    ));
}

#[tokio::test]
async fn storage_load_still_scans_directory_for_admin_views() {
    let dir = tempdir().unwrap();
    let http_path = dir.path().join("http-runs.jsonl");
    let cli_path = dir.path().join("cli-runs.jsonl");
    std::fs::write(
        &http_path,
        format!(
            "{}\n",
            serde_json::to_string(&run("http", 1, Classification::Match, false)).unwrap()
        ),
    )
    .unwrap();
    std::fs::write(
        &cli_path,
        format!(
            "{}\n",
            serde_json::to_string(&run("cli", 2, Classification::SuspiciousDifference, false))
                .unwrap()
        ),
    )
    .unwrap();

    let storage = Storage::load(http_path).await.unwrap();
    let stats = storage.stats().await;

    assert_eq!(stats.total_runs, 2);
    assert_eq!(stats.matches, 1);
    assert_eq!(stats.suspicious_differences, 1);
}

#[tokio::test]
async fn refresh_skips_reload_when_jsonl_files_are_unchanged() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("http-runs.jsonl");
    write_runs(&path, &[run("initial", 1, Classification::Match, false)]);
    let storage = Storage::load(path).await.unwrap();

    let refreshed = storage.refresh().await.unwrap();

    assert!(!refreshed);
    assert_eq!(storage.list().await.len(), 1);
}

#[tokio::test]
async fn refresh_loads_new_runs_when_write_file_changes() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("http-runs.jsonl");
    write_runs(&path, &[run("initial", 1, Classification::Match, false)]);
    let storage = Storage::load(path.clone()).await.unwrap();
    write_runs(
        &path,
        &[
            run("initial", 1, Classification::Match, false),
            run("changed", 2, Classification::SuspiciousDifference, false),
        ],
    );

    let refreshed = storage.refresh().await.unwrap();
    let runs = storage.list().await;

    assert!(refreshed);
    assert_eq!(runs.len(), 2);
    assert!(matches!(
        runs[0].input,
        RunInput::Http { ref path, .. } if path == "changed"
    ));
}

#[tokio::test]
async fn refresh_loads_new_runs_when_sibling_jsonl_file_changes() {
    let dir = tempdir().unwrap();
    let http_path = dir.path().join("http-runs.jsonl");
    let cli_path = dir.path().join("cli-runs.jsonl");
    write_runs(&http_path, &[run("http", 1, Classification::Match, false)]);
    let storage = Storage::load(http_path).await.unwrap();
    write_runs(
        &cli_path,
        &[run("cli", 2, Classification::ReferenceNoise, true)],
    );

    let refreshed = storage.refresh().await.unwrap();
    let stats = storage.stats().await;

    assert!(refreshed);
    assert_eq!(stats.total_runs, 2);
    assert_eq!(stats.reference_noise, 1);
}

#[tokio::test]
async fn stats_limits_latest_runs_to_20() {
    let dir = tempdir().unwrap();
    let storage = Storage::load(dir.path().join("http-runs.jsonl"))
        .await
        .unwrap();
    for index in 0..25 {
        storage
            .insert(run(
                format!("run-{index}"),
                index,
                Classification::Match,
                false,
            ))
            .await
            .unwrap();
    }

    let stats = storage.stats().await;

    assert_eq!(stats.total_runs, 25);
    assert_eq!(stats.latest_runs.len(), 20);
    assert!(matches!(
        stats.latest_runs[0].input,
        RunInput::Http { ref path, .. } if path == "run-24"
    ));
    assert!(matches!(
        stats.latest_runs[19].input,
        RunInput::Http { ref path, .. } if path == "run-5"
    ));
}

#[tokio::test]
async fn stats_handles_missing_secondary_latencies() {
    let dir = tempdir().unwrap();
    let storage = Storage::load(dir.path().join("http-runs.jsonl"))
        .await
        .unwrap();
    storage
        .insert(run("primary-candidate", 1, Classification::Match, false))
        .await
        .unwrap();

    let stats = storage.stats().await;

    assert_eq!(stats.total_runs, 1);
    assert_eq!(stats.latency.primary_avg_ms, 10.0);
    assert_eq!(stats.latency.candidate_avg_ms, 20.0);
    assert_eq!(stats.latency.secondary_avg_ms, None);
}

#[tokio::test]
async fn retention_rewrite_replaces_file_atomically() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("http-runs.jsonl");
    let storage = Storage::load_with_options(
        path.clone(),
        StorageOptions {
            retention_max_runs: Some(2),
            retention_max_bytes: None,
        },
    )
    .await
    .unwrap();
    for index in 0..5 {
        storage
            .insert(run(
                format!("run-{index}"),
                index,
                Classification::Match,
                false,
            ))
            .await
            .unwrap();
    }

    let lines = std::fs::read_to_string(&path).unwrap();
    let temp_files = std::fs::read_dir(dir.path())
        .unwrap()
        .filter_map(Result::ok)
        .filter(|entry| entry.path().extension().and_then(|value| value.to_str()) == Some("tmp"))
        .count();

    assert_eq!(lines.lines().count(), 2);
    assert_eq!(temp_files, 0);
    assert!(lines.contains("run-4"));
    assert!(lines.contains("run-3"));
    assert!(!lines.contains("run-2"));
}

#[tokio::test]
async fn retention_skip_rewrite_when_active_runs_are_already_within_limits() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("http-runs.jsonl");
    write_runs(
        &path,
        &[
            run("first", 1, Classification::Match, false),
            run("second", 2, Classification::Match, false),
        ],
    );
    let before = std::fs::read_to_string(&path).unwrap();
    let storage = Storage::load_with_options(
        path.clone(),
        StorageOptions {
            retention_max_runs: Some(10),
            retention_max_bytes: None,
        },
    )
    .await
    .unwrap();

    storage.apply_retention().await.unwrap();

    let after = std::fs::read_to_string(&path).unwrap();
    assert_eq!(after, before);
}