printobserver-server 0.20.2

The printobserver server.
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
//! A print started under an aligned camera check, drawn through that check's
//! correction from its first check.
//!
//! The server is the real composition over the scripted `OctoPrint` and a
//! scripted camera, as the composite-check journeys run it, configured with
//! the `core-one-2026-11-27.json` calibration. The camera is first checked on
//! the empty sheet, as the operator checks it before a print, and the print is
//! then started naming that check. Its frames are the 2026-11-28 print's own,
//! taken while the toolhead stood over the box, whose first-layer judgements
//! found the toolhead 46.04 and 42.38 px from where the calibration draws the
//! box, and which v0.17.0 showed as the plain frame for it. The slice is that
//! print's, with its two `M600` lines made comments of the same length so no
//! planned change interposes a check of its own and every byte offset stays the
//! print's. Each check is held open while the journey moves the job on, so
//! every check reads exactly the frame and position the journey means.
//!
//! The 2026-11-29 print's frames, under that day's calibration, prove what
//! each check's `camera_view_judged` measured: its own frame's landmarks and
//! residual, alongside the correction it was judged against.

use core::time::Duration;
use std::path::PathBuf;

use printobserver_octoprint::standin::JobScript;
use printobserver_server::Running;
use printobserver_types::serde_json::{Value, json};
use printobserver_types::{PrintId, Timestamp};

use crate::camera_host::{Scripted, ScriptedHost};
use crate::composite_checks::{
    Camera, FILE, Journey, block_under, calibration_at, expected_check, expected_composite, frame,
    index_of, sha256, slice,
};
use crate::lean_checks::handed;
use crate::world::{OPERATOR, presenting};

/// The installer whose template the journeys run.
const INSTALLER: &str = "scripts/install.sh";

/// The print the frames are of.
const CASE: &str = "two-colour-box-2026-11-28";

/// The seconds between two checks.
const INTERVAL_S: i64 = 2;

/// The checks v0.17.0 showed as the plain frame, each with the file position
/// it was taken at: at 07:00 the first-layer search found the toolhead 46.04
/// px off, at 07:07 42.38 px off, and at 07:09 the box beside the head.
const JUDGED: [(&str, u64); 3] = [
    ("070026-94b6cef20a02.jpg", 24_174),
    ("070721-f07bf91246a3.jpg", 39_844),
    ("070922-de189020b6f6.jpg", 51_973),
];

/// A later position of the print, for a check whose camera has moved.
const LATER: u64 = 60_000;

/// The calibration the 2026-11-28 frames were taken under.
fn calibration() -> Value {
    calibration_named("core-one-2026-11-27.json")
}

/// One committed calibration.
fn calibration_named(name: &str) -> Value {
    printobserver_types::serde_json::from_slice(
        &std::fs::read(
            PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("../../tests/real-prints/cameras")
                .join(name),
        )
        .expect("the committed calibration"),
    )
    .expect("JSON")
}

/// The print's slice, as `OctoPrint` held and printed it, with its colour
/// changes made comments.
fn box_slice() -> Vec<u8> {
    uninterrupted(&slice("two-colour-box-2026-11-28.gcode"))
}

/// The same slice as the slicer wrote it on the print PC, its local copy,
/// with its colour changes made comments the same way: every offset past its
/// head is somewhere other than `OctoPrint`'s copy's.
fn local_box_slice() -> Vec<u8> {
    uninterrupted(&slice("two-colour-box-2026-11-28.local-slice.gcode"))
}

/// A slice with each `M600` line made a comment of the same length.
fn uninterrupted(slice: &[u8]) -> Vec<u8> {
    slice
        .split(|byte| *byte == b'\n')
        .map(|line| {
            if line == b"M600" || line == b"M600\r" {
                line.iter()
                    .enumerate()
                    .map(|(at, byte)| if at == 0 { b';' } else { *byte })
                    .collect()
            } else {
                line.to_vec()
            }
        })
        .collect::<Vec<_>>()
        .join(&b'\n')
}

