Skip to main content

Module atomic_hop

Module atomic_hop 

Source
Expand description

Atomic Hop: Message-only Send, FlowCap addressing, Ask, selective receive.

§Atomic Hop (Byteflow core)

Handoff context for humans / other AIs working on this repo only (byteflow). Hardware (byteflow-hw) was removed from the monorepo — do not restore it here.

§Units: flows

Byteflow’s concurrent unit is a flow (Flow, FlowId, FlowHandle, FlowOutcome) — not an “actor” API surface.

Wire identity still uses Value::Pid (FlowId as u64) inside messages. Addressing for bytecode Send / Ask uses Value::Cap (FlowCap, ABI v5 / 0.9.0+). Scalars include Value::Str / Value::Bytes / Value::Map in the constant pool; hops remain Message-only. Untrusted .bf loads reject Cap / Pid / Message in the pool unless TrustLevel::Trusted is set.

§What “Atomic Hop” means

Every Send (bytecode or Runtime::send) must carry a full Message envelope:

Message { sender, reply_cap, request_id, tag, payload }
  • sender — authenticated origin FlowId (stamped by the worker)
  • reply_cap — SEND-only Cap back to the sender. One live token per (recipient, sender) pair (CapTable::mint_or_reuse); correlation is request_id, not a fresh Cap per hop.
  • request_id — correlation token. Prefer crate::Fn::fresh_request_id / crate::Fn::hop_fresh (per-flow, starts at 1). 0 is “unset”: Send / Ask mint a fresh id at the hop boundary. Ask refuses a second in-flight Ask that reuses a still-pending id.
  • tag — protocol discriminator (opaque to the VM)
  • payload — a Value: scalars, blobs, a list, a map, or another hop

Authenticated sender (security S1): bytecode Send / Ask overwrite the outer Message.sender and attach reply_cap before delivery. A nested envelope with sender == 0 is stamped with that same flow. A nested envelope that already has a sender keeps it. Host Runtime::send uses the same choke-point: sender = FlowId::HOST (0), reply_cap = CapId::NONE (host has no mailbox), and an unset request_id is minted. A nested sender == 0 stays 0 on that path. The make_msg native has no sender operand (3-arg: request_id, tag, payload). A 4-arg legacy form discards the first register and still writes sender = 0 until the hop is authenticated — see security.md.

FlowCap (security S6): bytecode Send / Ask targets must be Value::Cap. SelfPid / Spawn return Caps. Reply with msg_reply_cap, not msg_sender.

Bare scalars (Int, Pid, …) on Send → VM trap / SendError::NotAHop.
Mailbox park/push share one mutex → no lost-wakeup (scheduler/mailbox/). Inboxes are bounded — see mailbox.md.

§Selective receive (ReceiveMatch)

Receive takes the next hop. ReceiveMatch / ReceiveMatchImm wait for a hop whose Message.tag matches — earlier non-matching hops stay in the mailbox (FIFO skip, never drop). A parked selective waiter is woken only by a matching hop; junk is queued behind the same lock.

OpcodeForm
ReceiveMatch 0x53ra, rb — tag from r[b] (Int in 0..=u16::MAX)
ReceiveMatchImm 0x54ra, imm — immediate tag
FreshRequestId 0x5Cra — next per-flow correlation id
ReceiveMatchCorr 0x5Dra, rb, rc — tag == r[b] and request_id == r[c]
ReceiveMatchCorrImm 0x5Era, rb, imm — immediate tag + request_id from r[b]
ReceiveMatchKind 0x64ra, imm — wait for hop whose payload.wire_tag() == imm (0..=10; List is 9, Map is 10)
ReceiveMatchTimeout 0x67ra, rb, rc — tag from r[b], after r[c] ms → Unit
ReceiveMatchImmTimeout 0x68ra, rb, imm — immediate tag, timeout r[b]
IsAlive 0x69ra, rb — Bool: held Cap r[b] still names a live flow
ReceiveMatchEq 0x6Era, rb, rc — tag == r[b] and payload Int == r[c]
ReceiveMatchValue 0x70ra, rb, rc — tag == r[b] and payload equal to r[c] (any Value)
ReceiveMatchCmp 0x83ra, rb, rc, imm — tag == r[b] and Int payload Eq/Lt/Le against r[c] (imm 0/1/2). A miss stays queued
SetTrapExit 0x5Fra — BEAM trap_exit from truthy r[a] (see lifecycle.md)
SetRestartPolicy 0x65imm — 0 Always / 1 OnFailure / 2 Never (supervisor exit decision)
HostAwait 0x66ra, rb, imm — ticket id in r[a]; host completion is a TAG_SYS_AWAIT hop (see host-await.md)

Sample: samples::selective_receive (TAG_JUNK then TAG_REQ); samples::receive_match_kind (Str decoy then Int payload); samples::receive_match_eq (same tag, payload 0 then 41); samples::selective_receive_timeout (after → Unit).

