Changelog¶
All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
Dates are marked as DD-MM-YYYY
0.11.0 - 20-11-2026¶
Added¶
RequestRefused: an exception a request handler raises to refuse a request. The caller getsRequestErrorwith its type and message, as for any exception of a handler, and the serving process logs nothing for it. (#125)
def move(position: float) -> float:
if position > 10.0:
raise RequestRefused(f"{position} is past the end")
return position
Changed¶
SharedBox.snapshotcopies only the bytes each field uses when the record is larger than 4 KiB, where it used to copy the whole room of everystr,bytes, list, set, dict andMaxShapefield. C++ gets the same read ashandle::read_record_used. (#122)- Writing a
list,tuple,set,frozensetordictto a field of aSharedBoxno longer calls into Python to check the value's type; a write of 16 elements takes about a quarter less time. (#124) - A reference field annotated
Xis read withXitself when two classes of the process have the box's schema hash, as after a module is imported again; it used to be read with the one defined first. A box of a subclass ofXis read with the class of its hash defined last, a subclass ofXbefore any other, andBoxRef.box_classgives the class defined last. (#128) SharedBox.closeno longer waits for a thread of the same process that waits for the box's lock. That thread stops waiting within a millisecond and raisesBoxClosedError, where it used to wait out the class'slock_timeoutand raiseLockTimeoutError. C++ gets the same throughhandle::set_wait_cancel. (#128)- Reading one
MaxShapefield of aSharedBoxcopies the shape and the elements the array holds, where it used to copy the field's maximum size; a 4 by 4 array in a field of at most 1024 by 1024uint8elements is read about 300 times faster. C++ gets the same read fromhandle::read_used, which now takes amax_arrayfield. (#136) SharedBox.__sharedbox_box__raisesBufferErrorwhen the minor version ofmax_versionis older than the oldest whose readers open the box, such as(3, 2)for a box with aMaxShapefield. It used to hand the capsule over, and the consumer then refused the box as corrupt. (#140)
Fixed¶
- On Linux, a process that
killfinds but whose/proc/<pid>/statis missing is no longer taken for exited, so its waiter slot, its reader entry or its claim on a stream's sender is not freed while it may still run. (#126) ReceiveEvents.endedis emitted once for a reader. It used to be emitted again each time thereceivedcallbacks were all disconnected and one connected again after the stream had ended. (#128)- At interpreter exit, sharedbox waits up to a second for threads it woke
inside a call, such as a daemon thread waiting in
receive, to leave it. nanobind no longer reports the stream end such a thread called on as leaked. (#140) - On Linux, a process in a time namespace other than the initial one, as
unshare -Tor a CRIU restore gives, is no longer taken for exited by a process outside that namespace, whose reading of its start time from/proc/<pid>/statis shifted. Its waiter slot, its reader entry and its claim on a stream's sender are kept, as for a process of another pid namespace. (#140)
0.10.0 - 16-11-2026¶
Breaking¶
- A map in the metadata of a box or a stream reads back as a
frozendict, which can be pickled, deep-copied and converted to JSON, in place of atypes.MappingProxyType. It is the builtin type from Python 3.15 on and the type of thefrozendictpackage before, which is a new dependency on those versions. See "How to migrate from 0.9". (#112) - The size of a field is given in its annotation only, with
CapacityandShapeinAnnotated.field()no longer takescapacityorshape, a record member no longer takes its shape from the"shape"entry of its field metadata, and a default array no longer gives an array field its shape. See "How to migrate from 0.9". (#113) timeoutis keyword-only inSharedSendStream.send,asend,reserveandareserve, inSharedReceiveStream.receiveandfetch, and insharedbox.bluebox.DocumentReceiver.receive. See "How to migrate from 0.9". (#113)SharedBox.metadata_version_ofandSharedStream.metadata_version_ofare renamedmetadata_at, and a box field can no longer be namedmetadata_at. See "How to migrate from 0.9". (#113)SharedSendStream.writingandawritingare renamedreserveandareserve. See "How to migrate from 0.9". (#113)attr()no longer takestimedorsettable, andFieldno longer hastimedorsettableattributes. EveryAttrwith a value stores the time of each publish, sotimestamp_nsis always a key ofAttrValue, and only aSettinghassetpoint,set()andpublish(setpoint=...). See "How to migrate from 0.9". (#116)
Added¶
SharedBox.locked()holds the box's write lock for awithblock, so a write computed from the box's values loses no update to another process:
Leaving the block counts one write for each field it assigned; a block that
raises puts every field back and counts nothing. C++ gets the same through
handle::begin_record_write, held_bytes, write_held, end_record_write
and abort_record_write. (#109)
- sharedbox.bluebox carries the documents of bluesky runs to other
processes. DocumentSender is a RunEngine callback that sends on a named
channel, and DocumentReceiver receives the documents in the order they
were sent, in mode lossless, lossy or latest, with each event's
arrays copied through shared memory:
sender = DocumentSender.create("beamline")
engine.subscribe(sender)
for name, doc in DocumentReceiver.attach("beamline", mode="lossy"):
...
A receiver that attaches during a run first gets its start and descriptors.
ReceiverReleasedError and LateJoinError report a receiver that lost
documents or cannot join the run under way. The bluebox extra installs
what it needs. (#110)
- SharedReceiveStream.areceive, areceive_into and afetch receive and
fetch an item without blocking the event loop, as SharedSendStream.asend
sends one, and take a timeout. (#113)
- SharedBox and SharedStream work with async with, which closes them
when the block ends, as with does. (#113)
- SharedStream.unlink can be called on a stream with no argument, as
stream.unlink(), to remove that stream's name. (#113)
- sharedbox exports Mode, Start and OnFull, the literal types of a
reader's mode and start and of a sender's on_full, and IterInto, the
type SharedReceiveStream.iter_into returns. (#113)
- Setting[T], an Attr that also holds a setpoint, which other processes
change through set() (#116):
Changed¶
- Opening a box or stream that holds a kind this version does not read, inside
a field or as a stream item, raises
SchemaMismatchErrornaming the kind, such as "holds a value of kind 80, which this sharedbox does not read", instead of reporting a corrupt header. C++ getsstatus::unsupportedwith the kind inerror::found, and C getsSBX_E_UNSUPPORTED(-18), in place ofstatus::corruptandSBX_E_CORRUPT. (#108) - A changed field is decoded for
SharedBox.eventsonly when a callback is connected to it, and on Windows a wait for the lock of a box yields for 1 ms before it sleeps, so it no longer sleeps a whole timer tick behind a large write or a shortlocked()block. (#112) - The
identityclass keyword ofSharedBoxraisesValueErrorfor a string that contains|. (#112) - A
lossyreader that falls a whole ring behind goes on from the middle of the ring and counts the older half inmissed, where it used to go on from the oldest item. C++stream_reader::receivefollows the same rule. (#112) - A request that a later one replaced before any server took it raises
RequestSupersededErrorat once, also while no process serves the field. It used to stay pending until a server took the later request. C++handle::request_answer_ofreportsrequest_outcome::supersededfor it. (#112) - A blocking
SharedReceiveStream.receiveorSharedSendStream.sendthat has to wait no longer makes a first native call that fails, a waiting item is received without giving up the GIL, and writing alist,setordictfield no longer clears the field's whole capacity. (#112) FieldFuture.resultandRequestFuture.resultraiseRuntimeErrorwhen the result is not ready and the call comes from a callback of the same box'sevents, where they used to wait until their timeout. (#112)
Fixed¶
- A box class defined in a function, in a module with
from __future__ import annotations, can name a type defined in that function. (#112) - Assigning an enum value that is not one of its class's members raises
ValueErrornaming the field, in place ofIndexError. (#112) - A reference field may be annotated
Annotated[Box, ...]orFinal[Box]. (#112) CapacityraisesTypeErrorfor a size that is not anint. (#112)send_nowait,receive_nowaitand the first step ofasendandasync forreturn at once while another thread waits in a call on the same end, so they no longer block the event loop for up to a second. (#112)- A record type of 4 GiB or more, and a box class whose fields exceed the
size of a box, raise
TypeErrorsaying the size when the class is defined. (#112) reprof a box inside its ownlocked()block, and of the block's object after the block, returns<Name locked>in place of raising. (#112)SharedBox.closecancels the pending futures when a served field cannot be released, and a secondRequestServer.stopfrees a field that the first call, made inside alocked()block, could not. (#112)- The error of a request handler is logged with every character that UTF-8
cannot encode escaped, such as a lone surrogate, so the record can be
written to a log file. The traceback is part of the message text, and the
record no longer carries
exc_info. (#112) - A process no longer aborts at exit when a daemon thread is inside a box or
a stream call: a thread that the exit cleanup ends with
BoxClosedError,StreamClosedErrororLockTimeoutErrorprints no traceback. (#112) - Connecting a callback to the
eventsof a stream reader that nothing refers to any more logs a warning. (#112) - Reading metadata whose stored bytes are not a metadata document is
refused. C++
read_metadatareturnsstatus::corrupt. (#112) SharedBox.lockedworks for a class whose__init_subclass__accepts no keyword. (#112)receiveon alossyorlatestreader raisesTimeoutErrorat its timeout when the sender overwrites every item during its copy. (#112)- On Windows a process is counted as exited only when no process has its pid, not when the process cannot be opened for another reason. (#112)
- Reading a
boolfield whose stored byte is neither 0 nor 1 raisesValueErrornaming the field, as aboolinside a record does. (#112) - The thread behind
SharedBox.events,watchand requests keeps running after a callback raisesSystemExitor reading a changed value raises. AFieldFuturewhose value cannot be read fails with that error. (#112) - A first
SharedBox.eventsthat raises, such as on a lock timeout, no longer leaves a group that never emits. (#112) - On Linux, a sender that was killed while it claimed the stream, after it
stored its pid and before its namespace and start time, is replaced after
100 ms. It used to keep every later
SharedStream.senderbusy, and readers never saw the stream end. (#112) - A
latestreader returns the newest item when it had kept an older one from a cancelled receive, and counts the older one inmissed. (#112) - A
ReceiveEvents.receivedcallback that raisesSystemExitno longer stops delivery. (#112) BoxEvents.followraisesBoxClosedErrorwhen the box is closed while the call starts, where it used to start forwarding on the closed box. (#112)- A field that a box class takes from a base that is not a box class keeps
the default that base gives it, or its
field()options. It used to become a required field. (#112)
0.9.0 - 04-11-2026¶
Added¶
segment_status:segment_status("lab:counts")returns aSegmentStatus,missingwhen no box or stream is published under the name,runningwhile the process that created it runs andcreator_exitedonce it has ended.core.hppaddssegment_statusandsegment_statefor C++. (#94)SharedReceiveStream.fetch,fetch_intoandfetch_future:reader.fetch(120)returns the item at position 120, waiting until the sender has sent it, and leaves the reader's receive cursor andmissedunchanged.ItemGoneError, aLookupErrorwhoseoldestis the oldest position the ring held, is raised once the ring no longer holds the item.stream.hppaddsstream_reader::fetchandfetch_withfor C++. (#95)MaxShapeon box fields: a box field declared asAnnotated[npt.NDArray[np.uint16], MaxShape((2048, 2048))]holds an array of any shape up to that maximum, as kind 75 of box layout 3.3, and every read returns an array of the stored shape. A write stores the shape and only the elements in use.SharedBox.writingtakesshape, sobox.writing("image", shape=(480, 640))sets the shape and yields a view of it under one lock.read_intoraisesTypeErrorfor aMaxShapefield. (#97)BoundedList,BoundedSetandBoundedDicttake their element types as the first arguments when the class fixes none:BoundedList(int, [1, 2], capacity=4)equalsBoundedList[int]([1, 2], capacity=4), andBoundedDict(str, float, {"a": 1.0}, capacity=8)takes the key and value types. (#97)TimedandTimed.now: a box field, record member, collection element or stream item declared asTimed[float]stores the value with a timestamp in nanoseconds since the Unix epoch, andbox.temperature = Timed.now(21.5)stamps it with the system clock when the write holds the box's lock, or just before a stream send publishes the item. ATimedwith a timestamp of its own is stored as given. Timed values are kind 77, and streams use stream layout 1.5. (#99)Attr,attr,AttrValue,RequestFutureandRequestServer: a box field declared asexposure: Attr[float] = attr(timed=True, settable=True)holds a value its owner writes withbox.exposure.publish(value=..., setpoint=...)and any process reads with.value,.setpoint,.timestamp_nsorread(), or watches withwatchandevents. An attribute with arguments, such asmove: Attr[float, [float]] = attr(), or a settable one carries a typed request to the one process that serves it:box.move.serve(handler)answers with a sync or async handler, andbox.move(5.0)orbox.exposure.set(0.02)returns aRequestFuturewaited on with.result(timeout)orawait. Of the requests sent while the handler runs, only the newest is handled next.RequestError,RequestSupersededErrorandServerExitedErrorreport a failed, replaced or abandoned request, andAlreadyServedErrora second server. Attribute fields are kind 76 of box layout 3.3, andbox.hppaddsattr_publish,attr_read,attr_published,attr_value_atand the request protocol steps onhandlefor C++, andtype_viewgives an attribute's flags and where its value, timestamp and setpoint start. (#103)
Fixed¶
- On Windows, an operating system failure to create or open a box or stream raises
OSErrorwith the Windows error code inwinerror, such asPermissionErrorfor a segment the process may not open, instead ofRuntimeError. (#96)
0.8.0 - 30-10-2026¶
Breaking¶
sharedbox.Shapetakes its dimensions as one tuple,Shape((480, 640)), in place of one argument per dimension. See How to migrate from 0.7. (#88)SharedBoxreserves the namesmetadata,metadata_versionandmetadata_version_of: a field orInitVarwith one of them raisesTypeErrorwhen the class is defined. Rename the field:
# 0.7
class Parcel(SharedBox):
metadata: Annotated[str, Capacity(64)] = ""
# 0.8
class Parcel(SharedBox):
label: Annotated[str, Capacity(64)] = ""
SharedBox.update takes the keyword metadata, so a type checker refuses
update(**values) when the values of the dictionary have a type that the
box's metadata type does not accept, such as str:
# 0.7
def restock(parcel: Parcel, values: dict[str, str]) -> None:
parcel.update(**values)
# 0.8
def restock(parcel: Parcel, values: dict[str, Any]) -> None:
parcel.update(**values)
See How to migrate from 0.7. (#91)
Added¶
MaxShape: an array of a stream item declared with a maximum shape, as inAnnotated[npt.NDArray[np.uint16], MaxShape((2048, 2048))], stores its own shape with each item, as kind 75 of stream layout 1.2.writing()views the slot in the shape of the template's array,slot.sendpublishes the first rows of that view without a copy, andreceive_intoreturns a view of the stored shape overout. (#88)SharedStream.sender(on_full="release"): a send that has waited its wholetimeoutreleases the lossless readers a full ring behind and sends, as instream.sender(on_full="release").send(item, timeout=0.1). Each released reader raisesReaderReleased, whosemissedcounts the items it lost, and goes on at the newest item;ReceiveEvents.releasedreports the count to callbacks.SharedSendStream.asendandawritingtake atimeout. Instream.hpp,send,send_withandbegintake anon_fullpolicy, and a released reader'sreceivegivesstatus::released, in stream layout 1.3. (#89)MetadataFullErrorandMetadataGoneError: raised when an add finds no room for a version, and when the version a read asks for is no longer held. (#91)SharedStream.metadata: a stream keeps metadata the same way.SharedStream.create(Reading, capacity=8, metadata={"unit": "kg"})stores version 1.SharedSendStream.send,asend,send_nowaitandSendSlot.sendtakemetadata=and add a version that applies from that item.SharedReceiveStream.metadataandmetadata_versiongive the version of the item the reader received last.SharedStream.createtakesmetadata_capacityandmetadata_versions, andcreateandattachtakemetadata_type.sharedbox0.7.0 and earlier cannot open a stream created with metadata or ametadata_capacity. (#91)box.hpp,stream.hppandsharedbox_c.h: box layout 3.2 and stream layout 1.4 hold metadata after the record or the description table.handleandstreamgainmetadata_headandread_metadata, andstream_readergainsmetadata_version_at.handleandstream_sendergainadd_metadata.handle::write(values, doc, lock_timeout)andwrite_largewith the same arguments write fields and add a version in one write, andstream_sender::can_add_metadatachecks an add without making it.sharedbox_c.haddssbx_metadata_head,sbx_read_metadata,sbx_add_metadataandSBX_E_METADATA_FULL. (#91)SharedBox.metadata: a box keeps metadata, JSON-like values stored as CBOR in its segment, in numbered versions.Scale.create(name, metadata={"unit": "kg"})stores version 1, andSharedBox.update(metadata=...)adds the next one from any process, with or without field values, in one write.metadata,metadata_versionandmetadata_version_ofread the versions, a map as a read-only mapping and a list as a tuple.BoxEvents.metadatais emitted with each new version. The class keywordsmetadata_capacityandmetadata_versionssize the room for versions, andclass Scale(SharedBox[Calibration])gives the metadata's type to type checkers. (#91)
Changed¶
sharedbox.DTypeis aStrEnumwith one member per element type:DType(numpy.uint8)returnsDType.uint8, which equals"uint8". (#88)
Fixed¶
SharedBoxandSharedStreamat exit: theatexithook ofsharedboxcloses every box and stream the process still has open and releases the native objects ofSharedBoxsubclasses, their watches and events groups, so nanobind reports no leaked instances when a box class defined at module level outlives shutdown. A box or stream used after the hook raisesBoxClosedErrororStreamClosedError, and creating or attaching a box raisesBoxClosedError. (#90)
0.7.0 - 28-10-2026¶
Added¶
np.int8,np.int16,np.int32,np.uint8,np.uint16,np.uint32,np.uint64,np.float16,np.float32,np.complex64andnp.datetime64as field types, record members, collection elements and stream items, stored at their own width as kinds 13 to 23 of box layout 3.1 and stream layout 1.1. A field reads back as its numpy type, and a value that does not fit the width raisesOverflowError. Anp.datetime64field stores nanoseconds since 1970. (#66)sbx_read_float16,sbx_write_float16,sbx_read_float32andsbx_write_float32insharedbox_c.h. (#66)- An array annotated
X | Noneas a field, record member or stream item, holdingNoneor an array of its sizes, as inscan: npt.NDArray[np.uint8] | None = field(default=None, shape=(32, 32)).receive_intodoes not fill one. (#67) field(capacity=...): the capacity of a box field of text, bytes,bytearray,Decimalor a collection, as insamples: list[float] = field(capacity=16). (#68)- An array member of a dataclass or attrs record takes its sizes from
metadata={"shape": (32, 32)}on its field. (#68) BoundedList[T]: a list value that keeps the stored bytes of a list field, as insamples: Annotated[BoundedList[float], Capacity(65536)]. It takes every element typelist[T]takes and is stored aslist[T]is. A read copies the bytes without decoding an element, a write of aBoundedListof the field's element type copies them back, indexing decodes or encodes one element, and a change past the capacity raisesValueError. Subclasses, generic or with a fixed element type, can be declared in its place. (#73)BoundedSet[T]: a set value that keeps the stored bytes of a set field, as inseen: Annotated[BoundedSet[int], Capacity(65536)]. It is stored asset[T]is. A read copies the bytes without decoding an element, a write of aBoundedSetof the field's element type copies them back, andin,addandremoveencode one key and compare stored bytes, through an index after 64 lookups in a set of more than 8 elements. The set operators take any set and return aBoundedSetof the same class and capacity, the comparisons take any set, and a change past the capacity raisesValueError. A declaration raisesTypeErrorfor an element type whose equal values could be stored differently, such asDecimalorint | float. Subclasses, generic or with a fixed element type, can be declared in its place. (#77)BoundedDict[K, V]: a dict value that keeps the stored bytes of a dict field, as inweights: Annotated[BoundedDict[int, float], Capacity(4096)]. It is stored asdict[K, V]is. A read copies the bytes without decoding an item, a write of aBoundedDictof the field's key and value types copies them back, andd[key],getandinencode one key and compare stored bytes, through an index after 64 lookups in a dict of more than 8 keys. It keeps insertion order,|takes any mapping and returns aBoundedDictof the same class and capacity, and a change past the capacity raisesValueError. Keys follow the rules ofBoundedSetelements, and values can be of any type adictfield holds. Subclasses, generic or with fixed key and value types, can be declared in its place. (#82)BoundedListofint,float,bool,complexor NumPy integer, float, complex orbool_elements supports the buffer protocol:np.asarray(value)andmemoryview(value)share its elements without decoding them, read only forboolandbool_, and a change of length raisesBufferErrorwhile such a view exists. (#85)
Changed¶
- Reading a
list,tuple,set,frozensetordictfield allocates and copies less, and reading a record whose class takes every member by position no longer builds a dict of keyword arguments. (#65) - A union stores a number through its first member of the same kind of
number, so
np.int64(5)written tofloat | intreads back as5. (#66) int,float,complexandboolfields take numpy's integer, floating, complex and bool scalars, and read back the Python type.np.int64,np.float64,np.complex128andnp.bool_fields read back as those types and hash asint,float,complexandbool. (#66)- The extension is compiled for speed instead of size. Writing a
list,setordictfield, and reading, indexing or looking up aBoundedListorBoundedSet, take less time. The wheels are about 75 KB larger on Linux and 17 KB larger on Windows. (#79)
Fixed¶
- A
list,setordictwhose slots end short of its alignment, such asAnnotated[list[Color], Capacity(3)]for anEnumColor, is accepted; its size is rounded up to the alignment.sharedbox0.6 refuses a segment that holds one. (#66) - A
TypeErrorabout the sizes of an array member of a dataclass or attrs record names its metadata shape, as inmetadata shape (3), instead offield(shape=...). (#70)
0.6.0 - 24-10-2026¶
Added¶
status::foreignandSBX_E_FOREIGN(-12): the segment's magic is not one this version knows. Python raisesSchemaMismatchError. (#47)sharedbox::to_expectedandsharedbox::from_expected: convert asharedbox::resultto astd::expectedand back on C++23. (#47)KindMismatchError, aSchemaMismatchErrorraised when a name holds a segment of another kind;status::kind_mismatchandSBX_E_KIND(-11) insharedbox.hppandsharedbox_c.h. (#47)sharedbox::stream,sharedbox::stream_senderandsharedbox::stream_readerinstream.hpp, included bysharedbox.hpp: a ring in shared memory with one sender and up tomax_readersreaders, each readingread_mode::lossless,read_mode::lossyorread_mode::latest, laid out as stream layout 1.0. C++ only.stream_sender::begin,publishandabandonreserve a slot, fill it in place and publish it or give it up. (#48)status::busy(-13),status::ended(-14) andstatus::interrupted(-15), withSBX_E_BUSY,SBX_E_ENDEDandSBX_E_INTERRUPTEDinsharedbox_c.h. (#48)SharedStream,SharedSendStreamandSharedReceiveStream: send items of any type aSharedBoxfield takes from one process to up tomax_readersreaders, each readinglossless,lossyorlatest, with blocking, non-blocking and asyncio calls,receive_intointo the caller's arrays andreceive_future, aconcurrent.futures.Future. A stream passed to another process arrives attached, or raisesSchemaMismatchErrorif its name now holds a stream created since, andSharedStream.createwithout a name gives the stream a new one. The ends cannot be pickled;SharedSendStream.streamandSharedReceiveStream.streamreturn their stream. (#49)SharedReceiveStream.events, aReceiveEventspsygnal group whosereceivedandendedsignals deliver a reader's items to callbacks. (#49)WouldBlock,EndOfStream,StreamBusyErrorandStreamClosedError. (#49)SharedStreamStatisticsandReceiveStreamStatistics, returned bySharedStream.statistics(). (#49)WaiterSlotsFullErroris exported fromsharedbox; opening a reader raises it whenmax_readersreaders are open. (#49)benchbox ops: the rowwatched write int, a write while another process has a watcher open. (#50)sharedbox::handle::sleepers(): the number of threads inside a wait on the box, in any process. (#51)benchbox stream: items per second ofSharedStreamreaders in each mode againstmp.Queueand aSharedMemoryring with a lock, and a table ofsendandasendwithreceive,async forandevents.received, with the 50th, 90th and 99th percentile latency.--short,--table,--jsonand--markdownare its options;benchbox allruns it and writesstream.json. (#53)Streamsworkflow:benchbox streamon the base branch against the pull request, withscripts/stream_compare.pywriting the table. (#53)benchbox roundtrip: the rowSharedStream. (#53)benchmarks/test_bench_stream.py: a CodSpeed benchmark ofsendplusreceive_into. (#53)FieldWatch.future(), returning aFieldFuture, aconcurrent.futures.Futureof the next write to the field;FieldFutureis exported fromsharedbox. (#55)field(shape=...): the sizes of an array field of a box.
class Grid(SharedBox):
cells: npt.NDArray[np.uint8] = np.zeros((4, 6), np.uint8)
weights: npt.NDArray[np.float32] = field(shape=(3,))
A box array field also takes its sizes from a plain default array, so it
needs no Shape and, with a dtype in its annotation, no DType. (#56)
- SharedSendStream.writing() and SharedSendStream.awriting(), which yield a
SendSlot:
blank = Frame(0, np.empty((0, 0), np.uint16))
with sender.writing(blank) as slot:
slot.item.image.fill(0)
slot.send(replace(slot.item, index=1))
slot.item is an item built from a template, with arrays over the next slot
to fill in place, and slot.send(item) publishes an item without copying the
arrays already in the slot. (#58)
Changed¶
sharedbox.hpp: split intocore.hppandbox.hpp, which it includes.sharedbox::resultis the library's own type on C++20 and C++23 alike, and itserror()is asharedbox::errorholding the status, the OS error and what was found. The C++ names moved fromsharedbox::v2tosharedbox::v3. (#47)sharedbox::header: the magic, versions, schema hash, creator, waiter slot count and size moved into its first member,common, asharedbox::common_header;layout_majorandlayout_minorbecamecommon.kind_majorandcommon.kind_minor. (#47)sharedbox::error: astatus::osfailure carries the OS error inerror().os;errnoandGetLastError()no longer hold it reliably when the call returns. (#47)- Segment layout: every segment starts with a common first line (magic, core version, layout version of its kind, schema hash, creator), and boxes use layout 3.0. A box made by 0.5 cannot be opened by 0.6, nor the other way round. (#47)
sharedbox::inspect: returnsresult<common_header>. (#47)sharedbox::magic: renamedsharedbox::box_magic. (#47)box_ref: a reference field stores the name of its target in 240 bytes, so the field takes 256 bytes. (#47)SharedBoxnames: one or more segments of[A-Za-z0-9_-]joined by:, up to 240 characters, such asbl01:camera:det1:frames..is no longer allowed. The shared memory is/dev/shm/SBX:<name>on Linux andLocal\SBX:<name>on Windows, and Windows waiter events end in#w<i>. (#47)SharedBox.attach: a segment whose magic this version does not know, such as a box made by 0.5, raisesSchemaMismatchErrorat once, instead ofSegmentNotFoundErrorafter the timeout. (#47)SharedBoxwrite: makes a wake call only when a thread is waiting on the box.sleepers, at offset 84 of box layout 3.0, counts the threads inside a wait. It adds 1 towake_wordonly whensleepersis not 0. (#51)sharedbox::waiter_slot: 32 bytes, withasleep_on, at offset 24, the offset of the count the slot's current wait added 1 to, and a reserved word. Freeing the slot of a process killed inside a wait takes that thread out ofsleepersfor a box, and out ofdata_waitingorspace_waitingfor a stream. (#51)benchbox plot: writes plotly figure JSON (charts/ops.json,roundtrip.json,stream-throughput.json,stream-matrix.json) instead of SVG files. (#53)benchmarksextra and group: depend onplotlyinstead ofmatplotlib. (#53)- Array fields: an annotation that names its number of dimensions, as in
numpy.ndarray[tuple[int, int], numpy.dtype[numpy.uint8]], raisesTypeErrorwhen itsShapehas another number, in a box, a record and a stream item. (#56) - Array fields: a default array whose shape differs from the field's
ShaperaisesTypeErrorinstead ofValueErrorwhen the class is defined. (#56)
Removed¶
0.5.0 - 09-10-2026¶
Added¶
SharedBox.read_into: copies an array field into an array the caller passes and returns it, without allocating a new array.SharedBox.writing: a context manager that holds the box's write lock and yields an array field as an array to fill in place.benchbox contention: times writes and reads of anintwhile several writer and reader processes share it, for a box,mp.ValueandSharedMemorywith aLock.
Changed¶
SharedBox: a field namedread_intoraisesTypeError.SharedBox: a field namedwritingraisesTypeError.SharedBox: reading a collection, tuple or record field whose members arebool,int,floatorstrtakes less time: about 90 ns less for a list of 16floaton Windows.SharedBox: reading a field whose value cannot be changed (a frozen dataclass, attrs class or msgspec Struct, a NamedTuple, a tuple, a frozenset, an enum, flag or literal,complex,date,time,datetime,timedelta,UUIDorDecimal) returns the value the previous read built until the field is written: 40 ns instead of 540 ns for a frozen dataclass of four fields on Windows. A tuple, frozenset or record qualifies only when its members are of these kinds orbool,int,float,strorbytes.SharedBox: a frozen record's__post_init__, attrs converters and validators run on the first read after each write instead of on every read.
Fixed¶
SharedBox.attach: a box whose header gives a field count other than the class's raisesSchemaMismatchErrorinstead ofValueError.
0.4.1 - 07-10-2026¶
Changed¶
SharedBox.update: takes about 7 to 9 ns less per call on Windows.
Fixed¶
SharedBox.events,SharedBox.watchandBoxEvents.follow: a process that exits while watcher threads still run no longer aborts withterminate called without an active exceptionon Linux with CPython 3.11 to 3.13. At exit, sharedbox stops every watcher thread and waits up to 2 seconds in all for them to end, including any callback they are running.
0.4.0 - 05-10-2026¶
Added¶
benchbox plot: draws the results ofbenchbox allas SVG charts, in a light and a dark variant. Thebenchmarksextra now includes matplotlib.SharedBox: fields of typecomplex,datetime.date,datetime.time,datetime.datetime,datetime.timedelta,uuid.UUIDandAnnotated[decimal.Decimal, Capacity(n)].SharedBox:enum.Enum,enum.Flagandtyping.Literalfields.SharedBox:X | Noneand union fields.SharedBox: record fields: dataclasses,NamedTuple, fixed-length tuples,TypedDict, attrs classes andmsgspec.Struct.SharedBox:list,tuple[T, ...],set,frozenset,dictandbytearrayfields and theircollections.abcforms, with aCapacityin elements.Shape,DType,SupportsDLPack,register_array_type: array fields through DLPack.sharedbox.hpp:type_view,handle::field_type,handle::types_table,handle::major_version,oldest_layout_major,time_value,datetime_value,timedelta_value, the kind codeskind_complextokind_decimalandkind_enumtokind_array,max_type_depth,max_types_size,max_mapping_size,first_described_kind,max_date_ordinal,unix_epoch_ordinal,micros_per_day,max_offset_minutes,literal_nonetoliteral_enum,type_head,dl_dtype,literal_value,encode_*anddecode_*functions for complex, date, time, datetime, timedelta, uuid, flag and position values,decode_bool,decode_present,decode_tag,decode_length,handle::read_used,handle::read_large,handle::read_record_largeandhandle::write_large.sharedbox_c.h:sbx_field_desc, the structssbx_time,sbx_datetimeandsbx_timedelta, and typed reads and writes of complex, date, time, datetime, timedelta, UUID, enum and literal positions, flag bits and optional presence.benchbox ops: rows for datetime, record, list and array fields.
class Frame(SharedBox):
taken: datetime.datetime
image: Annotated[np.ndarray, Shape(480, 640), DType("uint8")]
tags: Annotated[list[Annotated[str, Capacity(16)]], Capacity(8)] = field(
default_factory=list
)
Changed¶
- Segments use layout 2.0. Releases 0.3.0 and 0.3.1 cannot open a box made by this version; this version opens boxes made by them.
SharedBox.eventsandSharedBox.watch(): a field counts as changed when its stored bytes change. WritingNaNagain no longer emits;-0.0after0.0does.Capacity: also sets the most elements of a collection.sharedbox.hpp: the inline namespace isv2;handle::createandhandle::create_unpublishedtake a description table.- The
benchmarksextra includes numpy. SharedBox.updateandSharedBox.snapshot: native methods, unless a class defines or inherits its own.
Fixed¶
SharedBox: a class with more than one box base keeps the defaults and default factories of the fields it inherits from every base, not only the first.
0.3.1 - 01-10-2026¶
Added¶
sharedbox.__version__: the version of the installed package, as a string.
0.3.0 - 01-10-2026¶
Added¶
SharedBox: base class whose annotated fields live in a shared-memory segment.Capacity: byte capacity forstrandbytesfields.FieldWatch:forandasync forover new values of a field.SharedBox.events: psygnalSignalGroupwith one(new, old)signal per field.BoxClosedError,LockTimeoutError,SchemaMismatchError,SegmentExistsError,SegmentNotFoundError.benchbox: command withops,roundtrip,sizeandallbenchmarks, also run aspython -m sharedbox.benchmarks.benchmarksextra: installs Typer and pyperf forbenchbox.SharedBox:identityclass keyword; it enters the schema hash and names the box.SharedBox:max_waitersclass keyword, 1 to 4096 box handles that watch at once, default 64.SharedBox.__sharedbox_box__(): returns a"sharedbox_box"PyCapsule for other extensions.SupportsSharedBox: protocol for functions that accept a box.get_include(): folder holdingsharedbox/sharedbox.hpp,sharedbox/sharedbox_c.handsharedbox/sharedbox_c.cpp.sharedbox.hpp: header-only C++20 implementation of the segment layout, installed in the wheel with a CMake config (sharedbox::headers), which linksbcrypton Windows andrtandThreads::Threadson Linux.sharedbox-config-version.cmake: installed next tosharedbox-config.cmake;find_package(sharedbox 0.3)accepts 0.3 versions only.sharedbox_c.h: minimal C interface (sbx_open,sbx_import,sbx_schema_hash,sbx_read,sbx_write,sbx_release), built throughsharedbox::c.
class Frame(SharedBox, identity="camera/frame/1", max_waiters=16):
exposure: float = 0.01
count: int = 0
field(): per-fielddefault,default_factory,init,repr,kw_only,metadataanddocforSharedBoxfields.fields(): theFieldof each field of aSharedBoxsubclass or box.Field: read-only description of oneSharedBoxfield.SharedBox:dataclasses.InitVarannotations, passed to__post_init__and not stored.SharedBox.__post_init__(): runs after a box is created and before other processes can attach to it.SharedBox:inspect.signature()of a subclass gives its constructor parameters.sharedbox.hpp:handle::create_unpublished()andhandle::publish().SharedBox: reference fields, annotated with aSharedBoxsubclassXorX | None; reading one attaches the box it refers to, with that box's own class.BoxRef: frozen dataclass (name,schema_hash,create_id, and thebox_classproperty) thatsnapshot(),eventsandwatch()report for a reference field.BrokenReferenceError: raised when the box a reference field refers to was removed or created again since it was assigned.UnknownBoxClassError: raised when the box a reference field refers to has a class this process has not defined.SharedBox.snapshot():followkeyword;follow=Truereplaces each reference with the snapshot of the box it refers to.sharedbox.hpp:kind_refandbox_ref, the kind code and stored value of a reference field.
class Motor(SharedBox):
position: int
limit: int = field(default=100, kw_only=True, metadata={"unit": "mm"})
offset: InitVar[int] = 0
def __post_init__(self, offset: int) -> None:
self.position += offset
class Stage(SharedBox):
motor: Motor | None = None
BoxEvents: psygnalSignalGroupsubclass thatSharedBox.eventsreturns.BoxEvents.follow(): given a reference field, returns a group whose signals are emitted for changes inside the box the field refers to, whichever box that is; given no field, emits onnestedevery change inside the boxes the reference fields reach.BoxEvents.unfollow(): stops forwarding started withfollow().BoxEvents.nested:(path, new, old)signal of a class with reference fields.
motor_events = stage.events.follow("motor")
motor_events.position.connect(lambda new, old: print(new))
stage.events.follow()
stage.events.nested.connect(lambda path, new, old: print(path, new))
- Documentation site at https://jacopoabramo.github.io/sharedbox: tutorial, how-to guides, explanations and the API reference.
Changed¶
- Building the extension requires nanobind 3.1.0 or newer and a C++20 compiler.
- Wheels per platform:
cp311-cp311,cp312-abi3for CPython 3.12 and newer, andcp314-cp314tfor free-threaded CPython 3.14. SharedBoxfields are converted in the native module and packed by alignment; segments use layout 1.0, a plain named mapping.SharedBox: the default box name is 16 hex digits of SHA-256 over the identity, with nosharedbox-prefix. A box created by an earlier release undersharedbox-<hash>is not found under the new default name.- Shared-memory objects are named
sharedbox.<name>(/dev/shm/sharedbox.<name>,Local\sharedbox.<name>); boxes of earlier releases are not found under them. SegmentExistsError: says whether the box's creator is still running, runs in another pid namespace, or has exited, or that the name holds no published box.- A pickled
SharedBoxcarries its class's schema hash and its box's create id; unpickling with a different class, or after the box was created again, raisesSchemaMismatchError. SharedBox.attach(): shared memory that does not become a box within 1 s raisesSegmentNotFoundError.SharedBox.attach(): a segment of another layout major version raisesSchemaMismatchErrornaming the version.SharedBoxfields: reading or writing one field runs no Python code; deleting one raisesAttributeError.SharedBox: a subclass whose__slots__names_segmentraisesTypeError.SharedBox: an error about a field names the field asClass.field.SharedBox: a read or write that waits for another writer's lock lets other threads run.SharedBox.update(): takes about half the time; field names are checked only when one is unknown.SharedBox.snapshot(): builds its dict in the native module.SharedBox: thekw_onlyclass keyword and aKW_ONLYannotation apply only to the fields of the class that declares them; a subclass keeps each inherited field's keyword-only setting.SharedBox: a subclass that sets an unannotated class attribute on the name of an inherited field raisesTypeError.SegmentExistsError: for a box whose creator is still running__post_init__, says the box is being created by that pid.SharedBox.__sharedbox_box__(): raisesBufferErrorbefore the box is published.sharedbox.hpp:handle::openandhandle::from_capsuleaccept a field whose kind code they do not know and treat its bytes as opaque.sharedbox.hpp:handle::writereturnsstatus::rangefor a field whose kind code it does not know, andsbx_writereturnsSBX_E_RANGE.SharedBox.attach(): a segment with a field of a kind this version cannot read raisesSchemaMismatchErrornaming the kind.SharedBox: an annotation naming an undefined class raisesTypeError.SharedBox: a field namedfollow,unfollowornestedraisesTypeError.SharedBox.close(): called from an event callback, on a watcher thread, does not wait for the watcher threads of the boxes it closes, and drops the writes they had not delivered.
Fixed¶
SharedBox.watch(): no longer yields the same value twice.SharedBox.attach(): no longer fails when it runs while another process is still creating the box.SharedBox: a process that attaches while the box is being created sees the initial values, never a zeroed record.SharedBox.close(): no longer deadlocks while another thread's read or write waits for the write lock.SharedBox.close(): returns without waiting for the watcher thread's 0.1 s poll.SharedBox.watch()andSharedBox.events: on Windows, a write no longer reaches one of several waiting threads up to 50 ms late.SharedBox.watch()andSharedBox.events: keep delivering when every waiter slot is taken.SharedBox: on Linux, a box larger than the free space of/dev/shmraisesOSErrorat creation instead of the process receivingSIGBUS.
Removed¶
- Python 3.10 support.
SharedDictandsharedbox.utils.- Boost and vcpkg: the build no longer needs
VCPKG_ROOT. docs/api.md,docs/library-authors.mdanddocs/design/: their content is on the documentation site.
0.2.4 - 05-10-2025¶
Changed¶
- Rewrite codebase in nanobind
Fixed¶
- Parallelize CI so that each wheel is built with the correct version
- Also faster builds
0.1.0 - 29-09-2025¶
Added¶
- Initial release