/// A frame moved `by` whole pixels right, its uncovered columns filled from
/// the nearest edge, as a camera knocked sideways shows the same scene.
fn shifted(bytes: &[u8], by: usize) -> Vec<u8> {
    let mut decoded = image::load_from_memory(bytes).expect("a frame").to_rgb8();
    let width = decoded.width() as usize;
    let raw: &mut [u8] = &mut decoded;
    for line in raw.chunks_exact_mut(width * 3) {
        let edge = [line[0], line[1], line[2]];
        line.copy_within(..(width - by) * 3, by * 3);
        for pixel in line[..by * 3].chunks_exact_mut(3) {
            pixel.copy_from_slice(&edge);
        }
    }
    let mut out = Vec::new();
    image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 95)
        .encode_image(&decoded)
        .expect("a frame encodes");
    out
}

/// The job printing at `position`.
fn job_at(journey: &Journey, position: u64) {
    journey.at(position);
}

/// A journey's checks, each held open until the journey lets it go.
struct Checks<'a> {
    journey: &'a Journey,
    hold: PathBuf,
    count: usize,
}

impl<'a> Checks<'a> {
    /// Hold the first check when it comes.
    fn holding(journey: &'a Journey) -> Self {
        let hold = journey.root.path().join("hold");
        std::fs::write(&hold, b"").expect("the hold is writable");
        Self {
            journey,
            hold,
            count: 0,
        }
    }

    /// The next check, its job at `position`, and what its harness was
    /// handed: the check before it is let go once the job has moved, and this
    /// one held as it comes.
    async fn next(&mut self, position: u64) -> Value {
        job_at(self.journey, position);
        if self.count > 0 {
            std::fs::remove_file(&self.hold).expect("the hold is removable");
            tokio::time::sleep(Duration::from_millis(400)).await;
            std::fs::write(&self.hold, b"").expect("the hold is writable");
        }
        self.count += 1;
        let seen = self.journey.runs(self.count).await;
        seen[self.count - 1].clone()
    }

    /// Let the last check go.
    fn release(self) {
        let _ = std::fs::remove_file(&self.hold);
    }
}

/// The situation a check's prompt carried.
fn situation(seen: &Value) -> Value {
    let (prompt, _) = handed(seen);
    block_under(&prompt, "## The situation when this turn began")
}

/// When a check's frame was captured, as its event says.
fn captured_at(seen: &Value) -> Timestamp {
    let (prompt, _) = handed(seen);
    printobserver_types::serde_json::from_value(
        block_under(&prompt, "## The event")["payload"]["frame_captured_at"].clone(),
    )
    .expect("the check's frame was captured at a time")
}

/// Check the camera on `sheet` at bed `z` mm, as the operator does before a
/// print.
async fn checked(server: &Running, sheet: &str, z: f64) -> Value {
    let response = presenting(OPERATOR)
        .get(format!(
            "{}/camera/check?sheet={sheet}&bed_z_mm={z}",
            server.base_url()
        ))
        .send()
        .await
        .expect("the server answers");
    assert_eq!(response.status(), reqwest::StatusCode::OK);
    response.json().await.expect("JSON")
}

/// Start the slice on `sheet` as the operator, its manifest naming
/// `camera_check`, every check it may override overridden; answer the print.
async fn started_under(server: &Running, sheet: &str, camera_check: &Value) -> PrintId {
    let path = printobserver_server::operation("start_print")
        .expect("`start_print` is served")
        .path
        .replace("{print_id}", &PrintId::new().to_string());
    let body = json!({
        "file_name": FILE,
        "manifest": {
            "file_name": FILE,
            "material": "PLA",
            "nozzle_diameter_mm": 0.6,
            "slicer_profile": "0.20mm STRUCTURAL",
            "sheet": sheet,
            "allowed": {},
            "metadata": {},
            "camera_check": camera_check,
        },
        "override_filament_check": true,
        "override_material_check": true,
        "override_sheet_check": true,
        "reason": "the camera was checked on the empty sheet",
        "actor": "operator",
    });
    let answer: Value = presenting(OPERATOR)
        .post(format!("{}{path}", server.base_url()))
        .json(&body)
        .send()
        .await
        .expect("the server answers")
        .json()
        .await
        .expect("JSON");
    assert_eq!(answer["record"]["decision"], "accepted", "{answer:#}");
    answer["record"]["print_id"]
        .as_str()
        .expect("a print")
        .parse()
        .expect("a print id")
}

