Skip to content

fix(mqtt): serialise numpy scalars and arrays in published payloads - #41

Open
rishabh-bansal wants to merge 1 commit into
cyberwave-os:mainfrom
rishabh-bansal:fix/mqtt-numpy-scalars
Open

rishabh-bansal wants to merge 1 commit into
cyberwave-os:mainfrom
rishabh-bansal:fix/mqtt-numpy-scalars

Conversation

@rishabh-bansal

Copy link
Copy Markdown

What changed and why?

A command argument computed with numpy/OpenCV is naturally a numpy scalar. For example, a distance from detected ArUco corners comes out as numpy.float32. Passing it to twin.move_forward(dist) makes json.dumps raise TypeError inside CyberwaveMQTTClient.publish(). That logs Error publishing to …: Object of type float32 is not JSON serializable and returns False, so the caller only sees CyberwaveMQTTError: … The MQTT client refused it; its log says why. and the twin stops mid-mission. I hit exactly this while building a DJI Tello marker-search demo in MuJoCo.

This PR:

  • adds a default= hook (_json_default) to the existing strict json.dumps calls in publish(), converting numpy scalars and arrays with .tolist();
  • makes _replace_non_finite handle numpy values too, so numpy NaN/inf still become null;
  • detects numpy by type(value).__module__, so cyberwave.mqtt still never imports numpy;
  • keeps rejecting other unknown objects as before (publish() returns False).

How did you test it?

  • New tests/test_mqtt_numpy_serialization.py (4 tests): numpy scalars/arrays publish as plain JSON (ints stay ints), numpy NaN/inf → null, _replace_non_finite handles numpy, unknown objects are still rejected.
  • The two numpy publish tests fail on main and pass with this change.
  • pytest tests/test_mqtt_numpy_serialization.py tests/test_mqtt_non_finite_serialization.py tests/test_mqtt_payload_limit.py → 68 passed.
  • mypy cyberwave/mqtt/__init__.py: the same 4 pre-existing errors (in other files) before and after; none added.
  • No hardware or live backend needed.

Contributor checklist

  • I added or updated tests for behavior changes, or explained why they are unnecessary.
  • I updated relevant documentation or examples. (n/a: no API change)
  • I noted any public API, optional dependency, or simulation/live behavior changes. (numpy values in payloads now publish instead of failing; no API or dependency change)

Recognition

  • Please skip the Discord celebration for this PR.

🤖 Generated with Claude Code

A command argument computed with numpy/OpenCV (e.g. a distance from detected
marker corners) is a numpy.float32. json.dumps raised TypeError on it, publish()
logged it and returned False, and the caller only saw "the MQTT client refused
it". Add a json default hook that converts numpy values via .tolist(), and let
_replace_non_finite handle numpy NaN/inf too. Detected by module, so mqtt still
never imports numpy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Slack team notifications

  • opened: sent

@github-actions

Copy link
Copy Markdown

Thanks for contributing to the Cyberwave Python SDK, @rishabh-bansal!

Maintainer contacts: @KhushiSharma22. When this PR is ready, we request a maintainer review and run an automated advisory review. CI and human review remain the source of truth.

Please describe what changed and how you tested it. See the contribution guide or ask for help on Discord. Drafts are welcome.

Merged human contributions receive a Discord thank-you. To opt out, check the PR template's Discord opt-out box or add <!-- cyberwave:no-celebration --> to the PR description.

@github-actions

Copy link
Copy Markdown

Automated advisory review · Claude

Commit: 7b0be0b4af20d913e5c944440f066f94709bbb00. Human review and CI are still required.

The patch adds numpy-aware JSON serialisation to the MQTT publish path. Two concrete defects are present: (1) a non-finite numpy scalar (e.g. numpy.float32('nan')) is converted to a Python float by tolist() inside _replace_non_finite, but the subsequent isinstance(value, float) branch then returns None correctly only for plain Python floats — however the more critical ordering issue is in _json_default, where a non-finite numpy scalar is converted to a non-finite Python float by tolist() and then returned directly to json.dumps with allow_nan=False, which will raise ValueError again rather than mapping it to null; (2) the first json.dumps call with allow_nan=False can now raise either ValueError (non-finite float) or TypeError (numpy value that slipped through a nested structure via default=), but only ValueError is caught, so a TypeError escaping from _json_default in the fallback path would surface as an unhandled exception, breaking the previous guarantee that publish() returns Fals

  • High · cyberwave/mqtt/__init__.py: In _json_default, when value is a non-finite numpy scalar (e.g. numpy.float32('nan') or numpy.float64('inf')), value.tolist() converts it to a non-finite Python float such as float('nan'). That Python float is then returned to json.dumps, which is called with allow_nan=False. json.dumps treats the returned value as the serialised replacement, encodes the float directly, and raises ValueError because nan is not valid JSON. The result is that non-finite numpy scalars are not sanitised to null; instead the first json.dumps raises ValueError, the fallback _replace_non_finite path is taken, but _replace_non_finite itself calls value.tolist() on the numpy scalar, then checks isinstance(value, float) — which is True for the resulting Python float — and correctly maps it to None. So the fallback path accidentally rescues this case. However, if the non-finite numpy value is nested inside a dict or list that also contains other numpy values, _json_default is called again in the fallback json.dumps, re-introducing the same ValueError and causing an unhandled exception that escapes publish(). Fix: in _json_default, after calling tolist() check whether the resulting Python value is a non-finite
  • Medium · cyberwave/mqtt/__init__.py: The except clause on line 1465 only catches ValueError, which is what json.dumps raises for non-finite floats when allow_nan=False. After the patch, _json_default can also raise TypeError (for non-numpy, non-serialisable objects). In the original code this TypeError was caught upstream and caused publish() to return False. With the new default= hook, TypeError now propagates from inside json.dumps as well, but only ValueError is caught. If a message contains a mix of an unserializable non-numpy object and something that triggers the ValueError path first, the subsequent fallback json.dumps call in the except ValueError block will raise TypeError, which is not caught and will propagate out of publish() as an unhandled exception instead of returning False. Fix: change the except clause to catch both ValueError and TypeError (except (ValueError, TypeError):) and ensure the fallback path also returns False on TypeError from the second json.dumps call.

Coverage: 2 of 2 changed files; patch excerpts only. Generated REST code, lockfiles, notebooks, SVGs, missing patches and files beyond the 40-file / 60,000-character budget are excluded. GitHub may truncate individual patches.

This branch has not been deployed

No deployments
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