subc-daemon 0.37.8

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
use super::*;
use subc_protocol::scope::ScopeAttributes;

fn run_scope(delegates: bool) -> ScopeRecord {
    ScopeRecord::new("s", 1, ScopeKind::Ephemeral)
        .with_carriers(vec![carrier(AFT, None)])
        .with_attributes(
            ScopeAttributes::new()
                .with_agent_id(Some("agent-1".into()))
                .with_run_id(Some("run:7".into()))
                .with_delegates(delegates),
        )
        .with_expires_at_ms(Some(2_000))
}

fn flow_scope() -> ScopeRecord {
    ScopeRecord::new("s", 1, ScopeKind::Ephemeral)
        .with_carriers(vec![carrier(AFT, None)])
        .with_attributes(ScopeAttributes::new().with_flow_id(Some("flow:7".into())))
        .with_expires_at_ms(Some(2_000))
}

async fn call_mode_rig(provides: &[&str]) -> Rig {
    let mut rig = rig_with_target_capabilities(provides).await;
    rig.handler = rig.handler.clone().with_wall_clock(|| 1_000);
    rig
}

fn bind_snapshot(bind: &Frame) -> Value {
    let mut body: Value = serde_json::from_slice(&bind.body).unwrap();
    // Route allocation and temporary directory names vary between opens; the
    // remaining wire fields must match the fixture, including omitted fields.
    body["route_channel"] = serde_json::json!(1);
    body["epoch"] = serde_json::json!(1);
    body["identity"]["project_root"] = serde_json::json!("/project");
    body
}

fn assert_golden(bind: &Frame, golden: &str) {
    let expected: Value = serde_json::from_str(golden).unwrap();
    assert_eq!(bind_snapshot(bind), expected);
}