/// Every event of a print's history, oldest first.
async fn history(server: &Running, print_id: PrintId) -> Vec<Value> {
    let body: Value = presenting(OPERATOR)
        .get(format!(
            "{}/prints/{print_id}/history?limit=1000",
            server.base_url()
        ))
        .send()
        .await
        .expect("the server answers")
        .json()
        .await
        .expect("JSON");
    let mut events = body["events"].as_array().expect("events").clone();
    events.sort_by_key(|event| event["id"].as_str().unwrap_or_default().to_owned());
    events
}

/// The payloads of one kind, oldest first.
fn payloads(events: &[Value], kind: &str) -> Vec<Value> {
    events
        .iter()
        .filter(|event| event["kind"] == kind)
        .map(|event| event["payload"].clone())
        .collect()
}

/// A check's correction's shift, `[dx, dy]`.
fn shift_of(check: &Value) -> [f64; 2] {
    let matrix = &check["correction"]["matrix"];
    [
        matrix[0][2].as_f64().expect("a shift"),
        matrix[1][2].as_f64().expect("a shift"),
    ]
}

/// The server over a journey's state, its camera answering `frames` in turn,
/// a check due every `interval_s` seconds.
async fn serving(journey: &Journey, frames: Vec<Vec<u8>>, interval_s: i64) -> (Running, Camera) {
    serving_under(journey, calibration(), frames, interval_s).await
}

/// The server over a journey's state under `calibration`, its camera
/// answering `frames` in turn, a check due every `interval_s` seconds.
async fn serving_under(
    journey: &Journey,
    calibration: Value,
    frames: Vec<Vec<u8>>,
    interval_s: i64,
) -> (Running, Camera) {
    let host = ScriptedHost::answering(frames.into_iter().map(Scripted::frame).collect()).await;
    let camera = Camera {
        host,
        calibration: Some(calibration),
        snapshot: true,
    };
    let started = journey.start(&camera, interval_s, &json!([])).await;
    (started.server, camera)
}

/// Check the camera on the empty sheet at bed Z 30 — its frame `empty` —
/// and start the print naming each check `starting` picks of those made, on
/// `sheet`, with no check of the print due; then stop that server, the job
/// left at `position`. Answers the checks and the print.
async fn checked_and_started(
    journey: &Journey,
    sheet: &str,
    empty: Vec<Vec<u8>>,
    starting: impl Fn(&[Value]) -> Value,
    position: u64,
) -> (Vec<Value>, PrintId) {
    journey.octoprint.reports("Operational", JobScript::idle());
    let count = empty.len();
    let (server, _camera) = serving(journey, empty, 3600).await;
    let mut checks = Vec::new();
    for _ in 0..count {
        checks.push(checked(&server, sheet, 30.0).await);
    }
    let print_id = started_under(&server, sheet, &starting(&checks)).await;
    job_at(journey, position);
    server.stop().await;
    (checks, print_id)
}

/// What a check of the 2026-11-28 print is drawn from: the index of the copy
/// `OctoPrint` printed, which the server spools, and the index of the
/// slicer's local copy, which it never sees.
struct Drawn<'a> {
    spool: &'a printobserver_core::GcodeIndex,
    local: &'a printobserver_core::GcodeIndex,
    url: &'a str,
    calibration: &'a printobserver_panels::CameraCalibration,
    correction: Option<[f64; 2]>,
}

