byteflow-actors 0.9.27

Embeddable flow runtime: M:N scheduler, Atomic Hop (Message+Cap), supervisor — use byteflow::
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
//! Ordered chain of flow supplements in front of an owner.
//!
//! [`install_supplement_door`] adds a door function to a [`Program`]. The
//! host spawns it with the owner Cap in `r0`. The door registers
//! `registry_name` and then serves three `Ask`s:
//!
//! | Tag | Payload | Effect |
//! |-----|---------|--------|
//! | [`TAG_SUPP_ATTACH`] | record `[index: Int, cap: Cap]` | Insert that Cap at `index` (`index == len` appends). |
//! | [`TAG_SUPP_DETACH`] | `Int` index | Remove that slot. |
//! | [`TAG_SUPP_ENTER`] | any value | Walk the chain, then deliver what remains to the owner. |
//!
//! Each supplement receives [`TAG_SUPP_JUDGE`] and answers
//! [`TAG_SUPP_FOLLOW`] (keep the value), [`TAG_SUPP_REJECT`] (stop; the
//! owner is not asked), or [`TAG_SUPP_REPLACE`] (continue with the reply
//! payload). A supplement that exits first is [`TAG_SUPP_REJECT`]: the
//! door does not skip a dead step. The owner is asked with
//! [`TAG_SUPP_DELIVER`] and uses the same three answers. The door's reply
//! to the caller is [`TAG_SUPP_FOLLOW`] with the final value, or
//! [`TAG_SUPP_REJECT`].
//!
//! The chain is eight Cap registers inside the door. Tables cannot store
//! a Cap, and `list_get` takes a constant index, so the walk is unrolled.
//! Nothing in this module hooks mailbox delivery: the door is an ordinary
//! flow, and the caller chooses it by Cap.
//!
//! # Addressing
//!
//! `Ask` needs [`CapRights::ASK`](crate::CapRights::ASK). Bytecode
//! [`Fn::whereis`](crate::Fn::whereis) mints only
//! [`CapRights::SEND`](crate::CapRights::SEND). The name the door
//! registers stores an
//! [`CapRights::ADDRESSING`](crate::CapRights::ADDRESSING) token whose
//! holder is the door. Pass that token from [`Runtime::whereis`](crate::Runtime::whereis)
//! as a spawn argument; the runtime reissues it to the caller with `ASK`.
//!
//! The door calls `make_msg`, `msg_tag`, `msg_payload`, `msg_request_id`,
//! and `msg_reply_cap`. Start the runtime with [`std_native_table`](crate::std_native_table).
//!
//! When the door exits, the scheduler revokes every Cap the door holds
//! and sweeps the registry name. Caps the host still holds stay valid.
//!
//! ```
//! use byteflow::{install_supplement_door, Program};
//!
//! fn main() -> Result<(), byteflow::SupplementError> {
//!     let mut program = Program::new("chain");
//!     let _door = install_supplement_door(&mut program, "front")?;
//!     let _chunk = program.build();
//!     Ok(())
//! }
//! ```

use crate::{FuncId, Label, Program, Reg};

/// Slots in one door. Index `0` is asked first.
pub const SUPPLEMENT_SLOTS: usize = 8;

/// Caller → door: judge `payload`, then deliver what the chain left.
pub const TAG_SUPP_ENTER: u16 = 0xBF10;
/// Door → supplement: judge this value.
pub const TAG_SUPP_JUDGE: u16 = 0xBF11;
/// Keep the value and continue.
pub const TAG_SUPP_FOLLOW: u16 = 0xBF12;
/// Stop the chain. The owner is not asked.
pub const TAG_SUPP_REJECT: u16 = 0xBF13;
/// Continue with the reply payload in place of the current value.
pub const TAG_SUPP_REPLACE: u16 = 0xBF14;
/// Caller → door: insert a Cap. Payload is record `[index, cap]`.
pub const TAG_SUPP_ATTACH: u16 = 0xBF15;
/// Caller → door: drop the slot at this `Int` index.
pub const TAG_SUPP_DETACH: u16 = 0xBF16;
/// Door → owner: the value the chain allowed through.
pub const TAG_SUPP_DELIVER: u16 = 0xBF17;

/// Why a door could not be added to the program.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SupplementError {
    /// `register_name` rejects an empty name, so the door is not emitted.
    EmptyName,
    /// This program already contains a door for the same registry name.
    AlreadyInstalled,
}

impl std::fmt::Display for SupplementError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SupplementError::EmptyName => f.write_str("supplement door name must be non-empty"),
            SupplementError::AlreadyInstalled => {
                f.write_str("a supplement door for this name is already in the program")
            }
        }
    }
}

