subc-daemon 0.56.17

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
use super::*;
use crate::router::test_log::{captured_logs, log_capture};
use std::sync::Arc;
use tokio::sync::{mpsc, oneshot};

const UNDECLARED: ConnectionId = ConnectionId::new(30);

fn restart_settings_rig() -> Rig {
    let mut rig = Rig::new();
    let fields = rig.declaration.schema["properties"]
        .as_object_mut()
        .unwrap();
    fields.remove("credential");
    for (field, apply) in [("model", "module_restart"), ("transport", "daemon_restart")] {
        fields.insert(
            field.into(),
            json!({"type":"string", "description":field, "default":"initial", "x-ck-apply":apply}),
        );
    }
    write_settings(&rig, "{}");
    rig
}

fn write_settings(rig: &Rig, contents: &str) {
    std::fs::write(&rig.declaration.user_file, contents).unwrap();
}

fn serve_settings(owner: &RuntimeOwner, connection: ConnectionId) -> ConfigView {
    let reply = owner
        .module_get(connection, "a", ConfigGetRequest::new())
        .unwrap();
    owner
        .module_view_delivered(connection, "a", &reply, tokio::time::Instant::now(), true)
        .unwrap();
    reply.active.unwrap()
}

#[test]
fn config_gate_unstamped_user_file_only_module_restart_wins_over_the_hint() {
    use crate::config_gate::runtime::unstamped::UserFileWatch;

    for (edit, served, fields, hint) in [
        (r#"{"model":"changed"}"#, true, &["/model"][..], false),
        (r#"{"limit":2,"model":"changed"}"#, true, &["/model"], false),
        (r#"{"limit":2}"#, true, &[], true),
        (
            r#"{"model":"changed","transport":"changed"}"#,
            true,
            &[],
            true,
        ),
        (r#"{"model":"changed","limit":false}"#, true, &[], false),
        (r#"{"model":"changed"}"#, false, &[], false),
    ] {
        let rig = restart_settings_rig();
        let owner = rig.owner("watch-restart-policy");
        rig.declare(&owner, INCUMBENT.get());
        if served {
            serve_settings(&owner, INCUMBENT);
        }
        let mut watch = UserFileWatch::default();
        write_settings(&rig, edit);
        owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
        let request = watch.take_restart();
        assert_eq!(
            request
                .as_ref()
                .map(|request| request.fields.as_slice())
                .unwrap_or_default(),
            fields,
            "{edit}"
        );
        assert_eq!(owner.take_unstamp_hint(INCUMBENT).unwrap(), hint, "{edit}");
        owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
        assert!(watch.take_restart().is_none(), "{edit}");
        assert!(!owner.take_unstamp_hint(INCUMBENT).unwrap(), "{edit}");
    }
}

#[test]
fn config_gate_unstamped_user_file_coalesces_queued_restart_then_watches_replacement() {
    use crate::config_gate::runtime::unstamped::UserFileWatch;

    let rig = restart_settings_rig();
    let owner = rig.owner("watch-restart-coalescing");
    rig.declare(&owner, INCUMBENT.get());
    serve_settings(&owner, INCUMBENT);
    let mut watch = UserFileWatch::default();
    write_settings(&rig, r#"{"model":"first"}"#);
    owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
    let queued = watch.take_restart().expect("first edit requests a restart");
    write_settings(&rig, r#"{"model":"second","limit":3}"#);
    owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
    assert!(watch.take_restart().is_none());
    assert!(!owner.take_unstamp_hint(INCUMBENT).unwrap());
    drop(queued);

    owner.disconnected(INCUMBENT);
    rig.declare(&owner, CANDIDATE.get());
    let replacement = serve_settings(&owner, CANDIDATE);
    assert_eq!(
        replacement.effective,
        json!({"model":"second","limit":3,"transport":"initial"})
    );
    let mut watch = UserFileWatch::default();
    owner.poll_user_file(CANDIDATE, "a", &mut watch).unwrap();
    assert!(
        watch.take_restart().is_none(),
        "unchanged file must not restart the replacement"
    );
    assert!(!owner.take_unstamp_hint(CANDIDATE).unwrap());

    write_settings(&rig, r#"{"model":"third","limit":3}"#);
    owner.poll_user_file(CANDIDATE, "a", &mut watch).unwrap();
    assert_eq!(watch.take_restart().unwrap().connection, CANDIDATE);
}

#[cfg(unix)]
mod supervision {
    use super::*;
    use crate::{
        router::OutboundFrame,
        supervise::{
            ModuleOverlap, RestartPolicy, SupervisedModule, Supervisor, SupervisorHandle,
            SwapOutcome,
        },
        ForwardingTable, FrameSink, Registry,
    };
    use subc_protocol::{Frame, FrameType};
    use tokio::time::timeout;

    struct RestartRig {
        rig: Rig,
        owner: Arc<RuntimeOwner>,
        registry: Arc<Registry>,
        forwarding: Arc<ForwardingTable>,
        module: SupervisedModule,
        handler: Arc<crate::ControlHandler>,
        idle: mpsc::UnboundedReceiver<(ConnectionId, oneshot::Sender<()>)>,
    }

    impl RestartRig {
        fn new(mode: &'static str) -> Self {
            let rig = restart_settings_rig();
            rig.write_native_program(mode);
            let mut spec = supervised_spec(&rig, "a");
            spec.protocol = subc_control::ModuleProtocol::Subc;
            spec.overlap = ModuleOverlap::Safe;
            spec.env = ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
                .into_iter()
                .map(|key| (key.into(), rig.path.display().to_string()))
                .collect();
            std::fs::write(rig.path.join("subc.jsonc"), serde_json::to_vec(&json!({
                "version":1, "modules":{"a":{
                    "program":spec.program, "args":spec.args, "env":spec.env.iter().cloned().collect::<BTreeMap<_,_>>(),
                    "protocol":"subc", "overlap":"safe", "registration_channel":true
                }}
            })).unwrap()).unwrap();
            let owner = Arc::new(rig.owner("supervised-settings-restart"));
            let registry = Arc::new(Registry::default());
            let forwarding = Arc::new(ForwardingTable::default());
            let handle = SupervisorHandle::new();
            // These fixtures supply the wire registration directly.
            handle.capture_registration_channels_for_test();
            let supervisor =
                Supervisor::new_for_test(registry.clone(), RestartPolicy::new(3, Duration::ZERO))
                    .with_handle(handle.clone())
                    .with_forwarding(forwarding.clone())
                    .with_config_runtime(owner.clone())
                    .with_drain_timeout(Duration::from_secs(10));
            let handler = Arc::new(
                crate::ControlHandler::with_forwarding(registry.clone(), forwarding.clone())
                    .with_supervisor(handle)
                    .with_config_runtime(owner.clone()),
            );
            let (sender, idle) = mpsc::unbounded_channel();
            *owner.user_file_test_idle.lock().unwrap() = Some(sender);
            let module = supervisor.spawn(spec).unwrap();
            Self {
                rig,
                owner,
                registry,
                forwarding,
                module,
                handler,
                idle,
            }
        }

        fn register(
            &self,
            connection: ConnectionId,
            candidate: bool,
        ) -> mpsc::Receiver<OutboundFrame> {
            let mut manifest =
                subc_protocol::manifest::ModuleManifest::builder("a", "1.0.0").build();
            manifest.ready = Some(true);
            manifest.capabilities =
                Some(serde_json::from_value(json!({"provides":["accepting-drain/v1"]})).unwrap());
            let version = subc_protocol::PROTOCOL_VERSION;
            let mut ops = vec!["config.review".into()];
            if candidate {
                ops.push("health.check".into());
            }
            let (sender, receiver) = mpsc::channel(8);
            let sink = FrameSink::new(sender);
            let concurrency = subc_protocol::manifest::Concurrency::ModuleManaged;
            if candidate {
                self.registry
                    .register_candidate_with_control_ops(manifest, version, connection, ops)
                    .unwrap();
                self.forwarding
                    .register_candidate_module_connection(
                        connection,
                        "a".into(),
                        version,
                        concurrency,
                        sink,
                    )
                    .unwrap();
            } else {
                self.registry
                    .register_with_control_ops(manifest, version, connection, ops)
                    .unwrap();
                self.forwarding
                    .register_module_connection(connection, "a".into(), version, concurrency, sink)
                    .unwrap();
            }
            receiver
        }

        async fn wait_for_starts(&self, count: usize) {
            wait_for_supervised_stage(&self.module, "fixture child started", || {
                std::fs::read_to_string(self.rig.path.join("a.launches"))
                    .is_ok_and(|text| text.lines().count() == count)
            })
            .await;
        }

        async fn worker_idle(&mut self, connection: ConnectionId) -> oneshot::Sender<()> {
            let (observed, resume) = timeout(Duration::from_secs(5), self.idle.recv())
                .await
                .unwrap()
                .unwrap();
            assert_eq!(observed, connection);
            resume
        }

        fn poll_again(&self, resume: oneshot::Sender<()>) {
            self.owner.notify_delivery_changed();
            resume.send(()).unwrap();
        }

        fn close(&self, connection: ConnectionId) {
            self.forwarding.cleanup_connection(connection).unwrap();
            self.registry.deregister_connection(connection).unwrap();
            self.owner.disconnected(connection);
        }
    }

    async fn next(receiver: &mut mpsc::Receiver<OutboundFrame>) -> Frame {
        timeout(Duration::from_secs(5), receiver.recv())
            .await
            .unwrap()
            .unwrap()
            .frame
    }

    fn body(frame: &Frame) -> serde_json::Value {
        serde_json::from_slice(&frame.body).unwrap()
    }

    #[tokio::test]
    async fn config_gate_unstamped_restart_drains_coalesces_and_preserves_crash_budget() {
        let mut rig = RestartRig::new("mark-first-exit23");
        rig.wait_for_starts(2).await;
        wait_for_supervised_stage(&rig.module, "incumbent published after the crash", || {
            rig.module
                .status()
                .is_ok_and(|status| status.process_alive && status.spawn_generation == 2)
        })
        .await;
        let incumbent = rig.module.status().unwrap();
        assert_eq!(incumbent.restart_count, 1, "the first child really crashed");
        let mut incumbent_frames = rig.register(INCUMBENT, false);
        rig.rig.declare(&rig.owner, INCUMBENT.get());
        serve_settings(&rig.owner, INCUMBENT);
        let _worker = WorkerGuard(rig.handler.spawn_config_delivery_worker().unwrap());
        let resume = rig.worker_idle(INCUMBENT).await;
        let (logs, _logs_guard) = log_capture(tracing::Level::INFO);

        write_settings(&rig.rig, r#"{"model":"private-first"}"#);
        rig.poll_again(resume);
        let notice = body(&next(&mut incumbent_frames).await);
        assert_eq!(
            notice["op"], "module.draining",
            "restart must replace the hint"
        );
        assert_eq!(notice["accepting"], true);
        let resume = rig.worker_idle(INCUMBENT).await;

        write_settings(&rig.rig, r#"{"model":"private-second","limit":3}"#);
        rig.poll_again(resume);
        let _paused_incumbent = rig.worker_idle(INCUMBENT).await;
        assert!(
            incumbent_frames.try_recv().is_err(),
            "nothing is pushed while draining"
        );
        assert_eq!(rig.module.status().unwrap().pid, incumbent.pid);

        let ack = Frame::build(
            FrameType::Response,
            subc_protocol::Flags(0),
            0,
            0,
            1,
            vec![],
        )
        .unwrap();
        assert!(rig
            .forwarding
            .mark_accepting_drain_ready(INCUMBENT, ack)
            .unwrap());
        assert_eq!(
            next(&mut incumbent_frames).await.header.ty,
            FrameType::Response
        );
        assert_eq!(
            next(&mut incumbent_frames).await.header.ty,
            FrameType::Goodbye
        );
        rig.close(INCUMBENT);
        let pid = rustix::process::Pid::from_raw(incumbent.pid.unwrap() as i32).unwrap();
        rustix::process::kill_process(pid, rustix::process::Signal::TERM).unwrap();

        rig.wait_for_starts(3).await;
        wait_for_supervised_stage(&rig.module, "replacement published after the drain", || {
            rig.module.status().is_ok_and(|status| {
                status.process_alive && status.spawn_generation > incumbent.spawn_generation
            })
        })
        .await;
        let replacement = rig.module.status().unwrap();
        assert_eq!(replacement.spawn_generation, incumbent.spawn_generation + 1);
        assert_eq!(
            replacement.restart_count, incumbent.restart_count,
            "a settings restart neither spends nor clears crash budget"
        );
        rig.rig.declare(&rig.owner, CANDIDATE.get());
        assert_eq!(
            serve_settings(&rig.owner, CANDIDATE).effective,
            json!({"model":"private-second","limit":3,"transport":"initial"})
        );
        let mut replacement_frames = rig.register(CANDIDATE, false);
        rig.owner.notify_delivery_changed();
        let resume = rig.worker_idle(CANDIDATE).await;
        rig.poll_again(resume);
        let _paused_replacement = rig.worker_idle(CANDIDATE).await;
        // A no-op hold acknowledges all earlier commands on this running actor.
        timeout(Duration::from_secs(5), rig.module.config_exit_hold())
            .await
            .unwrap()
            .unwrap();
        assert!(
            replacement_frames.try_recv().is_err(),
            "the replacement must not receive a hint or a drain for the same file"
        );
        assert_eq!(rig.module.status().unwrap().pid, replacement.pid);

        let text = captured_logs(&logs);
        let restarts: Vec<_> = text
            .lines()
            .filter(|line| line.contains("settings change needs a module restart"))
            .collect();
        assert_eq!(restarts.len(), 1, "{text}");
        for expected in ["INFO", "module_id=a", "fields=/model"] {
            assert!(restarts[0].contains(expected), "{}", restarts[0]);
        }
        assert!(!restarts[0].contains("private-"));
        rig.close(CANDIDATE);
        rig.module.stop().await.unwrap();
    }

    #[tokio::test]
    async fn config_gate_unstamped_restart_during_swap_is_discarded_after_cutover() {
        let mut rig = RestartRig::new("pid-sleep");
        rig.wait_for_starts(1).await;
        let mut incumbent_frames = rig.register(INCUMBENT, false);
        rig.rig.declare(&rig.owner, INCUMBENT.get());
        serve_settings(&rig.owner, INCUMBENT);
        let _worker = WorkerGuard(rig.handler.spawn_config_delivery_worker().unwrap());
        let resume = rig.worker_idle(INCUMBENT).await;
        let swap = tokio::spawn({
            let module = rig.module.clone();
            async move { module.swap(Some(Duration::from_secs(10))).await }
        });
        rig.wait_for_starts(2).await;
        write_settings(&rig.rig, r#"{"model":"swapped"}"#);
        rig.poll_again(resume);
        let _paused_incumbent = tokio::select! {
            paused = rig.worker_idle(INCUMBENT) => paused,
            frame = next(&mut incumbent_frames) => panic!("unexpected frame during warm-up: {:?}", body(&frame)),
        };
        // The enabled no-op is answered during warm-up, behind the restart.
        assert!(
            !timeout(Duration::from_secs(5), rig.module.set_enabled(true))
                .await
                .unwrap()
                .unwrap()
        );

        // The candidate cannot cut over until the warming actor has seen the request.
        rig.owner
            .declare(CANDIDATE, "a", rig.rig.declaration.clone(), false)
            .unwrap();
        assert_eq!(
            serve_settings(&rig.owner, CANDIDATE).effective["model"],
            "swapped"
        );
        let mut candidate_frames = rig.register(CANDIDATE, true);
        let probe = next(&mut candidate_frames).await;
        assert_eq!(body(&probe)["op"], "health.check");
        rig.forwarding
            .complete_module_control_rpc(
                CANDIDATE,
                probe.header.corr,
                Some("health.check"),
                crate::forwarding::ModuleControlRpcOutcome::Response(
                    subc_protocol::session::ModuleControlResponse::HealthCheck {
                        status: subc_protocol::session::HealthStatus::Ok,
                        detail: None,
                        metrics: None,
                        summary: None,
                    },
                ),
            )
            .unwrap();
        assert_eq!(
            timeout(Duration::from_secs(5), swap)
                .await
                .unwrap()
                .unwrap()
                .unwrap(),
            SwapOutcome::Cutover
        );
        timeout(Duration::from_secs(5), rig.module.config_exit_hold())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            rig.registry.get_module("a").unwrap().unwrap().connection_id,
            CANDIDATE
        );
        assert_eq!(rig.module.status().unwrap().spawn_generation, 2);
        while let Ok(OutboundFrame { frame, .. }) = candidate_frames.try_recv() {
            assert_eq!(
                body(&frame)["op"],
                "health.check",
                "the incumbent's request must not drain the candidate"
            );
        }
        rig.close(INCUMBENT);
        rig.close(CANDIDATE);
        rig.module.stop().await.unwrap();
    }
}

fn write_limit(rig: &Rig, limit: u64) {
    std::fs::write(
        rig.path.join("cortexkit/a.jsonc"),
        format!("{{\"limit\":{limit}}}"),
    )
    .unwrap();
}

struct LiveFiles {
    rig: Rig,
    owner: Arc<RuntimeOwner>,
    registry: Arc<crate::Registry>,
    forwarding: Arc<crate::ForwardingTable>,
    _handler: Arc<crate::ControlHandler>,
    _worker: WorkerGuard,
    _clock: WorkerGuard,
    idle: mpsc::UnboundedReceiver<(ConnectionId, oneshot::Sender<()>)>,
    paused: HashMap<ConnectionId, oneshot::Sender<()>>,
    receivers: Vec<(ConnectionId, mpsc::Receiver<crate::router::OutboundFrame>)>,
    pushes: Vec<(ConnectionId, serde_json::Value)>,
}

impl LiveFiles {
    async fn new() -> Self {
        let clock = hold_test_clock();
        let mut rig = Rig::new();
        // An absent user file is valid, so appearance and removal can be observed.
        rig.declaration.schema["properties"]
            .as_object_mut()
            .unwrap()
            .remove("credential");
        write_limit(&rig, 1);
        let owner = Arc::new(rig.owner("live-files"));
        rig.declare(&owner, INCUMBENT.get());
        let registry = Arc::new(crate::Registry::default());
        let forwarding = Arc::new(crate::ForwardingTable::default());
        let handler = Arc::new(
            crate::ControlHandler::with_forwarding(registry.clone(), forwarding.clone())
                .with_config_runtime(owner.clone()),
        );
        let (sender, idle) = mpsc::unbounded_channel();
        *owner.user_file_test_idle.lock().unwrap() = Some(sender);
        let worker = WorkerGuard(handler.spawn_config_delivery_worker().unwrap());
        let mut live = Self {
            rig,
            owner,
            registry,
            forwarding,
            _handler: handler,
            _worker: worker,
            _clock: clock,
            idle,
            paused: HashMap::new(),
            receivers: vec![],
            pushes: vec![],
        };
        live.register(INCUMBENT, "a");
        live.get();
        live.owner.notify_delivery_changed();
        live.until_idle(INCUMBENT).await;
        assert!(
            live.pushes.is_empty(),
            "an initial observation is not an edit"
        );
        live
    }

    fn register(&mut self, connection: ConnectionId, module: &str) {
        self.registry
            .register_with_control_ops(
                subc_protocol::manifest::ModuleManifest::builder(module, "0.1.0").build(),
                subc_protocol::PROTOCOL_VERSION,
                connection,
                vec!["config.review".into()],
            )
            .unwrap();
        let (sender, receiver) = mpsc::channel(8);
        self.forwarding
            .register_module_connection(
                connection,
                module.into(),
                subc_protocol::PROTOCOL_VERSION,
                subc_protocol::manifest::Concurrency::ModuleManaged,
                crate::FrameSink::new(sender),
            )
            .unwrap();
        self.receivers.push((connection, receiver));
    }

    fn get(&self) -> subc_protocol::config::ConfigGetReply {
        let reply = self
            .owner
            .module_get(INCUMBENT, "a", ConfigGetRequest::new())
            .unwrap();
        self.owner
            .module_view_delivered(INCUMBENT, "a", &reply, tokio::time::Instant::now(), true)
            .unwrap();
        reply
    }

    async fn until_idle(&mut self, connection: ConnectionId) {
        wait_for_blocking_delivery(|| {
            for (connection, receiver) in &mut self.receivers {
                while let Ok(mut outbound) = receiver.try_recv() {
                    assert_eq!(outbound.frame.header.ty, subc_protocol::FrameType::Push);
                    let body: serde_json::Value =
                        serde_json::from_slice(&outbound.frame.body).unwrap();
                    assert_eq!(body["op"], "config.changed");
                    self.pushes.push((*connection, body));
                    outbound.flushed.take().unwrap().send(()).unwrap();
                }
            }
            while let Ok((connection, resume)) = self.idle.try_recv() {
                assert!(self.paused.insert(connection, resume).is_none());
            }
            self.paused.contains_key(&connection)
        })
        .await;
    }

    async fn tick(&mut self) {
        // The worker is held just before select, with its two-second deadline set.
        tokio::time::advance(Duration::from_secs(2)).await;
        self.paused.remove(&INCUMBENT).unwrap().send(()).unwrap();
        self.until_idle(INCUMBENT).await;
    }

    fn expect_edit(&mut self) {
        assert_eq!(
            self.pushes.len(),
            1,
            "one generation-0 edit hint: {:?}",
            self.pushes
        );
        assert_eq!(self.pushes[0].0, INCUMBENT);
        assert_eq!(self.pushes[0].1["generation"], 0);
        self.pushes.clear();
    }

    async fn real_edit(&mut self) {
        write_limit(&self.rig, 2);
        self.tick().await;
        self.expect_edit();
        assert_eq!(self.get().active.unwrap().effective["limit"], 2);
    }
}

#[tokio::test(start_paused = true)]
async fn config_gate_unstamped_user_file_edit_pushes_and_get_returns_new_bytes() {
    let mut live = LiveFiles::new().await;
    live.real_edit().await;
    let path = live.rig.path.join("cortexkit/a.jsonc");
    let raw = b"{ /* literal user bytes */ \"limit\":3 }";
    std::fs::write(&path, raw).unwrap();
    live.tick().await;
    live.expect_edit();
    let reply = live.get();
    let view = reply.active.unwrap();
    assert_eq!(view.generation, 0);
    assert_eq!(view.status, ConfigStatus::Unstamped);
    assert_eq!(view.layers[0].bytes.as_deref(), Some(raw.as_slice()));
    assert!(reply.pending.is_none());

    std::fs::remove_file(&path).unwrap();
    live.tick().await;
    live.expect_edit();
    assert_eq!(live.get().active.unwrap().layers[0].bytes, None);
    std::fs::write(&path, raw).unwrap();
    live.tick().await;
    live.expect_edit();
    assert_eq!(
        live.get().active.unwrap().layers[0].bytes.as_deref(),
        Some(raw.as_slice())
    );

    live.owner.disconnected(INCUMBENT);
    let mut watch = crate::config_gate::runtime::unstamped::UserFileWatch::default();
    assert_eq!(
        live.owner
            .poll_user_file(INCUMBENT, "a", &mut watch)
            .unwrap(),
        crate::config_gate::runtime::unstamped::UserFilePoll::Stopped
    );
    assert!(!live
        .owner
        .lock()
        .unwrap()
        .delivery
        .unstamped_views
        .contains_key(&INCUMBENT));
}

#[tokio::test(start_paused = true)]
async fn config_gate_unstamped_user_file_same_bytes_and_touch_send_no_push() {
    let mut live = LiveFiles::new().await;
    live.real_edit().await;
    let path = live.rig.path.join("cortexkit/a.jsonc");
    let file = std::fs::File::options().write(true).open(&path).unwrap();
    let modified = file.metadata().unwrap().modified().unwrap() + Duration::from_secs(10);
    file.set_times(std::fs::FileTimes::new().set_modified(modified))
        .unwrap();
    live.tick().await;
    assert!(
        live.pushes.is_empty(),
        "a touch must not push: {:?}",
        live.pushes
    );

    let replacement = live.rig.path.join("same-bytes.jsonc");
    std::fs::write(&replacement, std::fs::read(&path).unwrap()).unwrap();
    std::fs::rename(replacement, path).unwrap();
    live.tick().await;
    assert!(
        live.pushes.is_empty(),
        "an identical replacement must not push: {:?}",
        live.pushes
    );
}

#[test]
fn config_gate_unstamped_user_file_refusal_logs_once_and_reports_path() {
    use crate::config_gate::runtime::unstamped::UserFileWatch;

    let mut rig = Rig::new();
    rig.declaration.schema["properties"]
        .as_object_mut()
        .unwrap()
        .remove("credential");
    write_limit(&rig, 1);
    let owner = rig.owner("user-file-refusal");
    rig.declare(&owner, INCUMBENT.get());
    let good = owner
        .module_get(INCUMBENT, "a", ConfigGetRequest::new())
        .unwrap();
    owner
        .module_view_delivered(INCUMBENT, "a", &good, tokio::time::Instant::now(), true)
        .unwrap();

    let (logs, _guard) = log_capture(tracing::Level::INFO);
    let mut watch = UserFileWatch::default();
    let path = &rig.declaration.user_file;
    let refused = br#"{"limit":2,"not/declared":true}"#;
    std::fs::write(path, refused).unwrap();
    for _ in 0..3 {
        // Run the same blocking poll as the delivery worker on this thread so
        // the scoped tracing subscriber can see its events.
        let _ = owner.poll_user_file(INCUMBENT, "a", &mut watch);
        assert!(!owner.take_unstamp_hint(INCUMBENT).unwrap());
    }
    let text = captured_logs(&logs);
    let warnings: Vec<_> = text
        .lines()
        .filter(|line| line.contains("user settings file refused"))
        .collect();
    assert_eq!(warnings.len(), 1, "{text}");
    for part in ["WARN", "module_id=a", path, "reason=a: /not~1declared"] {
        assert!(warnings[0].contains(part), "{}", warnings[0]);
    }
    assert_eq!(
        serde_json::to_value(owner.polled_status().unwrap()).unwrap()["file_errors"],
        json!([{
            "module_id":"a", "code":"value_invalid", "message":"a: /not~1declared", "path":path,
            "pointer":"/not~1declared"
        }])
    );
    assert_eq!(
        owner.lock().unwrap().delivery.unstamped_views[&INCUMBENT].as_ref(),
        good.active.as_ref().unwrap()
    );

    let replacement = rig.path.join("replacement.jsonc");
    std::fs::write(&replacement, refused).unwrap();
    std::fs::rename(replacement, path).unwrap();
    // A fresh worker after reconnect must not log the same bytes again.
    let mut watch = UserFileWatch::default();
    owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
    assert_eq!(
        captured_logs(&logs)
            .matches("user settings file refused")
            .count(),
        1
    );

    std::fs::write(path, br#"{"limit":3,"not/declared":true}"#).unwrap();
    owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
    assert_eq!(
        captured_logs(&logs)
            .matches("user settings file refused")
            .count(),
        2
    );
    assert!(!owner.take_unstamp_hint(INCUMBENT).unwrap());

    write_limit(&rig, 3);
    owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
    assert!(owner.take_unstamp_hint(INCUMBENT).unwrap());
    owner.poll_user_file(INCUMBENT, "a", &mut watch).unwrap();
    assert!(owner.polled_status().unwrap().file_errors.is_empty());
    let text = captured_logs(&logs);
    let recoveries: Vec<_> = text
        .lines()
        .filter(|line| line.contains("user settings file accepted after refusal"))
        .collect();
    assert_eq!(recoveries.len(), 1, "{text}");
    for part in ["INFO", "module_id=a", path] {
        assert!(recoveries[0].contains(part), "{}", recoveries[0]);
    }
}

#[tokio::test(start_paused = true)]
async fn config_gate_unstamped_user_file_stamp_stops_generation_zero_pushes() {
    let mut live = LiveFiles::new().await;
    live.real_edit().await;
    let generation = live.rig.stamp(&live.owner);
    // Finish adopting the approved stamp so its stamped state, rather than an
    // unfinished configuration transition, is what stops user-file polling.
    live.owner
        .complete_authority_exit_for_test(generation)
        .unwrap();
    write_limit(&live.rig, 3);
    live.tick().await;
    assert_eq!(
        live.pushes.len(),
        1,
        "the approved pending generation must still be delivered"
    );
    assert!(
        live.pushes
            .iter()
            .all(|(_, push)| push["generation"] == generation),
        "{:?}",
        live.pushes
    );
    let mut watch = crate::config_gate::runtime::unstamped::UserFileWatch::default();
    assert_eq!(
        live.owner
            .poll_user_file(INCUMBENT, "a", &mut watch)
            .unwrap(),
        crate::config_gate::runtime::unstamped::UserFilePoll::Stopped,
        "stamped files must not be watched"
    );

    let prepared = live.owner.prepare(PlanKind::Unstamp).unwrap();
    let plan = live.owner.finish_plan(prepared, daemon_review).unwrap();
    live.owner
        .desktop_view_delivered(ConnectionId::new(7), &plan)
        .unwrap();
    let challenge = live
        .owner
        .begin_approval(&plan.digest, &Rig::facts())
        .unwrap();
    let unstamped = live
        .owner
        .finish_approval(
            challenge.attempt(),
            &Rig::facts(),
            ApprovalReply::Presence(crate::config_gate::PresenceDecision::InteractiveApproval),
            2,
        )
        .unwrap();
    // A real daemon clears the authority-exit fence after reconciling supervised
    // processes. This fixture has no processes, so clear the fence before polling resumes.
    live.owner
        .complete_authority_exit_for_test(unstamped)
        .unwrap();
    live.pushes.clear();
    live.tick().await;
    assert!(live.pushes.iter().all(|(_, push)| push["generation"] == 0));
    live.pushes.clear();
    assert_eq!(live.get().active.unwrap().effective["limit"], 3);
    write_limit(&live.rig, 4);
    live.tick().await;
    live.expect_edit();
    assert_eq!(live.get().active.unwrap().effective["limit"], 4);
}

#[tokio::test(start_paused = true)]
async fn config_gate_unstamped_user_file_undeclared_module_gets_no_push() {
    let mut live = LiveFiles::new().await;
    live.real_edit().await;
    live.register(UNDECLARED, "c");
    std::fs::write(live.rig.path.join("cortexkit/c.jsonc"), b"{}").unwrap();
    live.owner.notify_delivery_changed();
    live.until_idle(UNDECLARED).await;
    assert!(
        live.pushes.is_empty(),
        "an opted-in but undeclared module must not get a push: {:?}",
        live.pushes
    );
    let mut watch = crate::config_gate::runtime::unstamped::UserFileWatch::default();
    assert_eq!(
        live.owner
            .poll_user_file(UNDECLARED, "c", &mut watch)
            .unwrap(),
        crate::config_gate::runtime::unstamped::UserFilePoll::Stopped
    );
}

#[tokio::test(start_paused = true)]
async fn config_gate_unstamped_user_file_over_bound_is_never_unchanged() {
    let live = LiveFiles::new().await;
    std::fs::write(
        live.rig.path.join("cortexkit/a.jsonc"),
        vec![b' '; 1024 * 1024 + 1],
    )
    .unwrap();
    let mut watch = crate::config_gate::runtime::unstamped::UserFileWatch::default();
    for _ in 0..2 {
        assert_eq!(
            live.owner
                .poll_user_file(INCUMBENT, "a", &mut watch)
                .unwrap(),
            crate::config_gate::runtime::unstamped::UserFilePoll::Observed
        );
    }
}

#[tokio::test(start_paused = true)]
async fn config_gate_unstamped_user_file_unchanged_tick_takes_no_owner_guard() {
    use std::sync::atomic::Ordering::SeqCst;
    let mut live = LiveFiles::new().await;
    live.real_edit().await;
    // Let the edit's notifications settle before counting.
    live.tick().await;
    live.tick().await;
    let guards = live.owner.owner_guards.load(SeqCst);
    let builds = live.owner.projection_builds.load(SeqCst);
    for _ in 0..3 {
        live.tick().await;
    }
    assert!(live.pushes.is_empty(), "{:?}", live.pushes);
    assert_eq!(
        live.owner.owner_guards.load(SeqCst),
        guards,
        "an unchanged timer pass must not take an owner guard"
    );
    assert_eq!(live.owner.projection_builds.load(SeqCst), builds);

    // A change on the next tick still takes the full pass and pushes.
    let modified = std::fs::metadata(live.rig.path.join("cortexkit/a.jsonc"))
        .unwrap()
        .modified()
        .unwrap();
    write_limit(&live.rig, 5);
    {
        // Filesystems can give two same-size writes the same modification time.
        // Keep that time identical even if this test runs across a clock tick.
        let file = std::fs::OpenOptions::new()
            .write(true)
            .open(live.rig.path.join("cortexkit/a.jsonc"))
            .unwrap();
        file.set_modified(modified).unwrap();
        assert_eq!(file.metadata().unwrap().modified().unwrap(), modified);
    }
    live.tick().await;
    live.expect_edit();
    assert!(live.owner.owner_guards.load(SeqCst) > guards);
}