#[tokio::test]
async fn on_behalf_of_agent_bind_stamp_bytes_are_gated_by_target_capability() {
    for provides in [
        vec![],
        vec![CALL_MODES_CAPABILITY],
        vec![subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY],
    ] {
        let mut rig = call_mode_rig(&provides).await;
        rig.sync(vec![session(1).with_attributes(
            ScopeAttributes::new().with_on_behalf_of_agent(Some("head-agent".into())),
        )])
        .await;
        let route = rig
            .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
            .await;
        assert!(rig.live(&route));
        let body: Value = serde_json::from_slice(&route.bind.body).unwrap();
        let expected = if provides.contains(&subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY) {
            serde_json::json!({"on_behalf_of_agent": "head-agent"})
        } else {
            serde_json::json!({})
        };
        assert_eq!(
            body["scope"]
                .get("attributes")
                .cloned()
                .unwrap_or_else(|| serde_json::json!({})),
            expected
        );
        assert_eq!(
            std::str::from_utf8(&route.bind.body)
                .unwrap()
                .contains(r#""on_behalf_of_agent":"head-agent""#),
            provides.contains(&subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY),
        );
        assert!(body["scope"]["attributes"].get("agent_id").is_none());
        assert!(body["scope"]["attributes"].get("delegates").is_none());
    }
}

#[tokio::test]
async fn on_behalf_of_agent_describe_reply_bytes_are_gated_by_caller_capability() {
    for provides in [
        vec![],
        vec![CALL_MODES_CAPABILITY],
        vec![subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY],
    ] {
        let mut rig = call_mode_rig(&provides).await;
        rig.sync(vec![ScopeRecord::new("s", 1, ScopeKind::Worker)
            .with_attributes(
                ScopeAttributes::new().with_on_behalf_of_agent(Some("head-agent".into())),
            )])
        .await;
        let request = ModuleControlRequestFromModule::ScopeDescribe {
            owner: Principal::Reserved {
                module_id: OWNER.into(),
            },
            scope_ref: "s".into(),
        };
        let reply = call(&rig.handler, &rig.modules[PLEXUS].0, &request).await;
        assert_eq!(reply.header.ty, FrameType::Response);
        let body: Value = serde_json::from_slice(&reply.body).unwrap();
        let supported = provides.contains(&subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY);
        let expected = if supported {
            serde_json::json!({"on_behalf_of_agent": "head-agent"})
        } else {
            serde_json::json!({})
        };
        assert_eq!(body["scope"]["kind"], "worker");
        assert_eq!(
            body["scope"]
                .get("attributes")
                .cloned()
                .unwrap_or_else(|| serde_json::json!({})),
            expected
        );
        assert_eq!(
            std::str::from_utf8(&reply.body)
                .unwrap()
                .contains(r#""on_behalf_of_agent":"head-agent""#),
            supported
        );
        let decoded: ModuleControlResponseToModule = serde_json::from_slice(&reply.body).unwrap();
        let ModuleControlResponseToModule::ScopeDescribe {
            scope: Some(stamp), ..
        } = decoded
        else {
            panic!("live scope.describe reply");
        };
        assert_eq!(
            stamp.attributes.on_behalf_of_agent.as_deref(),
            supported.then_some("head-agent")
        );

        // Even the scope owner must declare reader support; ownership is not a capability.
        let legacy = call(&rig.handler, &rig.owner, &request).await;
        assert_eq!(legacy.header.ty, FrameType::Response);
        assert!(!std::str::from_utf8(&legacy.body)
            .unwrap()
            .contains("on_behalf_of_agent"));
        let (direct, _rx) = wide_ctx(999);
        let refused = call(&rig.handler, &direct, &request).await;
        assert_eq!(refused.header.ty, FrameType::Error);
        assert_eq!(parse_error(&refused)["code"], "not_registered");
        assert!(!std::str::from_utf8(&refused.body)
            .unwrap()
            .contains("on_behalf_of_agent"));
    }
}

#[tokio::test]
async fn on_behalf_of_agent_changes_close_live_routes() {
    for delta in [false, true] {
        let mut rig = call_mode_rig(&[subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY]).await;
        rig.sync(vec![session(1)]).await;
        for (generation, agent) in [(2, Some("head")), (3, Some("other-head")), (4, None)] {
            let mut route = rig
                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
                .await;
            let changed = session(1).with_attributes(
                ScopeAttributes::new().with_on_behalf_of_agent(agent.map(str::to_string)),
            );
            if delta {
                let reply = call(
                    &rig.handler,
                    &rig.owner,
                    &ModuleControlRequestFromModule::ScopeApply {
                        generation,
                        upsert: vec![changed],
                        end: vec![],
                    },
                )
                .await;
                assert_eq!(reply.header.ty, FrameType::Response);
            } else {
                rig.sync(vec![changed]).await;
            }
            assert_eq!(
                route.closed_reason(),
                RouteCloseReason::ScopeDelegationChanged
            );
            assert!(!rig.live(&route));
            let goodbye = rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().unwrap();
            assert_eq!(goodbye.frame.header.ty, FrameType::Goodbye);
        }
    }
}

#[tokio::test]
async fn call_modes_declarer_stamps_classic_codemode_flow_and_deadlines() {
    for (record, mode) in [
        (None, "classic"),
        (Some(session(1).with_expires_at_ms(Some(2_000))), "classic"),
        (Some(run_scope(false)), "codemode"),
        (Some(flow_scope()), "flow"),
    ] {
        let mut rig = call_mode_rig(&[CALL_MODES_CAPABILITY]).await;
        let scoped = record.is_some();
        if let Some(record) = record {
            rig.sync(vec![record]).await;
        }
        let route = rig
            .bound(
                Some(AFT),
                PLEXUS,
                scoped.then(|| rig_selector("s", Some(1))),
            )
            .await;
        assert!(rig.live(&route));
        let body: Value = serde_json::from_slice(&route.bind.body).unwrap();
        assert_eq!(body["call_mode"], mode);
        if scoped {
            assert_eq!(body["scope"]["expires_at_ms"], 2_000);
            assert_eq!(route.stamp().unwrap().expires_at_ms, Some(2_000));
        } else {
            assert!(body.get("scope").is_none());
        }
    }
}

#[tokio::test]
async fn call_modes_legacy_scoped_binds_match_golden_without_new_fields() {
    for (provides, record, golden) in [
        (
            vec![],
            None,
            include_str!("../tests/golden/route_bind_legacy_unscoped.json"),
        ),
        (
            vec!["agent-run-scopes/v1"],
            Some(run_scope(false)),
            include_str!("../tests/golden/route_bind_legacy_run.json"),
        ),
        (
            vec!["flow-scopes/v1"],
            Some(flow_scope()),
            include_str!("../tests/golden/route_bind_legacy_flow.json"),
        ),
    ] {
        let mut rig = call_mode_rig(&provides).await;
        let scoped = record.is_some();
        if let Some(record) = record {
            rig.sync(vec![record]).await;
        }
        let route = rig
            .bound(
                Some(AFT),
                PLEXUS,
                scoped.then(|| rig_selector("s", Some(1))),
            )
            .await;
        assert!(rig.live(&route));
        assert_golden(&route.bind, golden);
    }
}

#[tokio::test]
async fn call_modes_declarer_run_bind_matches_golden_and_describe_returns_deadline() {
    let mut rig = call_mode_rig(&[CALL_MODES_CAPABILITY]).await;
    rig.sync(vec![run_scope(false)]).await;
    let route = rig
        .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
        .await;
    assert_golden(
        &route.bind,
        include_str!("../tests/golden/route_bind_declarer_run.json"),
    );
    let reply = call(
        &rig.handler,
        &rig.owner,
        &ModuleControlRequestFromModule::ScopeDescribe {
            owner: Principal::Reserved {
                module_id: OWNER.into(),
            },
            scope_ref: "s".into(),
        },
    )
    .await;
    let body: Value = serde_json::from_slice(&reply.body).unwrap();
    assert_eq!(body["scope"]["expires_at_ms"], 2_000);
    assert_eq!(body["scope"]["attributes"]["run_id"], "run:7");
}

#[tokio::test]
async fn call_modes_delegating_run_admitted_to_declarer() {
    let mut rig = call_mode_rig(&[CALL_MODES_CAPABILITY]).await;
    rig.sync(vec![run_scope(true)]).await;
    let route = rig
        .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
        .await;
    assert!(rig.live(&route));
    let body: Value = serde_json::from_slice(&route.bind.body).unwrap();
    assert_eq!(body["call_mode"], "codemode");
    assert_eq!(body["scope"]["attributes"]["delegates"], true);
}

#[tokio::test]
async fn call_modes_delegating_run_refused_at_admission_before_reservation() {
    let mut rig = call_mode_rig(&["agent-run-scopes/v1"]).await;
    rig.sync(vec![run_scope(true)]).await;
    let (client, _client_rx, frame) =
        rig.open_frame(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))));
    // Filling the response queue proves that refusal occurs before reservation,
    // rather than merely observing the same refusal from the relay re-check.
    for _ in 0..64 {
        client.egress.try_send(route_bind_ack(1)).unwrap();
    }
    let replies = tokio::time::timeout(
        Duration::from_millis(100),
        rig.handler.handle_control_frame(&client, frame),
    )
    .await
    .expect("delegating runs must be refused at admission")
    .unwrap();
    let body = parse_error(&replies[0]);
    assert_eq!(body["code"], error_codes::TARGET_AGENT_RUN_UNSUPPORTED);
    assert!(body["message"]
        .as_str()
        .unwrap()
        .contains("delegating agent authority"));
    assert!(body["message"]
        .as_str()
        .unwrap()
        .contains(CALL_MODES_CAPABILITY));
    assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
    assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
}