impl std::error::Error for SupplementError {}

/// Add the door and its judge helper to `program`.
///
/// The returned function has arity 1: `r0` is the owner Cap. Spawn it,
/// then wait until [`Runtime::whereis`](crate::Runtime::whereis) returns
/// the registered token before asking the door.
pub fn install_supplement_door(
    program: &mut Program,
    registry_name: &str,
) -> Result<FuncId, SupplementError> {
    if registry_name.is_empty() {
        return Err(SupplementError::EmptyName);
    }
    let door_name = format!("supplement-door:{registry_name}");
    let judge_name = format!("supplement-judge:{registry_name}");
    if program.function_index(&door_name).is_some() || program.function_index(&judge_name).is_some()
    {
        return Err(SupplementError::AlreadyInstalled);
    }
    let judge = emit_judge(program, &judge_name);
    Ok(emit_door(program, &door_name, registry_name, judge))
}

/// `Ask` the door to judge `payload`. The reply hop is [`TAG_SUPP_FOLLOW`]
/// or [`TAG_SUPP_REJECT`].
pub fn supplement_enter(f: &mut crate::Fn<'_>, door: Reg, payload: Reg) -> Reg {
    let hop = f.hop_fresh(i32::from(TAG_SUPP_ENTER), payload);
    f.ask(door, hop)
}

/// `Ask` the door to insert `cap` at `index` (`Int`). `index == len` appends.
/// A successful reply's payload is the new length.
pub fn supplement_attach(f: &mut crate::Fn<'_>, door: Reg, index: Reg, cap: Reg) -> Reg {
    let packed = f.window(2);
    f.mov(packed.at(0), index);
    f.mov(packed.at(1), cap);
    let record = f.record_pack(&[packed.at(0), packed.at(1)]);
    let hop = f.hop_fresh(i32::from(TAG_SUPP_ATTACH), record);
    f.ask(door, hop)
}

/// `Ask` the door to drop the slot at `index` (`Int`).
/// A successful reply's payload is the new length.
pub fn supplement_detach(f: &mut crate::Fn<'_>, door: Reg, index: Reg) -> Reg {
    let hop = f.hop_fresh(i32::from(TAG_SUPP_DETACH), index);
    f.ask(door, hop)
}

#[derive(Clone, Copy)]
struct ChainCode {
    len: Reg,
    slots: [Reg; SUPPLEMENT_SLOTS],
    empty: Reg,
    current: Reg,
    reply_body: Reg,
    follow: Label,
    reject: Label,
}

fn emit_judge(program: &mut Program, name: &str) -> FuncId {
    program.function(name, 2, |f| {
        let slot = f.reg(0);
        let current = f.reg(1);
        let request = f.hop_fresh(i32::from(TAG_SUPP_JUDGE), current);
        let reply = f.ask(slot, request);
        let got = f.hop_tag(reply);
        let body = f.hop_payload(reply);
        let verdict = f.load_i32(i32::from(TAG_SUPP_FOLLOW));
        let out = f.local();
        f.mov(out, current);

        let reject_lbl = f.label();
        let replace_lbl = f.label();
        let pack = f.label();

        let is_exit = f.eq_imm(got, i32::from(crate::TAG_SYS_EXIT));
        let not_exit = f.label();
        f.branch_if_falsy(is_exit, not_exit);
        f.jump(reject_lbl);
        f.bind(not_exit);

        let is_reject = f.eq_imm(got, i32::from(TAG_SUPP_REJECT));
        let not_reject = f.label();
        f.branch_if_falsy(is_reject, not_reject);
        f.jump(reject_lbl);
        f.bind(not_reject);

        let is_replace = f.eq_imm(got, i32::from(TAG_SUPP_REPLACE));
        let not_replace = f.label();
        f.branch_if_falsy(is_replace, not_replace);
        f.jump(replace_lbl);
        f.bind(not_replace);

        let is_follow = f.eq_imm(got, i32::from(TAG_SUPP_FOLLOW));
        let not_follow = f.label();
        f.branch_if_falsy(is_follow, not_follow);
        f.jump(pack);
        f.bind(not_follow);
        f.jump(reject_lbl);

        f.bind(reject_lbl);
        f.set(verdict, i32::from(TAG_SUPP_REJECT));
        f.jump(pack);

        f.bind(replace_lbl);
        f.set(verdict, i32::from(TAG_SUPP_REPLACE));
        f.mov(out, body);
        f.jump(pack);

        f.bind(pack);
        let packed = f.window(2);
        f.mov(packed.at(0), verdict);
        f.mov(packed.at(1), out);
        let rec = f.record_pack(&[packed.at(0), packed.at(1)]);
        f.return_(rec);
    })
}

