subc-daemon 0.44.7

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
#[tokio::test]
async fn agent_command_batch_caps_name_the_oversized_field() {
    let handler = ControlHandler::new(Arc::new(Registry::default()));
    let root = subc_protocol::session::AgentCommandRoot {
        pid: 42,
        start_time_ms: 1,
    };
    for (field, cap) in [("started", 256), ("finished", 256), ("known", 1_024)] {
        let request =
            Frame::build(FrameType::Request, control_flags(), 0, 0, 1, b"{}".to_vec()).unwrap();
        let reply = handler
            .handle_agent_commands(
                ConnectionId::new(998),
                request,
                if field == "started" {
                    vec![root; cap + 1]
                } else {
                    Vec::new()
                },
                if field == "finished" {
                    vec![
                        subc_protocol::session::AgentCommandFinished {
                            pid: root.pid,
                            start_time_ms: root.start_time_ms,
                            cpu_ms: None
                        };
                        cap + 1
                    ]
                } else {
                    Vec::new()
                },
                (field == "known").then(|| vec![root; cap + 1]),
            )
            .unwrap();
        let error: ErrorBody = serde_json::from_slice(&reply[0].body).unwrap();
        assert_eq!(error.code, "invalid_request");
        assert!(error.message.contains(field), "{error:?}");
    }
}

#[tokio::test]
async fn supervised_agent_commands_move_cpu_and_refuse_foreign_ownership() {
    exercise_agent_commands(0).await;
}

#[tokio::test]
async fn a_module_without_agent_declarations_has_no_agents_row() {
    exercise_agent_commands(0).await;
}

#[tokio::test]
async fn sampler_revision_conflicts_are_revalidated_before_the_reply() {
    exercise_agent_commands(2).await;
}

#[tokio::test]
async fn persistent_revision_contention_is_retryable_busy_not_unsupervised() {
    exercise_agent_commands(4).await;
}

#[tokio::test]
async fn currently_published_control_decodes_the_daemons_list_and_status_replies() {
    exercise_agent_commands_with_decoder(0, true, false).await;
}

#[tokio::test]
async fn verified_root_capacity_refusal_is_retryable_and_records_only_that_root() {
    exercise_agent_commands_with_decoder(0, false, true).await;
}

async fn exercise_agent_commands(conflicts: usize) {
    exercise_agent_commands_with_decoder(conflicts, false, false).await;
}

