Introduction
bsrs is a Rust-native re-implementation of the bluesky / ophyd acquisition stack — RunEngine, devices, plans, document sinks — built to be the kind of beamline data-acquisition daemon you can deploy without dragging a Python interpreter onto the IOC host.
What you get
- A
RunEnginethat mirrorsbluesky.run_engine.RunEngine: messages, states, suspenders, preprocessors, callbacks. Same wire-format Documents flow into the bluesky Python ecosystem (databroker, Tiled, BestEffortCallback) unchanged. - An ophyd-async-style device surface (
SignalRW,Movable,Triggerable,Stageable,Flyable) plus a sync facade so the same plan code works in both worlds. - Drop-in EPICS CA / PVA backends (
epics-ca-rs,epics-pva-rs) with sharded process-singleton registry, in-flight de-dup, RAII subscription tokens, and zero-copy NTNDArray decode for detector frames. - A bluesky-queueserver-compatible daemon (
bsrs qs-manager) that speaks JSON-RPC over 0MQ on the same control / document ports. - An interactive Lua REPL (
bsrs repl) for prototyping plans without recompile. - Document sinks for the bluesky Python ecosystem: JSONL, ZMQ (msgpack/JSON), Tiled (HTTP), Kafka, HDF5 (NeXus-flavored frame writer).
Who is this for
- Beamline scientists / controls engineers who want a faster, more predictable RunEngine with the same plan / device surface they already know.
- Sites running bluesky who want to keep their Python analysis pipelines but move acquisition off Python.
- Authors of new ophyd-style devices in Rust — the backend trait
set is small and stable (
SignalBackend,FrameSource/FrameSink,DetectorWriter).
Status (May 2026)
Core engine + plan library + document sinks are production-shape and tested. Notable opt-in features behind Cargo flags:
All flags below are features of the consolidated bsrs crate:
| Feature | Notes |
|---|---|
ca / pva (default) | live EPICS CA / PVA clients; pva also enables the NTNDArray monitor source |
zmq | bluesky Publisher envelope |
tiled | HTTP register + metadata patch via tiled-rs; Lua tiled.* read-side namespace |
kafka | pure-Rust rskafka crate, no librdkafka |
hdf5 | rust-hdf5 frame writer, NeXus layout |
metrics | Prometheus /metrics endpoint |
Roadmap items still open are listed in doc/10-roadmap.md.
Quickstart
The fastest path: open the Lua REPL, run a count, then a scan.
$ cargo run --bin bsrs -- repl
bsrs repl (Lua 5.4) — type `:help` for commands, Ctrl-D to exit
bsrs> det1 = soft_detector("det1")
bsrs> RE:run(count({det1}, 5))
exit_status=success run_uid=8e3f...
bsrs> m1 = soft_motor("m1", 0.0)
bsrs> RE:run(scan({det1}, m1, 0, 10, 11))
exit_status=success run_uid=...
Install
git clone https://github.com/physwkim/bsrs
cd bsrs
cargo build --release
ln -s "$PWD/target/release/bsrs" ~/.local/bin/
Sanity-check the environment
bsrs doctor
[ ok ] tokio runtime (multi-thread)
[ ok ] EPICS_CA_ADDR_LIST = 192.168.50.255
[warn] EPICS_CA_AUTO_ADDR_LIST = NO (not auto-detecting interfaces)
Add --tiled-url http://localhost:8000 and/or --kafka host:9092 to
probe those services too.
Write a plan
In Lua, mirror the bluesky bp.* / bps.* namespaces:
local det1 = soft_detector("det1")
local m1 = soft_motor("m1", 0.0)
-- Compound plans (bp.*)
RE:run(bp.count({det1}, 10))
RE:run(bp.scan({det1}, m1, 0, 1, 11))
RE:run(bp.grid_scan({det1}, m1, 0, 1, 5, m2, 0, 1, 5))
-- Stub plans (bps.*)
RE:run(bps.mv(m1, 0.5))
RE:run(bps.sleep(0.1))
Or write a coroutine-style plan that yields Msg values:
local function my_scan(detectors, motor, n)
coroutine.yield(msg.open_run({plan_name = "my_scan"}))
for i = 0, n - 1 do
local pos = i / (n - 1)
coroutine.yield(msg.set(motor, pos, "main"))
coroutine.yield(msg.wait("main"))
coroutine.yield(msg.create("primary"))
coroutine.yield(msg.read(motor))
for _, d in ipairs(detectors) do
coroutine.yield(msg.read(d))
end
coroutine.yield(msg.save())
end
coroutine.yield(msg.close_run("success"))
end
RE:run(plan(my_scan, {det1}, m1, 5))
Use the Lua REPL for fast iteration (no recompile). When the plan
is verified, port it to Rust — every coroutine.yield(msg.X) line
becomes a yield Msg::X in an async_stream::stream! block.
Subscribe to documents
RE:subscribe(function(name, body)
if name == "stop" then print("run finished:", body.exit_status) end
end)
RE:run(count({det1}, 5))
The callback runs on the REPL thread for every emitted Document
(start / descriptor / event / stop / resource / datum / …). For
document filters: pass an optional second arg, e.g.
RE:subscribe(cb, "event").
Persist runs to disk
-- (Inside the bsrs CLI the JsonlSink is the easiest writer to wire
-- up from Rust startup; from Lua REPL the engine has no sinks
-- attached by default. Production setups attach sinks during
-- `bsrs qs-manager` startup or via a small Rust glue binary.)
For the queueserver-style deployment (Documents fan out over ZMQ to
bluesky RemoteDispatcher and Tiled), see
CLI tour → qs-manager.
Migration from bluesky
bsrs is a drop-in replacement at the Document boundary. A site running bluesky today moves to bsrs by replacing one piece at a time, never the whole stack at once.
Where bsrs plugs in
bluesky / Python bsrs / Rust
Plan source generators (bp.*) / Lua coro bsrs::plans::* / Lua coro
RunEngine bluesky.RunEngine bsrs::engine::RunEngine
Devices ophyd / ophyd-async bsrs::devices, bsrs::protocols_async
Backends pyepics / aioca / p4p epics-ca-rs / epics-pva-rs
Document plumbing Publisher (ZMQ) ZmqDocumentSink
TiledWriter TiledSink + tiled-rs
suitcase-jsonl JsonlSink
bluesky-kafka KafkaDocumentSink
NDFileHDF5 (in IOC) Hdf5FrameSink (bsrs-stream)
queueserver worker bluesky-queueserver bsrs-qs (drop-in)
queueserver manager bluesky-queueserver unchanged (still Python)
Catalog browse databroker / Tiled tiled-rs / Python tiled
Live plot BestEffortCallback [open]
Three migration patterns
1. Keep bluesky-queueserver, swap the worker
You're running bluesky-queueserver with a Python worker today. Swap
the worker for bsrs qs-manager:
# Before
start-re-manager --kafka-server localhost:9092 ...
# After
bsrs qs-manager --control tcp://*:60615 --documents tcp://*:60625
The QS manager (and your existing 0MQ JSON-RPC clients, web UI, queue management) keep working. bsrs-qs implements the same RPC surface (~30 methods, see bsrs-qs/src/dispatch.rs).
Documents fan out from bsrs-qs's PUB socket to the same
RemoteDispatchers your downstream consumers already use.
2. Keep bluesky.RunEngine in Python, swap the document plumbing
bsrs has no in-process Python bindings (Rust-only by design). Instead,
run bsrs's RunEngine in a small Rust helper binary and ZMQ-publish
documents to your Python RemoteDispatcher setup. Same wire format as
bluesky.callbacks.zmq.
3. Native bsrs end-to-end
For new beamlines that don't have a bluesky / ophyd commitment yet:
bsrs repl --init beamline_devices.lua # interactive scans
bsrs qs-manager # production worker
Devices in Rust use #[derive(Device)] from bsrs-derive:
#![allow(unused)] fn main() { use bsrs::ophyd_async::*; #[derive(Device)] pub struct Motor<B> { #[signal(rw, "{prefix}.VAL")] pub setpoint: Signal<f64, B>, #[signal(ro, "{prefix}.RBV", kind = hinted)] pub readback: Signal<f64, B>, #[signal(rw, "{prefix}.VELO", kind = config)] pub velocity: Signal<f64, B>, } }
Plan code translation
bsrs-plans mirrors bluesky.plans 1:1 by name. Direct ports:
| bluesky | bsrs |
|---|---|
bp.count(dets, n) | bsrs::plans::count(dets, n) |
bp.scan(dets, m, a, b, n) | bsrs::plans::scan(...) |
bp.list_scan, rel_list_scan | bsrs::plans::list_scan, rel_list_scan |
bp.grid_scan, rel_grid_scan | bsrs::plans::grid_scan, rel_grid_scan |
bp.spiral_* | bsrs::plans::spiral_* |
bp.adaptive_scan | bsrs::plans::adaptive_scan |
bp.tune_centroid | bsrs::plans::tune_centroid |
bp.fly | bsrs::plans::fly |
bp.ramp_plan | bsrs::plans::ramp_plan |
bp.log_scan | bsrs::plans::log_scan |
bps.* (one-shot Msg helpers) | bsrs::plans::stubs::* |
bpp.run_wrapper | bsrs::plans::preprocessors::run_wrapper |
bpp.subs_wrapper | (no-op alias — see note below) |
bpp.relative_set_wrapper | bsrs::plans::preprocessors::relative_set_wrapper |
bpp.baseline_wrapper | bsrs::plans::preprocessors::baseline_wrapper |
bpp.contingency_wrapper | bsrs::plans::preprocessors::contingency_wrapper |
bpp.finalize_wrapper | bsrs::plans::preprocessors::finalize_wrapper |
bpp.configure_count_time_wrapper | bsrs::plans::preprocessors::configure_count_time_wrapper |
subs_wrapperis documented in bsrs as a no-op for parity. The recommended replacement isre.subscribe(cb)at engine creation time; bsrs has no equivalent of bluesky's per-runtemp_callback_idsswap.
Document compatibility
bsrs emits the bluesky event-model 1.x document shape verbatim, serialized as either JSON (default) or msgpack:
RunStart/EventDescriptor/Event/EventPageRunStopResource/Datum/DatumPageStreamResource/StreamDatum
A Python RemoteDispatcher configured with
deserializer=msgpack.unpackb consumes them unchanged; ditto
databroker if its catalog is wired to a Tiled / suitcase-jsonl
backend.
What's intentionally different
doc/03-runengine.md lists the few places bsrs diverges from
bluesky.run_engine.RunEngine:
msg_hook/state_hook/waiting_hook→tracingspans + broadcast subscribers.- string command + dictionary registry → typed
Msgenum +Msg::Custom { name, payload }escape hatch. _run_permit: asyncio.Event→tokio::sync::Notify+AtomicState.
These are equivalents, not omissions. See doc/03 for the full table.
What's deferred
bsrs does not (yet) ship a Python class for bsrs.RunEngine —
that's the M7 PyO3 layer in doc/10-roadmap.md. Until it lands,
the migration path is "bsrs binary on the IOC host, Python on the
analysis side, ZMQ between them."
Cookbook
Recipes for common beamline workflows. Every snippet is meant to be
pasted into either bsrs repl (local) or bsrs qs repl
(attached to a running daemon).
Count + scan + grid
The bluesky bp.* namespace is mirrored in bsrs. Common shapes
exposed in the Lua REPL:
RE:run(bp.count({det1}, 5))
RE:run(bp.scan({det1}, m1, 0, 10, 11))
RE:run(bp.grid_scan({det1}, {{m1, 0, 1, 5}, {m2, 0, 1, 5}}))
RE:run(bp.spiral({det1}, m1, m2, 0, 0, 1, 1, 0.1, 8)) -- last arg is integer nth
Not all bp.* plans are exposed in Lua yet (e.g. adaptive_scan,
tune_centroid are Rust-only as of this writing). Run them from
Rust via bsrs::plans::adaptive_scan(...) for now, or build the
plan as a Lua coroutine (see below).
mvr with baseline
mvr ("move relative") records a starting position, then sets the
motor to the new value. Wrap in baseline_wrapper so a snapshot of
your slits / monochromator / temperature is recorded at the start
and end of every run:
local plan_with_baseline = bpp.baseline_wrapper(
bp.scan({det1}, m1, 0, 1, 11),
{sl1, sl2, mono, sample_temp}, -- baseline devices
"baseline" -- stream name
)
RE:run(plan_with_baseline)
The result run has two extra streams (baseline_pre and
baseline_post) carrying one-shot reads of the listed devices.
Fly + HDF5 frame writer
For detectors that produce frames faster than a Python Read-loop
can drain, run a fly scan and write frames to NeXus-flavored HDF5
locally (no Document plane bytes). The fly_during_wrapper is
exposed from Rust:
#![allow(unused)] fn main() { use bsrs::plans::preprocessors::fly_during_wrapper; let fly_with_writer = fly_during_wrapper( bsrs::plans::count(vec![pilatus.clone()], 1), vec![(pilatus.clone(), pilatus.clone())], // (flyable, collectable) pair ); re.run_async(fly_with_writer).await?; }
For the multi-process layout (frame source on the IOC host,
RunEngine elsewhere), use bsrs frame-source — see
CLI tour → frame-source.
Custom subscriber
RE:subscribe(function(name, body)
if name == "stop" then
print("run finished:", body.exit_status, body.run_uid)
end
end)
RE:run(bp.count({det1}, 5))
The callback fires for every Document. Filter by name:
"start", "descriptor", "event", "stop", "resource",
"datum", "stream_resource", "stream_datum".
Inspect-driven debugging
Attach a REPL to the running daemon and inspect device state on the fly:
-- in bsrs qs repl
qs> motor:inspect()
=> {readback=0.5, setpoint=0.5, type="SoftMotor", units="mm", ...}
qs> det1:inspect()
=> {counts=42, type="SoftDetector", data_key="det1_counts", ...}
qs> -- check a Status object's progress
qs> local s = motor:set(2.0)
qs> s:inspect()
=> {done=false, success=null, exception=null, progress=0.0}
qs> s:wait()
qs> s:inspect()
=> {done=true, success=true, exception=null, progress=1.0}
Lua coroutine plans
For one-off scans you don't want to compile into bsrs::plans:
local function snake_grid(detectors, mx, my, x_pts, y_pts, exposure)
coroutine.yield(msg.open_run({plan_name = "snake_grid"}))
for j = 0, #y_pts - 1 do
coroutine.yield(msg.set(my, y_pts[j+1], "main"))
coroutine.yield(msg.wait("main"))
local order = (j % 2 == 0) and 1 or -1
for i = 0, #x_pts - 1 do
local xi = (order > 0) and (i + 1) or (#x_pts - i)
coroutine.yield(msg.set(mx, x_pts[xi], "main"))
coroutine.yield(msg.wait("main"))
coroutine.yield(msg.create("primary"))
coroutine.yield(msg.read(mx))
coroutine.yield(msg.read(my))
for _, d in ipairs(detectors) do
coroutine.yield(msg.read(d))
end
coroutine.yield(msg.save())
end
end
coroutine.yield(msg.close_run("success"))
end
RE:run(plan(snake_grid, {det1}, m1, m2,
{0, 0.5, 1.0, 1.5, 2.0},
{0, 0.5, 1.0},
0.1))
When the coroutine is verified, port to Rust by replacing every
coroutine.yield(msg.X) with yield Msg::X inside an
async_stream::stream! block. The Rust version executes at the
same Msg cadence with no Lua bridge cost per iteration.
Custom device methods (Rust → Lua)
Rust devices expose their own methods to Lua via #[lua_methods]:
#![allow(unused)] fn main() { use bsrs_derive::lua_methods; pub struct Diffractometer { /* ... */ } impl bsrs_core::msg::NamedObj for Diffractometer { /* ... */ } #[lua_methods] impl Diffractometer { #[lua_method] pub async fn set_orientation(&self, h: f64, k: f64, l: f64) -> Result<(), BsrsError> { /* ... */ } #[lua_method] pub async fn current_hkl(&self) -> (f64, f64, f64) { /* ... */ } } // at startup: let dx = Arc::new(Diffractometer::new(...)); reg.register_readable("dx", dx.clone() as Arc<dyn ReadableObj>); reg.register_lua_methods("dx", dx.clone()); }
From the daemon REPL:
qs> dx:set_orientation(1.5, 2.5, 3.5)
qs> table.unpack(dx:current_hkl())
=> 1.5 2.5 3.5
qs> dx:name() -- inherited from NamedObj
=> "dx"
The macro generates a JSON-shaped dispatch table so the daemon's
Lua bridge (host::manager_lua) can wire it into the mlua state at
startup.
Configure-time exposure
To set a uniform count_time across multiple detectors before a
plan, use the Rust-side wrapper (Lua exposure pending):
#![allow(unused)] fn main() { use bsrs::plans::preprocessors::configure_count_time_wrapper; let plan = configure_count_time_wrapper( bsrs::plans::scan(vec![det1, det2, det3], m1.clone(), m1.clone(), 0.0, 1.0, 11), 0.5, // exposure seconds vec![det1, det2, det3], // ConfigurableObj devices ); re.run_async(plan).await?; }
The wrapper emits Configure { obj, args: { count_time: 0.5 } }
for each detector at the head of the run. Detectors that don't
accept count_time will surface as Configure-time errors — the
wrapper does not suppress them.
Resilient cleanup
Run a finalize block whether or not the inner plan succeeds:
local cleanup = bps.mv(safety_shutter, 0) -- close shutter
RE:run(bpp.finalize_wrapper(
bp.scan({det1}, m1, -1, 1, 11),
cleanup
))
finalize_wrapper and the alias contingency_wrapper both run
the cleanup plan after the inner plan completes (success, abort,
or error). Pair with subs_wrapper (no-op alias for parity with
bluesky) if you're porting bpp.subs_wrapper calls verbatim.
Lock + RBAC for shared beamlines
The daemon supports a subsystem lock + per-group ACL:
# from one operator's terminal:
bsrs qs lock apply --queue --note "tuning the mono" alice-key
# any other client now sees:
$ bsrs qs queue start
{"error": {"code": -32000, "message": "operation rejected: subsystem is locked..."}}
# release:
bsrs qs lock release alice-key
For finer-grained control, supply a permissions.toml to
bsrs qs-manager --permissions <PATH>:
default_group = "viewer"
[user_groups.viewer]
read_only = true
[user_groups.scientist]
allowed_plans = ["count", "scan.*"]
allowed_devices = [".*"]
[user_groups.admin]
admin = true
allowed_plans = [".*"]
allowed_devices = [".*"]
[api_keys]
"k-alice" = "scientist"
"k-root" = "admin"
Clients identify themselves via params.api_key on each RPC.
Without a key they resolve to default_group. Admin-class methods
(lua_eval, permissions_*, manager_*) are restricted to
admin = true groups.
CLI tour
The bsrs binary aggregates several subcommands.
$ bsrs --help
Usage: bsrs <COMMAND>
Commands:
qs-manager Start a bsrs-qs server (replacement for `start-re-manager`)
qs REQ-side client (replacement for `qserver`)
repl Interactive Lua REPL with bsrs types pre-registered
doctor Validate the local environment
migrate Inspect / migrate bsrs's on-disk state directory
frame-source Run a frame-source process (D21 multi-process IPC)
qs-manager
bsrs qs-manager \
--control tcp://*:60615 \
--documents tcp://*:60625 \
--metrics 127.0.0.1:9090 \
--soft-detectors 2 --soft-motors 2
Drop-in replacement for start-re-manager. Speaks the
bluesky-queueserver JSON-RPC dialect on the control REP socket;
fans Documents out on the document PUB socket. Implements ~30 RPC
methods (status, ping, queue_, plans_, devices_, environment_,
re_, history_, lock_info, task_status, task_result,
permissions_get, manager_test, manager_version).
--metrics ADDR enables a Prometheus /metrics HTTP listener; the
binary must be built with --features bsrs-qs/metrics.
qs
bsrs qs status
bsrs qs queue add count det1 5
bsrs qs queue start
bsrs qs re pause
REQ-side client. Mirrors the qserver command palette.
qs inspect
bsrs qs inspect m1
# {"success": true, "name": "m1", "state": {
# "type": "SoftMotor", "setpoint": 1.5, "readback": 1.5,
# "units": "mm", "kind": "Hinted", "subscribers": 0,
# "connected": true
# }}
Dumps a registered device's live state via device_inspect RPC.
Calls NamedObj::inspect_dyn() server-side; sync, no I/O. The
JSON shape varies by device — the name and type fields are
always present.
qs repl
bsrs qs repl
bsrs qs repl --api-key <KEY> # for RBAC-gated daemons
bsrs qs repl --no-env-open # skip auto environment_open
bsrs qs repl --poll-ms 100 # adjust task poll interval
Attach an interactive Lua REPL to a running daemon. Each line is
sent to the server's lua_eval RPC; the daemon's shared mlua state
runs it and the client polls task_status / task_result. The
attached state has every registered device pre-published as a Lua
global, so motor:inspect(), motor:set(1.5):wait(), and
RE:run(count({det1}, 100)) all work the same as in the local
bsrs repl.
lua_eval is admin-class under RBAC — pass --api-key for an
admin api_key when permissions.toml is configured.
repl
bsrs repl
bsrs repl --init ~/.bsrsrc.lua
bsrs repl --script my_scan.lua
Interactive Lua REPL backed by an in-process RunEngine. Tab
completion of bsrs globals, persistent history at
~/.bsrs_repl_history, slash-style commands (:help, :quit,
:reset, :script <path>).
doctor
bsrs doctor
bsrs doctor --tiled-url http://localhost:8000 --kafka localhost:9092
Sanity-checks the local environment before a beamline session.
Prints one line per check with [ ok ], [warn], or [fail].
Exit code 0 on all-ok / warn-only, 1 if any check failed.
migrate
bsrs migrate # dry run on default state dir
bsrs migrate --state-dir /opt/bsrs # custom dir
bsrs migrate --apply # actually run migrations
Walks the state directory (~/.bsrs by default, overridable via
$XDG_CONFIG_HOME/bsrs), enumerates recognized state files
(profiles/, runs.jsonl, tokens/, config.toml), and applies
versioned migration steps in sequence. Today the step list is
empty — the entry point is in place so future schema breaks have
a place to land.
frame-source
bsrs frame-source \
--output /data/run-001.h5 \
--doc-pub-address tcp://*:5577 \
--source pva \
--source-uri 13SIM1:Pva1:Image
D21 multi-process scaffold. Runs a frame source out-of-band from
the RunEngine: writes detector frames locally to disk via
Hdf5FrameSink / BinaryFrameSink; publishes only Document-plane
messages (StreamResource / StreamDatum) to the configured
PUB endpoint. The RunEngine process subscribes via
ZmqDocumentSource and re-broadcasts.
The acquisition backends (pva, rogue) are feature-gated and
wired in a future commit; the wire format itself is stable.
Optional features
Opt-in functionality lives behind feature flags of the consolidated
bsrs crate so the default build stays small and dependency-light.
Document sinks
| Feature | Pulls in | Use when |
|---|---|---|
zmq | pure-Rust omq crate + rmp-serde | bluesky RemoteDispatcher consumers |
tiled | tiled-rs (HTTP) | Tiled catalog ingestion |
kafka | pure-Rust rskafka crate | Kafka topics, no librdkafka |
cargo build -p bsrs --features zmq,tiled,kafka
Frame sinks (stream module)
| Feature | Pulls in | Use when |
|---|---|---|
hdf5 | rust-hdf5 (pure Rust) | NeXus-flavored HDF5 detector files |
pva | epics-pva-rs | NTNDArray monitor source |
Hdf5FrameSink::new("det", "/data/run.h5", payload_size) writes
into /entry/instrument/<name>/data (chunked, optional gzip) and
emits Resource + Datum docs pointing at the file path. The
PvaMonitorSource subscribes to a PVA NTNDArray PV and pushes
frames into a FramePipe that fans out to one or more sinks.
EPICS backends
Both EPICS backends live in the consolidated bsrs crate as features
that are on by default:
| Crate | Feature | Behavior without the feature |
|---|---|---|
bsrs | ca | Stub backend that errors on call |
bsrs | pva | Stub backend that errors on call |
# Real backends build by default; opt out for an EPICS-free build:
cargo build -p bsrs --no-default-features
--no-default-features swaps in the stub backends so the rest of the
workspace compiles cleanly on systems without EPICS. CI build-tests
both the stub and the real paths; live IOC integration testing is on
the roadmap.
Lua read-side surface
| Feature | Adds |
|---|---|
cli + tiled | tiled.from_uri(url) Lua global + methods |
cargo build -p bsrs --features cli,tiled
Inside the REPL:
local cat = tiled.from_uri("http://localhost:8000")
for _, k in ipairs(cat:keys()) do print(k) end
local run = cat:get("scan_42")
print(run:metadata())
All HTTP calls run on bsrs's tokio runtime; the REPL thread re-enters mlua's reentrant lock, so calls inside Lua plans are safe.
Observability
| Crate | Feature | Adds |
|---|---|---|
bsrs-qs | metrics | Prometheus /metrics HTTP listener |
bsrs qs-manager --metrics 127.0.0.1:9090
# build first with: cargo build -p bsrs-qs --features metrics
Currently exported:
bsrs_qs_rpc_calls_total{method=...}bsrs_qs_rpc_errors_total{method=...}(when wired)bsrs_qs_queue_depth(gauge)bsrs_qs_runs_total{exit_status=...}bsrs_qs_documents_total{name=...}
Scrape with the standard Prometheus config:
scrape_configs:
- job_name: 'bsrs-qs'
static_configs:
- targets: ['localhost:9090']
Operations guide
How to run bsrs in production: process layout, configuration, and day-2 maintenance.
Process layout
A typical beamline deployment runs three or four bsrs processes:
[ qs-manager ] — control-plane (REQ/REP) + document fan-out (PUB)
[ frame-source ] — D21 acquisition process per detector (optional)
[ tiled (Python) ] — catalog HTTP server (optional)
[ kafka broker ] — durable doc bus (optional)
bsrs qs-manager is the always-on daemon. The rest are
deployment-specific: small sites can run everything in one process
(DocumentRouter + sinks attached directly to the engine inside qs).
Service unit (systemd)
[Unit]
Description=bsrs queueserver
After=network-online.target
[Service]
Type=simple
User=acquire
Environment=EPICS_CA_ADDR_LIST=192.168.50.255
Environment=EPICS_CA_AUTO_ADDR_LIST=NO
Environment=RUST_LOG=info,bsrs_qs=debug
ExecStart=/usr/local/bin/bsrs qs-manager \
--control tcp://*:60615 \
--documents tcp://*:60625 \
--metrics 127.0.0.1:9090
Restart=on-failure
RestartSec=2
[Install]
WantedBy=multi-user.target
Run bsrs doctor from the same shell environment as the unit
file to confirm EPICS / Tiled / Kafka are reachable before
starting the unit.
State directory
bsrs persists a small amount of state under
$XDG_CONFIG_HOME/bsrs (or ~/.bsrs on macOS):
~/.bsrs/
├── config.toml # default RPC ports, tiled url, kafka brokers
├── runs.jsonl # rolling run-history index (uid, start, stop, exit)
├── profiles/ # named device-table snapshots
└── tokens/ # auth tokens for outbound HTTP (Tiled, Kafka)
bsrs migrate walks this directory and runs versioned migration
steps. Today the migration list is empty; the entry point lands so
future schema breaks have a single owner.
Logging
bsrs uses tracing with the RUST_LOG env var:
RUST_LOG=info # default
RUST_LOG=info,bsrs::engine=debug # engine internals
RUST_LOG=info,bsrs_qs=trace # full RPC trace
For structured logs to a file:
RUST_LOG=info bsrs qs-manager 2>> /var/log/bsrs.log
Use tracing-subscriber's JSON format if you ship logs to Loki /
ELK — the default formatter is human-readable.
Metrics
/metrics (Prometheus exposition format) is enabled by passing
--metrics ADDR to qs-manager (binary built with the metrics
feature). See Optional features for
the metric list.
Suggested alert rules:
- alert: BsrsQsErrorRateHigh
expr: rate(bsrs_qs_rpc_errors_total[5m]) > 0.5
for: 5m
- alert: BsrsQsQueueStuck
expr: bsrs_qs_queue_depth > 100
for: 10m
Backup & restore
The state directory is small (kilobytes) and rsync-friendly. The
authoritative run history lives in your downstream Tiled / Kafka /
JSONL sink, not in bsrs state. Treat ~/.bsrs/runs.jsonl as
operational, not authoritative.
Upgrades
systemctl stop bsrs
cargo install --path crates/bsrs # or cp the binary in
bsrs migrate --apply # run any new schema steps
systemctl start bsrs
Document compatibility is part of the public contract: bsrs N+1 emits documents that are forwards-compatible with bluesky readers that worked against bsrs N.
Troubleshooting
| Symptom | Likely cause |
|---|---|
bsrs doctor warns on EPICS | EPICS_CA_ADDR_LIST empty or unset |
qs-manager exits with address in use | another process bound the control / doc port |
| Documents arrive at consumer with gaps | consumer is not draining its 0MQ queue fast enough; raise SUB HWM |
re-pause returns immediately but engine keeps running | check engine state via status RPC — pause arrives at next checkpoint, not mid-Msg |
| HDF5 file is empty after a run | check bsrs_qs_documents_total{name="datum"} — frames may be writing to a different sink |
For deeper diagnosis, raise RUST_LOG=bsrs_qs=trace for the
duration of one failing scan and capture the resulting log.
Architecture
bsrs is a single crate plus a proc-macro companion. Each module has a single responsibility; boundaries are designed so a downstream user can swap one implementation without touching the others.
Module map
crates/bsrs # library + `bsrs` binary (feature: cli)
├── core # Msg, Status, errors, runtime
├── engine # RunEngine, state machine, suspenders, preprocessors
├── event_model # Document types: RunStart, EventDescriptor, Event, RunStop, ...
├── plans # bp.* / bps.* / bpp.* mirrors (count, scan, grid_scan, ...)
├── protocols_sync # Movable, Triggerable, Stageable, Readable (sync facade)
├── protocols_async # ophyd-async-style traits over async fns
├── devices # SoftMotor, SoftDetector, NDSimDetector, ...
├── backends # SignalBackend over EPICS CA / PVA (features: ca, pva)
├── callbacks # Document sinks: jsonl, zmq, tiled, kafka
├── stream # FrameSink/FrameSource: hdf5, binary, pva
├── qs # bluesky-queueserver-compatible daemon (feature: qs)
├── host # Lua host runtime + CA/PVA devices (feature: host)
└── bin/bsrs # CLI: qs-manager, qs, repl, doctor, migrate, frame-source
crates/bsrs-derive # #[derive(Device)], #[signal(...)], #[lua_methods] proc-macros
Each module's docs live at doc/0N-<topic>.md in the repo. This
chapter is a high-level orientation; for protocol contracts go to
the doc/ tree.
The RunEngine
bsrs::engine::RunEngine owns the dispatch loop. A plan is an
async_stream::Stream<Item = Msg>; the engine drives it forward,
matches each Msg, and dispatches to the right handler.
#![allow(unused)] fn main() { pub enum Msg { OpenRun { md: BTreeMap<String, Value> }, CloseRun { exit_status: ExitStatus }, Create { name: String }, Read(DeviceRef), Save, Set { device: DeviceRef, target: Value, group: Option<String> }, Wait { group: String }, Trigger { device: DeviceRef, group: Option<String> }, Pause { defer: bool, hard: bool }, Checkpoint, Stage(DeviceRef), Unstage(DeviceRef), // ... Custom { name: String, payload: Value }, Fail(String), // plan-internal abort with reason } }
Engine state is an AtomicState: Idle, Running, Pausing,
Paused, Aborting, Halting, Halted. State transitions go
through one owner (the dispatch loop) and are visible to consumers
via a tokio::sync::watch channel.
The Document plane
Every Msg::Save (and a few other handlers) emits one or more
Documents. Documents are typed:
#![allow(unused)] fn main() { pub enum Document { Start(RunStart), Descriptor(EventDescriptor), Event(Event), EventPage(EventPage), Stop(RunStop), Resource(Resource), Datum(Datum), DatumPage(DatumPage), StreamResource(StreamResource), StreamDatum(StreamDatum), } }
Each Document is fanned out through a DocumentRouter to all
attached subscribers. Subscribers are anything implementing
async fn handle(&self, name: &str, body: Value):
JsonlSink— append line-delimited JSON to a fileZmqDocumentSink—<prefix> <name> <body>envelope on a PUB socketTiledSink— register Resources via tiled-client HTTPKafkaDocumentSink— produce to a Kafka topicHdf5FrameSink— turnDatum(frame_uid → bytes) into a NeXus group
The router is not the place to put business logic. Its job is fan-out; if a subscriber is slow it doesn't block other subscribers because each handler runs in its own task.
The frame plane
Frame bytes never travel through the Document plane. A camera fills
buffers via FrameSource; those buffers go through a FramePipe
(a bounded channel) to one or more FrameSinks. The Document plane
sees only StreamResource (one per channel) + StreamDatum (one
per chunk of frames written), with file paths or shape descriptors
that downstream readers use to fetch the bytes.
This is what makes bsrs's "RunEngine on the IOC host" deployment shape work: frame bytes stay local to the IOC host, only Documents cross the network.
Multi-process: D21
For sites where the camera produces faster than a single process
can write, the bsrs frame-source subcommand splits the picture:
[ frame-source ] --pva--> camera
↓ writes frames locally to HDF5
↓ publishes only StreamResource/StreamDatum docs
↓ via ZMQ PUB
[ qs-manager ] ←--ZMQ----- subscribes via ZmqDocumentSource
↓ rebroadcasts on its own document PUB
↓ to downstream consumers
Each process can run on a different host. The wire format is stable: anything that consumes bluesky 0MQ documents already consumes the rebroadcast.
Backend traits
The single most important interface for new device implementers:
#![allow(unused)] fn main() { pub trait SignalBackend: Send + Sync + 'static { type Datatype: Serialize + DeserializeOwned + Clone + Send + Sync; async fn get(&self) -> Result<Self::Datatype, BackendError>; async fn put(&self, value: Self::Datatype) -> Result<(), BackendError>; async fn subscribe(&self) -> Result<SubscriptionHandle<Self::Datatype>, BackendError>; // ... } }
epics-ca-rs and epics-pva-rs are concrete impls. A
hand-written backend (REST, custom binary, simulated) is roughly
~100 lines and slots into existing devices via the B generic
parameter.
See also
doc/01-overview.md— high-level diagramdoc/02-events.md— Document shape contractdoc/03-runengine.md— bluesky parity matrixdoc/04-devices.md— device authoring guidedoc/05-backends.md— backend trait setdoc/06-callbacks.md— sink authoring guidedoc/07-frames.md— frame plane in detaildoc/08-qs.md— queueserver wire compatdoc/09-d21.md— multi-process designdoc/10-roadmap.md— what's next