fn emit_door(program: &mut Program, name: &str, registry_name: &str, judge: FuncId) -> FuncId {
    program.function(name, 1, |f| {
        let owner = f.reg(0);
        let registered = f.load_str(registry_name);
        f.register_name(registered);
        let empty = f.load_i32(0);
        let len = f.load_i32(0);
        let mut slots = [empty; SUPPLEMENT_SLOTS];
        for slot in &mut slots {
            *slot = f.load_i32(0);
        }
        let chain = ChainCode {
            len,
            slots,
            empty,
            current: f.local(),
            reply_body: f.local(),
            follow: f.label(),
            reject: f.label(),
        };
        let loop_lbl = f.label();
        f.bind(loop_lbl);
        let msg = f.receive();
        let got = f.hop_tag(msg);
        let payload = f.hop_payload(msg);

        let is_attach = f.eq_imm(got, i32::from(TAG_SUPP_ATTACH));
        let not_attach = f.label();
        f.branch_if_falsy(is_attach, not_attach);
        emit_attach(f, payload, &chain);
        f.bind(not_attach);

        let is_detach = f.eq_imm(got, i32::from(TAG_SUPP_DETACH));
        let not_detach = f.label();
        f.branch_if_falsy(is_detach, not_detach);
        emit_detach(f, payload, &chain);
        f.bind(not_detach);

        let is_enter = f.eq_imm(got, i32::from(TAG_SUPP_ENTER));
        let not_enter = f.label();
        f.branch_if_falsy(is_enter, not_enter);
        emit_enter(f, owner, payload, judge, &chain);
        f.bind(not_enter);

        f.mov(chain.reply_body, chain.empty);
        f.jump(chain.reject);

        // One reply tail for every path. Unrolling `send_reply` at each
        // branch would spend a fresh register window per site and overflow
        // the 255-slot frame.
        f.bind(chain.follow);
        f.send_reply(msg, i32::from(TAG_SUPP_FOLLOW), chain.reply_body);
        f.jump(loop_lbl);
        f.bind(chain.reject);
        f.send_reply(msg, i32::from(TAG_SUPP_REJECT), chain.reply_body);
        f.jump(loop_lbl);
    })
}

fn emit_attach(f: &mut crate::Fn<'_>, payload: Reg, chain: &ChainCode) {
    let idx = f.record_get(payload, 0);
    let cap = f.record_get(payload, 1);
    let negative = f.lt_imm(idx, 0);
    let nonneg = f.label();
    f.branch_if_falsy(negative, nonneg);
    f.mov(chain.reply_body, chain.empty);
    f.jump(chain.reject);
    f.bind(nonneg);

    let fits = f.le(idx, chain.len);
    let bad = f.label();
    f.branch_if_falsy(fits, bad);
    let room = f.lt_imm(chain.len, SUPPLEMENT_SLOTS as i32);
    f.branch_if_falsy(room, bad);

    // Shift the tail up so `idx` is a free slot. `i` walks from the back
    // so a slot is copied before it is overwritten.
    for i in (1..SUPPLEMENT_SLOTS).rev() {
        let at = f.load_i32(i as i32);
        let idx_before = f.lt(idx, at);
        let skip = f.label();
        f.branch_if_falsy(idx_before, skip);
        let within = f.le(at, chain.len);
        f.branch_if_falsy(within, skip);
        f.mov(chain.slots[i], chain.slots[i - 1]);
        f.bind(skip);
    }
    for (i, slot) in chain.slots.iter().enumerate() {
        let is_i = f.eq_imm(idx, i as i32);
        let skip = f.label();
        f.branch_if_falsy(is_i, skip);
        f.mov(*slot, cap);
        f.bind(skip);
    }
    f.add_imm(chain.len, 1);
    f.mov(chain.reply_body, chain.len);
    f.jump(chain.follow);
    f.bind(bad);
    f.mov(chain.reply_body, chain.empty);
    f.jump(chain.reject);
}

