logs.gokuls.in

3 pull requests merged across 1 repo

Offline-Protocol/offline-protocol-sdk

Problem

On two Raspberry Pi 4s (Linux 6.18, BlueZ 5.87) the Python peripheral failed every start with Failed to register advertisement, and every replacement service failed the same way. It looked like advertisements left behind by replaced containers were filling the slots. They weren't: BlueZ reported ActiveInstances 0 and SupportedInstances 5 while it was failing, and a full set of slots gets a different answer ("Maximum advertisements reached").

Root cause

Linux loses track of the controller's advertising state. hci_event.c (le_conn_complete_evt, line 5650 in v6.18) clears HCI_LE_ADV on every LE Connection Complete, assuming the controller stopped advertising. A controller only stops for a link in which it is the peripheral.

Captured in the HCI trace on the Pi (13:41:40 UTC):

1. Our central dials a peer, and the kernel pauses advertising.

2. While the dial is still pending, a discovery restart makes the kernel enable advertising again.

3. LE Connection Complete, role Central. The kernel clears its flag, but the controller keeps advertising.

4. From then on the kernel never disables advertising. Every LE Set Advertising Parameters and LE Set Random Address is answered Command Disallowed (0x0c), so every new advertisement is refused until the controller is reset.

Fix

  • BlePeripheral._bring_up: on Linux, when the start fails with Failed to register advertisement and BlueZ reports a free slot, it powers the adapter off and on through Adapter1.Powered (which sends an HCI Reset and clears the stale advertising), then starts once more. It does this once only, because the reset drops every link on the adapter. Any other refusal is raised unchanged.
  • bluez_restarts: an adapter's Powered turning true now triggers the same re-registration as a bluetoothd restart. BlueZ drops every discovery session on power-off, so without this the central in the same process stopped scanning after the reset. The same applies to any power toggle by another process.
  • Docs: docs/bridges/python.md P17, the bridges README row, and a CHANGELOG entry.

Verification

  • pytest bindings/python/tests: 1128 passed. There are new tests for the reset path (it resets once, any other error is left alone, the free-slot check, the power-off-then-on order) and for the power-on signal. Each of 7 deliberate code breakages makes a test fail.
  • Hardware: redeployed on pi-a while it was in the broken state. The start reset the adapter once, the central re-registered, and the peripheral was running about 1.5 s later. The HCI trace shows one last Command Disallowed, then Reset, then Set Advertising Parameters and Set Advertise Enable succeeding.
  • Full lab rerun with the fix: lan, outage and a 4-member group including an Android phone pass. The Pi-to-Pi BLE phase still fails because pi-b's LE radio has stopped working (no advertising reports while actively scanning, not visible to any other device, and an HCI Reset doesn't help). That is a hardware or firmware problem outside this change, and a rerun after a power cycle is owed.

Not covered

  • If the controller gets into this state while the peripheral is already running, it keeps advertising our existing data, so peers can still find us. The reset only runs at the next start.
  • The kernel race itself is upstream. This change recovers from it but doesn't prevent it.

On BlueZ 5.87, bluetoothd exits the moment a discovery filter naming a service UUID is set. The Python central set exactly that filter (BleakScanner(service_uuids=[SERVICE_UUID])) at every start, so each start of the service took bluetoothd down within about half a second. With it went the peripheral's GATT application and advertisement, and the central's scan. Neither role noticed: the peripheral kept logging "advertising" with nothing registered, and the central waited on a scan that had ended.

Symptoms this explains, all seen on two Raspberry Pi 4s running BlueZ 5.87 in containers:

  • Two Linux boxes never formed a Bluetooth LE link with each other.
  • The peripheral failed to start about half the time with "Message recipient disconnected from message bus without replying" (bluetoothd exiting mid-call).
  • A box stopped being visible to phones a few minutes after start, while still logging "advertising".
  • A peer's Identity read failed with GATT Unlikely Error (0x0E), because the link died with bluetoothd mid-read.

Root cause, bisected on the device

A test app registered the same GATT service with bless one step at a time, watching NameOwnerChanged for org.bluez:

Stepbluetoothd
bless setup, GATT RegisterApplicationstays up
RegisterAdvertisementstays up
unfiltered bleak scanstays up
bleak scan with service_uuids=[SERVICE_UUID]exits immediately

btmon (HCI monitor) shows the old bluetoothd closing its management socket with no "Terminating" line, and a new one starting about 150 ms later.