async fn exercise_agent_commands_with_decoder(
    conflicts: usize,
    published_reader: bool,
    at_capacity: bool,
) {
    use std::fs;
    use subc_protocol::session::{AgentCommandFinished, AgentCommandRoot};
    async fn measured(
        handler: &ControlHandler,
        handle: &SupervisorHandle,
        deadline: tokio::time::Instant,
        minimum: u64,
    ) -> crate::resource_totals::Readings {
        loop {
            let readings = handler
                .resource_tracker
                .read(handle.list(), true, "test")
                .await;
            if readings
                .agent_commands
                .as_ref()
                .is_some_and(|agents| agents.first().is_some_and(|agent| agent.cpu_ms >= minimum))
            {
                return readings;
            }
            assert!(
                tokio::time::Instant::now() < deadline,
                "no complete command measurement reached the independently burned CPU: {:?}",
                readings.agent_commands
            );
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    }
    for reported in [false, true]
        .into_iter()
        .filter(|reported| !(published_reader || at_capacity) || !*reported)
    {
        let dir = ScratchDir::new("supervised-agent-commands");
        let registry = Arc::new(Registry::default());
        let handle = SupervisorHandle::new();
        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
            .with_handle(handle.clone());
        let mut program = std::env::current_exe()
            .unwrap()
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .join("ckdev-resource-helper");
        if cfg!(windows) {
            program.set_extension("exe");
        }
        assert!(
            program.is_file(),
            "resource fixture was not built: {program:?}"
        );
        let module = supervisor
            .supervise_configured(
                crate::ModuleSpec {
                    module_id: "resource-module".into(),
                    program,
                    args: Vec::new(),
                    env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
                        .into_iter()
                        .map(|key| (key.to_owned(), dir.display().to_string()))
                        .chain([(
                            "SUBC_RESOURCE_FIXTURE_DIR".to_owned(),
                            dir.display().to_string(),
                        )])
                        .collect(),
                    reserved: false,
                    reserved_prefixes: Vec::new(),
                    protocol: ModuleProtocol::Subc,
                    overlap: Default::default(),
                    carry_containment: false,
                },
                true,
            )
            .unwrap();
        let configured_version = "9.8.7-resource-test";
        let handler = ControlHandler::new(registry)
            .with_daemon_version(configured_version.to_owned())
            .with_supervisor(handle.clone());
        let (ctx, mut wire) = route_ctx(ConnectionId::new(200));
        let nonce = handle.spawn_launch_nonce_for("resource-module").unwrap();
        hello_via_sink(
            &handler,
            &ctx,
            &mut wire,
            hello_frame_with_nonce("resource-module", PROTOCOL_VERSION, 1, Some(&nonce)),
        )
        .await;
        let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
        let root = loop {
            if let Ok(contents) = fs::read_to_string(dir.join("root-ready")) {
                let fields: Vec<_> = contents.split_whitespace().collect();
                if fields.len() == 2 {
                    break AgentCommandRoot {
                        pid: fields[0].parse().unwrap(),
                        start_time_ms: fields[1].parse().unwrap(),
                    };
                }
            }
            assert!(
                tokio::time::Instant::now() < deadline,
                "supervised fixture never started its command"
            );
            tokio::time::sleep(Duration::from_millis(5)).await;
        };
        let request = |corr, request: &ModuleControlRequestFromModule| {
            Frame::build(
                FrameType::Request,
                control_flags(),
                0,
                0,
                corr,
                serde_json::to_vec(request).unwrap(),
            )
            .unwrap()
        };
        let foreign = AgentCommandRoot {
            pid: std::process::id(),
            start_time_ms: subc_os::process_start_time_ms(std::process::id()).unwrap(),
        };
        let before_declaration = loop {
            let reading = handler
                .resource_tracker
                .read(handle.list(), true, "test")
                .await;
            if reading.agent_commands.is_some()
                && reading
                    .modules
                    .get("resource-module")
                    .is_some_and(|(tree, _)| tree.is_some())
            {
                break reading;
            }
            assert!(tokio::time::Instant::now() < deadline);
            tokio::time::sleep(Duration::from_millis(5)).await;
        };
        let no_agents = before_declaration
            .agent_commands
            .as_ref()
            .is_some_and(Vec::is_empty);
        if !no_agents {
            fs::write(dir.join("burn-root"), "").unwrap();
            fs::write(dir.join("finish-root"), "").unwrap();
            while !dir.join("reaped").exists() {
                assert!(tokio::time::Instant::now() < deadline);
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
            handler.cleanup_connection(ctx.connection_id).unwrap();
            module.stop().await.unwrap();
            assert!(
                no_agents,
                "a module's own process-tree uncertainty is not an agent declaration"
            );
        }
        let tree = before_declaration.modules["resource-module"]
            .0
            .as_ref()
            .unwrap();
        if tree.source == subc_control::TreeSource::ProcessTree {
            assert_eq!(tree.bound, Some(subc_control::ResourceBound::Lower));
        }
        let batch = ModuleControlRequestFromModule::AgentCommands {
            started: vec![foreign, root],
            finished: Vec::new(),
            known: None,
        };
        handler
            .resource_tracker
            .inject_revision_conflicts(conflicts);
        if at_capacity {
            handler
                .resource_tracker
                .fill_root_capacity_for_test("resource-module");
        }
        let replies = handler
            .handle_control_frame(&ctx, request(2, &batch))
            .await
            .unwrap();
        assert!(
            replies.is_empty(),
            "agent validation must be dispatched away from the connection reader"
        );
        let mut replies = [tokio::time::timeout(Duration::from_secs(2), wire.recv())
            .await
            .unwrap()
            .unwrap()];
        if at_capacity {
            let error: ErrorBody = serde_json::from_slice(&replies[0].body).unwrap();
            fs::write(dir.join("burn-root"), "").unwrap();
            fs::write(dir.join("finish-root"), "").unwrap();
            while !dir.join("reaped").exists() {
                assert!(tokio::time::Instant::now() < deadline);
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
            handler.cleanup_connection(ctx.connection_id).unwrap();
            module.stop().await.unwrap();
            assert_eq!(error.code, "agent_roots_full");
            assert_eq!(
                handler.resource_tracker.loss_diagnostics()["resource-module"]["lost_identities"],
                1
            );
            return;
        }
        if conflicts >= 4 {
            let error: ErrorBody = serde_json::from_slice(&replies[0].body).unwrap();
            assert_eq!(error.code, "busy");
            let loss_rows = handler
                .resource_tracker
                .read(handle.list(), false, "test")
                .await
                .agent_commands
                .unwrap_or_default();
            assert_eq!(
                loss_rows.len(),
                1,
                "loss-only zero rows must remain visible"
            );
            assert_eq!((loss_rows[0].cpu_ms, loss_rows[0].process_count), (0, 0));
            assert_eq!(loss_rows[0].bound, Some(subc_control::ResourceBound::Lower));
            handler
                .handle_control_frame(&ctx, request(22, &batch))
                .await
                .unwrap();
            replies = [tokio::time::timeout(Duration::from_secs(2), wire.recv())
                .await
                .unwrap()
                .unwrap()];
        }
        assert_eq!(
            replies[0].header.ty,
            FrameType::Response,
            "{}",
            String::from_utf8_lossy(&replies[0].body)
        );
        assert_eq!(
            serde_json::from_slice::<Value>(&replies[0].body).unwrap(),
            serde_json::json!({})
        );
        let readings = measured(&handler, &handle, deadline, 0).await;
        let agents = &readings.agent_commands.as_ref().unwrap()[0];
        let historical = fs::read_to_string(dir.join("historical-cpu"))
            .unwrap()
            .parse::<u64>()
            .unwrap();
        let current = subc_os::resource_usage(root.pid).unwrap();
        let current = u64::try_from((current.cpu_user + current.cpu_system).as_millis()).unwrap();
        assert!(
            agents.cpu_ms <= current.saturating_sub(historical),
            "pre-acceptance CPU stays in the module row"
        );
        fs::write(dir.join("burn-root"), "").unwrap();
        while !dir.join("root-burned").exists() {
            assert!(
                tokio::time::Instant::now() < deadline,
                "the accepted command did not burn new CPU"
            );
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        // Reads within one second intentionally reuse the same process walk.
        // Require the known post-acceptance burn to become visible by the
        // existing setup deadline instead of treating a cached zero as fresh.
        let readings = measured(&handler, &handle, deadline, 100).await;
        let agents = &readings.agent_commands.as_ref().unwrap()[0];
        assert_eq!(
            readings.daemon.as_ref().unwrap().version,
            configured_version
        );
        assert!(
            agents.cpu_ms >= 100,
            "declared root must have burned CPU: {agents:?}"
        );
        let published_body = if published_reader {
            #[cfg(windows)]
            {
                let (tree, hour) = &readings.modules["resource-module"];
                assert_eq!(tree.as_ref().unwrap().source, subc_control::TreeSource::Job);
                assert_eq!(tree.as_ref().unwrap().bound, None);
                assert_eq!(
                    hour.as_ref().unwrap().bound,
                    None,
                    "an exact job hour does not inherit process-tree uncertainty"
                );
            }
            // The published-reader fixture needs an hour with a bound value
            // even when the normal native-container reading is exact.
            handler
                .resource_tracker
                .inject_model_loss_for_test("resource-module");
            let body = loop {
                handler
                    .resource_tracker
                    .read(handle.list(), true, "published_reader_fixture")
                    .await;
                let frame =
                    Frame::build(FrameType::Request, control_flags(), 0, 0, 900, Vec::new())
                        .unwrap();
                let replies = handler.handle_supervisor_list(frame).await.unwrap();
                let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
                if body["modules"][0].get("tree").is_some()
                    && body["modules"][0]["cpu_last_hour"].get("bound").is_some()
                    && body.get("daemon").is_some()
                    && body["agent_commands"]
                        .as_array()
                        .is_some_and(|agents| !agents.is_empty())
                {
                    break body;
                }
                if tokio::time::Instant::now() >= deadline {
                    fs::write(dir.join("finish-root"), "").unwrap();
                    handler.cleanup_connection(ctx.connection_id).unwrap();
                    module.stop().await.unwrap();
                    panic!("populated list diagnostics never became available: {body}");
                }
                tokio::time::sleep(Duration::from_millis(5)).await;
            };
            Some((body, handler.registry.generation().unwrap()))
        } else {
            None
        };
        assert_eq!(
            agents.process_count, 1,
            "the foreign root must be ignored without refusing its valid batch peer"
        );
        let (consumer, _wire) = route_ctx(ConnectionId::new(201));
        let refused = handler
            .handle_control_frame(&consumer, request(3, &batch))
            .await
            .unwrap();
        assert_eq!(refused[0].header.ty, FrameType::Error);
        let body: ErrorBody = serde_json::from_slice(&refused[0].body).unwrap();
        assert_eq!(body.code, "not_supervised");
        let sampled_cpu = agents.cpu_ms;
        fs::write(dir.join("finish-root"), "").unwrap();
        while !dir.join("reaped").exists() {
            assert!(
                tokio::time::Instant::now() < deadline,
                "supervised module did not reap command"
            );
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        let reported_cpu = fs::read_to_string(dir.join("root-cpu"))
            .unwrap()
            .parse::<u64>()
            .unwrap();
        let batch = ModuleControlRequestFromModule::AgentCommands {
            started: Vec::new(),
            finished: vec![AgentCommandFinished {
                pid: root.pid,
                start_time_ms: root.start_time_ms,
                cpu_ms: reported.then_some(u64::MAX),
            }],
            known: Some(Vec::new()),
        };
        let replies = handler
            .handle_control_frame(&ctx, request(4, &batch))
            .await
            .unwrap();
        assert!(
            replies.is_empty(),
            "agent validation must be dispatched away from the connection reader"
        );
        let replies = [tokio::time::timeout(Duration::from_secs(2), wire.recv())
            .await
            .unwrap()
            .unwrap()];
        assert_eq!(replies[0].header.ty, FrameType::Response);
        let readings = measured(&handler, &handle, deadline, sampled_cpu).await;
        let credited = readings.agent_commands.as_ref().unwrap()[0].cpu_ms;
        assert!(
            credited >= sampled_cpu && credited <= reported_cpu,
            "settlement uses only CPU measured by the daemon, never the supplied u64::MAX"
        );
        assert_eq!(
            readings.agent_commands.as_ref().unwrap()[0].process_count,
            0
        );
        handler
            .handle_control_frame(&ctx, request(5, &batch))
            .await
            .unwrap();
        tokio::time::timeout(Duration::from_secs(2), wire.recv())
            .await
            .unwrap()
            .unwrap();
        let readings = measured(&handler, &handle, deadline, sampled_cpu).await;
        assert_eq!(
            readings.agent_commands.as_ref().unwrap()[0].cpu_ms,
            credited,
            "duplicate finish must be idempotent"
        );
        handler.cleanup_connection(ctx.connection_id).unwrap();
        module.stop().await.unwrap();
        // Decode only after the command was reaped and its module stopped, so
        // a decoder regression cannot strand the live process fixture.
        if let Some((body, generation)) = published_body {
            assert_published_readers_decode_list_and_status(body, generation);
        }
    }
}

fn assert_published_readers_decode_list_and_status(body: Value, generation: u64) {
    assert_eq!(body["modules"][0]["cpu_last_hour"]["bound"], "lower");
    let old: subc_control_published::ClientControlResponse =
        serde_json::from_value(body.clone()).unwrap();
    let encoded = serde_json::to_value(old).unwrap();
    assert_eq!(encoded["generation"], generation);
    assert_eq!(encoded["modules"][0]["module_id"], "resource-module");
    assert!(encoded.get("daemon").is_none());
    assert!(encoded.get("agent_commands").is_none());
    assert!(encoded["modules"][0].get("tree").is_none());
    assert!(encoded["modules"][0].get("cpu_last_hour").is_none());
    // The command-line client's module status reads this list entry.
    let status: subc_control_published::SupervisorEntry =
        serde_json::from_value(body["modules"][0].clone()).unwrap();
    assert_eq!(status.module_id, "resource-module");
    let mut future = body;
    future["future"] = json!({"unexpected": [1, false]});
    future["modules"][0]["future"] = json!(false);
    let future: subc_control_published::ClientControlResponse =
        serde_json::from_value(future).unwrap();
    assert_eq!(serde_json::to_value(future).unwrap(), encoded);
}