impl Drawn<'_> {
    /// That the check handed `image` of `frame` at `position` is drawn through
    /// the camera check's correction and split where the job stands in
    /// `OctoPrint`'s copy; answers whether the slicer's local copy would have
    /// put the job somewhere else in the layer, which the image then is not.
    fn holds(
        &self,
        file: &str,
        position: u64,
        image: &[u8],
        frame: &[u8],
        earlier: Option<(&[u8], Timestamp)>,
    ) -> bool {
        let of = |index| {
            expected_check(
                index,
                position,
                frame,
                earlier,
                self.url,
                self.calibration,
                self.correction,
            )
        };
        let drawn = of(self.spool);
        assert_eq!(
            image, drawn.jpeg,
            "{file} is drawn through the camera check's correction, split where the job \
             stands in OctoPrint's copy"
        );
        let misplaced = of(self.local);
        if misplaced.text == drawn.text {
            return false;
        }
        assert_ne!(
            image, misplaced.jpeg,
            "{file}: the split is not where the slicer's local copy stands"
        );
        true
    }
}

/// A print started naming an aligned check of its sheet is shown the
/// three-panel image through that check's correction at each of the checks
/// v0.17.0 showed the plain frame at, the first-layer judgements that found the
/// toolhead still recorded; and a check whose landmarks moved beyond the
/// check's reference is shown the plain frame saying why, with no pause.
#[tokio::test(flavor = "multi_thread")]
async fn a_print_started_under_an_aligned_check_is_drawn_from_its_first_check() {
    let slice = box_slice();
    let journey = Journey::new(INSTALLER, &slice, 0);
    let (made, print_id) = checked_and_started(
        &journey,
        "smooth-pei",
        vec![frame("empty-sheets", "smooth-pei-z030.jpg")],
        |made| made[0]["id"].clone(),
        JUDGED[0].1,
    )
    .await;
    let check = made[0].clone();
    assert_eq!(check["verdict"], "aligned", "{check:#}");
    let mut frames: Vec<Vec<u8>> = JUDGED.iter().map(|(file, _)| frame(CASE, file)).collect();
    let moved = shifted(&frame(CASE, JUDGED[2].0), 40);
    frames.push(moved.clone());
    let mut checks = Checks::holding(&journey);
    let (server, camera) = serving(&journey, frames.clone(), INTERVAL_S).await;
    let url = camera.host.url();

    let spool = tempfile::TempDir::new().expect("a spool directory");
    let index = index_of(&slice, &spool.path().join("index.gcode"));
    let local = index_of(&local_box_slice(), &spool.path().join("local.gcode"));
    let calibrated = calibration_at(&calibration(), &url);
    let mut previous: Option<(Vec<u8>, Timestamp)> = None;
    let mut told_apart = 0;
    for (at, (file, position)) in JUDGED.iter().enumerate() {
        let seen = checks.next(*position).await;
        let shown = situation(&seen);
        assert_eq!(shown["image_kind"], "three_panel", "{file}: {shown:#}");
        let (_, image) = handed(&seen);
        let earlier = previous.as_ref().map(|(bytes, at)| (bytes.as_slice(), *at));
        let drawn = Drawn {
            spool: &index,
            local: &local,
            url: &url,
            calibration: &calibrated,
            correction: Some(shift_of(&check)),
        };
        told_apart += usize::from(drawn.holds(file, *position, &image, &frames[at], earlier));
        previous = Some((frames[at].clone(), captured_at(&seen)));
    }
    assert!(
        told_apart > 0,
        "at least one check stands somewhere else in the slicer's local copy"
    );
    let events = history(&server, print_id).await;
    let judged: Vec<String> = payloads(&events, "first_layer_alignment_judged")
        .iter()
        .map(|payload| {
            payload["frame_sha256"]
                .as_str()
                .unwrap_or_default()
                .to_owned()
        })
        .collect();
    for (file, _) in &JUDGED[..2] {
        assert!(
            judged.contains(&sha256(&frame(CASE, file))),
            "{file}'s first-layer judgement is still recorded: {judged:#?}"
        );
    }
    let started = payloads(&events, "print_started");
    assert_eq!(started[0]["camera_check"], check["id"], "{started:#?}");

    let seen = checks.next(LATER).await;
    let shown = situation(&seen);
    assert_eq!(shown["image_kind"], "whole_frame", "{shown:#}");
    assert_eq!(
        shown["image_fallback"]["code"], "view_refit_rejected",
        "{shown:#}"
    );
    let events = history(&server, print_id).await;
    let changed = payloads(&events, "check_image_changed");
    assert!(
        changed
            .iter()
            .any(|payload| payload["kind"] == "whole_frame"
                && payload["fallback"]["code"] == "view_refit_rejected"
                && payload["frame_sha256"] == sha256(&moved)),
        "the change to the plain frame is noticed, naming why: {changed:#?}"
    );
    assert!(
        !journey
            .octoprint
            .job_commands()
            .iter()
            .any(|command| command == "pause"),
        "a moved camera pauses nothing"
    );
    checks.release();
    server.stop().await;
}

