Skip to content

v0.2.0: bb 0.31 migration, cmd_stop fix, and full audit remediation - #2

Merged
houllette merged 17 commits into
mainfrom
chorus/session-d1e155a5-231c-4f7d-b08a-08c2042775a9
Sep 2, 2026
Merged

houllette merged 17 commits into
mainfrom
chorus/session-d1e155a5-231c-4f7d-b08a-08c2042775a9

Conversation

@houllette

Copy link
Copy Markdown
Member

Summary

Two bodies of work, in 15 commits:

The v0.2.0 release (first two commits): migrates from bb 0.22 to 0.31 (handle_command/2 pipeline, command_payloads, capabilities, BB.Loop for the 100 Hz loop, synchronous set_position/4), fixes the inverted cmd_stop SET_STATE semantics (state 0 is the firmware's motion-ready state — the safety stop was commanding the arm into motion mode), adds Stop/Hold support, a first-class CartesianMove payload, and the reach toolchain on Elixir 1.20.4.

Full audit remediation (remaining commits): five parallel reviewers swept the wire protocol (cross-checked against the xArm-Python-SDK), controller/OTP layer, actuators, test suite, and docs; every confirmed finding is fixed with regression tests. Highlights:

  • Quick start actually works: use BB.Ufactory.Robots.XArm6 had no __using__/1 — the flagship snippet in README and both tutorials never compiled, and bb's DSL has no link-level actuators, so the documented accessory pattern was equally fictional. The macro now takes host:/controller:/cartesian:/gripper:/linear_track: options with accessories on fixed mount joints; compiling the documented snippets is now a test.
  • ETS lost-update race fixed: report ingestion and joint commands both did read-whole-row-then-insert on shared rows — an interleave could silently drop a fresh command or undo a Stop/Hold brake latch. Both sides now use column-atomic :ets.update_element/3, pinned by a stress test that fails against the old code within one run.
  • send_and_recv matches replies by register (in-flight 100 Hz move-acks could be handed to RS485 callers, refusing healthy linear-track Stops) and its default timeout drops 5 s → 500 ms since it blocks the controller mid-stream.
  • The loop no longer streams motion blind: ticks skip when report feedback is stale (report_stale_ms, default 250 ms) and the controller stops + reports to BB.Safety after 3 s of blindness with motion pending.
  • Legacy {:move_cartesian, ...} casts moved a disarmed robot — now armed-gated, logged, and deprecated. Sensors no longer crash the whole robot tree when the controller is unreachable at init. Command.Position velocity hints are honored.
  • Protocol hardening: gripper clamp to the SDK's true 850-pulse fully-open value, RS485 exception replies no longer decode as positions, u16 clamps, >7-angle guard, byte-exact RS485 frame pins (host/device/function/register), and stream_data properties for fp32 round-trips and parsing across arbitrary TCP split points.
  • CI gates: test files compile with --warnings-as-errors (a tag-excluded simulator test calling a removed API previously slipped through as a warning), publish refuses a version without a CHANGELOG entry, and new firmware-tier stop-semantics tests verify what byte assertions cannot — that cmd_stop actually halts motion.

Locally: 489 tests + 5 properties pass, mix check green (except reuse, which needs Docker and validates here).

Test plan

  • Static checks & unit tests job (full mix check, including reuse via Docker)
  • Five-model firmware-simulator matrix — first execution of the new stop-semantics tests and the --warnings-as-errors gate
  • Note: merging to main auto-publishes v0.2.0 to hex.pm once the gate passes — hold the merge if the release should wait

🤖 Generated with Claude Code

https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2

houllette and others added 17 commits September 1, 2026 18:39
…hain

Upgrade the BB framework dependency from 0.22.1 to 0.31.0 and adapt to
every breaking change in between:

- Actuator command delivery goes through handle_command/2 (bb 0.23):
  actuators no longer self-subscribe to their command topics, and the
  framework enforces the armed check and payload gating before the
  driver sees a command.
- Each actuator declares its accepted payloads (bb 0.25). Cartesian
  moves get a first-class BB.Ufactory.Message.Command.CartesianMove
  payload (6-DOF pose + optional speed/acceleration) through the gated
  pipeline; the raw {:move_cartesian, pose} cast is kept for
  compatibility.
- The 100 Hz control loop runs on BB.Loop (bb 0.26): absolute monotonic
  deadlines instead of drift-prone send_after chains, with overruns
  reported via [:bb, :loop, :tick] telemetry.
- Synchronous set_position (bb 0.30): Gripper, LinearTrack, and
  Cartesian reply {:error, reason} when the controller cannot deliver.
- Joint declares capabilities [:position_feedback, :effort_feedback]
  (the controller publishes JointState from report frames), silencing
  bb's missing-position-sensor warnings on the XArm6 robot.

Fix a safety bug found during the audit: Protocol.cmd_stop/1 sent
SET_STATE 0, which is the firmware's motion-ready ("sport") state, not
stop. The :stop disarm action - including the fresh-connection safety
disarm - was commanding the arm INTO motion state. It now sends
SET_STATE 4 (terminate motion, clear queued commands), with the
cmd_set_state doc table corrected and a byte-level regression test.

New motion capabilities: Joint accepts Command.Stop/Command.Hold by
latching the current reported position as the loop target; LinearTrack
accepts Command.Stop by reading the carriage position over RS485 and
re-targeting it (refusing when the read fails rather than guessing).

Toolchain: require Elixir ~> 1.20 (CI on 1.20.4 / OTP 29); add reach
2.8 with a .reach.exs architecture policy machine-checking wire-layer
purity, wired into mix check as --arch --smells --strict; fix all six
reach smell findings; import bb's exported formatter locals instead of
a hand-maintained copy; update docs, tutorials, and demo scripts off
the removed bb APIs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
- simulator_test.exs still called BB.Actuator.set_position!/3 (removed in
  bb 0.30); it would have raised UndefinedFunctionError in all five CI
  simulator jobs, since :simulator tests only execute there.
- mix bb_ufactory.sim called Atom.to_string/1 on @models' string keys, so
  the unknown-model error path raised ArgumentError instead of printing
  usage.
- Registers.set_state/0 doc still carried the inverted state table
  (0 = stop) that caused the original cmd_stop bug; align it with the
  corrected Protocol.cmd_set_state table.
- Cartesian moduledoc example matched :ok from BB.call/3, but bb replies
  {:ok, :accepted} for a {:noreply, ...} handle_command — the snippet
  raised MatchError as written.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
`use BB.Ufactory.Robots.XArm6` — the flagship snippet in README, both
tutorials, and two moduledocs — raised UndefinedFunctionError: the module
was itself a robot and exported no __using__/1. The documented accessory
pattern was equally fictional: bb's DSL only allows actuators under
joints, so the tutorial's link-level `actuator :gripper` never compiled.

- Extract the robot DSL into a shared Definition macro; the concrete
  XArm6 robot and a new `__using__` both expand it. Options: :host,
  :loop_hz, :simulation, :controller (extra controller opts, e.g.
  tcp_offset/reduced_mode), :gripper and :linear_track (accessory
  actuators on fixed mount joints — gripper at link6, track at base).
- Sensors now survive an unreachable controller at init (noproc exits
  from BB.Process.call were crashing the whole robot supervision tree in
  simulation mode, and would after a controller crash-restart race on
  hardware). ForceTorque and Collision degrade to the existing warning
  path instead.
- Rewrite every `use BB.Ufactory.Robots.XArm6` snippet (README, tutorials
  01/02, BB.Ufactory + XArm6 moduledocs, AGENTS.md) to the new options
  form, including the BaristaBot combined example, and bump the stale
  `~> 0.1` install pins that excluded this release.
- Compile-level tests for the documented snippets: quick start, accessory
  mounts, controller opt passthrough, unknown-option raise, and kinematic
  simulation boots for both derived robots.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
The controller's report handler and the Joint actuator both did
lookup-then-full-row-insert on the same public ETS rows from different
processes, with reports landing at ~100 Hz. An interleave let the report
handler resurrect a stale set_position — silently dropping a freshly
acked Position command, or undoing a Stop/Hold brake latch so the joint
resumed motion toward its pre-Stop target.

Each side now writes only its own columns with :ets.update_element/3
(atomic per row): the controller updates current_position/current_torque,
the actuator updates set_position. A concurrent stress test pins the
behavior — it fails within one run against the old read-modify-write.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
While armed, the 100 Hz move stream keeps responses in flight that the
pre-send drain cannot clear, and send_and_recv parsed whichever frame
arrived first — so an RS485 read (e.g. the linear track's Stop position
read) could consume a move-ack and refuse the Stop as :position_unknown
on a healthy link. It also returned {:more} to callers when a response
split across TCP segments.

The reply is now matched by register with the same scan-until-found
approach poll_error_code uses (which now shares the scanner): foreign
frames are skipped, partial frames are accumulated until the deadline,
and a desynchronized stream reports {:error, :desync} instead of leaking
parser internals. The default timeout drops from 5 s to 500 ms — this
call blocks the controller GenServer, and a multi-second wait would
stall joint streaming while the robot stays armed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
maybe_send_joint_move checked only "targets pending" and "armed": with
the report socket down (or never delivering), the loop kept streaming
cmd_move_joints built from frozen ETS positions — commanding the arm
blind, with joints lacking an explicit target re-driven to their
last-known angle — while the reconnect chain retried quietly forever.

The loop now skips ticks (logged once) whenever the report socket is
down or the last report frame is older than report_stale_ms (default
250 ms), and after feedback_loss_fatal_ms (default 3 s) of continuous
staleness with motion pending it stops the controller and reports to
BB.Safety — the same recovery path as a dead command socket. Both
thresholds are controller options.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
- register_arm_frames replied :ok to the accessory even when the send
  failed and the controller was stopping; it now replies {:error, reason}
  so the accessory never believes its enable frames reached the arm.
- create_ets returned a name atom from one branch and a tid reference
  from the other; actuators cache the handle, and a stale tid raises
  after a controller crash-restart. Always return the table name.
- The out-of-band disarm now waits briefly for the firmware's response
  and logs when the stop went unconfirmed, instead of closing the socket
  right after send (failures still swallowed — the callback never raises).
- Simulator.command/3 accumulates TCP segments until a complete frame or
  the deadline, so a split response no longer leaks {:more} through
  reachable?/3 in violation of its spec.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
Every joint move was dispatched at the model's maximum speed;
set_position(robot, :j1_motor, x, velocity: 0.1) moved at full speed
with the hint silently discarded.

The ETS joint rows gain a set_velocity column written atomically with
the target. cmd_move_joints takes one speed for the whole batch, so the
loop uses the SLOWEST pending hint (clamped into (0, model max]), with
acceleration scaling at 10x the commanded speed as before. Stop/Hold
brake latches clear the hint — braking happens at full model speed, not
at the pace the interrupted move requested.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
- Legacy {:move_cartesian, ...} casts moved a DISARMED robot: bb's
  command pipeline never sees casts, the controller's send_command has no
  gate, and disarm_action :hold sends no SET_STATE 4 — so the firmware
  executed MOVE_LINE while BB considered the robot disarmed. The cast
  path now enforces BB.Safety.armed? itself (dropped with a warning when
  disarmed) and logs a deprecation nudge toward CartesianMove.
- Stop/Hold refusals are logged: pubsub/cast delivery discards the error
  reply, so a joint that refused Hold or a track that refused Stop
  (position read failed, carriage may still be moving) left zero trace.
- LinearTrack Stop does exactly one RS485 read — the position read
  doubles as BeginMotion's initial estimate instead of a second blocking
  round-trip that doubled worst-case braking latency.
- Joint.init refuses a topology transmission ({:stop,
  {:unsupported_transmission, name}}): bb hands handle_command
  motor-space values, this driver streams joint angles to firmware, and
  a non-identity transmission silently skews every command.
- Topology limit narrowing now uses the MotorProfile bb 0.31 injects
  into resolved opts instead of hand-rolled robot introspection — and is
  finally under test (narrow + no-widen), which the old path never was.
- CartesianMove accepts integer fields (x: 300) and the actuator
  normalizes to floats before the fp32 encoders.
- Gripper/LinearTrack BeginMotion no longer fabricate initial positions:
  the gripper tracks its last commanded target, the track falls back to
  a zero-travel estimate instead of claiming a 0.0 start.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
- Gripper clamp raised 840 → 850 pulses: the SDK's mm→pulse conversion
  tops out at ~850 for the 84 mm stroke, so fully-open commands stopped
  ~0.9 mm short. Docs updated everywhere that claimed 0–840 (and the
  README's "mm" units corrected to pulse units).
- cmd_move_joints raises for >7 angles (matching cmd_get_fk and
  cmd_joint_limit_check) instead of silently dropping the extras.
- u16 speed fields (gripper speed, track speed units) clamp to 0xFFFF
  instead of bit-syntax wrapping to a slow crawl.
- parse_linear_track_position requires function code 0x03 — RS485
  exception replies (func 0x83) and write acks no longer decode as
  garbage positions.
- cmd_set_mode documents the full firmware mode table (0..7) and rejects
  anything else; build_frame documents + tests the txn-id u16 wrap.
- New byte-exact RS485 frame tests pin host id (0x09 gripper bus vs
  0x0B control-box bus), device id, Modbus function, servo register
  address, and payload for every accessory builder — self-referential
  assertions could not catch a swapped bus, the cmd_stop bug class.
  cmd_linear_track_enable and cmd_clean_warn gain their first tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
- XArm6 __using__ gains a :cartesian option, ON by default — the README's
  flagship CartesianMove example targets :cartesian, which quick-start
  robots previously did not have (and `use` users had no way to add).
- Accessory disarm docs no longer promise a "fresh TCP connection" that
  bypasses a crashed controller — gripper and F/T disarm route through
  the controller best-effort; only the controller's own disarm/1 opens an
  out-of-band socket.
- F/T sensor is documented as push-based (wrench data arrives in 135+
  byte report frames); the dead poll_interval_ms option is removed
  (0.2.0 is already a breaking release).
- BB.Ufactory's "Full Robot Definition Example" now compiles: controller
  wrapped in a controllers block, accessory actuators on fixed mount
  joints (verified by compiling the extracted snippet); heartbeat bytes
  corrected to the real GET_STATE frame; module inventory no longer
  claims the F/T sensor polls register 0xC8.
- Tutorials standardize on synchronous BB.Actuator.set_position (with
  the new velocity-hint example) over raw BB.Process.cast; the legacy
  Cartesian cast is documented as deprecated and armed-gated.
- Model doc softens "factory hard limits" for max_speed_rads to what it
  is: a conservative uniform cap, with the limit tables remaining the
  firmware-enforced values.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
- All test-compile warnings fixed (0.0 float patterns, unused defaults,
  a type-checker-flagged doctest) and now kept at zero: the simulator CI
  jobs run mix test --warnings-as-errors (an undefined-function call in
  tag-excluded simulator tests previously surfaced only as a warning
  until the five-model matrix executed it), and mix check's coveralls
  invocation gains the same flag so test-file compilation is covered
  where the compiler task (lib only) cannot see.
- The publish job refuses to release a version with no CHANGELOG entry.
- Coverage additions: terminate/2 (loop cancel + socket close),
  undeclared-payload fallback replies for Joint and LinearTrack.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
stream_data properties cover what example-based tests cannot: arbitrary
values through the fp32 encoders (round-trip within fp32's 2^-24
relative precision) and — critically — arbitrary TCP segmentation. Both
the command-response parser and the report parser are now verified to
produce identical results for a multi-frame stream split at every
pseudo-random boundary, the way the sockets actually deliver bytes.
Command frames are additionally verified as parse_response ∘ build_frame
identities across random register/status/params.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
The cmd_stop SET_STATE value shipped inverted while every unit test
passed — byte assertions cannot distinguish a well-formed frame carrying
the wrong register VALUE. Two simulator-tagged tests (CI's five-model
matrix; no local Docker) now exercise the semantics for real:

- Protocol level: a long slow move is visibly under way, cmd_stop is
  sent, and the joint must settle well short of its target, STAY there
  (queue cleared, not paused), and re-enable via SET_STATE 0.
- Actuator level: BB.Actuator.stop_sync mid-move must brake J1 short of
  its target via the latched ETS brake target and hold it there.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
The unreleased v0.2.0 entry now documents the full audit outcome:
breaking changes (XArm6 use-macro options, 5-tuple ETS rows, 500 ms
send_and_recv default, removed poll_interval_ms, >7-angle guard,
transmission refusal, deprecated+gated legacy cast), the safety fixes
(ETS race, register matching, stale-feedback gate, sensor init
resilience, gripper 850 clamp, RS485 parsing), and the new features
(velocity hints, freshness options, confirmed out-of-band disarm).

Lint follow-ups: explicit :erlang.float/1 coercions, two nesting-depth
refactors extracted into named helpers, alias ordering, and a scoped
credo disable where aliasing inside a __using__ quote would leak into
the caller's module.

mix check --no-retry: all tools pass; reuse alone fails locally
(no Docker socket in this environment — validated in CI).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
First CI run of the new firmware-tier tests: the protocol-level cmd_stop
test passed on all five models, but the actuator-level Stop test failed
everywhere with "J1 never settled" — a 5 mrad stability threshold is
unreachable while the loop keeps STREAMING the latched brake target and
the firmware micro-dithers under continuous re-planning. (Stop itself
worked: an unbraked joint would have finished its move and failed the
short-of-target assertion instead.) Settle detection now uses the
suite's 0.02 rad convergence tolerance, still an order of magnitude
below real motion between samples.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
Second CI signal: even at 0.02 rad the joint never reads as "settled" —
under the brake latch the loop keeps streaming the latched target and
the firmware limit-cycles around it with real amplitude. Stillness was
the wrong property. The discriminating one is distance from target over
time: an unbraked 1.0 rad move at 0.25 rad/s parks J1 AT the target
within ~4 s, so after 6 s a working brake must leave the 1-second mean
position >0.3 rad short — and still short (and within 0.15 rad of the
first mean) two seconds later, proving the cleared move never resumes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUhijXQHjWkYY3wm7L1mz2
@houllette
houllette merged commit 5ef77df into main Sep 2, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant