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)runsfas a boundary that catches a panic it raises — a served request answering500, a replay task failing alone — andis_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 theShowabletrait behind the LOGOSShowverb. Primitives print unquoted, collections as[..], maps as{..},Noneasnothing, CRDTs as their logical value, and aDurationhuman-formatted.obs: the observation channel for compiled (AOT-Rust) programs. In the observed profile,Note/Warn/Record/Duringemit 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 oflogicaffeine_data::temporalre-exported (LogosDate, days since epoch with Hinnantto_ymd;LogosMoment, nanoseconds;LogosTime;LogosSpan, months and days kept incommensurable), besidecurrent_moment(), the instant the system clock reads, and theShowableprinting of each.testworld: the sealed test world behindlargo 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_metaputs 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 asx-csrf-tokenon the page’s state-changing requests. The dev server, a compiled server and the in-process host share this one definition.relay_proto: theRelayFrameWebSocket wire protocol (Subscribe/Unsubscribe/Publish/SubAck/Event), serde and bincode only, shared verbatim by the native and browser relay clients.addr:multiaddr_to_ws_urlnormalizes a libp2p multiaddr (or a rawws:///wss://address) to the URL the relay dials. Pure string logic, no libp2p.timeandrandom:now()(ms since epoch;js_sys::Dateon wasm32) andsleep(ms)(a no-op on wasm32, which cannot block its thread);randomInt(min, max)andrandomFloat()(a thread-local RNG, seeded fromgetrandom’sjsbackend on wasm32). Every execution tier’snow/randomInt/randomFloatnatives 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, withconnect/subscribe/publish/drainover the nativetokio-tungsteniteclient or the browserweb-syssocket. Messages are drained, not awaited, soSyncstays 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’sMainruns 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 everymallocandfreeon the C library’s locked path). A run past the end of the stack writes out what the program had shown, reportsStack 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 runsMainon a thread of its own.text:parseInt,parseFloat,chr(camelCase to match the codegen builtins).tcp: the synchronous TCP client natives behind the stdlibtcp.lg(tcpConnect/tcpSend/tcpRecvExact/tcpListen/tcpAccept, and the rest) that the AOT execution tier calls throughmap_native_function, plus one shared set of error-message formatters every tier reuses so theirErrtext cannot drift. TLS rides the same handles:connect_tlsopens a rustls client connection verified against thewebpki-rootsstore,upgrade_tlsupgrades an open connection in place (STARTTLS), andLOGOS_TLS_EXTRA_ROOTnames a PEM file of extra trusted roots.
Feature-gated:
file(persistence): synchronousread/writereturningResult<_, String>, for callers that do not need the async VFS.fs(persistence): the asyncVfstrait (read/write/append/exists/remove/rename/create_dir_all/list_dir) withVfsError/VfsResult/DirEntry. Backends:NativeVfs(tokio::fs, sandboxed paths, atomic write-then-rename),UringVfs(a Linux io_uring worker), and onwasm32OpfsVfs/WorkerOpfsVfs/IndexedDbVfsbehind aWebVfsenum (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.serveis a pure browser-to-browser hub, andserve_bridgedcross-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, aweb-sysWebSocket speakingrelay_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. Itsupgrades()table registers/_relay, the path every LOGOS page dials forPublish, message handlers andshared onstores, onlargo serveand on a compiled backend’sServe.http(http, native): the HTTP/1.1 server a LOGOSServestatement runs on; the program does the routing, and this crate serves the connections.wireis a hand-rolled parser and writer (no hyper) with the client-side mirror.serveris the tokio accept loop (serve,spawn,serve_with_upgrades,serve_with_statics), including RFC 6455 upgrade dispatch (try_upgrade).enginepicks between that loop and a Linux thread-per-core io_uring engine (engine_uring, behindio-uring) byLOGOS_HTTP_ENGINE(shards:LOGOS_HTTP_SHARDS). It defaults to io_uring wherever a ring initializes and announces the choice on stderr.lifecycleis the production state machine the compiled server andlargo serveshare. It provides graceful drain, readiness separate from liveness (LOGOS_READY_PATH/LOGOS_HEALTH_PATH), bounded backpressure that sheds with503(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, orLOGOS_CORRELATION_ID) serves on tokio instead, and says so.
network(networking): libp2p peer-to-peer networking withlisten/connect/send,local_peer_id,PeerAgent,MeshNode, GossipSubgossip_publish/gossip_subscribe, mDNS discovery andNetworkError, plusFileSipperchunked transfer (FileManifest/FileChunk/DEFAULT_CHUNK_SIZE).crdt(networking):Synced<T>, an auto-replicated (ephemeral) CRDT wrapper.concurrency(concurrency):spawn/TaskHandle, Go-like boundedPipechannels, andseeded_pick/deterministic_replay_enabledfor replayable scheduling.memory(concurrency):Zone, region-based allocation with bulk deallocation. A zone is a bumpalo heap arena or, withpersistencealso 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, andselect/ready_arms/Arm. It is a port oflogicaffeine_runtime’s scheduler, since a compiled program never links the runtime, and it draws every choice from one seeded chooser, so a binary run atLOGOS_SEED=sprints what the interpreter prints at seeds.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_encodeand 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.encapsanddecapsapply 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 returnKemErrorfor 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.signreturnsSignErrorwhere 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_randomizedis the hedged variant, andverifyanswers 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 theWord8/Word16/Word32/Word64ring types in compiled LOGOS (word32,rotl, and theShowableglue), the execution-side complement tologicaffeine_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.
| Feature | Default | Enables |
|---|---|---|
relay | off | The thin WebSocket relay (relay, and net on native) via tokio-tungstenite and futures; no libp2p |
http | off | The native HTTP/1.1 Serve server (http) over tokio’s net; no hyper |
networking | off | libp2p peer-to-peer networking (network, crdt); implies relay |
persistence | off | file, fs (VFS) and storage, pulling in memmap2 and sha2 |
concurrency | off | concurrency, memory and replay, pulling in bumpalo |
io-uring | off | UringVfs and the io_uring HTTP engine (Linux only) via io-uring, crossbeam-channel and libc; implies persistence |
full | off | networking + persistence + concurrency + http (io-uring stays opt-in) |
distributed | off | Distributed<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.
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
Word32ARX cipher (the same primitive theassets/std/crypto.lgchacha20Blockships 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-tokenon 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
Servestatement 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/shake256stdlib functions. Verified against the NIST FIPS-202 KATs (see the tests). Input/output are LOGOSIntbytes (0..255) carried in aSeq 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), soX²⁵⁶+1splits 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) andcrate::keccak(SHA3-256/512, SHAKE256). This is the exact same primitive set theassets/std/crypto.lgLogos ML-KEM orchestrates and that thelogicaffeine-testsAOT 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 fastWord16carrier 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
mlkemNttstdlib function. Ported from the validatedscripts/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 SAMERelayFramewithbincode, so a browser tab and a native node speak an identical language across the WebSocket. - stack
- The stack a compiled program’s
Mainruns 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 theirErrtext. - 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 howShowprints them. - testworld
- The sealed test world.
- text
- time
- Time Utilities
- word_rt
- Runtime support for the
Word8/Word16/Word32/Word64ring types in COMPILED LOGOS.
Structs§
- Lanes4
Word32 - 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 thesha1rnds4hardware sequence (AOT) and runs the byte-identical software speccrate::sha_opson the interpreter. Laneiis bits[32i+31 : 32i]— index 0 low, index 3 high — matching_mm_loadu_si128. - Lanes4
Word64 - 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. - Lanes8
Word32 - Eight lanes of
Word32(one 256-bit SIMD register). Operations are lane-wise over the ℤ/2³² ring. - Lanes16
Word8 - Sixteen
Word8lanes = one 128-bit register (__m128i) — the BYTE-SHUFFLE carrier for SIMD text codecs (hex encode/decode). Its vocabulary isshuffle(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 thepshufbsequence (AOT, when SSSE3 is statically enabled) and runs the byte-identical scalar spec on the interpreter. Laneiis bytei(index 0 low), matching_mm_loadu_si128. - Lanes16
Word16 - 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’smulhi). Ops have an AVX2 fast path proven byte-identical to the scalar lanes. - Logos
Date - Date stored as days since Unix epoch (1970-01-01).
- Logos
Moment - Moment stored as nanoseconds since Unix epoch.
- Logos
Span - Calendar span with separate month and day components.
- Logos
Time - Time-of-day stored as nanoseconds from midnight — the wall-clock face of a
Moment, with no date or zone. RendersHH:MM:SS[.frac], lossless to the nanosecond (the AOT mirror of the interpreter’sTime). - 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)