async fn relay_to_legacy_replacement(delegates: bool) {
    use std::future::Future;

    let mut rig = call_mode_rig(&[CALL_MODES_CAPABILITY]).await;
    rig.sync(vec![run_scope(delegates)]).await;
    let (client, mut client_rx, frame) =
        rig.open_frame(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))));
    // Pause after admission by exhausting response permits. The relay must use
    // the replacement's legacy declaration, not the admitted module's modes.
    for _ in 0..64 {
        client.egress.try_send(route_bind_ack(1)).unwrap();
    }
    let handler = rig.handler.clone();
    let mut open = Box::pin(handler.handle_control_frame(&client, frame));
    std::future::poll_fn(|cx| {
        assert!(open.as_mut().poll(cx).is_pending());
        std::task::Poll::Ready(())
    })
    .await;
    assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
    rig.handler
        .cleanup_connection(rig.modules[PLEXUS].0.connection_id)
        .unwrap();
    let (replacement, mut replacement_rx) = wide_ctx(200);
    hello_via_sink(
        &rig.handler,
        &replacement,
        &mut replacement_rx,
        hello_with_capabilities(PLEXUS, 200, &["agent-run-scopes/v1"]),
    )
    .await;
    while client_rx.try_recv().is_ok() {}
    if delegates {
        let replies = tokio::time::timeout(Duration::from_secs(2), open)
            .await
            .expect("the delegating run is refused without awaiting an ack")
            .unwrap();
        let body = parse_error(&replies[0]);
        assert_eq!(body["code"], error_codes::TARGET_AGENT_RUN_UNSUPPORTED);
        assert!(body["message"]
            .as_str()
            .unwrap()
            .contains("delegating agent authority"));
        assert!(
            replacement_rx.try_recv().is_err(),
            "no delegating bind reaches the legacy replacement"
        );
        assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
    } else {
        let bind = tokio::select! {
            result = &mut open => panic!("non-delegating legacy bind refused: {result:?}"),
            outbound = tokio::time::timeout(Duration::from_secs(2), replacement_rx.recv()) => {
                outbound.expect("the replacement receives a bind").unwrap().frame
            }
        };
        assert_golden(
            &bind,
            include_str!("../tests/golden/route_bind_legacy_run.json"),
        );
        rig.handler
            .handle_control_frame(&replacement, route_bind_ack(bind.header.corr))
            .await
            .unwrap();
        assert!(tokio::time::timeout(Duration::from_secs(2), open)
            .await
            .unwrap()
            .unwrap()
            .is_empty());
        let (channel, epoch) = published_route(&client_rx.recv().await.unwrap().frame);
        assert!(matches!(
            rig.forwarding
                .lookup_data_route(client.connection_id, channel, epoch)
                .unwrap(),
            DataRoute::Client(DataRouteState::Bound(_))
        ));
        assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
    }
    assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
}

#[tokio::test]
async fn call_modes_relay_legacy_run_omits_new_fields_from_admission_declarer() {
    relay_to_legacy_replacement(false).await;
}

#[tokio::test]
async fn call_modes_relay_delegating_run_refused_and_reservation_released() {
    relay_to_legacy_replacement(true).await;
}