Fix

  • On Linux the central scans unfiltered, and _on_advertisement drops any advertisement without the mesh service UUID before tracking or dialling it. CoreBluetooth keeps the filter, which it needs to scan in the background.
  • Both roles follow bluetoothd through the new bluez_restarts.StaysRegistered, which watches NameOwnerChanged for org.bluez:
  • A start cut short because bluetoothd exited part-way is retried once the new bluetoothd holds the name. A start refused for any other reason is raised at once, as before.
  • A role running when bluetoothd restarts is torn down and registered again, retrying with backoff for about 15 s (a bluetoothd that has just started refuses for a while, e.g. InProgress).
  • Linux only and best effort: with no system bus to watch it stays inert, which is the old behaviour.
  • The helper holds the role's methods weakly. A strong cycle kept a dropped ProtocolManager and its open stores alive until the cycle collector ran, which test_file_stores caught.

Documented as P16 in docs/bridges/python.md, with a line in the bridges index and a CHANGELOG Fixed entry.

Verification

  • pytest bindings/python/tests/: 1104 passed, 1 skipped (the skip and the one RuntimeWarning are on main too).
  • 13 new tests: tests/test_bluez_restarts.py covers the watch, start retry vs refusal, recovery, stop during recovery, and restarts folded together. test_ble_manager.py covers the per-platform scan filter and the callback filter. Mutation-checked: removing the refusal check fails test_a_refusal_is_raised_at_once_and_not_retried.
  • Hardware, with the three changed modules laid over the 0.29.0 package (they are unchanged on main since 0.29.0):
  • Two Raspberry Pi 4s, the cable path between them turned off: an HTTP-front call from one Pi to the other over Bluetooth LE alone succeeds in about 1 s, repeatedly.
  • A bluetoothd restart under a running service: both roles logged "registered with the restarted bluetoothd" within about 1 s, and the box linked to a phone right after.

Not fixed here

bluetoothd 5.87 still restarts occasionally about 150 ms after one of these boxes connects out to another, before any GATT traffic of ours. That points at a BlueZ profile plugin on the OS image, not at this SDK. With this change, that costs a short blip and a re-registration instead of a device silently off the air.

The C binding's tests covered the contract but never the way a host uses it. 16 of the 211 dispatcher arms were called by any test. No test saw a transport notification fire. The README quick start was never compiled, and no C was compiled against a shipped library or on Windows.

What this adds

CheckCatchesRuns
consumer-check/exchange.cA C host cannot move frames between two engines, form an MLS session, or deliver a message each wayCI, Linux and macOS
The README quick start, extracted by quickstart.shThe example a reader copies stops compiling or runningCI, Linux and macOS (run), Windows (cl -W4 -WX)
make SANITIZE=1Double free, wrong allocator, leaks (K1), UBCI, Linux (ASan, UBSan, LSan) and macOS (ASan, UBSan)
every_arm_refuses_bad_parameters_before_it_reaches_the_engineAn arm that decodes after calling, misnames a parameter, or panicscargo test, every system
scripts/check-c-library.shA shipped library that links and then cannot load (the #572 install-name bug), a broken Windows import libraryRelease, before publishing, on macOS, Linux and Windows; CI on Windows
tools/capi-fuzz + fuzz.ymlA panic, Internal or non-JSON result from Engine::call (an abort under minisize)Nightly on Linux, and on demand

The archive README's link line now has one source, scripts/c-link-line.sh, which the packager and the release check both read. The release and crates.io publish gates both wait for the new test-c-library job.

Verified locally

  • macOS: the consumer check, the exchange and the quick start pass, plain and with SANITIZE=1. 47 capi tests pass, and clippy is clean with and without default features.
  • Linux, in a Docker container on aarch64: the same programs pass plain and with SANITIZE=1, LeakSanitizer included. check-c-library.sh passes against the .so.
  • Fuzzing, Linux container: a five-minute run made 6.7M executions with no crash. The corpus grew from 9 seeds to 1,249.
  • Linters: actionlint passes on all three workflows, and shellcheck passes on the new scripts. The packaging harness passes.

Negative controls, each of which fails as it should:

  • ASan reports a library string freed twice.
  • LSan reports a library string never freed.
  • A frame with one base64 character corrupted in transit is never delivered.
  • The arm test fails on a dispatcher that misnames send_message's recipient, and on one that runs start before checking its parameters.
  • check-c-library.sh fails, at load, on a dylib whose install name is an absolute build path.

Not verified

  • Windows has not been run. Neither the CI job nor the release leg has run: no local MSVC. CI on this PR is the first run.
  • The release test-c-library job runs only on a release dispatch. That dry run is still owed.
  • Linux was checked on aarch64 only. CI runs x86_64.
  • The fuzz target has no negative control for its panic detection, which is libFuzzer's standard crash path.
  • The fuzzer does not link on macOS. Without a sanitizer, the linker refuses the library's dylib. With ASan, the nightly runtime deadlocks before main. The docs say to fuzz on Linux.

Found on the way

  • main.c's storage provider leaked its entries at exit, which LSan reported. Fixed.
  • usleep is gone under _XOPEN_SOURCE 700 on glibc, which a first draft of exchange.c hit. It now uses nanosleep.