/// A check of a frame as captured and one of a copy shifted 4 px right are
/// both `aligned`, the copy's translation the original's moved by that shift;
/// and a print started naming the copy's check, its frames carrying the same
/// shift, is drawn where the calibration's projection translated by that
/// check's correction puts the plan — not where the projection alone does.
#[tokio::test(flavor = "multi_thread")]
async fn a_shifted_camera_is_drawn_through_the_shift_its_check_found() {
    let slice = box_slice();
    let journey = Journey::new(INSTALLER, &slice, 0);
    let empty = frame("empty-sheets", "textured-pei-z030.jpg");
    let (made, _print_id) = checked_and_started(
        &journey,
        "textured-pei",
        vec![empty.clone(), shifted(&empty, 4)],
        |made| made[1]["id"].clone(),
        JUDGED[0].1,
    )
    .await;
    let (original, copy) = (&made[0], &made[1]);
    for answer in [&original, &copy] {
        assert_eq!(answer["verdict"], "aligned", "{answer:#}");
    }
    let [ox, oy] = shift_of(original);
    let [cx, cy] = shift_of(copy);
    assert!(
        (cx - ox - 4.0).hypot(cy - oy) <= 1.0,
        "the copy's correction is the original's moved 4 px right: {:?} against {:?}",
        [cx, cy],
        [ox, oy]
    );
    let offset = copy["offset_px"].as_f64().expect("an offset");
    assert!(
        (offset - cx.hypot(cy)).abs() <= 1.0,
        "the copy's offset is the length of its translation: {offset} against {:?}",
        [cx, cy]
    );
    assert!(
        cx.hypot(cy) > 1.0,
        "the copy's correction moves the drawing"
    );

    let print_frame = shifted(&frame(CASE, JUDGED[0].0), 4);
    let mut checks = Checks::holding(&journey);
    let (server, camera) = serving(&journey, vec![print_frame.clone()], INTERVAL_S).await;
    let url = camera.host.url();
    let seen = checks.next(JUDGED[0].1).await;
    assert_eq!(situation(&seen)["image_kind"], "three_panel");
    let (_, image) = handed(&seen);
    let spool = tempfile::TempDir::new().expect("a spool directory");
    let index = index_of(&slice, &spool.path().join("index.gcode"));
    let calibrated = calibration_at(&calibration(), &url);
    let drawn = |correction: Option<[f64; 2]>| {
        expected_composite(
            &index,
            JUDGED[0].1,
            &print_frame,
            None,
            &url,
            &calibrated,
            correction,
        )
    };
    assert_eq!(
        image,
        drawn(Some([cx, cy])),
        "the first check is drawn through the copy's correction"
    );
    assert_ne!(
        image,
        drawn(None),
        "the first check is not drawn where the uncorrected projection puts it"
    );
    checks.release();
    server.stop().await;
}

/// The 2026-11-29 print: the calibration fitted that morning, and the frames
/// of its checks, in the order they were judged.
const NOV_29: &str = "two-colour-box-2026-11-29";

/// The empty smooth sheet the 2026-11-29 print's camera check was made on,
/// and the bed height it was made at.
const NOV_29_EMPTY: (&str, f64) = ("131508-empty-smooth-pei.jpg", 59.67);

