Skip to main content

Module beam_mapping

Module beam_mapping 

Source
Expand description

BEAM / OTP concepts mapped to Byteflow flows, Caps, and Atomic Hop.

§BEAM → Byteflow (mental model)

Guide for Erlang/Elixir developers reading this codebase. Byteflow is not BEAM — but many ideas rhyme once you map terminology.

§Units

BEAMByteflowNotes
processflowFlowId, FlowHandle, FlowOutcome
pid()hop_sender(msg)Identity inside a delivered hop
pid() as addressValue::CapSelfPid / Spawn return Caps, not Pids
registered nameFn::register_name / Fn::whereis (also host Runtime::*)Stores a Cap, not a FlowId. Bytecode whereis remints SEND for the caller. Swept on exit.

Key difference: on BEAM, a Pid is both identity and delivery address. In Byteflow, Cap = address, Pid = identity inside Message.sender.

BEAM:     send(Pid, Term)
Byteflow: send(Cap, Message)   // Message envelope required

See atomic-hop.md and security.md (S1, S6).

§Messaging

BEAMByteflow APIOpcode / host
spawn(fun)Fn::spawn(fn, argc)Spawn → Cap
Pid ! MsgFn::send(cap, hop)Send
receiveFn::receive()Receive
selective receive (pattern)Fn::receive_match_imm(tag) / Fn::receive_match_kind(kind) / Fn::receive_match_eq(tag, int)Tag, payload wire-tag, or tag + Int payload — not arbitrary term patterns
receive … after TFn::receive_match_imm_timeout(tag, ms) / Fn::receive_timeoutMatch + timeout writes Unit (hops stay queued)
is_process_alive(Pid)Fn::is_alive(cap)Held Cap → live flow? false if revoked / not held
exit(Pid, Reason)Fn::exit_signal(cap, reason)Needs LINK. Normal ignored. Killed untrappable
put / get / eraseFn::dict_put / dict_get / dict_erasePer-flow dict, Int keys, scalar values
supervisor:start_childFn::start_child(fn, policy)Caller must already be a supervised child
gen_server:callFn::ask(cap, hop) / Fn::ask_timeoutAsk / AskTimeout
gen_server:castFn::send(cap, hop)fire-and-forget
host async I/O (no BEAM equiv.)Fn::host_await(op, args) + HostAwaitBridgeHostAwait — see host-await.md
reply to callerFn::send_reply(req, tag, payload)uses msg_reply_cap
build messageFn::hop(req_id, tag, payload)scheduler stamps sender
unpack messageFn::hop_payload(msg) etc.std natives

§Message shape

BEAM messages are arbitrary terms. Byteflow Atomic Hop is a fixed envelope:

Message { sender, reply_cap, request_id, tag, payload }
  • payload is a nested Value (ABI v5) — scalars, Str / Bytes, or another hop.
  • sender is authenticated by the runtime on bytecode Send / Ask. make_msg has no sender operand (3-arg: request_id, tag, payload). A leftover 4-arg encoding is ignored — see samples::forged_sender_send.

§Typical server loop (BEAM-style)

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

const TAG_REQ: i32 = 1;
const TAG_REP: i32 = 2;

let mut program = Program::new("server");
let server = program.function("server", 0, |f| {
    let req = f.receive_match_imm(TAG_REQ as u16);
    let payload = f.hop_payload(req);
    f.add_imm(payload, 1);
    f.send_reply(req, TAG_REP, payload);
    f.exit(payload);
});
program.function("main", 0, |f| {
    let cap = f.spawn(server, 0);
    let n = f.load_i32(41);
    let req = f.hop_fresh(TAG_REQ, n);
    let reply = f.ask(cap, req);
    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(42))));

Sample helper (same shape): samples::server_loop.

§Lifecycle (mapped)

BEAM / OTPByteflow today
linksRuntime::link / Fn::link — abnormal exit kills the peer unless trap_exit
monitors {'DOWN', ...}Runtime::monitor / Fn::monitor → TAG_SYS_DOWN hop
OTP supervisor strategiesHost Supervisor + RestartStrategy (OneForOne / OneForAll / RestForOne)
register / whereisFn::register_name / Fn::whereis (and host Runtime::*). Cap, not FlowId
exit(Pid, Reason)Fn::exit_signal(cap, reason) (LINK required). Host Runtime::kill / admin_kill are the untrappable Killed path
process_flag(trap_exit, …)Fn::set_trap_exit / Runtime::set_trap_exit → TAG_SYS_EXIT hop (done)
capability passFn::delegate / Cap::attenuate (AND of rights + native mask)
confined spawnFn::spawn_confined (child rights NONE)
child_spec restartFn::set_restart_policy + host ChildSpec. Fn::start_child adds a sibling under the host supervisor that started this flow
process dictionaryFn::dict_put / dict_get / dict_erase — Int keys, scalar values only

§What BEAM has that Byteflow does not (yet)

BEAM / OTPByteflow today
distributionSingle node on purpose. The host owns I/O; Byteflow does not open sockets or speak EPMD
arbitrary term patternsTag, payload kind, Int equality (ReceiveMatchEq), and after. No guards, tuples, or maps
ETSNo
supervisor strategy in bytecodeStartChild (0x6F) only extends the host Supervisor that started the caller. OneForOne / OneForAll / RestForOne stay on that Rust supervisor

Failures without trap_exit / monitors surface as FlowOutcome::Failed on join, not as mailbox messages.

§Backpressure

PathMailbox full + Reject
Runtime::send(FlowId, …)Err(SendError::MailboxFull)
bytecode Send / Asksender parks (WAITING_SEND); one waiter per freed slot

§Host Rust vs bytecode

TaskWhere
spawn top-level flowsRuntime::spawn
trusted host sendRuntime::send(FlowId, Value::Message)
restart policySupervisor (Rust)
protocol in flowsProgram / Fn bytecode

The supervisor thread is host Rust (Supervisor / ChildSpec). A flow started that way may call Fn::start_child to add another child to the same supervisor (samples::supervised_tree). SetRestartPolicy still overrides that flow’s own restart decision at exit. A flow started with Runtime::spawn has no supervisor, so StartChild fails that flow.

§Quick equivalence cheat sheet

self()              →  hop_sender on received msg; self_address() for Cap
!                   →  send(cap, hop(...))
receive             →  receive() / receive_match_imm(TAG) / receive_match_kind(kind)
receive … after     →  receive_match_imm_timeout(TAG, ms) / receive_timeout(ms)
is_process_alive    →  is_alive(cap)
exit(Pid, Reason)   →  exit_signal(cap, reason)   // reason = FlowExitReason as Int
put/get/erase       →  dict_put / dict_get / dict_erase
start_child         →  start_child(fn, RestartPolicy)  // inside a supervised flow
actor loop          →  actor_loop(TAG, \|f, req\| { … })
cast                →  cast(cap, hop(...))   // alias of send
call                →  ask(cap, hop(...)) / ask_timeout(cap, hop, ms)
reply               →  send_reply(req, TAG_REP, payload)
spawn               →  spawn(fn) → Cap; spawn_confined(fn) → Cap with rights NONE
register/whereis    →  Fn::register_name / whereis (Cap reminted for caller); host Runtime::*; ChildSpec.name also registers
link/monitor        →  Fn::link / Fn::monitor (need LINK / MONITOR on the addressing Cap)
delegate            →  Fn::delegate(cap, rights) → weaker Cap
trap_exit           →  Fn::set_trap_exit / Runtime::set_trap_exit
restart policy      →  Fn::set_restart_policy / ChildSpec.restart

§Further reading