Tag, kind (0..=10), Int equality, an integer comparison (ReceiveMatchCmp), and structural payload equality are still not arbitrary BEAM term patterns: no tuples, and no guard language beyond that one comparison. Maps are values (MapPack / MapGet / MapLen), not patterns. exit/2, the process dictionary, StartSupervisor, and StartChild are lifecycle opcodes — see lifecycle.md and beam-mapping.md.

§HostAwait — async bridge (0x66)

Register a host operation and hand (op, args) to crate::HostAwaitBridge. The flow keeps running; r[a] receives the ticket id. The host completes with an authenticated crate::TAG_SYS_AWAIT hop (request_id = ticket), not a CallNative / std-native slot. Bytecode reads it with Receive. See host-await.md.

§Ask — atomic RPC hop (0x55)

Ask ra, rb, rc delivers r[c] (Message) to r[b] (Cap), then parks the caller until a reply matches:

reply.request_id == request.request_id
&& reply.sender  == resolved_FlowId(target_cap)

Implemented via mailbox WaitFilter::Correlation { expect_request_id, expect_sender: Some(flow_id) }. FIFO skip applies: unrelated hops (wrong id or wrong sender) stay queued.

AskTimeout (0x5A) is the same hop plus a deadline: the dest register gets Value::Unit if no correlated reply arrives in time (same writeback as ReceiveTimeout). If the target exits first, dest is a TAG_SYS_EXIT hop instead (see lifecycle.md). Sample: samples::ask_reply, samples::ask_timeout_expires, samples::ask_target_exits.

Cap in payload: any Value::Cap the sender holds is reissued so the recipient becomes the new holder (CapTable::delegate). The walk includes a List, a Map, a nested hop’s payload, and that hop’s reply_cap. On a local hop a nested reply_cap of NONE is minted for the pair. This is additive (the sender keeps their token). A cap the sender does not hold fails the hop. SendRemote refuses a live cap before spending a send token. encode_frame then writes that hop with the .bf value encoding and also refuses a Pid. The frame header and the envelope must name the same sender.

That is the deliberate difference vs classic actor runtimes that allow any value on send.

§Make / unpack (std natives)

Stable indices in natives.rs:

IdxNameArgs → result
0printvalues… → Unit (flow-visible log)
1now_ms→ Int
2make_msgrequest_id, tag, payload → Message (sender stamped on Send)
3msg_sendermsg → Pid (identity)
4msg_request_idmsg → Int
5msg_tagmsg → Int
6msg_payloadmsg → any Value
7msg_reply_capmsg → Cap (SEND grant)

Runtime must use Runtime::with_natives(chunk, std_native_table()), Runtime::with_std_natives_and_config, or a custom table.

§Sample + refresh

Runnable host sketch (same API the examples use):

use byteflow::{FlowOutcome, Program, Runtime, Value, std_native_table};

const TAG_PING: i32 = 10;
const TAG_PONG: i32 = 11;

let mut program = Program::new("ping-pong");
let pong = program.function("pong", 0, |f| {
    let msg = f.receive();
    let payload = f.hop_payload(msg);
    f.add_imm(payload, 1);
    f.send_reply(msg, TAG_PONG, payload);
    f.exit(payload);
});
program.function("main", 0, |f| {
    let child = f.spawn(pong, &[]);
    let payload = f.load_i32(1);
    let req = f.hop_fresh(TAG_PING, payload);
    let rid = f.hop_request_id(req);
    f.send(child, req);
    let reply = f.receive_match_corr_imm(TAG_PONG as u16, rid);
    let out = f.hop_payload(reply);
    f.return_(out);
});

let rt = Runtime::with_natives(program.build(), std_native_table())?;
let Some(main) = rt.function_index("main") else {
    return Err("missing main".into());
};
let outcome = rt.spawn(main, &[])?.join();
rt.shutdown();
assert!(matches!(outcome, FlowOutcome::Completed(Value::Int(2))));
# unit + sample tests
cargo test -p byteflow-actors

# demos (assemble Program + run Runtime — see examples/)
cargo run -p byteflow-actors --example ping_pong
cargo run -p byteflow-actors --example atomic_actors

# Windows PowerShell — scheduler logs
$env:BYTEFLOW_LOG="info"
cargo run -p byteflow-actors --example atomic_actors

§Hard rules (do not regress)

  1. Opcodes are append-only — never renumber.
  2. Std natives 0–6 frozen; 7 is msg_reply_cap (append-only thereafter).
  3. Fail-closed: no PoisonError::into_inner(); mutex helpers → Result.
  4. Preserve long design comments (mailbox, directory, oneshot, timer, sync_lock).
  5. Clippy: unwrap_used + expect_used = deny (including tests).