/// The stored frames the 2026-11-29 print's camera view was judged on, in
/// order. That print judged eleven; the eleventh, at 13:30:28, was kept only
/// as its three-panel image, so its frame is not among these.
const NOV_29_JUDGED: [&str; 10] = [
    "131554-b01119f6990d.jpg",
    "131755-5842c74b5065.jpg",
    "131956-8a3ce32a6fef.jpg",
    "132157-5d22bfb320b6.jpg",
    "132358-816895e6f37e.jpg",
    "132902-97a82c15735e.jpg",
    "133103-1641ff612f0d.jpg",
    "133433-6a83aa24e6f8.jpg",
    "133634-c89df3006848.jpg",
    "134237-d01779ded38c.jpg",
];

/// Check the camera on the empty smooth sheet of 2026-11-29 under that day's
/// calibration and start the print naming the check; then serve the print's
/// checks, a check due every [`INTERVAL_S`] seconds, its camera answering
/// `frames` in turn. Answers the check, the print, the server and its camera.
///
/// The frames are judged against the plan of the 2026-11-28 slice, the same
/// box, at positions past its first layer: a view judgement reads the
/// frame's landmarks alone, and a print under a camera check is drawn through
/// that check's correction whatever its first-layer search found.
async fn nov_29_print(
    journey: &Journey,
    frames: Vec<Vec<u8>>,
) -> (Value, PrintId, Running, Camera) {
    let calibration = calibration_named("core-one-2026-11-29.json");
    journey.octoprint.reports("Operational", JobScript::idle());
    let (server, _camera) = serving_under(
        journey,
        calibration.clone(),
        vec![frame(NOV_29, NOV_29_EMPTY.0)],
        3600,
    )
    .await;
    let check = checked(&server, "smooth-pei", NOV_29_EMPTY.1).await;
    assert_eq!(check["verdict"], "aligned", "{check:#}");
    let print_id = started_under(&server, "smooth-pei", &check["id"]).await;
    job_at(journey, JUDGED[0].1);
    server.stop().await;
    let (server, camera) = serving_under(journey, calibration, frames, INTERVAL_S).await;
    (check, print_id, server, camera)
}

/// Every landmark of the 2026-11-29 calibration as `bytes` shows it, found by
/// the panels crate's own search: what a judgement of that frame measures.
fn measured(camera: &Camera, bytes: &[u8]) -> Vec<printobserver_panels::FoundLandmark> {
    let url = camera.host.url();
    let calibrated = calibration_at(&calibration_named("core-one-2026-11-29.json"), &url);
    printobserver_panels::landmarks_in_frame(&calibrated, bytes, &url)
        .expect("the frame is the calibration's")
}

/// That a judgement's record carries the landmarks `found` on its own frame:
/// each one's offset and score, and whether it was visible.
fn carries_its_frames_landmarks(
    judged: &Value,
    found: &[printobserver_panels::FoundLandmark],
    what: &str,
) {
    let carried = judged["landmarks"].as_array().unwrap_or_else(|| {
        panic!("{what}: the judgement says which landmarks it measured: {judged:#}")
    });
    assert_eq!(carried.len(), found.len(), "{what}: {judged:#}");
    for (carried, found) in carried.iter().zip(found) {
        assert_eq!(carried["name"], found.name.as_str(), "{what}");
        for axis in 0..2 {
            let written = carried["offset_px"][axis].as_f64().expect("an offset");
            assert!(
                (written - found.located.offset_px[axis]).abs() < 1e-9,
                "{what}: {} is written at {written} on axis {axis}, and the frame shows it at {}",
                found.name,
                found.located.offset_px[axis]
            );
        }
        let score = carried["score"].as_f64().expect("a score");
        assert!(
            (score - f64::from(found.located.score)).abs() < 1e-6,
            "{what}: {}",
            found.name
        );
        assert_eq!(
            carried["visible"],
            found.visible(),
            "{what}: {}",
            found.name
        );
    }
}

