Skip to main content

Crate logicaffeine_system

Crate logicaffeine_system 

Source
Expand description

§logicaffeine-system

The runtime library where LOGOS meets the outside world: console and clock, files and sockets, HTTP serving, peer-to-peer networking, persisted CRDTs, and the post-quantum cryptography primitives. Where logicaffeine_data keeps values pure and WASM-safe, this crate owns the effects: the console, clocks, files and sockets that a program’s Show, file read or Sync bottoms out in, natively or in a browser. The default build is lean: networking, persistence, parallelism and the HTTP server are Cargo features, off until you ask for them.

Part of the Logicaffeine workspace, tier 2. The module list below marks what is native-only, wasm32-only, or feature-gated.

§Role in the workspace

This is the runtime library linked into compiled LOGOS programs (via logicaffeine-compile) and shared with the interpreter and the web app. A program’s Show, file access, Spawn, Sync/Connect, and persisted-CRDT verbs all bottom out in these primitives. The same surface compiles on native and wasm32 behind platform seams (get_platform_vfs() for files, net::Net for networking), so generated code is written once and runs on both. concurrency.md covers networking and distributed state.

§Public API

Always available (native and wasm32):

  • failure: where a runtime failure ends. caught(f) runs f as a boundary that catches a panic it raises — a served request answering 500, a replay task failing alone — and is_caught() tells a generated program’s failure hook whether a boundary will catch this one or the program ends with exit status 1. Every place the runtime catches a panic goes through it.
  • io: console and stream IO (show, print, println, eprintln, read_line) and the Showable trait behind the LOGOS Show verb. Primitives print unquoted, collections as [..], maps as {..}, None as nothing, CRDTs as their logical value, and a Duration human-formatted.
  • obs: the observation channel for compiled (AOT-Rust) programs. In the observed profile, Note/Warn/Record/During emit events into a thread-local buffer that a host sink drains, separate from program output. It is a no-op when no sink is installed, and the elided release profile never calls it.
  • temporal: the temporal values of logicaffeine_data::temporal re-exported (LogosDate, days since epoch with Hinnant to_ymd; LogosMoment, nanoseconds; LogosTime; LogosSpan, months and days kept incommensurable), beside current_moment(), the instant the system clock reads, and the Showable printing of each.
  • testworld: the sealed test world behind largo test, a thread-local that intercepts the IO natives with simulated resources (a virtual clock frozen at a synthetic epoch, an in-memory filesystem, an empty environment, a per-test seeded RNG). A test is a pure function of (program, seed), and capability grants opt individual resources back to reality under --live.
  • csrf: the page half of CSRF protection. with_csrf_meta puts a visitor’s token in a page document’s head as <meta name="csrf-token"> (CSRF_META_NAME), where the browser host reads it and sends it back as x-csrf-token on the page’s state-changing requests. The dev server, a compiled server and the in-process host share this one definition.
  • relay_proto: the RelayFrame WebSocket wire protocol (Subscribe/Unsubscribe/Publish/SubAck/Event), serde and bincode only, shared verbatim by the native and browser relay clients.
  • addr: multiaddr_to_ws_url normalizes a libp2p multiaddr (or a raw ws:///wss:// address) to the URL the relay dials. Pure string logic, no libp2p.
  • time and random: now() (ms since epoch; js_sys::Date on wasm32) and sleep(ms) (a no-op on wasm32, which cannot block its thread); randomInt(min, max) and randomFloat() (a thread-local RNG, seeded from getrandom’s js backend on wasm32). Every execution tier’s now/randomInt/randomFloat natives route through these two, and both honour the sealed test world.
  • net (wherever a relay client exists): Net, the cross-target relay handle the interpreter holds, with connect/subscribe/publish/drain over the native tokio-tungstenite client or the browser web-sys socket. Messages are drained, not awaited, so Sync stays a sync point.

Native-only (cfg(not(target_arch = "wasm32")), no feature needed):

  • env: get(key), args().
  • stack: run_main(main), the stack a compiled program’s Main runs on: MAIN_STACK_BYTES (64 MiB) mapped between two guard pages and switched to on the thread that started the program, so deep recursion has its room and the process stays single-threaded (a second thread, even one only waiting, puts every malloc and free on the C library’s locked path). A run past the end of the stack writes out what the program had shown, reports Stack overflow: maximum call depth exceeded, the sentence every tier reports for it, and ends with exit status 1. A target the switch does not support runs Main on a thread of its own.
  • text: parseInt, parseFloat, chr (camelCase to match the codegen builtins).
  • tcp: the synchronous TCP client natives behind the stdlib tcp.lg (tcpConnect/tcpSend/tcpRecvExact/tcpListen/tcpAccept, and the rest) that the AOT execution tier calls through map_native_function, plus one shared set of error-message formatters every tier reuses so their Err text cannot drift. TLS rides the same handles: connect_tls opens a rustls client connection verified against the webpki-roots store, upgrade_tls upgrades an open connection in place (STARTTLS), and LOGOS_TLS_EXTRA_ROOT names a PEM file of extra trusted roots.

Feature-gated:

  • file (persistence): synchronous read/write returning Result<_, String>, for callers that do not need the async VFS.
  • fs (persistence): the async Vfs trait (read/write/append/exists/remove/rename/create_dir_all/list_dir) with VfsError/VfsResult/DirEntry. Backends: NativeVfs (tokio::fs, sandboxed paths, atomic write-then-rename), UringVfs (a Linux io_uring worker), and on wasm32 OpfsVfs/WorkerOpfsVfs/IndexedDbVfs behind a WebVfs enum (OPFS with an IndexedDB fallback). get_platform_vfs() selects the best backend per target.
  • storage (persistence): Persistent<T>, journal-based, crash-resilient CRDT storage (mount/get/mutate/compact/entry_count/maybe_compact) over an append-only WAL replayed entry by entry on mount.
  • relay (relay, native): the thin WebSocket relay server and client. serve is a pure browser-to-browser hub, and serve_bridged cross-forwards the libp2p gossipsub mesh, so a browser dialing a native node joins the real mesh. No libp2p reaches the browser.
  • relay_browser (wasm32): RelayBrowserClient, a web-sys WebSocket speaking relay_proto, the browser’s door into a native node’s relay.
  • relay::RelayHub (relay): the relay without a listener of its own, for embedding in another server’s accept loop. Its upgrades() table registers /_relay, the path every LOGOS page dials for Publish, message handlers and shared on stores, on largo serve and on a compiled backend’s Serve.
  • http (http, native): the HTTP/1.1 server a LOGOS Serve statement runs on; the program does the routing, and this crate serves the connections.
    • wire is a hand-rolled parser and writer (no hyper) with the client-side mirror.
    • server is the tokio accept loop (serve, spawn, serve_with_upgrades, serve_with_statics), including RFC 6455 upgrade dispatch (try_upgrade).
    • engine picks between that loop and a Linux thread-per-core io_uring engine (engine_uring, behind io-uring) by LOGOS_HTTP_ENGINE (shards: LOGOS_HTTP_SHARDS). It defaults to io_uring wherever a ring initializes and announces the choice on stderr.
    • lifecycle is the production state machine the compiled server and largo serve share. It provides graceful drain, readiness separate from liveness (LOGOS_READY_PATH/LOGOS_HEALTH_PATH), bounded backpressure that sheds with 503 (LOGOS_MAX_INFLIGHT), a per-request time budget (LOGOS_REQUEST_TIMEOUT_MS), body and read-deadline caps, and a correlation id on every response (X-Correlation-Id). Setting a lifecycle knob the io_uring engine cannot enforce (the request budget, the in-flight cap, a probe path, or LOGOS_CORRELATION_ID) serves on tokio instead, and says so.
  • network (networking): libp2p peer-to-peer networking with listen/connect/send, local_peer_id, PeerAgent, MeshNode, GossipSub gossip_publish/gossip_subscribe, mDNS discovery and NetworkError, plus FileSipper chunked transfer (FileManifest/FileChunk/DEFAULT_CHUNK_SIZE).
  • crdt (networking): Synced<T>, an auto-replicated (ephemeral) CRDT wrapper.
  • concurrency (concurrency): spawn/TaskHandle, Go-like bounded Pipe channels, and seeded_pick/deterministic_replay_enabled for replayable scheduling.
  • memory (concurrency): Zone, region-based allocation with bulk deallocation. A zone is a bumpalo heap arena or, with persistence also on, a read-only memory-mapped file; values allocated in a zone borrow from it and cannot outlive it, so the whole region frees at once.
  • replay (concurrency): the executor a deterministic Rust build (compile_to_rust_deterministic) runs its tasks on: run/run_seeded, spawn/Task, Pipe (open/send/recv/try_send/try_recv/close), sleep, and select/ready_arms/Arm. It is a port of logicaffeine_runtime’s scheduler, since a compiled program never links the runtime, and it draws every choice from one seeded chooser, so a binary run at LOGOS_SEED=s prints what the interpreter prints at seed s.
  • distributed (networking + persistence): Distributed<T>, the bridge between the mesh and the journal. Local mutations go RAM → journal → network, remote updates go network → RAM → journal, and the journal compacts itself once it passes a fixed entry count.

§Post-quantum cryptography and runtime primitives

Always available (native and wasm32, no feature needed). These are the native routines behind crypto.lg’s ## To native functions (ML-KEM’s NTT, sampling and serialization; the ML-KEM and ML-DSA primitives), which every execution tier reaches through logicaffeine_compile’s native-function table (semantics::native_kernels). They are also the primitives of the post-quantum channel handshake:

  • keccak: Keccak-f[1600] and the FIPS-202 sponge (sha3_256/sha3_512/shake128/shake256, multi-block squeeze), the hash and XOF layer everything below rides on.
  • ntt: the ML-KEM (Kyber) negacyclic NTT, a verified scalar reference plus an AVX2 i16×16 path, with the byte-encode/decode, compression and CBD samplers (mlkem_ntt/mlkem_inv_ntt/mlkem_base_mul/mlkem_byte_encode and the rest) re-exported at the crate root.
  • mlkem: ML-KEM-768 (FIPS-203) keygen, encapsulation and decapsulation, the post-quantum key exchange for the channel handshake, composed from the NTT and Keccak primitives. encaps and decaps apply FIPS 203 §7’s input checks (the encapsulation key’s length and modulus check, the ciphertext’s and decapsulation key’s lengths, the decapsulation key’s hash check) and return KemError for whatever fails one; decapsulation always derives both K′ and K̄ and chooses between them by a mask over a full-length compare.
  • mldsa: ML-DSA-65 (FIPS-204, Dilithium) keygen, sign and verify, the post-quantum signature complement to ML-KEM. sign returns SignError where FIPS 204 returns ⊥: a context longer than 255 bytes, a secret key of the wrong length, or one with an s₁ or s₂ coefficient outside [−η, η]. sign_randomized is the hedged variant, and verify answers false for every malformed input.
  • aead: ChaCha20-Poly1305 (RFC 8439), the symmetric seal that closes the post-quantum channel once the shared secret is established.
  • word_rt: runtime support for the Word8/Word16/Word32/Word64 ring types in compiled LOGOS (word32, rotl, and the Showable glue), the execution-side complement to logicaffeine_base::word.

Every LOGOS-facing function among them answers Result<_, String>. It refuses an argument that breaks its contract (an item that is not a byte, a seed or key of the wrong length, a coefficient outside its range, a width outside FIPS 203’s) with the reason, which every tier reports after the kernel’s name, and never folds the argument into one it was not given. The arithmetic on secret coefficients divides by no modulus: Barrett multiplies and masked corrections stand in for / and %, so no target compiles a variable-time divide into it.

The crate root re-exports the io/temporal items and the keccak/ntt functions, plus tokio and tokio_rustls (native), and adds panic_with(reason) and a fmt helper module.

§Feature flags

The default feature set is empty: no networking, no persistence, no parallelism.

FeatureDefaultEnables
relayoffThe thin WebSocket relay (relay, and net on native) via tokio-tungstenite and futures; no libp2p
httpoffThe native HTTP/1.1 Serve server (http) over tokio’s net; no hyper
networkingofflibp2p peer-to-peer networking (network, crdt); implies relay
persistenceofffile, fs (VFS) and storage, pulling in memmap2 and sha2
concurrencyoffconcurrency, memory and replay, pulling in bumpalo
io-uringoffUringVfs and the io_uring HTTP engine (Linux only) via io-uring, crossbeam-channel and libc; implies persistence
fulloffnetworking + persistence + concurrency + http (io-uring stays opt-in)
distributedoffDistributed<T>, as networking + persistence

docs.rs documents with full.

§Dependencies

Internal: logicaffeine-base, logicaffeine-data.

Always-on external: indexmap, serde, bincode, async-trait, once_cell, async-lock, crc32fast. Native targets also pull tokio, rustls, webpki-roots, tokio-rustls, rand, getrandom and uuid; unix targets pull psm and libc (stack); wasm32 targets pull wasm-bindgen(-futures), js-sys, web-sys, futures, rand, and getrandom (js).

Feature-gated external: libp2p (networking), tokio-tungstenite and futures (relay), memmap2 and sha2 (persistence), bumpalo (concurrency), io-uring and crossbeam-channel (io-uring, Linux).

§License

MIT License — see LICENSE.md.


Docs index · Root README · Changelog

Re-exports§

pub use io::eprintln;
pub use io::print;
pub use io::println;
pub use io::read_line;
pub use io::show;
pub use io::Showable;
pub use keccak::sha3_256;
pub use keccak::sha3_512;
pub use keccak::shake128;
pub use keccak::shake256;
pub use ntt::mlkem_base_mul;
pub use ntt::mlkem_byte_decode;
pub use ntt::mlkem_byte_encode;
pub use ntt::mlkem_cbd2;
pub use ntt::mlkem_cbd3;
pub use ntt::mlkem_compress;
pub use ntt::mlkem_decompress;
pub use ntt::mlkem_inv_ntt;
pub use ntt::mlkem_ntt;
pub use ntt::mlkem_sample_a;
pub use ntt::mlkem_sample_ntt;
pub use ntt::mlkem_to_mont;
pub use word_rt::and_not4;
pub use word_rt::byte_add16;
pub use word_rt::hsum_lanes4;
pub use word_rt::int_of_word16;
pub use word_rt::int_of_word32;
pub use word_rt::int_of_word64;
pub use word_rt::int_of_word8;
pub use word_rt::interleave_hi16;
pub use word_rt::interleave_lo16;
pub use word_rt::lanes16_word16;
pub use word_rt::lanes16_word8;
pub use word_rt::lanes4_of;
pub use word_rt::lanes4_word32;
pub use word_rt::lanes4_word64;
pub use word_rt::lanes8_word32;
pub use word_rt::maddubs16;
pub use word_rt::montmul32;
pub use word_rt::mul32x32to64;
pub use word_rt::mulhi16;
pub use word_rt::packus16;
pub use word_rt::rotl;
pub use word_rt::rotr;
pub use word_rt::seq_of_lanes16;
pub use word_rt::seq_of_lanes16w8;
pub use word_rt::seq_of_lanes4;
pub use word_rt::seq_of_lanes4w32;
pub use word_rt::seq_of_lanes8;
pub use word_rt::sha1msg1;
pub use word_rt::sha1msg2;
pub use word_rt::sha1nexte;
pub use word_rt::sha1rnds4;
pub use word_rt::shr_bytes16;
pub use word_rt::shuffle16;
pub use word_rt::splat16_word16;
pub use word_rt::splat16_word8;
pub use word_rt::splat4_word64;
pub use word_rt::splat8_word32;
pub use word_rt::word16;
pub use word_rt::word32;
pub use word_rt::word32_shr;
pub use word_rt::word64;
pub use word_rt::word64_and;
pub use word_rt::word64_shl;
pub use word_rt::word64_shr;
pub use word_rt::word8;
pub use word_rt::word_and;
pub use word_rt::word_not;
pub use word_rt::word_or;
pub use word_rt::WordRotate;
pub use tokio;
pub use tokio_rustls;

Modules§

addr
Address normalization — libp2p multiaddr → WebSocket URL.
aead
ChaCha20-Poly1305 AEAD (RFC 8439) — the symmetric seal that closes the post-quantum channel: an ML-KEM-768 handshake establishes the shared secret, HKDF derives this 32-byte key, and every wire message is sealed here. ChaCha20 is a pure Word32 ARX cipher (the same primitive the assets/std/crypto.lg chacha20Block ships in Logos); Poly1305 is the one-time authenticator in constant-time 5×26-bit limbs (no bignum). Verified against the RFC 8439 §2.4.2 / §2.5.2 / §2.8.2 known-answer vectors. The tag compare is constant-time.
csrf
The page half of CSRF: a page document carries its visitor’s token in its head, where the browser host reads it and sends it back as x-csrf-token on the page’s state-changing requests to its own server. One definition for every tier that composes or reads a page — the dev server, a compiled server, the in-process host and the browser runtime’s shared name.
env
Environment Variable and Argument Access
failure
Where a failure ends: the program, or the boundary that catches it.
file
Simple File I/O Operations
fmt
Formatting utilities
fs
Virtual File System Abstraction
http
A native HTTP/1.1 server — the runtime a LOGOS program’s Serve statement executes on.
io
I/O Operations for LOGOS Programs
keccak
Keccak-f[1600] + SHA-3 / SHAKE runtime kernels — the symmetric/hash layer ML-KEM is built on (SHA3-256/512 for hashing, SHAKE128 for matrix expansion, SHAKE256 for the PRF). Reached from compiled LOGOS via the sha3_256 / sha3_512 / shake128 / shake256 stdlib functions. Verified against the NIST FIPS-202 KATs (see the tests). Input/output are LOGOS Int bytes (0..255) carried in a Seq of Int.
mldsa
ML-DSA-65 (FIPS-204 / Dilithium) runtime kernels — the post-quantum SIGNATURE scheme that complements ML-KEM-768 in the channel. This module builds bottom-up: the length-256 NTT over the Dilithium prime q = 8380417 (a COMPLETE transform, unlike Kyber’s incomplete one — q ≡ 1 (mod 512), so X²⁵⁶+1 splits fully), with signed Montgomery reduction. Validated against the schoolbook negacyclic convolution.
mlkem
ML-KEM-768 (FIPS-203) keygen / encapsulation / decapsulation as a Rust composition of the verified native kernels in crate::ntt (NTT, base-multiply, CBD, compress, byte-encode, 4-way AVX2 matrix expansion) and crate::keccak (SHA3-256/512, SHAKE256). This is the exact same primitive set the assets/std/crypto.lg Logos ML-KEM orchestrates and that the logicaffeine-tests AOT gates prove bit-exact vs the FIPS-203 reference — here orchestrated in Rust so the post-quantum channel (logicaffeine_compile::concurrency::channel) can run the handshake. Coefficients ride the fast Word16 carrier throughout.
net
Net — the cross-target relay-backed network handle the interpreter holds.
ntt
ML-KEM (Kyber) negacyclic NTT runtime kernel — the verified scalar reference + AVX2 i16×16 path that compiled LOGOS reaches through the mlkemNtt stdlib function. Ported from the validated scripts/dev/ntt_simd_proto.rs (round-trip + AVX2==scalar bit-identical). q = 3329, R = 2¹⁶, the incomplete 7-level transform over ℤ_q[X]/(X²⁵⁶+1). The Montgomery reduction it uses is kernel-certified (logicaffeine_kernel::field_algebra::montgomery_reduction_*).
obs
The observation channel for COMPILED (AOT-Rust) programs — Wave 13.
random
Random Number Generation
relay
Thin WebSocket relay — the v1 browser↔mesh bridge.
relay_proto
The relay wire protocol — shared verbatim by the native server/client (super::relay) and the browser client (super::relay_browser). Both targets serialize the SAME RelayFrame with bincode, so a browser tab and a native node speak an identical language across the WebSocket.
stack
The stack a compiled program’s Main runs on.
storage
Persistent Storage with Journaling
tcp
TCP client natives (tcp.lg): the SYNC implementations the AOT tier calls via map_native_function, plus the shared error-message formatters every tier reuses — one wording, so the tiers cannot drift even in their Err text.
temporal
Temporal types for Logicaffeine. The date, moment, time-of-day and calendar span values are logicaffeine-data’s (logicaffeine_data::temporal), where every value model reaches them, re-exported here beside what only a system has: the clock, and how Show prints them.
testworld
The sealed test world.
text
time
Time Utilities
word_rt
Runtime support for the Word8/Word16/Word32/Word64 ring types in COMPILED LOGOS.

Structs§

Lanes4Word32
Four lanes of Word32 = one 128-bit register (__m128i) — the SHA-1 state/message carrier. Unlike the arithmetic lane types, its vocabulary is the four Intel SHA operations (sha1rnds4/sha1msg1/ sha1msg2/sha1nexte), so SHA-1 WRITTEN in Logos over these compiles to the sha1rnds4 hardware sequence (AOT) and runs the byte-identical software spec crate::sha_ops on the interpreter. Lane i is bits [32i+31 : 32i] — index 0 low, index 3 high — matching _mm_loadu_si128.
Lanes4Word64
Four lanes of Word64 (one 256-bit SIMD register) — the Poly1305 accumulator lane vector. Carries [u64; 4]; ops have an AVX2 fast path proven byte-identical to the scalar lanes.
Lanes8Word32
Eight lanes of Word32 (one 256-bit SIMD register). Operations are lane-wise over the ℤ/2³² ring.
Lanes16Word8
Sixteen Word8 lanes = one 128-bit register (__m128i) — the BYTE-SHUFFLE carrier for SIMD text codecs (hex encode/decode). Its vocabulary is shuffle (pshufb, a 16-entry byte LUT), byte AND, per-byte shift, and the two byte interleaves — so a hex codec WRITTEN in Logos over it compiles to the pshufb sequence (AOT, when SSSE3 is statically enabled) and runs the byte-identical scalar spec on the interpreter. Lane i is byte i (index 0 low), matching _mm_loadu_si128.
Lanes16Word16
Sixteen lanes of Word16 (one 256-bit SIMD register) — the NTT coefficient lane vector. Carries [u16; 16]; the multiply-high is the SIGNED _mm256_mulhi_epi16 (the Montgomery butterfly’s mulhi). Ops have an AVX2 fast path proven byte-identical to the scalar lanes.
LogosDate
Date stored as days since Unix epoch (1970-01-01).
LogosMoment
Moment stored as nanoseconds since Unix epoch.
LogosSpan
Calendar span with separate month and day components.
LogosTime
Time-of-day stored as nanoseconds from midnight — the wall-clock face of a Moment, with no date or zone. Renders HH:MM:SS[.frac], lossless to the nanosecond (the AOT mirror of the interpreter’s Time).
Word8
A 8-bit wrapping integer: the ring ℤ/2^8ℤ, where every operation is total and wraps modulo 2^8.
Word16
A 16-bit wrapping integer: the ring ℤ/2^16ℤ, where every operation is total and wraps modulo 2^16.
Word32
A 32-bit wrapping integer: the ring ℤ/2^32ℤ, where every operation is total and wraps modulo 2^32.
Word64
A 64-bit wrapping integer: the ring ℤ/2^64ℤ, where every operation is total and wraps modulo 2^64.

Functions§

panic_with
Panic with a custom message (used by generated LOGOS code)