fn emit_detach(f: &mut crate::Fn<'_>, idx: Reg, chain: &ChainCode) {
    let negative = f.lt_imm(idx, 0);
    let nonneg = f.label();
    f.branch_if_falsy(negative, nonneg);
    f.mov(chain.reply_body, chain.empty);
    f.jump(chain.reject);
    f.bind(nonneg);

    let in_range = f.lt(idx, chain.len);
    let bad = f.label();
    f.branch_if_falsy(in_range, bad);

    for i in 0..SUPPLEMENT_SLOTS - 1 {
        let at = f.load_i32(i as i32);
        let idx_le = f.le(idx, at);
        let skip = f.label();
        f.branch_if_falsy(idx_le, skip);
        let next = f.load_i32((i + 1) as i32);
        let next_in = f.lt(next, chain.len);
        f.branch_if_falsy(next_in, skip);
        f.mov(chain.slots[i], chain.slots[i + 1]);
        f.bind(skip);
    }
    let last = f.local();
    f.mov(last, chain.len);
    f.sub_imm(last, 1);
    for (i, slot) in chain.slots.iter().enumerate() {
        let is_last = f.eq_imm(last, i as i32);
        let skip = f.label();
        f.branch_if_falsy(is_last, skip);
        f.mov(*slot, chain.empty);
        f.bind(skip);
    }
    f.sub_imm(chain.len, 1);
    f.mov(chain.reply_body, chain.len);
    f.jump(chain.follow);
    f.bind(bad);
    f.mov(chain.reply_body, chain.empty);
    f.jump(chain.reject);
}

fn emit_enter(f: &mut crate::Fn<'_>, owner: Reg, payload: Reg, judge: FuncId, chain: &ChainCode) {
    f.mov(chain.current, payload);
    for (i, slot) in chain.slots.iter().enumerate() {
        let at = f.load_i32(i as i32);
        let live = f.lt(at, chain.len);
        let skip = f.label();
        f.branch_if_falsy(live, skip);
        let ret = f.call(judge, &[*slot, chain.current]);
        let verdict = f.record_get(ret, 0);
        let next = f.record_get(ret, 1);
        let rejected = f.eq_imm(verdict, i32::from(TAG_SUPP_REJECT));
        let keep = f.label();
        f.branch_if_falsy(rejected, keep);
        f.mov(chain.reply_body, chain.current);
        f.jump(chain.reject);
        f.bind(keep);
        let replaced = f.eq_imm(verdict, i32::from(TAG_SUPP_REPLACE));
        let same = f.label();
        f.branch_if_falsy(replaced, same);
        f.mov(chain.current, next);
        f.bind(same);
        f.bind(skip);
    }

    let hop = f.hop_fresh(i32::from(TAG_SUPP_DELIVER), chain.current);
    let reply = f.ask(owner, hop);
    let got = f.hop_tag(reply);
    let body = f.hop_payload(reply);
    let replaced = f.eq_imm(got, i32::from(TAG_SUPP_REPLACE));
    let not_replace = f.label();
    f.branch_if_falsy(replaced, not_replace);
    f.mov(chain.current, body);
    f.mov(chain.reply_body, chain.current);
    f.jump(chain.follow);
    f.bind(not_replace);
    let followed = f.eq_imm(got, i32::from(TAG_SUPP_FOLLOW));
    let not_follow = f.label();
    f.branch_if_falsy(followed, not_follow);
    f.mov(chain.reply_body, chain.current);
    f.jump(chain.follow);
    f.bind(not_follow);
    f.mov(chain.reply_body, chain.current);
    f.jump(chain.reject);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Opcode, Program};

    fn function_traps(chunk: &crate::Chunk, id: u32) -> bool {
        let Some(func) = chunk.function(id) else {
            return true;
        };
        let start = func.entry as usize;
        let end = chunk
            .functions
            .iter()
            .map(|function| function.entry)
            .filter(|entry| *entry > func.entry)
            .min()
            .unwrap_or(chunk.code.len() as u32) as usize;
        chunk.code[start..end]
            .iter()
            .any(|instruction| instruction.op == Opcode::Trap)
    }

    #[test]
    fn empty_name_is_rejected() {
        let mut program = Program::new("chain");
        assert_eq!(
            install_supplement_door(&mut program, ""),
            Err(SupplementError::EmptyName)
        );
    }

    #[test]
    fn second_door_for_the_same_name_is_rejected() -> Result<(), SupplementError> {
        let mut program = Program::new("chain");
        let _door = install_supplement_door(&mut program, "front")?;
        assert_eq!(
            install_supplement_door(&mut program, "front"),
            Err(SupplementError::AlreadyInstalled)
        );
        Ok(())
    }

    #[test]
    fn door_frame_verifies_without_a_trap() -> Result<(), SupplementError> {
        let mut program = Program::new("chain");
        let door = install_supplement_door(&mut program, "front")?;
        let judge = program
            .function_index("supplement-judge:front")
            .unwrap_or(u32::MAX);
        let chunk = program.build();
        if let Err(err) = crate::verify(&chunk) {
            panic!("{err}");
        }
        assert!(
            !function_traps(&chunk, door),
            "door frame emitted Trap (register file overflow)"
        );
        assert!(
            !function_traps(&chunk, judge),
            "judge frame emitted Trap (register file overflow)"
        );
        Ok(())
    }
}