Skip to content

Latest commit

 

History

History
321 lines (258 loc) · 13.9 KB

cpp.md

File metadata and controls

321 lines (258 loc) · 13.9 KB

C++ binding

Two APIs: mpmc::queue in mpmc.h for the in-process queue, and mpmc::shm::channel in mpmc/shm.hpp for named shared-memory channels. Both are thin RAII wrappers over the C implementation.

Queue mpmc::queue, a bounded MPMC FIFO of std::uint64_t.
Channel mpmc::shm::channel with message and send_with for zero-copy I/O.
Install //bindings/cpp:mpmc_cpp, or tools/install.sh for the installed SDK.
Proof Lean checks the SC kernel core; CBMC checks selected C. The C++ wrapper is audited, not proved.

Overview

mpmc::queue owns one C queue handle. It is movable, non-copyable, and throws only for bad construction. push/pop are noexcept and non-blocking.

mpmc::shm::channel owns one C channel handle. message owns one received token and releases it on destruction or through release(). send_with owns the reserve/publish/cancel sequence, so the C ticket type is not exposed.

The queue wrapper stays in mpmc.h for source compatibility with code that already includes the C header.

Requirements and installation

Bazel builds the repository. For an installed SDK:

tools/install.sh "$PWD/stage"

//bindings/cpp:mpmc_cpp publishes mpmc/shm.hpp and depends on the compiled C queue. Queue-only code can depend on //bindings/c:mpmc.

Bazel consumption modes

Compiled (recommended). Depend on //bindings/cpp:mpmc_cpp, or on //bindings/c:mpmc for the queue. MPMC_LINKED is transitive, and no consumer-side -mcx16 is needed.

cc_binary(
    name = "app",
    srcs = ["app.cpp"],
    deps = ["//bindings/cpp:mpmc_cpp"],
)

Header-only queue. Depend on //bindings/c:mpmc_header_only and add copts = ["-mcx16"] on x86-64. The implementation is compiled into your translation unit. //bindings/c:mpmc_header is the compiled alias.

The installed pkg-config and CMake packages use header-only mode and carry -mcx16 on x86-64. Define MPMC_LINKED and link the installed library to use the compiled C ABI.

Toolchain and flags

  • Includes: -Ibindings/c/include -Ibindings/cpp/include, or installed -I<prefix>/include / pkg-config --cflags mpmc.
  • Link: -lmpmc and -pthread on POSIX.
  • x86-64: a CX16-capable CPU; direct header-only builds need -mcx16. Linux may need -latomic.
  • Linux arm64: Clang only for shared memory. LSE and baseline builds are supported; GCC arm64 is not.
  • macOS: arm64 with Apple Clang. Windows, 32-bit, and big-endian are unsupported.

Quick start

Queue:

#include "mpmc.h"
#include <cstdint>

int main() {
  mpmc::queue q(1024);
  q.push(1);
  q.push(2);
  std::uint64_t value = 0;
  while (q.pop(value)) { /* 1, then 2 */ }
}

Channel:

#include "mpmc/shm.hpp"

int main() {
  auto ch = mpmc::shm::channel::connect(
      "demo", {64, 256, mpmc::shm::peers::same_uid});
  ch.try_send("hello", 5);

  mpmc::shm::message msg;
  if (ch.try_recv(msg) != mpmc::shm::status::ok) return 1;
  // msg.data() has msg.size() bytes, valid until msg is released or destroyed.
}

msg is destroyed before ch, so it returns its slot before the channel closes.

Queue API

Member Signature
constructor/destructor explicit queue(std::uint64_t capacity); ~queue()
move queue(queue&&) noexcept; queue& operator=(queue&&) noexcept
copy deleted
push bool push(std::uint64_t value) noexcept
pop bool pop(std::uint64_t& value) noexcept

Capacity must be a power of two in [2, 2^24]. Construction allocates 384 + 128 * capacity bytes and touches every slot. It throws std::invalid_argument for a bad capacity and std::runtime_error when allocation fails or the target lacks lock-free 16-byte atomics.

push returns false when full or at the publication horizon. pop returns false when empty and leaves value untouched. Both are non-blocking, noexcept, and never allocate or lock; they are not wait-free. Successful pushes are totally ordered.