/// The RMS distance of `found`'s visible landmarks from where `reference`
/// had them, over those it names.
fn residual_from(reference: &Value, found: &[printobserver_panels::FoundLandmark]) -> f64 {
    let distances: Vec<f64> = found
        .iter()
        .filter(|landmark| landmark.visible())
        .filter_map(|landmark| {
            let at = reference["landmarks"]
                .as_array()?
                .iter()
                .find(|kept| kept["name"] == landmark.name.as_str())?;
            let [x, y] = [0, 1].map(|axis| at["offset_px"][axis].as_f64().unwrap_or(f64::NAN));
            Some((landmark.located.offset_px[0] - x).hypot(landmark.located.offset_px[1] - y))
        })
        .collect();
    let count = f64::from(u32::try_from(distances.len()).expect("a few"));
    (distances
        .iter()
        .map(|distance| distance * distance)
        .sum::<f64>()
        / count)
        .sqrt()
}

/// The 2026-11-29 print's own frames, its camera unmoved, judged at each check
/// through the supervisor's own path: every judgement names the frame it read
/// and carries that frame's own landmark offsets and residual, which differ
/// from frame to frame though its correction — what each was judged against —
/// stays the camera check's; and none of them finds a shift, takes a re-fit,
/// raises a camera notice or shows the plain frame, and nothing is sent to the
/// printer.
#[tokio::test(flavor = "multi_thread")]
async fn each_check_of_an_unmoved_camera_records_its_own_frames_landmarks() {
    let slice = box_slice();
    let journey = Journey::new(INSTALLER, &slice, 0);
    let frames: Vec<Vec<u8>> = NOV_29_JUDGED
        .iter()
        .map(|file| frame(NOV_29, file))
        .collect();
    let (check, print_id, server, camera) = nov_29_print(&journey, frames.clone()).await;
    let sent = journey.octoprint.job_commands();
    let mut checks = Checks::holding(&journey);
    for (at, file) in NOV_29_JUDGED.iter().enumerate() {
        let position = JUDGED[0].1 + 7_000 * u64::try_from(at).expect("a few");
        let seen = checks.next(position).await;
        let shown = situation(&seen);
        assert_eq!(shown["image_kind"], "three_panel", "{file}: {shown:#}");
        assert!(shown["image_fallback"].is_null(), "{file}: {shown:#}");
    }
    let events = history(&server, print_id).await;
    let judged = payloads(&events, "camera_view_judged");
    assert_eq!(
        judged.len(),
        frames.len(),
        "one judgement a check: {judged:#?}"
    );
    let tolerance = calibration_named("core-one-2026-11-29.json")["drift_tolerance_px"]
        .as_f64()
        .expect("a tolerance");
    let mut residuals = Vec::new();
    for ((file, bytes), judged) in NOV_29_JUDGED.iter().zip(&frames).zip(&judged) {
        assert_eq!(judged["frame_sha256"], sha256(bytes), "{file}");
        assert_eq!(
            judged["schema_version"],
            printobserver_server::CAMERA_VIEW_JUDGED_SCHEMA_VERSION,
            "{file} is written at the version carrying its own measurements"
        );
        assert_eq!(judged["outcome"], "unshifted", "{file}: {judged:#}");
        assert_eq!(
            judged["view_correction"], check["correction"],
            "{file} is judged against the camera check's correction"
        );
        let found = measured(&camera, bytes);
        carries_its_frames_landmarks(judged, &found, file);
        let residual = judged["residual_px"].as_f64().expect("a residual");
        let expected = residual_from(&check["correction"], &found);
        assert!(
            (residual - expected).abs() < 1e-9,
            "{file}: its residual is its own landmarks' from the check's: {residual} against {expected}"
        );
        assert!(residual < tolerance, "{file}: {residual} px");
        residuals.push(residual);
    }
    let first = residuals[0];
    assert!(
        residuals
            .iter()
            .any(|residual| (residual - first).abs() > 1e-6),
        "the frames' own residuals are not one number repeated: {residuals:?}"
    );
    let offsets: Vec<&Value> = judged.iter().map(|payload| &payload["landmarks"]).collect();
    assert!(
        offsets.iter().any(|landmarks| *landmarks != offsets[0]),
        "the frames' own landmark offsets are not one set repeated"
    );
    assert!(
        payloads(&events, "camera_view_refit").is_empty(),
        "no re-fit"
    );
    assert!(
        payloads(&events, "camera_degraded").is_empty(),
        "no camera notice"
    );
    let changed = payloads(&events, "check_image_changed");
    assert!(
        changed
            .iter()
            .all(|payload| payload["kind"] == "three_panel" && payload["fallback"].is_null()),
        "no check is shown the plain frame: {changed:#?}"
    );
    assert_eq!(
        journey.octoprint.job_commands(),
        sent,
        "an unmoved camera sends the printer nothing after the print's start"
    );
    checks.release();
    server.stop().await;
}

