Segment layout¶
This page is the full contract for how a box and a stream are stored in
shared memory: the names of the objects, every byte of the mapping, and the
steps every process follows to read, write, send, receive and wait. You
need it if you write code that opens a box without sharedbox.hpp, or if
you change sharedbox itself;
to understand the ideas first, read
How a box is stored.
include/sharedbox/core.hpp, include/sharedbox/box.hpp and
include/sharedbox/stream.hpp implement this contract, and the Python
extension runs on the first two.
It describes core version 1.0, box layout 3.3 and stream layout 1.5. It
also opens box layout 3.0 and stream layout 1.0, which sharedbox 0.6.0
writes, box layout 3.1 and stream layout 1.1, which 0.7.0 writes, box
layout 3.2 and stream layout 1.4, which 0.8.0 writes, and nothing older:
box layouts 1.0 and 2.0, which 0.5 and earlier wrote, are refused.
Goal¶
C++ and C code can use a sharedbox box, both as an extension loaded in a Python process and as a standalone program with no Python, without linking a library that sharedbox ships. The layout and protocols below are versioned, and a header-only C++20 library implements them.
Decisions¶
| Topic | Decision | Not taken |
|---|---|---|
| Model | the Arrow PyCapsule Interface; the closest analogue is ArrowArrayStream, a live handle rather than a one-shot transfer |
numpy's __array_struct__ |
| Scope | every segment starts with the same first line; the box and the stream are the kinds implemented, and the stream is C++ only; the handle struct is versioned so that streams can get their own dunder later | streams in the same step |
| Contract | a documented memory layout plus a header-only reference implementation | a compiled C library; definitions only |
| Language | the C++20 headers core.hpp and box.hpp, which sharedbox.hpp includes, namespace sharedbox |
a C99 header with static inline functions |
| Atomics | std::atomic_ref on plain integer fields |
wrappers over compiler intrinsics; C11 <stdatomic.h> |
| C interface | a minimal sharedbox_c.h, whose functions call sharedbox.hpp, in one .cpp file the consumer compiles |
a static library in the wheel; a C implementation of the protocols |
| Dunder and capsule | __sharedbox_box__, capsule "sharedbox_box" |
_c_ in the name, which reads as "implemented in C" |
| Negotiation | DLPack's max_version; the consumer renames the capsule "used_sharedbox_box"; other keywords raise NotImplementedError, as in Arrow |
none |
| Object names | SBX: + box name + suffix, for every object |
the bare box name; names stored in the header |
| Windows scope | Local\ only |
Global\ (see Out of scope) |
| Versioning | the core version and the box layout each have a major that refuses and a minor that opens and ignores what it does not know | exact match; flag masks |
| Capsule lifetime | the handle maps the segment again from the box's OS handle | sharing the box's mapping and keeping the box alive |
| Schema identity | identity= class keyword, default module.qualname; it enters the schema hash and names the box; handle::create is available to other languages |
the Python module path written into other languages; open-only for other languages |
| Distribution | headers in the wheel, sharedbox.get_include() and a CMake config |
a vcpkg port or a headers-only wheel |
Names¶
Every OS object of a box is named from the box name:
| Object | Linux | Windows |
|---|---|---|
| mapping | shm_open("/SBX:<name>"), seen as /dev/shm/SBX:<name> |
CreateFileMappingW(INVALID_HANDLE_VALUE, ..., L"Local\\SBX:<name>") |
| wake word | inside the mapping, no name | not used |
waiter slot i |
inside the mapping, no name | auto-reset event Local\SBX:<name>#w<i> |
- A name is one or more segments of
[A-Za-z0-9_-]joined by:, such asoffice-3:sorting:letters, up to 240 characters. A segment is never empty, so a name neither starts nor ends with:and has no::..is reserved for a latername.fieldaddress, and#for the waiter event suffix. Every function that takes a name returnsstatus::rangefor one that breaks these rules. The longest Windows object name,Local\SBX:(10 characters), a 240-character name and#w4095(6), is 256 characters, under the 260-character limit on object names. On Linux the file nameSBX:plus the name is 244 bytes, under the 255 ofNAME_MAX. - The default name of a class is 16 hex digits of SHA-256 over its identity
(see Schema identity). Without an
identity=keyword the identity ismodule.qualname, with__mp_main__counted as__main__. - Linux: the mapping is created with
O_CREAT | O_EXCL | O_RDWRand mode0600; a name that exists givesstatus::exists.unlink()callsshm_unlink. - Windows: the mapping is backed by the page file.
CreateFileMappingWreportingERROR_ALREADY_EXISTSmeans the name is taken: the creator closes its handle and givesstatus::exists.ERROR_INVALID_HANDLE, an object of another kind under the name, givesstatus::existstoo.unlink()does nothing; the OS frees the mapping with its last handle.
Layout¶
The first 64 bytes of every segment, whatever its kind, are the common line: the same fields at the same offsets, so a process can tell what it has found before it knows how to read it. A box then adds a second line and the rest of its mapping. The mapping holds, from offset 0:
offset 0 common line 64 bytes, one cache line (every kind)
offset 64 box line 64 bytes, one cache line
offset 128 field table field_count x 8 bytes
write counts field_count x 8 bytes
waiter slots waiter_slots x 32 bytes
description table types_size bytes, 8-aligned
(zero padding up to a multiple of 64)
record record record_size bytes, 64-byte aligned
(zero padding up to a multiple of 64)
metadata metadata area metadata_size bytes; only when metadata is not 0
(zero padding up to a multiple of 4096)
No structure has implicit padding: gaps are explicit pad and reserved
members, and static_asserts in core.hpp and box.hpp pin each
structure's sizeof, alignof and every offsetof, and that it is
standard-layout and trivially copyable.
struct common_header { // sharedbox::common_header, 64 bytes
uint64_t magic; // 0 one per kind; written last, with release ordering
uint16_t core_major; // 8
uint16_t core_minor; // 10
uint16_t kind_major; // 12 the layout version of this kind
uint16_t kind_minor; // 14
uint64_t schema_hash; // 16
uint64_t create_id; // 24 random at create, never 0
uint64_t creator_start; // 32 creator's start time, see Liveness
uint64_t creator_pidns; // 40 creator's pid namespace; 0 on Windows
uint32_t creator_pid; // 48
uint16_t waiter_slots; // 52 1 to 4096
uint16_t reserved0; // 54 zero
uint64_t size; // 56 mapping size in bytes
};
struct header { // sharedbox::header, 128 bytes
common_header common; // 0
// line 1: the words writes and waits change, then geometry written once
uint64_t seq; // 64 sequence lock: even when free, odd while writing
uint32_t writer_pid; // 72 holder of the write lock, 0 if none
uint32_t wake_word; // 76 futex word (Linux)
uint32_t waiters; // 80 occupied waiter slots
uint32_t sleepers; // 84 threads inside a wait on this box
uint16_t field_count; // 88 1 to 256
uint16_t reserved1; // 90 zero
uint32_t record_size; // 92
uint32_t record; // 96 offset of the record
uint32_t tail; // 100 offset of the field table, always 128
uint32_t types_size; // 104 bytes of the description table
uint32_t metadata_size; // 108 bytes of the metadata area, 0 for none
uint64_t metadata; // 112 offset of the metadata area, 0 for none
uint64_t metadata_head; // 120 the newest metadata version, 0 for none
};
The common line is written once at creation. Line 1 starts with the words
that writes and waits change (seq, writer_pid, wake_word, waiters,
sleepers), so a write touches one header line, then holds geometry
written once at creation, bytes 88 to 119, and ends with metadata_head,
which each added metadata version changes. Attach copies the common line
and bytes 88 to 119, never the changing words, and uses only the copy.
Box layout 3.2 uses the last spare bytes of line 1 for the metadata fields, so
only the two bytes of reserved1 are left. A reader accepts a mapping larger
than its geometry needs (see Attach), which lets a later minor version add
after the metadata area. There is one header per box, and readers and writers
touch only line 1. The waiter slots, not the header, are the large part of the
tail, and max_waiters sizes them. Worked example, a box with an int, a
float and a bool and the default 64 waiter slots: header 128, field table
24, write counts 24, waiter slots 2048, padding 16, record 24 (the Python side
rounds a record up to a multiple of 8): 2264 bytes used, one 4 KiB page. A box
with three fields and 64 slots stays in one page up to about 1.8 KB of record
(4096 - 2240 = 1856).
- Versions: bytes 8 to 11 are
01 00 00 00(core 1.0:core_major1,core_minor0) and bytes 12 to 15 are03 00 03 00(box layout 3.3:kind_major3,kind_minor3). The two versions count the segment format and are not tied to the package version. - Magic:
SBX_BOX_for a box andSBX_STRMfor a stream, each read as a little-endianu64. The magic names the kind, so attach checks it first. A box opens only a box, and a stream only a stream (see Stream layout). - Field table entry, 8 bytes:
u32 offset,u32 capacity_and_kind: top 8 bits the kind code. For kinds below 64 the low 24 bits are the size or capacity; for kinds 64 and up they are the offset of the field's description in the table. - Offsets are the creator's choice. The Python side packs fields by descending alignment; another creator may pack differently. Attachers read offsets from the field table and never compute them, so a box created elsewhere with its own packing reads correctly from Python as long as the field order, names, kinds and capacities match, which the schema hash checks.
- Write counts: one
u64per field, incremented under the write lock. - Metadata: a box created without a metadata area has
metadataandmetadata_size0. Otherwisemetadatais the first multiple of 64 at or after the end of the record,metadata + metadata_sizeis at most 2^32 - 4096, and the area is laid out as Metadata describes. - Waiter slot, 32 bytes:
struct waiter_slot { // sharedbox::waiter_slot
uint64_t owner_start; // 0 process start time, see Liveness
uint64_t owner_pidns; // 8 pid namespace, see Liveness; 0 on Windows
uint32_t owner_pid; // 16 0 = free
uint32_t interrupt; // 20 set by interrupt(), cleared by the waiter
uint32_t asleep_on; // 24 offset of the count the current wait added 1 to; 0 = none
uint32_t reserved; // 28 0
};
- A
reffield refers to another box, which keeps its own segment. Its capacity is always 256:
struct box_ref { // sharedbox::box_ref
uint64_t create_id; // 0 the box's create_id; 0 = empty
uint64_t schema_hash; // 8 the box's schema_hash
char name[240]; // 16 its name, NUL-padded; ends at the first NUL or at 240
};
An empty reference is 256 zero bytes. A non-empty one always has a
nonzero create_id, since create never draws 0. It is written under the
referring box's sequence lock like any other field. A reader that
attaches the named box compares its create_id with the stored one to
tell it from a box created again under the same name.
Kind codes¶
| code | kind | entry's low 24 bits | size, alignment |
|---|---|---|---|
| 0 | bool | 1 | 1, 1 |
| 1 | int | 8 | 8, 8 |
| 2 | float | 8 | 8, 8 |
| 3 | str | capacity | 4 + capacity, 4 |
| 4 | bytes | capacity | 4 + capacity, 4 |
| 5 | ref | 256 | 256, 8 |
| 6 | complex | 16 | 16, 8 |
| 7 | date | 4 | 4, 4 |
| 8 | time | 16 | 16, 8 |
| 9 | datetime | 16 | 16, 8 |
| 10 | timedelta | 12 | 12, 4 |
| 11 | uuid | 16 | 16, 1 |
| 12 | decimal | capacity | 4 + capacity, 4 |
| 13 | int8 | 1 | 1, 1 |
| 14 | int16 | 2 | 2, 2 |
| 15 | int32 | 4 | 4, 4 |
| 16 | uint8 | 1 | 1, 1 |
| 17 | uint16 | 2 | 2, 2 |
| 18 | uint32 | 4 | 4, 4 |
| 19 | uint64 | 8 | 8, 8 |
| 20 | float16 | 2 | 2, 2 |
| 21 | float32 | 4 | 4, 4 |
| 22 | complex64 | 8 | 8, 4 |
| 23 | datetime64 | 8 | 8, 8 |
| 64 | enum | description offset | 2, 2 |
| 65 | flag | description offset | 8, 8 |
| 66 | literal | description offset | 2, 2 |
| 67 | optional | description offset | from the description |
| 68 | union | description offset | from the description |
| 69 | record | description offset | from the description |
| 70 | tuple | description offset | from the description |
| 71 | list | description offset | from the description |
| 72 | set | description offset | from the description |
| 73 | dict | description offset | from the description |
| 74 | array | description offset | data size, 64 |
| 75 | max_array | description offset | 64 + data size of the maximum shape, 64 |
| 76 | attr | description offset | from the description |
| 77 | timed | description offset | from the description |
A field of a kind the reader does not know is opened as opaque bytes: a
kind below 64 is sized by its entry, one from 64 by its description's
head. A member entry inside a description records no size, so a reader
refuses, with status::unsupported, a description that holds a kind it
does not know. Every described size is a multiple of its alignment.
Encodings¶
Little-endian.
bool: 1 byte,0x00or0x01.int: 8 bytes, signed.float: 8 bytes, IEEE 754 double.str,bytes:u32length, then up tocapacitybytes (UTF-8 forstr).ref: 256 bytes, asbox_refabove.complex: twof64, real then imaginary.date:i32date.toordinal(), 1 to 3652059.time:i64microseconds since midnight (wall time),i16UTC offset in minutes,u8flags (bit 0 naive, bit 1 fold), 5 reserved zero bytes.datetime:i64microseconds since 1970-01-01T00:00 (wall time if naive, UTC if aware),i16offset in minutes,u8flags astime, 5 reserved zero bytes.timedelta:i32days,i32seconds,i32microseconds.uuid:UUID.bytes, in network byte order.decimal:u32length, then the text ofstr(value).int8toint32: signed, two's complement, at their width;uint8touint64: unsigned, at their width.float16: IEEE 754 binary16;float32: IEEE 754 binary32.complex64: twof32, real then imaginary.datetime64:i64nanoseconds since 1970-01-01T00:00 UTC, with-2**63for NaT.enum,literal:u16position;flag:u64bits.optional: a presence byte, padding to the member's alignmentA, then the member; sizeround_up(A + member size, A).union: au8tag, padding to the largest member alignmentA, then the member; sizeround_up(A + largest member size, A).record,tuple: members at the offsets their entries give.list,set:u32length, padding tomax(4, A), thencapacityslots ofround_up(element size, element alignment)bytes, and padding that rounds the whole up to a multiple ofmax(4, A).dict: aslist, with a key and value pair as the slot: the key at 0, the value atround_up(key size, value alignment).array: the elements in C order.max_array: a 64-byte line holding thendimu64dimensions of the stored value, each from 0 to its maximum, then zero bytes; the elements follow at offset 64, packed in C order for the stored dimensions. The bytes after them, up to the room for the maximum shape, keep what an older item or write left there. A reader checks each dimension against its maximum before it copies any element. A dimension above it in a torn copy is retried like any torn copy; in a stable copy it makes the value corrupt.timed: the member at offset 0, then ani64timestamp in nanoseconds since 1970-01-01T00:00 UTC atround_up(member size, 8); sizeround_up(round_up(member size, 8) + 8, A)withAthe larger of the member's alignment and 8. The timestamp-2**63is the mark a write replaces (see "The timestamp of a timed value").attr: up to three parts in this order, each present only when the description's flags (see Descriptions) and value typeTgive it.- The request part, with flag
request(4). From offset 0, the request lineu64 sent,u64 takenandu64 answered, then the server'su64 start,u64 pidns,u32 pidand 4 zero bytes, all 0 when none serves. The arguments follow from offset 48 in order, each at a multiple of its own alignment, and then, atanswers = round_up(end of the arguments, A_t), four answer entries ofstridebytes. An entry isu64 number,u32 status(0 empty, 1 answered, 2 failed),u32 lengthof the error text, the error text in 256 bytes of UTF-8, and the result, aT, atresult_at = round_up(272, alignment of T), or no result whenTis absent.A_tis the larger of 8 and the alignment ofT(8 with noT),stride = round_up(result_at + size of T, A_t), and the part ends atanswers + 4 * stride. "The request protocol" says how the steps use these bytes. - The value part, when
Tis present, atvalue_at = round_up(end of the request part, A_t), which is 0 without a request part: au64 published, the number ofattr_publishsteps since creation, which starts at 0; thenTatround_up(value_at + 8, alignment of T); then, with flagtimed(1), ani64timestamp in nanoseconds since 1970-01-01T00:00 UTC atround_up(size of T, 8)afterT. - The setpoint, with flag
settable(2), aTatsetpoint_at = round_up(end of the value part, alignment of T).
The field's alignment A is the largest of 8, A_t and, with a request
part, every argument's alignment, and its size is the end of the last
part rounded up to A. An attr with a value of int takes 16 bytes
with no other part, 24 when timed, 1192 with a request part taking one
int, and 1208 with all three parts; one with a request part only takes
1136 bytes. A step of the request protocol leaves the value part as it was;
attr_publish leaves the request part as it was.
Descriptions¶
The description table follows the waiter slots. Each description is an
8-byte head, u8 kind, u8 flags (zero, except for an attr),
u16 count, u32 size, a body, and zero padding to a multiple of 8. An
entry inside a body has the shape of a field table entry, with the offset
counted from the start of the value. A name is a u16 length, then UTF-8.
| kind | count | body |
|---|---|---|
| enum | 1 to 65535 | count member names |
| flag | 1 to 64 | count members: a name, then u64 bits |
| literal | 1 to 65535 | count values: a u8 tag, then 0 None (nothing), 1 bool (u8), 2 int (i64), 3 str (a name), 4 bytes (u32 length, then bytes), 5 enum member (a name) |
| optional | 1 | one entry |
| union | 2 to 255 | count entries; member i has tag i |
| record | 1 to 256 | count entries, then count member names |
| tuple | 1 to 256 | count entries |
| list, set | 1 | u32 capacity, then the element's entry |
| dict | 2 | u32 capacity, then the key's entry and the value's |
| array | 0 | u8 DLPack code, u8 bits, u16 lanes (1), u8 ndim (1 to 8), 3 zero bytes, then ndim u64 dimensions |
| max_array | 0 | as array, the dimensions being the maximum ones |
| timed | 1 | one entry, at offset 0 |
| attr | value + arguments, 1 to 256 | u16 argument count, 6 zero bytes, then the entry of T if there is one, then the arguments' entries, all with offsets from the field's start. The flags byte holds 1 for timed, 2 for settable and 4 for a request part; the Python side sets the timed flag on every attribute with a value. |
Attach copies the table and checks it before using it: every description
is 8-aligned, inside the table, read once, after its parent and apart from
every other; nesting is at most 16 deep; counts are in the ranges above;
members lie inside their parent, aligned and apart; every size the
description implies is computed without overflow and matches the head; an
array's code is one of 0, 1, 2, 4, 5, 6, its bits a multiple of 8 and every
dimension at least 1. A failure refuses the segment. A reference may only
be a field, and an array only a field, a record or tuple member, or the
member of an optional or a timed. A max_array may only be a box field
or a stream's item, or the member of a record, tuple or timed reached
from one through records, tuples and timed values alone; a max_array
under any other kind is refused. A timed may go wherever a record may.
An attr may only be a box field, never a stream's item or a member, and
its T and arguments may not be or hold a timed, an attr or a
reference. A reader recomputes every offset and the size from the encoding
above and refuses a description that differs, and refuses with
status::corrupt:
- a flag other than the three above;
- settable without a request part, or settable with anything but one
argument whose type is
T; - timed or settable when
Tis absent; - arguments without a request part;
- an
attrwith neither aTnor a request part, or whose head count is not the argument count plus 0 or 1; - a nonzero byte among the 6 after the argument count.
A nonzero flags byte on any other kind is refused too.
Decoding checks¶
A stable sequence number shows a copy is consistent, not that it holds a
value Python can have. Readers check presence bytes and bool (0 or 1),
reserved flag bits (0), union tags and enum and literal positions (below
their count), lengths (at most the capacity), date ordinals (1 to
3652059), times (below a day), offsets (within 1439 minutes either way)
and timedeltas (within Python's range), and treat a failure as a corrupt
value.
Only a bool inside a described kind has to be 0 or 1. A bool field
(kind 0) whose byte is not 0 reads as True.
Writing a max_array box field¶
The bytes written for a max_array box field are its shape line and the
elements that line counts, no more, so a box write of a small array
copies only that array. A writer that sends any other length, or a line
with a dimension above its maximum, gets status::range and the field
keeps its value. A max_array inside a record, a tuple or a timed is
written with the whole value around it, at the size of its maximum.
The timestamp of a timed value¶
A writer that wants the time of the write in a timed value stores the mark
-2**63 as its timestamp. A box write replaces every mark in the values it
stores with the system clock in nanoseconds since the Unix epoch, read once
after the write takes the lock, so all the marks of one write get one time
and, unless the system clock is set back, the stamps follow the order of the
writes. Create stamps the initial
values the same way before it stores the magic, and a stream sender stamps
an item before it publishes its slot. A C or C++ writer may store the mark
or a time of its own. Since the mark is replaced, a timestamp of -2**63
cannot be stored, and no reader finds one in a value it reads.
The request protocol¶
An attr field with a request part carries requests from any process to the
one process that serves the field, and carries the answers back. Each step
that changes the field runs under the box's write lock, as a write does (see
Sequence lock), so it moves the generation and the field's write count and
wakes the waiters, and every existing wait notices it. A step that finds
nothing to change gives the lock back with seq and the write count as they
were and wakes nobody, because otherwise an idle server and the process
watching it would wake each other forever. The steps, with the handle
function of each:
- Send (
request_send) adds 1 tosent, stores the arguments and returnssentas the request's number. Numbers start at 1, and no two callers get the same one. - Take (
request_take) returns 0 whentakenequalssent, since no request is waiting. Otherwise it copies the arguments, setstakentosentand returns that number, which leaves every request below it that was never taken superseded. - Answer (
request_answer) runs after the server's handler, which runs without the lock. It writes the answer to requesttakeninto entryanswered % 4and adds 1 toanswered: status 1 with the result, or status 2 with an error text of at most 256 bytes. An answer to any other request, or to one already answered, writes nothing and givesstatus::ended, so a handler that finishes after its server left changes nothing. - Claim (
serve_claim) records the serving process'sstart,pidnsandpid(see Liveness). While the recorded process runs, a claim givesstatus::busy, including a second claim by that same process. When the recorded process has exited, the claim replaces it and first writes the failed answer "the server exited" to the request it took and never answered. - Release (
serve_release) clears the identity when it names the releasing process, and writes the failed answer "the server stopped" to a request that process took and never answered. A release by any other process changes nothing.
A caller learns what became of its request n through request_answer_of,
which reads without the lock: it copies the request line, the identity and
the four entries and retries on seq, as a read does. It then decides in
this order:
- an entry numbered
nholds the answer, or its error text; nof 0 or abovesentisstatus::range;nabovetakenand belowsentis superseded: a later send replaced it and no server took it, so none ever will;- any other
nat or abovetakenis still pending, or, when the caller asks for the server check,server_exitedonce a recorded server's process has ended; - when all four entries hold numbers above
n, four later answers overwrote its answer; - otherwise a later request superseded it before the server took it.
The answers form a ring of four because a single entry would let a fast
handler overwrite an answer before a caller woken late had read it. The
ring is indexed by answered rather than by request number, so the entries
stay in the order they were written and an answer is overwritten only by
four later ones, which only a caller that stalls through four whole handler
runs sees.
Writing a list, set or dict¶
The bytes written for a list, set or dict field are its length and the slots it uses, shorter than the field when it is not full; a reader copies the same part.
A writer fills each slot of a set or dict with zero bytes before it
encodes the element or item there, so the bytes after a str's length,
under an absent optional and in padding are zero. A reader that finds an
element or key by comparing slot bytes, as BoundedSet and BoundedDict
do, relies on this and does not clear them, so an element or key another
writer stores with nonzero bytes there is not found.
Schema identity¶
The schema is the list of fields that fixes a record's shape: names, kinds, capacities and their order. The schema hash shows that a creator and an attacher agree on it and on the class's meaning.
- Hash text: the identity, then one
name:kind:capacityper field in declaration order (base class fields first), joined with|, encoded as UTF-8. Kinds are the wordsbool,int,float,str,bytes; capacity is the payload size in bytes (8 forintandfloat, 1 forbool). Areffield enters asname:ref:<identity>, orname:ref?:<identity>when it may be empty (annotatedX | None), with the identity of the class it refers to in place of the capacity. -
A field of a kind from 6 on enters as
name:<type text>. The type text of each kind, withTfor the type text of a member:complex,date,time,datetime,timedelta,uuidand the kinds 13 to 23 (int8todatetime64): the kind name alone.bool:1,int:8andfloat:8are the texts of those kinds inside a described type.numpy.int64,numpy.float64,numpy.complex128andnumpy.bool_have the bytes of kinds 1, 2, 6 and 0, so they enter asint:8,float:8,complexandbool:1, as the Python types do.str:n,bytes:nanddecimal:n:nis the capacity in bytes. Abytearrayisbytes:n.enum(A,B): the member names in definition order.flag(R=1,W=2): each member name with its value.literal(v,...): each value in order asNone,TrueorFalse,int:1,str:'x'(the Pythonrepr),bytes:b'x'ormember:NAMEfor an enum member.optional(T), andunion(T,...)with the members in the order stored.record(name:T,...)for a dataclass,NamedTuple,TypedDict, attrs class ormsgspec.Struct, with the members in order. ATypedDictkey that may be missing enters asname?:optional(T).tuple(T,...)for a fixed-length tuple.list[n](T),set[n](T)anddict[n](K,V):nis the capacity in elements. Afrozensetis aset;tuple[T, ...]is alist.array(dtype,d1xd2x...), as inarray(float32,2x3).max_array(dtype,d1xd2x...)with the maximum dimensions, as inmax_array(uint16,2048x2048).attr(F;T;A,...)withFthe flags that are set, amongtimed,settableandrequestin that order, joined by,,Tthe value's text ornone, andA,...the argument texts in order, as inattr(timed,request;float:8;int:8).
-
schema_hash: the first 8 bytes of SHA-256 over that text, read as a little-endianu64. - Identity: the
identity=class keyword, a non-empty string without|, the character that separates the parts of the schema text; without it,module.qualname. A subclass does not inherit its base's identity. - The default box name is 16 hex digits of SHA-256 over the identity, so a
class that sets
identity=is found by that identity from any package or language, with no explicit name. - A set identity lets another language agree with Python on a string both
sides write down, rather than on a Python module path. Moving or renaming
the Python class then keeps the hash, two packages can each declare a
matching class and share a box, and changing the identity (
"mailbox/2") refuses processes of the old meaning when no field changed (a change of units, for instance). sharedbox.hppdoes not carry SHA-256; C and C++ callers compute the hash with their own library.- Test vector:
__main__.Mailbox|letters:int:8|flag_up:bool:1|owner:str:32
schema_hash = 0x8538759c8a4421cd
default name = e0c7ece8401e643a (16 hex digits of SHA-256 over "__main__.Mailbox")
__main__.Carrier|label:str:4|stop:ref:mailbox/1
schema_hash = 0xd7d5cb9582628433
__main__.Carrier|label:str:4|stop:ref?:mailbox/1
schema_hash = 0xbc2d9647a100ee6b
demo/1|when:date|mode:enum(RED,BLUE)|tags:list[2](str:4)|note:optional(int:8)
schema_hash = 0x2a9e5c5cc2876a4c
scale/1|grams:uint16|reading:float32|raw:int:8|left_at:datetime64|parts:list[4](int8)
schema_hash = 0x3c1107337e5bf226
The demo/1 line is a class with identity="demo/1" and the fields
when: date, mode: Color (members RED and BLUE),
tags: Annotated[list[Annotated[str, Capacity(4)]], Capacity(2)] and
note: int | None. The scale/1 line is a class with
identity="scale/1" and the fields grams: np.uint16,
reading: np.float32, raw: np.int64, left_at: np.datetime64 and
parts: Annotated[list[np.int8], Capacity(4)].
Stream layout¶
A stream is a ring of capacity slots, at least 2, that one sender writes
and up to max_readers readers (1 to 4095) copy out of. Its common line
holds the magic SBX_STRM (0x4D5254535F584253), kind_major 1 and
kind_minor 5 (stream layout 1.5), and a waiter_slots of
max_readers + 1, one slot for each reader and one for the sender. Every
size and offset is 64-bit, so a ring may pass 4 GiB; the slots end at or
below 2^46 bytes. The mapping holds, from offset 0:
offset 0 common line 64 bytes (every kind)
offset 64 line 1 written once at creation
offset 128 line 2 the sender's words
offset 192 line 3 the readers' words
offset 256 reader table max_readers x 64 bytes
waiter slots (max_readers + 1) x 32 bytes
(zero padding up to a multiple of 64)
slots slots capacity x slot_size bytes
types description table types_size bytes
(zero padding up to a multiple of 64)
metadata metadata area metadata_size bytes; only when metadata is not 0
(zero padding up to a multiple of 4096)
struct stream_header { // sharedbox::stream_header, 256 bytes
common_header common; // 0
// line 1: written once at creation
uint64_t capacity; // 64 slots in the ring, at least 2
uint64_t slot_size; // 72 bytes per slot, a multiple of 64
uint64_t readers; // 80 offset of the reader table, always 256
uint64_t slots; // 88 offset of the first slot
uint64_t types; // 96 offset of the description table
uint32_t types_size; // 104 bytes of the description table
uint32_t item_entry; // 108 the item's capacity_and_kind
uint32_t max_readers; // 112 1 to 4095
uint32_t metadata_size; // 116 bytes of the metadata area, 0 for none
uint64_t metadata; // 120 offset of the metadata area, 0 for none
// line 2: the sender's words
uint64_t write_pos; // 128 items sent; the next send's position
uint64_t sender_start; // 136 start time of the sender's process
uint64_t sender_pidns; // 144 its pid namespace; 0 on Windows
uint32_t sender_pid; // 152 0 = no sender
uint32_t state; // 156 0 open, 1 ended
uint32_t data_word; // 160 readers sleep on it (Linux)
uint32_t readers_epoch; // 164 changed when a reader joins, leaves or is freed
uint32_t space_waiting; // 168 sender threads asleep on space_word
uint8_t reserved3a[4]; // 172 zero
uint64_t release_floor; // 176 marked lossless readers below it do not block
uint64_t metadata_head; // 184 the newest metadata version, 0 for none
// line 3: the readers' words
uint32_t space_word; // 192 the sender sleeps on it (Linux)
uint32_t lossless_readers; // 196 open lossless readers
uint32_t data_waiting; // 200 reader threads asleep on data_word
uint32_t waiters; // 204 claimed waiter slots
uint8_t reserved4[48]; // 208 zero
};
struct reader_entry { // sharedbox::reader_entry, 64 bytes
uint64_t position; // 0 the next position this reader reads
uint64_t owner_start; // 8 process start time, see Liveness
uint64_t owner_pidns; // 16 pid namespace; 0 on Windows
uint32_t owner_pid; // 24 0 = free
uint32_t mode; // 28 0 until the entry has a position, 1 lossless, 2 lossy, 3 latest
uint64_t release_mark; // 32 owner_start of a reader that can be released
uint32_t release_pid; // 40 owner_pid of a reader that can be released
uint8_t reserved[20]; // 44 zero
};
waitersand the waiter slots are the core's; see Waiter slots. A waiter slot's index is not tied to a reader entry's index.release_flooris a position, 0 until a sender first releases a reader. Only the sender stores it, and it only grows. A lossless reader whose entry is marked and whosepositionis below it does not hold the sender back; see Send and receive.- An entry is marked while its
release_markequals itsowner_startand itsrelease_pidequals itsowner_pid. A reader of stream layout 1.3 stores its own start time and pid there when it joins; a reader of an older layout never writes the two fields, so an entry it takes over keeps another process's start and pid and is not marked, even when the two processes started at the same time. The sender never releases a reader whose entry is not marked. - Slot
istarts atslots + i * slot_size. It holds an 8-byteseqat its start and the item atmax(8, item alignment), so an item aligned to 64 bytes (an array, or a record holding one) starts 64 bytes in.slot_sizeis the end of the item rounded up to a multiple of 64. - The item is the bytes of one value in the encodings above, a length prefix
included, described by
item_entry(acapacity_and_kindword, as a field table entry has) and the description table. An item of a kind this build does not know is refused. - The item's
seqfor positionpis2p + 1while the sender writes it and2p + 2once it is published. 0 means the slot was never written. Positionplives in slotp % capacity. - Open copies lines 0 and 1, checks only that copy and uses it; lines 2
and 3 change while the stream is open. It checks the common line as for
every kind, with
kind_major1. It then requires every offset to be the one the shape gives: the reader table at 256, the waiter slots right after it, the slots at the next multiple of 64, and the description table right after the slots. Without a metadata area,metadataandmetadata_sizeare 0 and the mapping is at least the description table's end rounded up to 4 KiB. With one,metadatais a multiple of 64 at or after the description table's end,metadata_sizeis at least 64, and the mapping is at least the area's end rounded up to 4 KiB; the area is then checked as Metadata describes. A larger mapping is accepted, so a later minor version can add after the area.capacitymust be at least 2,max_readers1 to 4095,waiter_slotsmax_readers + 1,slot_sizea multiple of 64, andtypes_sizea multiple of 8 and at most 16 MiB. A failed check isstatus::corrupt. Last, open parses the item type and requires thatslot_sizeis what the item needs. An item of a kind open does not know, or holding one, isstatus::unsupported.
Metadata¶
A box or a stream may have a metadata area, which holds numbered versions of one document each. Three header fields describe it:
| field | box | stream | written |
|---|---|---|---|
metadata_size (u32), the area's size in bytes |
offset 108 | offset 116 | once, at creation |
metadata (u64), the area's offset, 0 for none |
offset 112 | offset 120 | once, at creation |
metadata_head (u64), the newest version, 0 for none |
offset 120 | offset 184 | by each add |
The area starts at the first multiple of 64 after the last part of the
segment, which is the record for a box and the description table for a
stream, and the mapping grows to cover it. A segment created without a
metadata area has metadata 0, metadata_size 0 and metadata_head 0,
so its bytes are those of box layout 3.1 or stream layout 1.3 apart from
kind_minor. The area holds, from metadata:
offset 0 first line 64 bytes, written once at creation
offset 64 version entries entries x 32 bytes
ring ring_size bytes, holding the documents
struct metadata_line { // sharedbox::detail::metadata_line, 64 bytes
uint32_t entries; // 0 version entries, 2 to 65535
uint32_t reserved0; // 4 zero
uint64_t ring_size; // 8 bytes of the ring, a multiple of 8, at least 24
uint64_t reserved1[6]; // 16 zero
};
struct metadata_entry { // sharedbox::detail::metadata_entry, 32 bytes
uint64_t seq; // 0 odd while written, 2v + 2 once it holds version v, 0 once reclaimed
uint64_t version; // 8 the version it holds
uint64_t position; // 16 where the version takes effect
uint32_t offset; // 24 start of the document in the ring
uint32_t length; // 28 bytes of the document
};
64 + entries * 32 + ring_sizeis at mostmetadata_sizeand at most 2^32 - 1, so every ring offset fits au32.- Versions count from 1, and version
vlives in entryv % entries. - A document starts at a multiple of 8 and is stored whole: right after the
end of the newest version's document, rounded up to a multiple of 8, or
at 0 when it would pass the end of the ring there. A document is at most
a third of
ring_size, rounded down to a multiple of 8, so a new document never overwrites the newest one, and with at least two entries the newest version's entry is never reused either. - A version's
positionis where it takes effect. On a stream it iswrite_poswhen the version was added, so the version applies from the next item sent; version 1 given at creation has position 0. On a box it is the generation (seq >> 1) that the write adding it leaves; version 1 given at creation has generation 0. - The Python side sizes the ring as
metadata_capacityrounded up to a multiple of 8 (65536 whenmetadatais given andmetadata_capacityis not), withmetadata_versionsentries, 64 by default. - Open copies the area's first line, checks the copy and uses only the
copy:
entries2 to 65535,ring_sizeat least 24 and a multiple of 8, and the sizes above. A failed check isstatus::corrupt. An entry'soffsetandlengthchange with each add, so a read checks them (see Add and read metadata).
Documents¶
A document is one value encoded as CBOR (RFC 8949), restricted to a subset that maps one to one onto the values the Python side accepts:
| Python | CBOR |
|---|---|
None |
simple value null (major type 7, 22) |
bool |
false and true (7, 20 and 21) |
int from -2^64 to 2^64 - 1 |
major types 0 and 1 |
float |
half, single or double float (7, 25 to 27), NaN and infinities included |
str |
text string (major type 3), valid UTF-8 |
bytes |
byte string (major type 2) |
list or tuple |
array (major type 4) |
mapping with str keys |
map (major type 5) whose keys are text strings, each key once |
Every length is definite, and nothing follows the value. Tags (major type
6), undefined, the other simple values, and nesting deeper than 32 arrays
and maps are outside the subset. sharedbox::metadata_ok checks that a
document is well formed and inside the subset, not that it is canonical,
so a C or C++ producer brings its own encoder. The Python side encodes
canonically, so equal values give equal bytes, and decodes a map as a
frozendict and an array as a tuple.
Versioning rules¶
A segment carries two versions in its common line: the core version, for what every kind shares (the common line, the object names, liveness), and the layout version of its kind, for the rest. Each has a major and a minor.
- A reader refuses a
core_majorit does not know: this version opens core major 1. It also refuses akind_majorits kind does not know: this version opens box layout major 3 and stream layout major 1, so it does not open segments written by 0.5 and earlier, whose magic it does not know. - A reader opens a segment whose
core_minororkind_minoris higher than its own, and ignores what it does not know. A handle reports the lower of the segment's box minor and its own. - A minor version may only add: fields in bytes that are reserved and zero in older minors, or features that stay off unless the segment says they are on and the reader knows them.
- That includes field kinds:
handle::openandhandle::from_capsuleaccept a field whose kind code they do not know. Its bytes are otherwise opaque, and the field must lie inside the record without overlapping another. A reader opens and reads a field of a kind it does not know; it never writes one, andwritereturnsstatus::rangefor it. The Python extension, which converts every field, refuses such a segment withSchemaMismatchError. - For an unknown kind below 64, the entry's low 24 bits are the field's
whole span in the record (1 byte to 1 MiB), so a future kind with a length
prefix counts the prefix in it, and no alignment is asked. For an unknown
kind from 64 on, the low 24 bits are the offset of its description, whose
head's
sizeis the span, and no alignment is asked either. - Box layout 3.0 has the description table and the kinds 6 to 12 and 64 to
- Box layout 3.1 and stream layout 1.1 add the kinds 13 to 23. A minor
version may add kinds: a reader of an older minor opens a top-level box
field of a kind it does not know as opaque bytes, and refuses, with
status::unsupported, a segment that uses one inside a described type or as a stream item. Readers from beforestatus::unsupportedexisted refuse it withstatus::corrupt. Box layout 3.1 and stream layout 1.1 also allow an array as the member of an optional, which a reader of box layout 3.0 or stream layout 1.0 refuses withstatus::corrupt. Stream layout 1.2 adds kind 75,max_array, which a reader of stream layout 1.1 or 1.0 refuses withstatus::corruptas a stream item or inside one. Stream layout 1.3 addsrelease_floor,release_markandrelease_pidfrom reserved bytes; a stream that an older version created keeps them at 0, so none of its readers is released until a sender of 1.3 raises the floor. - Box layout 3.2 and stream layout 1.4 add
metadata_size,metadataandmetadata_headfrom reserved bytes, and the metadata area after the record or the description table. A reader of an older minor ignores them. A box reader of 3.1 or older opens a box with a metadata area, since it accepts a mapping larger than its geometry needs. A stream reader of 1.3 or older requires the mapping to be exactly the size the stream's geometry gives, so it refuses a stream with a metadata area withstatus::corrupt, and opens a stream created without one. A segment that an older version created hasmetadata0: a reader of 3.2 or 1.4 finds no metadata in it, and an add givesstatus::metadata_full. - Box layout 3.3 allows kind 75,
max_array, as a box field and inside one. A reader of box layout 3.2 refuses a box that has such a field withstatus::corrupt. A reader of 3.1 or older opens a box whosemax_arrayis a field, as a field of a kind it does not know, and refuses one inside a record or tuple. Every older reader opens a box of 3.3 that has none. - Box layout 3.3 also adds kind 77,
timed, wherever a record may go. A reader of box layout 3.2 or older opens a box whosetimedis a field, as a field of a kind it does not know: its C++handlereads the bytes and refuses to write them withstatus::range, and its Python extension refuses the box withSchemaMismatchError. It refuses a box with atimedinside a described type withstatus::corrupt. - Box layout 3.3 also adds kind 76,
attr, as a box field. A reader of box layout 3.2 or older opens a box with anattrfield as one with a field of a kind it does not know: its C++handlereads the bytes and refuses to write them withstatus::range, and its Python extension refuses the box withSchemaMismatchError. - Stream layout 1.5 allows kind 77 in a stream's item. A reader of stream
layout 1.4 or older refuses a stream whose item is or holds a
timedwithstatus::corrupt, and opens one whose item holds none. - A change to how existing bytes are read or written raises a major: the
core's (the common line, the object names, liveness) raises
core_major, and a kind's own (the sequence lock, field encoding, the slot layout) raises itskind_major. - The package takes a semver major step whenever a major changes; before 1.0, a minor version step does.
Protocols¶
Every shared word is a plain integer in the mapping, accessed through
std::atomic_ref with the orderings given here.
Create¶
- Create the mapping (see Names) at its full size, rounded up to 4096.
On Linux the size is reserved with
posix_fallocate, retried onEINTR, so a/dev/shmtoo small for the box fails here with an OS error instead of a laterSIGBUS;ftruncateis the fallback where the file system does not support it. New pages read as zero on both platforms. - Write the field table, the creator fields and the rest of the common
line except
magic, then the box line's geometry.core_major,core_minor,kind_majorandkind_minorare the versions of this library.create_idcomes from the OS random source (getrandomon Linux, falling back to/dev/urandomwhere it is missing or refused;BCryptGenRandomon Windows) and is drawn again if 0. The creator fields are this process's pid, start time and pid namespace. Every waiter slot is free because the pages are zero. - Write the initial field values into the record. If the box has a metadata area, write its first line and zero entries and, with an initial document, add it as version 1 at generation 0 without taking the lock (see Add and read metadata).
- Store
magic(SBX_BOX_) with release ordering. Until then no attach succeeds.handle::createdoes this at once.handle::create_unpublishedstops before it, so the creator can write through its handle first (the Python layer runs__post_init__there), andhandle::publish()storesmagiclater, with a compare-exchange from 0; it returnsstatus::rangewhenmagicis already stored, which is always the case for a handle made byopenorfrom_capsule. - On a failure after step 1, remove the name (Linux) and close.
Attach¶
- Open the mapping by name and map all of it. Linux:
fstatgives the size, and a mapping smaller than one page is waited for, since its creator sizes it right after making the name. Windows:VirtualQueryon the view gives the size. - Wait for
magicwith acquire ordering, with backoff (spin, yield, then sleeps doubling up to 1 ms), up to the timeout. A mapping that never getsmagicisstatus::not_found. - Copy the common line and bytes 88 to 119 of the box line, leaving out
the words that writes, waits and metadata adds change, and check only
the copy.
Checks run in this order, and the first to fail decides the status:
- The magic is one this library knows, else
status::foreign: the segment was made by another version ofsharedboxor is not asharedboxsegment. - The magic is the one of a box, else
status::kind_mismatch: the name holds a segment of another kind. core_majoris 1, elsestatus::layout.kind_majoris 3, elsestatus::layout.sizeequals the mapping size andwaiter_slotsis in 1 to 4096, elsestatus::corrupt.- Every geometry field against the mapping size, before reading
through it: the mapping is at most 2^32 - 4096 bytes,
field_countis in range,tail == 128, the record is 64-byte aligned, after the waiter slots and inside the mapping, withrecord + record_sizeat most 2^32 - 4096, then the metadata area:metadataandmetadata_sizeboth 0, ormetadataa multiple of 64 at or after the record's end, withmetadata_sizeat least 64 and the area inside the mapping, then each field table entry (capacity 1 byte to 1 MiB, and the sizes of Kind codes for the fixed kinds, alignment for the known kinds, the field inside the record, no two fields overlapping), then the description table (Descriptions). A field of an unknown kind is opaque (Versioning rules), and a description holding one isstatus::unsupported. Any other failed check isstatus::corrupt. Forforeignandkind_mismatch, the error'sfoundholds the magic that was read. Forlayoutit holds both versions:core_major << 48 | core_minor << 32 | kind_major << 16 | kind_minor. Forunsupportedit holds the kind.
- The magic is one this library knows, else
- Copy the field table and use only the copy afterwards. If
metadatais not 0, copy the metadata area's first line, check it (see Metadata) and use only that copy too. - Free the waiter slots of dead processes (see Waiter slots).
handle::open does not compare schema hashes: the caller compares
schema_hash() with its own.
Sequence lock¶
- Read: load
seqwith acquire; if odd, back off and retry; copy the field and load its write count; an acquire fence; loadseqagain and retry if it moved. The count is read inside the same window, so a value and its version always match. - Write: compare-and-swap
seqfrom evenstos + 1(acquire), then a release fence; storewriter_pid; write the values; increment each written field's count; unlock; wake. - Unlock: if
seqstill equalss + 1, clearwriter_pid; then compare-and-swapseqfroms + 1tos + 2(release), and do nothing if the swap fails. A failed swap means aforce_unlock()released this writer's lock while it was still running, andseqmay now belong to a later writer's lock. A plain store ofs + 2would release that later writer's lock and moveseqbackwards. The check and the clear are two operations, so aforce_unlock()and a new writer's lock that both land between them leave the new writer'swriter_pidat 0; the lock is not affected, and only a laterLockTimeoutErrornames pid 0 instead of the holder. - Record write (
begin_record_write): the write's lock, held across any number of stores; each field it changed has its count incremented once, then unlock and wake. An aborted record write gives the lock back without counting and wakes nobody.seqstill becomess + 2, so the generation moves by one and a reader that copied bytes during the write retries; watchers compare write counts, so they report nothing. - Generation: there is no separate counter. Every write adds exactly 2 to
seq, so the generation isseq >> 1(generation()returns it). Aforce_unlock()that storesseq + 1counts as one generation, since the dead writer may have changed data. - A reader or writer gives up after the lock timeout with
status::lock_timeout. force_unlock(): ifseqis odd, compare-and-swap it toseq + 1;writer_pidstays as it was, as a record of who held the lock.
Waiter slots¶
waiter_slotsis set at creation: themax_waitersclass keyword, default 64, 1 to 4096.- Register: first free every slot whose owner is dead (Liveness). Claim a
slot with a compare-and-swap of
owner_pidfrom 0 to this process's pid, then incrementwaiters, clearinterrupt, storeowner_pidnsand lastowner_start(release). A slot with a nonzeroowner_starthas always been counted, so freeing it may decrementwaiters. A slot whoseowner_startis still 0 belongs to a claim in progress; if its pid is no longer running, the claimer died mid-claim and the slot is freed without a decrement. A claimer killed between its compare-and-swap and its increment therefore cannot pushwaitersbelow the true count; one killed after the increment leaves it one too high, which costs a system call on each wake and never loses one. No slot free givesstatus::no_slot. - Free a dead owner's slot: change
owner_startwith a compare-and-swap from the value read toUINT64_MAX - 1(thestart_freeingmarker), which is never a start time on Linux (clock ticks since boot) or Windows (FILETIME). Only the process whose compare-and-swap succeeds goes on, and every scan skips a slot holding the marker. It then checks thatowner_pidstill holds the pid it read; if not, it puts the oldowner_startback and leaves the slot to its new owner. Otherwise it decrementswaitersif the value it read was nonzero, then exchangesasleep_onfor 0. If the old value is the offset of a count this kind keeps (a box'ssleepersat 84; a stream'sspace_waitingat 168 ordata_waitingat 200), the owner died inside a wait and the freer subtracts 1 from that count; any other value is ignored, so a corrupt slot cannot make the freer write elsewhere. It then storesowner_pidns = 0, thenowner_pid = 0(release), and last changesowner_startfrom the marker to 0 with a compare-and-swap, which fails harmlessly once a new claimer has stored its own. - A scan reads
owner_pid, thenowner_startandowner_pidns, thenowner_pidagain, and skips the slot if the pid changed: otherwise a slot freed and claimed between the first two reads would pair the dead pid with the new owner's start, and the compare-and-swap would mark a live slot. - Release: store
owner_start = 0(release), decrementwaiters, storeowner_pidns = 0, thenowner_pid = 0(release). A handle frees only a slot it claimed that still records its own(pid, start, pidns); a child created byforkinherits its parent's claims but leaves them to the parent. - A thread waits in a slot it holds, one thread at a time, and a slot is
not released while a wait in it runs. The Python watcher registers one slot
for its lifetime, and a one-off
Segment.wait()without a slot claims one for the call. - The slot table and the protocol above are the core's, shared by every
kind. A box's
waitersis the count of claimed slots in its header; a stream's iswaitersin its line 3, and the stream sizes its table atmax_readers + 1.
Known limits, each after a process is killed at one specific step:
- A freer killed while holding the marker, before it clears
owner_pid, leaves the slot unusable until the segment is created again, andwaitersone too high if it was killed before its decrement. Killed after it won the slot and before its subtraction of the sleeper count, it leaves that count one too high and the slot stuck with the marker. - An owner killed between its exit exchange of
asleep_onand its subtraction of the sleeper count leaves that count one too high. - An owner killed partway through a release leaves a slot with no start,
which is freed without a decrement, so
waitersstays one too high if the kill came before the decrement. On Linux, a kill afterowner_pidns = 0leaves a namespace of 0, which is never freed (see Liveness); the count stays correct. - A claimer killed on Linux before it stores
owner_pidnsleaves the slot stuck the same way, and counted once too many if it had already incrementedwaiters. - The check that
owner_pidstill holds the pid cannot tell an unstamped claimer from another one with the same pid, which needs the pid to be reused within a few instructions. - A thread killed inside a wait after it adds 1 to the sleeper count and
before it stores the count's offset in
asleep_onleaves that count one too high, for a box and for a stream alike. Killed later in the wait, before its exit exchange ofasleep_on, it leavesasleep_onset, and freeing its slot takes the 1 back.
A count that is too high costs a system call on each write; it never loses a wake-up.
Wait and wake¶
- Wait (slot
i, last seen generationg, timeout): - Add 1 to
sleepers, then store its offset, 84, in sloti'sasleep_on, both sequentially consistent, for the whole wait. Then loadwake_word(sequentially consistent), then return at once ifseq >> 1 != gor sloti'sinterruptis set (clearing it with a compare-and-swap). - On every return, exchange
asleep_onfor 0 and subtract 1 fromsleepersonly if the exchange gave a nonzero value. The order keeps the count from going below the number of threads inside a wait: a freer of the slot takes the 1 back only after the store, and only once. - Linux:
FUTEX_WAIT(shared, not private) onwake_wordwith the value loaded before the check, so a write in between makes the call return at once. - Windows: wait on event
i, which the waiter's process opens on first use and keeps. - Check again after waking; a wake may be spurious. Past the timeout the
result is
status::timeout. - Wake, after every write:
- The swap that unlocks
seqis sequentially consistent. Then loadsleepers(sequentially consistent). If it is 0, stop: no change towake_wordand no system call on the normal path. The load comes before the waiter's increment ofsleepersin the single order of sequentially consistent operations, and the swap comes before the load, so the waiter's check ofseqsees the new value. - Otherwise increment
wake_word(sequentially consistent) before the wake. A Linux waiter whose load ofwake_wordcame before the increment is refused sleep or woken. One whose load comes after it reads this increment or a later change, every change towake_wordbeing a read-modify-write, so the swap happens before its check ofseq. On Windows the value ofwake_wordis not used, and the waiter's load stays. - Linux: one
FUTEX_WAKEwithINT_MAXwaiters. - Windows:
SetEventon the event of every occupied slot. interrupt(slot): set the slot'sinterrupt, then wake that slot. On Linux it incrementswake_wordand callsFUTEX_WAKE, and the other waiters check their own flag and sleep again; on Windows it sets that slot's event only. The flag stays set until the waiter sees it, so an interrupt sent before the wait starts still ends it.- Each kind names the word a wait sleeps on: a box's
wake_word; for a stream,data_wordfor readers andspace_wordfor the sender. A wait returns when its kind's condition holds, the slot'sinterruptflag is set, or the timeout passes. A box counts the threads inside a wait insleepers, a stream the threads asleep on each word indata_waitingandspace_waiting; a wake is made only when the count is not 0. Each wait names its count in its slot'sasleep_onas a box's wait does. On Windows a wake sets the event of every claimed slot, so the other end of a stream may wake and sleep again.interrupton a stream end adds 1 to that end's word and wakes it on Linux, and sets that slot's event on Windows. - The Python watcher waits in steps of at most 1 s. Writes and
interruptwake it at once; after each step it checks that its slot still records its own(pid, start, pidns)and claims a new slot if not. While every slot is taken it checks for changes once a second instead of waiting.
Liveness¶
A process is named by its pid and its start time.
- Start time: Windows, the creation time from
GetProcessTimes; Linux, field 22 of/proc/<pid>/stat, parsed after the last). A real value of 0 counts as 1. - Dead: no process has the pid; or one does and its start time differs
(the pid was reused); or, on Linux, its state is
ZorX. On Windows a process whose handle is signalled has exited. - Alive: the process exists but its start time cannot be read (another
user,
/procmounted withhidepid, access denied on Windows), or the recorded start time was the unreadable marker. A slot is never freed on a guess. - Pid namespaces (Linux): a slot records its owner's pid namespace, the
inode number of
/proc/self/ns/pid. When the inode number of/proc/self/ns/timeis not that of the initial time namespace,0xEFFFFFFA, it goes in the upper 32 bits of the same value, because/proc/<pid>/statshifts a start time by the reading process's time namespace. A kernel without time namespaces leaves the upper bits 0, and a/proc/self/ns/timethat exists but cannot be read makes the whole value 0. A slot whoseowner_pidnsdiffers from the checking process's own counts as alive, because its pid cannot be checked from there; only its owner, or creating the segment again, frees it. This covers containers that share/dev/shmbut not a pid namespace. A process that cannot read its own namespace records 0, which means unknown: a slot whose namespace is 0, or a checker whose own is 0, is never freed. Windows has no pid namespaces and records 0. - The current pid is cached, and a
pthread_atforkhandler resets the cache in the child afterfork; the start time and namespace are read on first use.
The Python extension uses the same rules for the creator fields: when a
create finds the name taken, SegmentExistsError says whether the creator
still runs, runs in another pid namespace, or has exited. For a box not
published yet it reads the creator fields without waiting for magic,
and a creator that still runs is reported as still creating the box.
Send and receive¶
The sender writes position p into slot p % capacity, where p is
write_pos. Only the sender stores write_pos, and the process that claims
a dead sender (see Dead stream ends).
Send:
- Gate. With no lossless reader open (
lossless_readersis 0) the sender skips this step. Otherwise it keeps the smallestpositionamong the entries whosemodeis lossless, and rescans the reader table whenreaders_epochhas changed or whenpreaches that smallest position pluscapacity. Whilepis at least the smallest position pluscapacity, the ring is full for a lossless reader and the sender waits: with a timeout of 0 it givesstatus::timeoutat once. Otherwise it rescans up to 1000 times (spin_before_sleep), then sleeps onspace_wordin steps of at most 0.1 s (liveness_delay), counting itself inspace_waitingwhile it sleeps.status::timeoutfollows when the timeout passes. The scan leaves out every marked entry whosepositionis belowrelease_floor. A send underon_full::releasewhose wait times out, a timeout of 0 included, releases the readers that hold it back instead. It takes the candidate floorp - capacity + 1, since exactly the readers withposition + capacity <= phold positionpback, and scans the table again with that floor. If the send can then go on, the sender storesrelease_floor, issues a release fence and goes on to step 2. If an entry that is not marked still holds it back, it stores nothing and givesstatus::timeout. The stored floor never goes down. A wait that ends instatus::interruptedreleases nothing. - Store
seq = 2p + 1, then a release fence, copy the item, storeseq = 2p + 2with release, and storewrite_pos = p + 1with release. - A sequentially consistent fence, then, if
data_waitingis not 0, add 1 todata_wordand wake it.
A sender may reserve a slot (step 1 and the odd seq of step 2), fill it
for as long as it needs, and then either publish it (the rest of step 2,
then step 3) or give it up. The odd seq already ends the item
p - capacity that the slot held, so a lossy reader that has not taken it
misses it however the reservation ends. A slot given up keeps its odd
seq, which readers skip as they skip a send in progress, and write_pos
does not move, so the next send writes the same position again.
Receive, for a reader whose next position is r:
- A lossless or lossy reader first loads the
seqof slotr % capacity. If it is2r + 2the reader copies the item as in step 3 without readingwrite_pos, so it may take an item a moment before the sender storeswrite_posfor it, and its position may bewrite_pos + 1until the sender, or whoever claims a dead sender, storeswrite_pos. Otherwise it loadswrite_poswith acquire. If that is at mostrthere is nothing to read. The reader givesstatus::endedifstateis ended (read beforewrite_pos, since the sender storesstateafter its lastwrite_pos). Otherwise, with a timeout of 0 it givesstatus::timeoutat once. With a longer timeout it checkswrite_posup to 1000 times, then sleeps ondata_wordin steps of at most 0.1 s, counting itself indata_waitingwhile it sleeps. - A lossy reader with
write_pos - r > capacitymoves towrite_pos - (capacity - capacity / 2), with integer division: the middle of the ring, not its oldest item, whose slot the sender writes next. A latest reader withwrite_pos - r > 1moves towrite_pos - 1. Both count the items they pass as missed. - Load
seq, which must be2r + 2, copy the item, issue an acquire fence and loadseqagain. If it changed, the sender wrote a later position over the slot. A lossy or latest reader counts the item as missed and moves on. A lossless reader first issues an acquire fence and loadsrelease_floorwith acquire. The sender stored the floor before the release fence that comes before the oddseqthe copy failed on, so the reader sees it. Ifris below the floor the reader was released: it moves tomax(write_pos - 1, release_floor), counts the positions it passes as missed, stores the newpositionwith release, adds 1 toreaders_epoch, issues a sequentially consistent fence, wakes a waiting sender as in step 4 and givesstatus::released. It then reads as if it had just joined at the newest item. A lossless reader that is not below the floor moves on without counting until it has received its first item; after that the gate rules this out, and it getsstatus::corrupt. - Store
position = r + 1in its entry with release. A lossless reader then issues a sequentially consistent fence and, ifspace_waitingis not 0, adds 1 tospace_wordand wakes it.
A wait that ends with the slot's interrupt flag set gives
status::interrupted and clears the flag; the flag stays set until a wait
sees it, as for a box.
A reader joins in this order:
- Free the entries and waiter slots of dead processes (see Dead stream
ends), then claim a waiter slot. No slot free gives
status::no_slot. - Claim a free entry with a compare-and-swap of
owner_pidfrom 0 to this process's pid, then storeowner_pidnsandowner_start. No entry free gives the waiter slot back andstatus::no_slot. - Store the starting
positionwith release: forstart_at::newestwrite_pos - 1, or 0 before the first send, and forstart_at::oldestwrite_pos - capacity, or 0. Before it, the reader stores its start time inrelease_markand its pid inrelease_pid. A lossless reader starts no lower thanrelease_floor, loaded with acquire, since a reader below the floor would be released at its first receive. - If the reader is lossless, add 1 to
lossless_readers. Then store itsmodewith release, add 1 toreaders_epoch, and issue a sequentially consistent fence. The count comes first so that a process killed in between leaves it too high, never too low.
A reader leaves only if its entry still records this process: store
mode = 0, subtract 1 from lossless_readers if it was lossless, add 1 to
readers_epoch, then clear owner_start, owner_pidns and owner_pid. A
lossless reader then adds 1 to space_word and wakes it, since it may have
been the one holding the sender back. Last it gives back its waiter slot.
The sender claims sender_pid with a compare-and-swap from 0 to its pid,
after claiming a waiter slot, and stores sender_pidns and sender_start.
It gives status::busy while another running process holds sender_pid.
Closing the sender stores state = 1 (ended), clears sender_start,
sender_pidns and sender_pid, adds 1 to data_word, wakes it, and gives
back the waiter slot. ended is never undone: sender() on an ended stream
gives status::ended, and so does a sender() that finds the stream ended
after it claimed sender_pid, which it then clears. A reader opened after
the sender closed receives what is buffered, then status::ended.
A process created by fork inherits its parent's senders and readers but
cannot use them: a send or receive from the child gives status::range, and
closing them in the child leaves the parent's entries alone.
Dead stream ends¶
A wait never sleeps for more than 0.1 s (liveness_delay) at a time. After
each step that ends without a change, it checks the processes it waits for
with the rules of Liveness:
- A sender waiting for space frees the entries of readers whose process has
exited, with the
start_freeingexchange that waiter slots use (see Waiter slots). For each it setsmodeto 0, subtracts 1 fromlossless_readersif the mode was lossless, clears the owner, and adds 1 toreaders_epochonce for the scan. It then frees the waiter slots of dead processes.reader()does the same before it claims anything. - A reader waiting for data ends the stream when the sender's process has
exited. It first claims the dead sender by changing
sender_startfrom the value it read tostart_freeingwith a compare-and-swap. If that succeeds, it completes the dead sender's last publish (see below), then changesstatefrom 0 to 1, clearssender_pidns,sender_pidandsender_start, adds 1 todata_wordand wakes it. Readers then receive what was published, thenstatus::ended. sender()replaces a recorded sender whose process has exited. It claims the dead sender the same way, so a replacement and an ending never both act on one dead owner, completes the dead sender's last publish, then stores its own pid.- A sender killed after storing
seqof slotp % capacityas2p + 2and before storingwrite_posleaveswrite_posatpwith itempwhole in its slot. Whoever claims the dead sender loadswrite_pos, and if that slot'sseqis2p + 2storeswrite_pos = p + 1and wakesdata_wordas a send does, before ending the stream or letting a replacement send. Readers then receive the item the dead sender published, thenstatus::endedor the replacement's items.
Known limits:
- Only a wait notices a dead process. A sender that only sends with a timeout of 0 never frees a dead lossless reader, and a reader that only receives with a timeout of 0 never sees the stream end after its sender dies.
- A process killed while it waits, after it adds 1 to
data_waitingorspace_waitingand before it stores the count's offset in its slot'sasleep_on, leaves that count one too high for good. That costs a wake call on each send or receive; no wake is lost. Killed later in the wait, before its exit exchange ofasleep_on, it leaves the offset, and freeing its waiter slot takes the 1 back. Killed between that exchange and its subtraction, it leaves the count one too high. A freer of its slot killed after it won the slot and before its subtraction leaves the count one too high and the slot stuck with the marker. - A process killed in the few instructions between setting
sender_starttostart_freeingand its next store leavessender_startatstart_freeing. Every latersender()then givesstatus::busy, and readers wait until their timeout instead of gettingstatus::ended. The waiter slots have the same limit. - A process killed while it frees a reader entry leaves the entry unusable until the stream is created again.
- A waiting end spins for up to 1000 checks before it sleeps, which uses a CPU for that time whenever the timeout is above 0.
Add and read metadata¶
On a box any process adds metadata versions, under the box's write lock.
On a stream only the sender adds them, never during a send on the same
sender, since the add reads write_pos. To add version
v = metadata_head + 1 to an area (see Metadata), the writer:
- Checks the document: inside the subset of Documents, and no longer than
a third of the ring rounded down to a multiple of 8. A failure gives
status::range, and a segment without a metadata area givesstatus::metadata_full; both write nothing. - On a box, takes the write lock as a write does (see Sequence lock). The
version's position is the generation that the unlock leaves, one more
than the generation before the lock. On a stream the position is
write_pos. - Finds where the document goes: right after the newest version's document, its end rounded up to a multiple of 8, or at 0 when the document would pass the end of the ring there.
- Checks that the older versions it overwrites can go: the version whose
entry
vtakes,v - entries, and every version whose ring bytes the document covers. A box lets them go freely. A stream lets versionugo only when no item still in the ring was sent under it: when versionu + 1took effect at a position no later thanwrite_pos - capacity, or whenu + 1took effect at the same position asu, so that no item was sent underu, and every version older thanuis gone or goes in this add. When version 1 took effect after position 0, the items sent before it count as a version older than 1, so version 1 goes only by the first condition. Without the condition on older versions a version could go while an older one stays, and the walk back from the head below would stop at the gap. Without the rule for version 1, it could go while an item sent before it is still in the ring, and a reader could not tell that item from one whose version was reclaimed. Otherwise the add givesstatus::metadata_fulland writes nothing. - Stores
seq0 in the entry of each older version whose ring bytes it overwrites while its entry is kept, so the entry reads as reclaimed. - Stores the entry's
seqas2v + 1, issues a release fence, copies the document into the ring, storesversion,position,offsetandlength, storesseq = 2v + 2with release, and thenmetadata_head = vwith release. - On a box, unlocks and wakes as after a write (see Wait and wake): the generation moves on by 1, and no field and no write count changes. On a stream the add wakes nobody; readers see a version when they look it up.
To read version v, a reader loads seq of entry v % entries with
acquire and checks that it is 2v + 2 and that version is v; a
version of 0, or any mismatch, gives status::not_found. It checks that
offset + length lies inside the ring, which gives status::corrupt while
seq is unchanged. It then copies the document, issues an acquire fence
and loads seq again. A change means the version was reclaimed during the
copy, and the read gives status::not_found. The latest version is the
one metadata_head names.
The version of the stream item at position p is the newest version whose
position is at most p. A reader finds it by walking back from
metadata_head, at most entries steps and usually one. Step 4 means that
an item still in the ring always finds its version, and that the stream
holds version 1 while an item sent before it is in the ring. The walk gives
status::not_found when a version it passes was reclaimed, or when p
comes before every version the area holds. Once an item has left the ring
its version can be reclaimed, so a reader that looks it up later can find
it gone. For a lossy or latest reader that can happen right after the
receive, when the sender overwrote the item just after the reader copied
it. The Python reader reports version 0 for an item sent before the first
version: while the stream still holds version 1, no version has been
reclaimed, so status::not_found then means the item came before every
version.
Close and unlink¶
- Destroying a handle releases any waiter slot it holds, then unmaps its view and closes its OS handles, including the events it opened.
unlink(name): Linuxshm_unlink("/SBX:<name>"); Windows does nothing.
Implementation language¶
The library is C++20, header-only, in namespace sharedbox. core.hpp
holds what every kind of segment uses: results and errors, liveness, names,
mappings, the open step, waiter slots and the type codec. box.hpp holds
the box: its layout, the protocols and handle. stream.hpp holds the
stream: its layout, the protocols and stream, stream_sender and
stream_reader. sharedbox.hpp includes every kind and is the
header consumers include. Names are declared in the inline namespace
sharedbox::v3, which changes when the
C++ interface changes incompatibly, so code built against headers with
different inline namespaces can be linked into one program. Names in
sharedbox::detail may change without a new inline namespace, so shared
libraries build with hidden visibility to keep their copies apart. C
programs use it through sharedbox_c.h, whose sbx_* functions are not
versioned this way and are declared with hidden visibility outside
Windows.
- The layout structs are plain standard-layout types with integer members.
- Atomics:
std::atomic_refon those members.static_asserts requirestd::atomic_ref<std::uint32_t>andstd::atomic_ref<std::uint64_t>to be always lock-free, because only lock-free atomics work on memory shared between processes; a fallback that takes a lock would keep that lock in one process.std::atomic_ref::waitandnotify_*are not used, since implementations do not promise they work across processes, andstd::atomicmembers are not used because the standard does not fix their size or layout. Withstd::atomic_refthe compiler emits the barriers each CPU needs, with one code path for every compiler. - 64-bit little-endian targets only; the header refuses a big-endian target at compile time.
- No allocation on the read and write paths. No exceptions: every function
that can fail returns
result<T>, a value or anerror.result<T>is the library's own class on C++20 and C++23 alike, with the part of the interface ofstd::expected<T, error>it needs (has_value,operator bool,operator*,->,value,error,and_then,transform,or_else,value_or);value()on an error callsstd::terminate. Anerrorholds thestatus(code), the OS error (os, theerrnoorGetLastError()value read where the OS call failed) and what the call found (found, see Attach). Every function returning aresultis[[nodiscard]], and the header builds with-fno-exceptions. - Where the standard library has
std::expectedwith__cpp_lib_expected >= 202211L(C++23), the free functionsto_expected(result<T>)andfrom_expected(std::expected<T, error>)convert one into the other. Becauseresultis never an alias and its definition does not depend on the C++ version, translation units built as C++20 and as C++23 can be linked into one program.
sharedbox.hpp¶
namespace sharedbox {
inline namespace v3 {
inline constexpr std::uint16_t core_major = 1, core_minor = 0;
inline constexpr std::uint16_t layout_major = 3, layout_minor = 3; // the box layout
inline constexpr std::uint64_t box_magic = 0x5F584F425F584253; // "SBX_BOX_"
inline constexpr std::uint64_t stream_magic = 0x4D5254535F584253; // "SBX_STRM"
// Also: the layout constants handle_version, header_size, name_max, max_fields,
// max_capacity, max_waiter_slots, default_waiter_slots, record_alignment, page_size,
// max_timeout, default_lock_timeout, kind_shift, capacity_mask, max_types_size,
// max_type_depth, max_mapping_size, first_described_kind, max_date_ordinal,
// unix_epoch_ordinal, micros_per_day, max_offset_minutes, literal_none through
// literal_enum, and the kind codes kind_bool, kind_int, kind_float, kind_str,
// kind_bytes, kind_ref, kind_complex through kind_decimal, kind_enum through
// kind_max_array, kind_attr and kind_timed, attr_timed, attr_settable and
// attr_request, publish_value, publish_timestamp and publish_setpoint,
// timed_mark, the timestamp a write replaces, and request_answers, request_error_size and request_arguments_at
// (see Encodings);
// the structs common_header, header, stored_field, waiter_slot, box_ref and
// type_head (see Layout); dl_dtype and literal_value, which type_view's dtype()
// and literal() return (see the list below); error, result<T> and unexpected (see
// Implementation language).
enum class status : int { ok = 0, exists = -1, not_found = -2, layout = -3, schema = -4,
corrupt = -5, lock_timeout = -6, timeout = -7, no_slot = -8,
range = -9, os = -10, kind_mismatch = -11, foreign = -12,
busy = -13, ended = -14, interrupted = -15, released = -16,
metadata_full = -17, unsupported = -18 };
struct field_spec { std::uint32_t offset; std::uint32_t capacity; std::uint8_t kind; };
struct value { std::uint16_t field; std::span<const std::byte> bytes; };
using seconds = std::chrono::duration<double>;
struct read_value { std::size_t len; std::uint64_t version; };
enum class wake { changed, interrupted }; // a timeout is status::timeout
struct metadata_spec { std::span<const std::byte> initial; std::uint64_t capacity; std::uint32_t versions; };
bool metadata_ok(std::span<const std::byte> doc) noexcept;
enum class request_outcome : std::uint8_t { pending, answered, failed, superseded, overwritten, server_exited };
struct request_reply { request_outcome outcome; std::uint32_t length; };
class handle { // move-only; the destructor releases it
public:
static result<handle> create(std::string_view name, std::span<const field_spec> fields,
std::uint32_t record_size, std::uint64_t schema_hash,
std::uint16_t waiter_slots, std::span<const value> initial,
std::span<const std::byte> types = {},
const metadata_spec &metadata = {});
static result<handle> create_unpublished(std::string_view name, std::span<const field_spec> fields,
std::uint32_t record_size, std::uint64_t schema_hash,
std::uint16_t waiter_slots, std::span<const value> initial,
std::span<const std::byte> types = {},
const metadata_spec &metadata = {});
result<void> publish() noexcept;
static result<handle> open(std::string_view name, seconds timeout);
static result<handle> from_capsule(sbx_handle *capsule);
result<handle> duplicate() const;
sbx_handle *to_capsule() &&;
std::string_view name() const noexcept;
std::uint16_t field_count() const noexcept;
const field_spec &field(std::uint16_t index) const noexcept;
type_view field_type(std::uint16_t index) const noexcept;
std::span<const std::byte> types_table() const noexcept;
std::uint32_t record_size() const noexcept;
std::uint64_t schema_hash() const noexcept;
std::uint64_t create_id() const noexcept;
std::uint16_t waiter_slots() const noexcept;
std::uint16_t minor_version() const noexcept;
std::uint16_t major_version() const noexcept;
void *base() const noexcept;
std::uint64_t size() const noexcept;
result<void> set_lock_timeout(seconds timeout) noexcept;
result<read_value> read(std::uint16_t field, std::span<std::byte> buf) const;
result<std::uint64_t> read_record(std::span<std::byte> buf) const;
result<read_value> read_used(std::uint16_t field, std::span<std::byte> buf) const;
result<std::uint64_t> read_record_used(std::span<std::byte> buf) const;
result<read_value> read_large(std::uint16_t field, std::span<std::byte> buf) const;
result<std::uint64_t> read_record_large(std::span<std::byte> buf) const;
result<void> write_large(std::span<const value> values, seconds lock_timeout);
result<std::uint64_t> write_large(std::span<const value> values, std::span<const std::byte> doc,
seconds lock_timeout);
std::span<const std::byte> payload(std::uint16_t field, std::span<const std::byte> record) const noexcept;
result<void> write(std::span<const value> values, seconds lock_timeout);
result<std::uint64_t> write(std::span<const value> values, std::span<const std::byte> doc, seconds lock_timeout);
std::uint64_t generation() const noexcept;
std::uint64_t version(std::uint16_t field) const noexcept;
std::uint32_t writer_pid() const noexcept;
result<void> force_unlock() noexcept;
result<record_write> begin_record_write(seconds lock_timeout);
std::span<std::byte> held_bytes(const record_write &w, std::uint16_t field) const;
result<void> write_held(const record_write &w, std::span<const value> values);
void end_record_write(const record_write &w, std::span<const std::uint16_t> changed) noexcept;
void abort_record_write(const record_write &w) noexcept;
result<std::uint16_t> register_waiter();
void release_waiter(std::uint16_t slot) noexcept;
bool waiter_held(std::uint16_t slot) const noexcept;
std::uint32_t waiters() const noexcept;
std::uint32_t sleepers() const noexcept;
result<wake> wait(std::uint16_t slot, std::uint64_t last_generation, seconds timeout);
result<void> interrupt(std::uint16_t slot);
std::uint64_t metadata_head() const noexcept;
result<std::uint32_t> metadata_length(std::uint64_t version) const;
result<std::uint32_t> read_metadata(std::uint64_t version, std::span<std::byte> out) const;
result<std::uint64_t> add_metadata(std::span<const std::byte> doc, seconds lock_timeout);
result<std::uint64_t> request_send(std::uint16_t field, std::span<const std::byte> arguments,
seconds lock_timeout);
result<std::uint64_t> request_take(std::uint16_t field, std::span<std::byte> arguments, seconds lock_timeout);
result<void> request_answer(std::uint16_t field, std::uint64_t number, bool ok,
std::span<const std::byte> bytes, seconds lock_timeout);
result<request_reply> request_answer_of(std::uint16_t field, std::uint64_t number, std::span<std::byte> out,
bool check_server) const;
result<void> serve_claim(std::uint16_t field, seconds lock_timeout);
result<void> serve_release(std::uint16_t field, seconds lock_timeout);
result<void> attr_publish(std::uint16_t field, std::uint8_t parts, std::span<const std::byte> bytes,
seconds lock_timeout);
result<void> attr_read(std::uint16_t field, std::span<std::byte> out) const;
result<std::uint64_t> attr_published(std::uint16_t field) const;
std::uint32_t attr_value_at(std::uint16_t field) const noexcept;
};
result<void> unlink(std::string_view name) noexcept;
result<common_header> inspect(std::string_view name) noexcept;
enum class segment_state { missing, running, creator_exited };
result<segment_state> segment_status(std::string_view name, seconds wait = seconds(1.0)) noexcept;
} // namespace v3
} // namespace sharedbox
Every function returning result is [[nodiscard]]. handle also has
lock, unlock, set_wait_hooks and set_wait_cancel, which the tests
and the Python extension use. set_wait_cancel takes a flag that ends
every wait for another writer's lock, as timed out, once it is true.
The header also declares these names:
type_viewandhandle::field_type(index): a field's type, read from its description.handle::types_table()returns the table's bytes. For anattr,attr_flags()gives its flags byte, andvalue_offset(),timestamp_offset()andsetpoint_offset()give where each part starts in the field, 0 for a part theattrlacks.time_value,datetime_valueandtimedelta_value, with anencode_*and adecode_*function for each, and the same pair forcomplex,date,uuid,flagand enum and literal positions (encode_position,decode_position).decode_bool,decode_present,decode_taganddecode_lengthhave no encoder.handle::major_version(), the box layout major of the segment.- The constants
first_described_kind,max_date_ordinal,unix_epoch_ordinal,micros_per_day,max_offset_minutesandliteral_nonethroughliteral_enum, and the structstype_head,dl_dtypeandliteral_value. handle::read_used, which copies only the used part of a list, set or dict field;read_large,read_record_largeandwrite_large, which copy a large value, running the wait hooks once around the copy.- A
typesparameter onhandle::createandhandle::create_unpublished: the description table, empty by default. - A
metadataparameter onhandle::createandhandle::create_unpublished, ametadata_spec:initialis the document of version 1, none when empty;capacityis the ring's size in bytes, rounded up to a multiple of 8, and 0 for no metadata area;versionsis the number of entries, 2 to 65535.status::rangefor a capacity above what an area ofu32size holds, a ring below 24 bytes, a version count out of range, an initial document outside the subset or longer than a third of the ring, or an initial document with a capacity of 0.metadata_okis the subset check of Documents. -
The inline namespace is
v3. -
status:ok, and one code per error the Python side raises, so the extension maps each to its exception class.exists: the name is taken.not_found: no mapping under the name, or one that never becomes a box within the timeout.layout: anothercore_majoror boxkind_major.kind_mismatch: the name holds a segment of another kind.foreign: the magic is not one this library knows, so the segment was made by another version ofsharedboxor is not asharedboxsegment.schemais kept for callers that compare schema hashes.corrupt: a header or field table that fails the attach checks.lock_timeout,timeout,no_slot: see Protocols.range: an argument out of range.os: an OS call failed, and the error'sosholds itserrnoorGetLastError().busy: the sender is held by a running process.ended: the stream's sender closed or died and every published item was received.interrupted: a stream wait ended byinterrupt().metadata_full: an add to a segment without a metadata area, or to a stream whose ring still holds an item sent under a version the add would overwrite.unsupported: the segment holds, inside a field or as a stream item, a kind this version does not know, which the error'sfoundnames; a newer version probably created it. createandwritetake raw bytes in the record encoding, without the length prefix ofstr,bytesandDecimal; converting language values stays in each binding.opentakes no schema hash; callers compareschema_hash()with their own. Itstimeout, in(0, 86400], only bounds the wait for a creator (the Python extension passes at most 1 s). Reads use a lock timeout of 5 s untilset_lock_timeoutchanges it;writetakes its own.readreturnsread_value. When the stored value is longer thanbuf, nothing is copied andlensays how long it is; a buffer of the field's capacity always fits.read_recordcopies every field from one moment and returns the generation of that moment;payloadfinds a field in such a copy.read_record_useddoes the same and copies only the bytes each field uses, which are the length and the bytes of astr,bytesorDecimal, the length and the slots in use of a list, set or dict, and the shape line and the elements of amax_array. It leaves the other bytes ofbufas they were, so it costs what the stored values cost, not the room the fields reserve.inspect(name)copies the common line of a published segment of any kind, without waiting and without the checks ofopen. The Python extension uses it to name the layout of a segment it refuses and the creator inSegmentExistsError.segment_status(name, wait)says whether a segment of any kind is callednameand whether its creator still runs. It waits up towaitfor a segment being created and counts one still unpublished asmissing. A creator it cannot judge, in another pid namespace or with a start time it cannot read, counts asrunning. A core major version other than 1 isstatus::layout, withfoundasopengives it, and awaitthat is negative, not a number or above 86400 s isstatus::range.duplicate()makes a second handle with its own mapping from this handle's OS handle (dupandmmapon Linux,DuplicateHandleandMapViewOfFileon Windows), not from the name, so it works afterunlink().minor_version()is the lower of the segment'skind_minorand thelayout_minorof thebox.hppthe caller was compiled with.- Shared memory that never becomes a box within the timeout is
status::not_found. metadata_head()is the newest metadata version, 0 when there is none or the box has no metadata area.metadata_lengthandread_metadatagivestatus::not_foundfor a version the box no longer holds or has not added yet, and for a box without a metadata area, andstatus::corruptfor an entry that places its document outside the ring.read_metadatacopies the document intooutand returns its length, and givesstatus::rangefor anoutshorter than the document. Metadata is read without the write lock.add_metadataaddsdocas the next version and returns it, as one write under the write lock (see Add and read metadata): the generation moves on by 1 and waiters wake, but no field and no write count changes.status::metadata_fullfor a box without a metadata area,status::rangefor a document outside the subset or longer than a third of the ring, andstatus::lock_timeoutas forwrite. A refused add leaves the generation as it was.write(values, doc, lock_timeout)writesvaluesaswritedoes and addsdocas the next version in the same write: one generation, so a reader sees the values and the version together. It returns the version, and gives the statuses ofwriteand ofadd_metadata. A refused document writes no field.write_large(values, doc, lock_timeout)is the same write for large values, running the wait hooks once around it.begin_record_writetakes the write lock, waiting at mostlock_timeout, and returns arecord_writethat holds it across any number of stores, for a write computed from what the record holds.held_bytesis a field's whole slot in the record, its 4-byte length included forstr,bytesandDecimal, and empty for a field pastfield_count(); read it to see the field, or copy it to restore it later.write_heldchecks and storesvaluesaswritedoes,Timedstamps included, without locking or counting, and givesstatus::rangefor a valuewriterefuses, storing nothing.end_record_writecounts one write for each field inchanged, which must hold distinct field indices belowfield_count(), then unlocks and wakes waiters.abort_record_writeunlocks without counting and wakes nobody. The generation still moves by one, and watchers, which compare write counts, report nothing. A caller that wrote fields copies their saved slots back first. Every record write ends with exactly one of the two.request_send,request_take,request_answer,request_answer_of,serve_claimandserve_releaseare the steps of the request protocol on anattrfield with a request part (see The request protocol).request_sendtakes the bytes from offset 48 toanswers, andrequest_takecopies them into a span of that size.request_answertakes the result at its exact size whenok, otherwise the error text.request_answer_ofcopies the result or the error text intoout, which holds at least the larger of the result's size and 256 bytes, andrequest_reply::lengthgives how many bytes it copied. Each givesstatus::rangefor a field that is not anattrwith a request part or for a span of the wrong size, and the steps that take the lock givestatus::lock_timeoutaswritedoes.attr_publishwrites the parts of a field's value part that itspartsargument names, a bit ofpublish_value(1),publish_timestamp(2) andpublish_setpoint(4) each, frombytes, which holds[value_at, size)of the field with each part at its own offset. Under the write lock it copies the named parts, stamps a value named without a timestamp, or withtimed_markas its timestamp, on a timedattrwith the system clock in nanoseconds since the Unix epoch, adds 1 topublished, counts one write of the field and wakes the waiters. It givesstatus::range, writing nothing, for a field that is not anattr, a part theattrlacks, a timestamp named without the value, no part at all orbytesof another size.attr_readcopies the same[value_at, size)range intooutfrom one moment, without the lock, and givesstatus::rangefor a field that is not anattror has no value part, or anoutof another size.attr_publishedreadspublishedalone the same way, and givesstatus::rangefor the same fields. When the bytesattr_publishorattr_readcopies arelarge_copyor more, it runs the wait hooks once around the copy, aswrite_largeandread_largedo.attr_value_atgives the offset in the field where the value part starts, which is the field's size minus the size ofattr_read'sout, ordetail::attr_absentfor a field that is not anattror has no value part.- Thread safety: every member function may be called from several threads on one handle. Destroying or moving a handle must not overlap another call on it.
- Known limit: on Linux every open handle keeps the mapping's file
descriptor, so about 1000 open boxes reach the default
ulimit -nof 1024.
stream.hpp¶
inline constexpr std::uint16_t stream_layout_major = 1, stream_layout_minor = 5;
inline constexpr std::uint32_t stream_header_size = 256;
inline constexpr std::uint64_t min_stream_capacity = 2;
inline constexpr std::uint32_t max_stream_readers = max_waiter_slots - 1; // 4095
inline constexpr std::uint64_t max_stream_size = std::uint64_t{1} << 46;
inline constexpr std::uint32_t stream_open = 0, stream_ended = 1;
inline constexpr double liveness_delay = 0.1; // seconds a wait lasts before it checks for dead processes
inline constexpr unsigned spin_before_sleep = 1000; // checks a waiting end makes before it sleeps
enum class read_mode : std::uint32_t { lossless = 1, lossy = 2, latest = 3 };
enum class start_at { newest, oldest };
enum class on_full { wait, release };
struct received { std::uint64_t position; std::uint64_t missed; };
struct reader_info { std::uint64_t position; read_mode mode; std::uint32_t pid; };
class stream_sender { // move-only; the destructor closes it
public:
std::uint64_t item_size() const noexcept;
result<std::uint64_t> send(std::span<const std::byte> item, seconds timeout,
on_full policy = on_full::wait);
template <class F> requires std::is_nothrow_invocable_v<F &, std::span<std::byte>>
result<std::uint64_t> send_with(F &&fill, seconds timeout, on_full policy = on_full::wait);
result<std::span<std::byte>> begin(seconds timeout, on_full policy = on_full::wait);
result<std::uint64_t> publish() noexcept;
result<std::uint64_t> add_metadata(std::span<const std::byte> doc);
result<void> can_add_metadata(std::span<const std::byte> doc) const;
void abandon() noexcept;
result<void> interrupt();
void close() noexcept;
};
class stream_reader { // move-only; the destructor closes it
public:
read_mode mode() const noexcept;
std::uint64_t position() const noexcept;
std::uint64_t missed() const noexcept;
std::uint64_t item_size() const noexcept;
result<received> receive(std::span<std::byte> out, seconds timeout);
template <class F> requires std::is_nothrow_invocable_v<F &, std::span<const std::byte>>
result<received> receive_with(F &©, seconds timeout);
result<received> fetch(std::uint64_t position, std::span<std::byte> out, seconds timeout);
template <class F> requires std::is_nothrow_invocable_v<F &, std::span<const std::byte>>
result<received> fetch_with(std::uint64_t position, F &©, seconds timeout);
result<void> interrupt();
result<std::uint64_t> metadata_version_at(std::uint64_t position) const;
void close() noexcept;
};
class stream { // move-only; the destructor releases it
public:
static result<stream> create(std::string_view name, std::span<const std::byte> types,
std::uint32_t item_entry, std::uint64_t capacity,
std::uint32_t max_readers, std::uint64_t schema_hash,
const metadata_spec &metadata = {});
static result<stream> open(std::string_view name, seconds timeout);
std::string_view name() const noexcept;
std::uint64_t schema_hash() const noexcept;
std::uint64_t create_id() const noexcept;
std::uint64_t capacity() const noexcept;
std::uint32_t max_readers() const noexcept;
std::uint64_t item_size() const noexcept;
type_view item_type() const noexcept;
std::span<const std::byte> types_table() const noexcept;
void *base() const noexcept;
std::uint64_t size() const noexcept;
result<stream_sender> sender();
result<stream_reader> reader(read_mode mode, start_at start);
std::uint64_t write_position() const noexcept;
bool ended() const noexcept;
std::uint32_t sender_pid() const noexcept;
std::uint64_t metadata_head() const noexcept;
result<std::uint32_t> metadata_length(std::uint64_t version) const;
result<std::uint32_t> read_metadata(std::uint64_t version, std::span<std::byte> out) const;
std::size_t readers(std::span<reader_info> out) const noexcept;
};
The header also declares the structs stream_header and reader_entry (see
Stream layout). Every function returning a result is [[nodiscard]].
stream::createtakes the item as anitem_entry, acapacity_and_kindword as a field table entry has, and the description tabletypesthat entry refers to.status::rangefor a name that breaks the rules, acapacitybelow 2, amax_readersoutside 1 to 4095, a table that does not parse or an item of an unknown kind, or a shape whose slots would pass 2^46 bytes;status::existsif the name is taken.stream::opencompares nothing: the caller comparesschema_hash()with its own. Its errors are those of Attach, andstatus::corruptfor an item type or slot size that does not fit.sendergivesstatus::busywhile a running process holds the sender,status::endedonce a sender has closed the stream, andstatus::no_slotwhen no waiter slot is free.readergivesstatus::no_slotwhenmax_readersreaders are open or no waiter slot is free.sendcopiesitem_size()bytes into the next slot and returns its position.send_withcallsfillwith the slot'sitem_size()bytes instead;fillmust not throw or call the sender. Both givestatus::timeoutwhile a lossless reader is a full ring behind (at once for a timeout of 0),status::interruptedafterinterrupt(), andstatus::rangefor a sender that is closed, used from a child offorkor given an item of the wrong size. Underon_full::release, a timeout releases the marked lossless readers that hold the send back and sends instead; it still givesstatus::timeoutwhile a reader whose entry is not marked holds the send back (see Send and receive).beginreserves the next slot assenddoes and returns itsitem_size()bytes to fill in place, which stay valid untilpublishorabandon. It gives the status codessendgives, except the one for an item of the wrong size.publishpublishes the slot and returns its position, andabandongives it up. While a reservation is open,begin,sendandsend_withgivestatus::busy.publishgivesstatus::rangewithout a reservation, for a closed sender and in a child offork.closegives an open reservation up.receivecopies the next item intooutand returns its position and the number of items this reader skipped since its previous receive (always 0 for a lossless reader).receive_withcallscopywith the item's bytes in the slot; the sender may change them during the call, socopymust only copy and must not throw.status::timeoutwhen no item arrives in time (at once for 0),status::endedonce the sender has closed or died and every published item was received,status::interruptedafterinterrupt(), andstatus::rangefor anoutshorter thanitem_size(). A lossless reader that a sender released getsstatus::released, already moved to the newest item, so its next receive works.fetchcopies the item atpositionintoout, waiting asreceivedoes until the sender has sent it, andfetch_withcallscopyunder the same rule asreceive_with. Neither moves the reader:position()andmissed()stay as they were, and a release is reported by the next receive. The item is whole when its slot'sseqreads2 * position + 2before and after the copy.write_posis read before that check, and because the sender storeswrite_posonly after it publishes, a failed check withwrite_posabovepositionmeans a later item overwrote the slot. The call then givesstatus::not_found, withfoundset to the oldest position the ring held:write_pos - capacityor 0, but at leastposition + 1, because a reservation in progress or abandoned ends the itemwrite_pos - capacitybeforewrite_posmoves. It givesstatus::endedwhen the sender closed or died without sending the item, andstatus::rangefor a position above(UINT64_MAX - 2) / 2, where2 * position + 2would wrap.missed()counts the items this reader skipped. For a lossless reader it counts the items lost to releases, and the count of one release ismissed()after the call that gavestatus::releasedminusmissed()before it.interruptends the wait in progress withstatus::interrupted. Sent while nothing waits, it ends the next wait. It must not overlapclose.closeon the sender ends the stream for good.closeon a reader frees its entry.write_position()is the number of items sent.readers(out)fillsoutwith the open readers, as many as fit, and returns how many are open.stream::createtakes ametadata_specashandle::createdoes and places the area after the description table; version 1 takes effect at position 0.metadata_head,metadata_lengthandread_metadatawork as on ahandle.stream_sender::add_metadataaddsdocas the next version, in force from the item the next send publishes, and returns it. It wakes nobody.status::metadata_fullfor a stream without a metadata area, and while an item still in the ring, or yet to be sent, needs a version the add would overwrite; an add after enough further sends succeeds.status::rangefor a document outside the subset or longer than a third of the ring, for a closed sender, and in a child offork. It must not overlap a send on the same sender.stream_sender::can_add_metadata(doc)gives the statusadd_metadata(doc)would give now, and writes nothing. The answer holds until the next send or add on the same sender.stream_reader::metadata_version_at(position)is the version in force at an item's position, such as the onereceivereturned: the newest version added at or before it.status::not_foundwhen that version was reclaimed, when the position comes before every version the stream holds, and for a stream without a metadata area.- Calls on one sender or one reader must not overlap, except
interruptandstream_reader::metadata_version_at, which must not overlapclose; a reservation is not a call, so other calls may come betweenbeginandpublish. Senders and readers must not outlive thestreamthat made them.
Capsule handle¶
sbx_handle is the struct a capsule holds. It is plain C data with function
pointers, declared in sharedbox_c.h and included by box.hpp,
because it passes between extensions compiled separately, possibly with
different compilers and standard libraries. No C++ standard-library type
crosses the capsule.
typedef struct sbx_handle {
uint16_t layout_major, layout_minor;
uint32_t handle_version; /* 1; grows by appending fields */
void *base; /* this handle's own mapping */
uint64_t size;
const char *name; /* the box name, for slot events */
void (*release)(struct sbx_handle *);
void *private_data; /* owned by the build that made the handle */
} sbx_handle;
private_databelongs to the build that made the handle, and only that build'sreleasereads it.- A consumer never reads another build's
private_data. It takes the handle withhandle::from_capsule(orsbx_import). It does not wait formagic: it loads it once and returnsstatus::corruptif it is not set orsizeis below 4096, then runs steps 3 and 4 of Attach on the segment atbase, which includes the kind and version checks. It keeps its own copy of the struct and of the field table, and checks no schema: the consumer comparesschema_hash(). On success it clears the capsule struct'srelease, and destroying the new handle calls the producer'srelease. The consumer's handle opens slot events bynamewhen it first waits. to_capsule()moves a handle to the heap and returns a newsbx_handlewhosereleasedestroys it; the caller deletes the struct afterwards.- The Python extension's capsule destructor deletes the struct while the
capsule is named
"sharedbox_box"or"used_sharedbox_box", and callsreleaseonly under the first name.
sharedbox_c.h¶
include/sharedbox/sharedbox_c.h is a minimal C99 interface, documented as
"minimal, may be removed in a future major version". Removing it would only
delete code: a semver major step for the headers, with no change to the
layout.
#define SBX_OK 0 /* SBX_E_* have the values of sharedbox::status */
typedef struct sbx_value { uint16_t field; const void *data; size_t len; } sbx_value;
int sbx_open(const char *name, double timeout, sbx_handle *out);
int sbx_import(sbx_handle *capsule, sbx_handle *out);
int sbx_read(const sbx_handle *h, uint16_t field, void *buf, size_t cap,
size_t *len, uint64_t *version);
int sbx_write(sbx_handle *h, const sbx_value *values, size_t n, double lock_timeout);
uint64_t sbx_schema_hash(const sbx_handle *h);
void sbx_release(sbx_handle *h);
uint64_t sbx_metadata_head(const sbx_handle *h);
int sbx_read_metadata(const sbx_handle *h, uint64_t version, void *out, size_t cap,
size_t *len);
int sbx_add_metadata(sbx_handle *h, const void *doc, size_t len, double lock_timeout,
uint64_t *version);
- It holds
sbx_handle,sbx_value, the status codes, the nine functions above and the typed functions below. Creating, waiting,interrupt,force_unlockandunlinkare in the C++ API only. - The status codes are
SBX_E_EXISTS(-1) toSBX_E_OS(-10), thenSBX_E_KIND(-11) andSBX_E_FOREIGN(-12), the values ofstatus::kind_mismatchandstatus::foreign, andSBX_E_BUSY(-13),SBX_E_ENDED(-14) andSBX_E_INTERRUPTED(-15), the values ofstatus::busy,status::endedandstatus::interrupted, andSBX_E_METADATA_FULL(-17) andSBX_E_UNSUPPORTED(-18), the values ofstatus::metadata_fullandstatus::unsupported. Streams have no C functions.sbx_openandsbx_importreturnSBX_E_KINDfor a segment of another kind andSBX_E_FOREIGNfor a magic they do not know (see Attach). A C caller gets the code only, without theerror's OS error andfound. sbx_field_descreturns a field's kind code and its description's bytes.sbx_read_*andsbx_write_*exist forcomplex,float16,float32,date,time,datetime,timedelta,uuid, enum and literal positions (position), flag bits (flag) and an optional's presence (present, read only). A read givesSBX_E_RANGEfor a field of another kind andSBX_E_CORRUPTfor a stored value no Python value has; a write givesSBX_E_RANGEfor a value out of range.sbx_read_float16andsbx_read_float32give afloat;sbx_write_float16andsbx_write_float32take adouble, round it to the field's width, and giveSBX_E_RANGEfor a finite value past it. NaN and the infinities are stored as they are. The integer kinds,complex64anddatetime64hold plain C types, whichsbx_readandsbx_writecopy.sbx_timeandsbx_datetimeholdint64_t micros,int16_t offset_minutesanduint8_t naive, fold;sbx_timedeltaholdsint32_t days, seconds, microseconds. Asbx_timecounts microseconds since midnight in wall-clock time; asbx_datetimecounts microseconds since 1970-01-01T00:00, wall time when naive and UTC when aware.- Each function converts its arguments and calls
sharedbox.hpp.sbx_openfillsoutwith a handle whoseprivate_dataholds asharedbox::handleand whosereleasedeletes it.sbx_importwraps a capsule's handle throughhandle::from_capsule. sbx_read,sbx_writeandsbx_schema_hashaccept only handles made bysbx_openorsbx_import; for any other,sbx_readandsbx_writereturnSBX_E_RANGEandsbx_schema_hashreturns 0.sbx_writealso returnsSBX_E_RANGEfor a field of a kind the header does not know, and stores atimedvalue's mark as the time of the write. Anattrfield's bytes move as they are, at the field's full size, without the request protocol or the publish step. When the stored value is longer thancap,sbx_readcopies nothing, sets*lenand returnsSBX_E_RANGE.sbx_releasereleases any handle.sbx_metadata_headreturns the box's newest metadata version, 0 when it has none orhwas not made bysbx_openorsbx_import.sbx_read_metadatacopies the document ofversionintoout; when the document is longer thancapit copies nothing, sets*lento its length and returnsSBX_E_RANGE. It returnsSBX_E_NOT_FOUNDwhen the box does not hold that version, andlenmay beNULL.sbx_add_metadataadds the document as the next version, as one write under the write lock, and stores the new version in*versionunless that isNULL. The document is one CBOR value of the subset of Documents:SBX_E_RANGEfor one outside it or longer than a third of the ring,SBX_E_METADATA_FULLfor a box without a metadata area, andSBX_E_LOCK_TIMEOUTwhen the lock is not free withinlock_timeoutseconds. Both returnSBX_E_RANGEfor a handle not made bysbx_openorsbx_import.- The implementation,
include/sharedbox/sharedbox_c.cpp, needs a C++20 compiler: a C program compiles that one file with its C++ compiler next to its own sources, and the CMake targetsharedbox::cadds it for them. One source file rather than a static library in the wheel, because a static library is tied to the compiler and C runtime that built it.
The PyCapsule interface¶
class Parcel(SharedBox, identity="post/parcel/1", max_waiters=64):
weight: float
count: int
with Parcel(0.5, 0) as parcel:
printer.run(parcel) # an extension that supports sharedbox
The dunder is a protocol for library authors, as __arrow_c_array__ and
__dlpack__ are: Python users pass the box to a consuming library, which
calls it. A capsule is an opaque pointer Python code cannot use, so there is
no Python-level export method.
SharedBox.__sharedbox_box__(self, max_version=None, **kwargs)returns a PyCapsule named"sharedbox_box"holding a heap-allocatedsbx_handlemade byduplicate()andto_capsule(), so it works afterunlink().max_versionis(major, minor); a major the box does not have raisesBufferError, and so does a minor older than the oldest whose readers open the box, following "Versioning rules": 3 for a box with amax_arrayfield, or amax_arrayortimedinside a described type; 1 for one with the kinds 13 to 23 inside a described type, or an array as an optional's member; 0 otherwise. Inside anattrortimedfield nothing counts, since an older reader keeps such a field as opaque bytes.Nonemeans the current version. Any other keyword raisesNotImplementedError.- A consumer that takes the handle renames the capsule
"used_sharedbox_box"and releases the handle itself. releaseunmaps and closes OS handles only: no Python objects, no GIL, so it may run on any thread and after interpreter shutdown.box.close()and the handle never affect each other. On Windows the segment stays alive while a handle is held.sharedbox.get_include()returns the folder holdingsharedbox/sharedbox.hpp,sharedbox/sharedbox_c.handsharedbox/sharedbox_c.cppin the installed package.sharedbox.SupportsSharedBoxis atyping.Protocolwith__sharedbox_box__, for annotations in consuming libraries.sharedbox._native.LAYOUT_VERSIONis(3, 3), the box layout.
Rust crate (deferred)¶
A Rust crate is not part of this release. It will be a safe layer over
the headers through cxx, so Python, C++ and Rust share one
implementation of the protocols, with schema_hash and the default name
computed in Rust and checked against the test vector above.
Build and packaging¶
include/sharedbox/core.hpp,box.hpp,stream.hpp,sharedbox.hpp,sharedbox_c.handsharedbox_c.cppare in the repository; the build installs them into the wheel undersharedbox/include/, andcmake/sharedbox-config.cmakeundersharedbox/share/cmake/sharedbox/, next to asharedbox-config-version.cmakethe build writes from the package version. Before 1.0 it accepts a request for the same minor version only (SameMinorVersion), from 1.0 on the same major version.- CMake targets:
sharedbox::headers, an interface target that requirescxx_std_20(and linksrtandThreads::Threadson Linux,bcrypton Windows), andsharedbox::c, which linkssharedbox::headersand addssharedbox_c.cppto the sources of whatever links it. Both work throughFetchContentand throughfind_package(sharedbox). A project that linkssharedbox::cwithout the CXX language enabled stops at configure time with a message saying so. - A Python extension that uses the header adds
sharedboxto its[build-system] requires, callssharedbox.get_include()and builds as C++20. The sharedbox extension itself builds as C++20.
Out of scope¶
- Queues, which would get
__sharedbox_queue__. - A Python class, a capsule (
__sharedbox_stream__) and C functions for streams. A stream is C++ only in this version. Global\names on Windows. They would let a service in session 0 share a box with a desktop application, but creating a file mapping there needsSeCreateGlobalPrivilegeand a security descriptor that lets the other session's user open it.- A vcpkg port and a headers-only wheel.
- macOS. Every platform detail lives in
core.hppandbox.hpp, so macOS would be a third platform there. Known obstacles: POSIX shared memory names are limited to 31 characters, whichSBX:<name>with names of up to 240 characters does not fit; there is no futex; there is noposix_fallocate; leftover segments cannot be listed. - A read-only open mode.
- Big-endian hosts.
References¶
- Arrow PyCapsule Interface: https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html
- DLPack Python specification (
__dlpack__,max_version, capsule renaming): https://dmlc.github.io/dlpack/latest/python_spec.html - Ulrich Drepper, "Futexes Are Tricky": https://www.akkadia.org/drepper/futex.pdf
- psutil, process start time as identity: https://github.com/giampaolo/psutil
- Microsoft, kernel object namespaces (
Local\,Global\): https://learn.microsoft.com/en-us/windows/win32/termserv/kernel-object-namespaces