Destruction requires quiescence. Moving is noexcept and leaves the source empty; a moved-from queue returns false from push and pop. Self-move assignment leaves the object usable.

Shared-memory API

mpmc/shm.hpp calls the compiled C implementation. It adds no C++ object to shared memory and no hot-path allocation.

Member Behavior
channel::connect(name, config) Create or attach; throws mpmc::shm::error.
channel::remove(name) Retire the name; returns a status.
channel::remove_if_generation(name, generation) Retire only the given generation; mismatch leaves a replacement untouched.
atomic_backend_class() Observe the compiled 16-byte atomic backend after the runtime CPU gate.
channel::recover(name) Recover a pre-prefix creator death.
capacity(), slot_size(), generation() Geometry and 128-bit nonce.
try_send(data, len) / try_send(string_view) Copy once; returns a status.
send_with(fn) Reserve, call fn(buffer, capacity), publish the returned length.
try_recv(message&) Receive in publication order; invalid if out already owns a message.
message::release() Consume the token; return the C status. Invalidates the message and its views even on failure.
message::requeue() Consume the token and append the same descriptor as a new publication event; no payload copy.

config is aggregate-initialized as {slots, slot_size, peers}. Slots are a power of two in [2, 2^24], slot size is [1, 1 GiB], and the mapping is at most 64 GiB by default. peers::same_uid is required; peers::none returns trust_not_declared.

connect validates the name before C. A name that is empty, over 200 bytes, or contains NUL throws invalid_name; C also rejects / and the exact names . and ... error::code() returns the status and error::what() returns strerror(code).

message is movable and non-copyable. valid() reports whether it owns a token; size() and data() describe the payload. data() is non-NULL for a valid message, including zero length. release() consumes the token, returns the C status, and invalidates the message and every view even when recycling fails. A failed release leaks that slot for the generation, so a caller that must detect the failure has to fail the run. Destruction releases exactly once but discards the status, so it cannot report a failed recycle. A failed try_recv leaves out untouched.

Recycle failures are observable differently by binding. C releases explicitly and returns a status. C# exposes the same failure through ReceiveSession.Release(), whose ShmReceiveResult reports Cleanup and CleanupStatus; the one-shot TryReceive reports cleanup the same way, and ShmChannel.RecycleFailures counts failed native recycles. Rust returns a release status from Message::release() and counts failures observed by release() or Drop in Channel::recycle_failures().

send_with writes only up to the provided capacity, may see stale initialized bytes, and publishes the returned length.

  • Zero is a valid length.
  • A callback exception cancels and rethrows.
  • A length above capacity cancels and throws std::length_error.
  • A reserve failure returns a status without invoking the callback.

The callback must not close, move, move-assign, or destroy the channel. The reservation stays bound to the original handle. The buffer is valid only during the callback; do not retain it.

Fluent consumers (C++20)