/// Two checks of one print, its camera knocked 40 px sideways between them —
/// beyond the calibration's tolerance — judged through the supervisor's own
/// path: each judgement names its own frame and carries that frame's own
/// landmarks, the second's moved by the knock and its residual the knock's;
/// the second is refused and shown the plain frame saying why, and nothing is
/// sent to the printer.
#[tokio::test(flavor = "multi_thread")]
async fn a_camera_knocked_between_two_checks_is_measured_and_refused_on_the_second() {
    let slice = box_slice();
    let journey = Journey::new(INSTALLER, &slice, 0);
    let before = frame(NOV_29, NOV_29_JUDGED[3]);
    let after = shifted(&before, 40);
    let frames = vec![before.clone(), after.clone()];
    let (check, print_id, server, camera) = nov_29_print(&journey, frames).await;
    let sent = journey.octoprint.job_commands();
    let mut checks = Checks::holding(&journey);
    let seen = checks.next(JUDGED[0].1).await;
    assert_eq!(situation(&seen)["image_kind"], "three_panel");
    let seen = checks.next(JUDGED[1].1).await;
    let shown = situation(&seen);
    assert_eq!(shown["image_kind"], "whole_frame", "{shown:#}");
    assert_eq!(
        shown["image_fallback"]["code"], "view_refit_rejected",
        "{shown:#}"
    );

    let events = history(&server, print_id).await;
    let judged = payloads(&events, "camera_view_judged");
    assert_eq!(judged.len(), 2, "{judged:#?}");
    assert_eq!(judged[0]["frame_sha256"], sha256(&before));
    assert_eq!(judged[1]["frame_sha256"], sha256(&after));
    for payload in &judged {
        assert_eq!(
            payload["schema_version"],
            printobserver_server::CAMERA_VIEW_JUDGED_SCHEMA_VERSION,
            "{payload:#}"
        );
    }
    assert_eq!(judged[0]["outcome"], "unshifted", "{:#}", judged[0]);
    assert_eq!(
        judged[1]["outcome"], "view_refit_rejected",
        "{:#}",
        judged[1]
    );
    let (found_before, found_after) = (measured(&camera, &before), measured(&camera, &after));
    carries_its_frames_landmarks(&judged[0], &found_before, "before the knock");
    carries_its_frames_landmarks(&judged[1], &found_after, "after the knock");
    let moved = found_before
        .iter()
        .zip(&found_after)
        .filter(|(was, now)| was.visible() && now.visible())
        .filter(|(was, now)| {
            (now.located.offset_px[0] - was.located.offset_px[0] - 40.0).abs() <= 2.0
                && (now.located.offset_px[1] - was.located.offset_px[1]).abs() <= 2.0
        })
        .count();
    assert!(
        moved >= 2,
        "the second frame's landmarks moved with the knock"
    );
    let residual = |payload: &Value| payload["residual_px"].as_f64().expect("a residual");
    assert!(residual(&judged[0]) < 6.0, "{:#}", judged[0]);
    assert!(
        (residual(&judged[1]) - residual_from(&check["correction"], &found_after)).abs() < 1e-9
            && residual(&judged[1]) > 30.0,
        "the second frame's residual is the knock's: {:#}",
        judged[1]
    );
    assert_eq!(
        journey.octoprint.job_commands(),
        sent,
        "a knocked camera sends the printer nothing after the print's start"
    );
    checks.release();
    server.stop().await;
}