mpmc/shm_fluent.hpp is an additive C++20 consumer façade. It is a separate header and Bazel target (//bindings/cpp:mpmc_cpp_fluent); the installed CMake package exposes mpmc::mpmc_fluent. C++17 code is unaffected.

#include "mpmc/shm_fluent.hpp"

namespace fluent = mpmc::shm::fluent;

auto ch = fluent::channel::connect(
    "orders", {1024, 64, mpmc::shm::peers::same_uid});

auto result = ch.consume()
    .keep_if_length_at_least(2)
    .take(10)
    .try_for_each_borrowed([](fluent::borrow_ref &payload) {
      consume(payload.at(0));
      return fluent::flow::next;
    });
auto disposition = ch.consume()
    .keep_if_length_at_least(2)
    .take(10)
    .timeout(std::chrono::milliseconds(250))
    .for_each_disposition([](fluent::disposition_borrow &payload) {
      return handle(payload) ? fluent::disposition::ack
                             : fluent::disposition::requeue;
    });

for_each_disposition/try_for_each_disposition add Ack, AckAndStop, and Requeue. disposition_borrow has the same read surface as borrow_ref but deliberately no pin() and no conversion to borrow_ref. A successful requeue stops with drain_status::requeued; a failed requeue stops with cleanup_failure and a separate requeue_status. Requeue is a cooperative retry, not crash recovery or exactly-once. deadline and timeout are cooperative attempt-boundary deadlines; they never preempt an action. drain_result gained trailing requeues/requeue_status fields; positional aggregate initialization with the old field count still compiles, but structured bindings that name every old field and the result object layout changed. Recompile C++ consumers.

borrow_ref never returns a payload pointer, span, iterator, or element reference. A borrow_ref is confined to its callback thread: concurrent use of one borrow from multiple threads is unsupported. It provides bounds-checked scalar access, FNV-1a hash, IEEE CRC-32, find/starts_with/compare, and checked fixed-width loads. keep_if_* conditions are destructive: rejected messages are released for every consumer. take counts matches; attempt_budget bounds scans. A fluent::stop_source creates a copyable fluent::stop_token that owns its shared state, so a token cannot dangle; stop_token/stop_when are checked between attempts. pin() transfers the token to a move-only pinned_borrow for explicit retention; failed or fork-abandoned dispositions are counted in channel::recycle_failures().

The C++ type system cannot reject a stored &borrow_ref or reference to it; using one after the callback is undefined behavior. The supported API returns no payload address, and pin() is the supported retention mechanism. See the fluent design and cooperative disposition for the exact claim and residual risks.

Lifetime and concurrency

  • mpmc::queue may be shared by any number of threads for push/pop; destruction requires quiescence. Moving or destroying the wrapper must not race another thread.
  • mpmc::shm adds no thread-safety beyond the C handle. Each message is single-threaded.
  • A message borrows its channel; the channel must outlive every message. Move construction keeps that handle, but no operation may race a move. A send_with callback must not move the wrapper. Move assignment into or destruction of the channel before the message is released is not allowed. No operation may race destruction even when no message is outstanding.
  • A send_with buffer is valid only during the callback; do not retain it.
  • release() invalidates data() and every view, including when recycling fails. A failed release is a run failure, not a retryable receive state.
  • Close-with-live-message aborts in every build. An atomic counter detects it; it does not make concurrent destruction safe. C instead allows abandoning the token and leaking the slot.
  • A moved-from channel returns invalid from operations; getters return zero, and generation() is {0,0}. A moved-from message is invalid and releases nothing.
  • After a multithreaded fork, the child must exec or _exit. A single-threaded child may close the inherited handle and connect again.

Errors and limits

The queue constructor throws std::invalid_argument or std::runtime_error; push and pop never throw. Shared-memory calls return status, except connect, which throws mpmc::shm::error, and send_with, which throws std::length_error for an oversized result and propagates callback exceptions.

Status Meaning
ok, empty, no_buffer Success; no message now; no free slot now (retryable).
too_large, exhausted Payload too large; horizon reached (unreachable in practice).
removed, not_found Retirement observed; no object for the name.
corrupt, mismatch, version_mismatch Inconsistent state; different identity; incompatible ABI.
forked, unsupported Inherited across fork; atomic backend unavailable.
invalid, invalid_name, invalid_config, trust_not_declared Bad argument, name, geometry, or undeclared trust.
permission, name_collision Wrong owner or mode; name collision during creation (not proof of another scope).
timeout, busy, io, no_space Lock timeout; holder busy; I/O failure; store full.

Limits match the C API: queue capacity [2, 2^24]; channel slots [2, 2^24]; slot size [1, 1 GiB]; names 1..200 bytes. There is no blocking send or receive and no size, peek, clear, or replace. A live consumer may requeue explicitly, but a dead consumer leaks its received slot; a killed process can leak capacity or lose an in-flight message. Under the peer contract it must not corrupt a cell or leave the queue unusable; that behavior is tested, not proved.

Examples

Six C++ examples are Bazel cc_test targets:

bazel test -c opt //examples/cpp/... --test_output=errors

See 01_job_queue for the queue, 03_ping_pong for two-process channels, 04_zero_copy for send_with, and 06_large_object for a streamed 4/8 GiB object. Shared-memory examples are tagged no-sandbox.

Verification boundary

Lean checks an SC model of the queue kernel and a shared-memory layout/ownership model. It does not prove the C or C++ source, the C printer, atomic lowering, weak memory, POSIX lifecycle, or progress. The live-message counter catches one misuse in tests but is not a proof. Do not describe either API as verified. See the verification boundary.