Skip to content

fix(mcu): mark a command pending before its bytes are written - #871

Open
hongquanli wants to merge 1 commit into
masterfrom
fix/mcu-busy-flag-before-write
Open

hongquanli wants to merge 1 commit into
masterfrom
fix/mcu-busy-flag-before-write

Conversation

@hongquanli

@hongquanli hongquanli commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

What fails

Microcontroller.send_command set mcu_cmd_execution_in_progress = True after self._serial.write(...) returned. It set last_command, the send time, the retry count and the cleared abort error after the write too. The reader thread clears the flag when it parses the status packet that acks the command. When that reply is parsed before send_command sets the flag, this happens:

  1. The reader sees the ack for the current id, finds the flag already False, and does nothing.
  2. send_command then sets the flag to True.
  3. The flag stays True until another status packet acks the same id.

SimSerial answers only inside write(), so in simulation the next such packet is the reply to the next command. For a wait that sends nothing else, that is the heartbeat, up to 2.5 s later. A CMD_EXECUTION_ERROR reply in the same window is lost the same way: send_command clears the abort that the reader just recorded, and the wait times out instead of raising CommandAborted.

How it was found: test_HighContentScreeningGui.py::test_home_stage_proceeds_with_only_the_host_busy_flag_set was slow in CI, and under load it hit its 10 s waitUntil. Each command in the homing sequence whose reply landed in the window made that step's wait_till_operation_is_completed last until the next heartbeat.

How often: rarely, per command. The reader has to be scheduled in the few bytecodes between the write returning and the flag being set. In a bare process with SimSerial:

  • 0 hits in 4000 commands at the default GIL switch interval;
  • 1 hit in 2000 commands at a 1 µs switch interval.

The GUI process runs many threads, and under CI load it hits the window more often.

On hardware: the window is the time between the write returning and the flag being set. That is microseconds, but a fast USB reply can land in it. The controller sends its status every 10 ms with the same id and status, so on hardware a hit should cost about one status period, not a stuck wait.

Fix

  • Everything the reader matches a reply against is now set before the write: last_command, the send time, the retry count, the cleared abort error and the packet count at send. The in-progress flag is set last, so a reader that sees it turn on finds the rest already set for this command.
  • If the write raises, that state is put back as the write found it, flag first. A failed write therefore leaves no pending command behind, and the reader has nothing to resend on an ack timeout.
  • The send time is taken again after the write, so the ack timeout still counts from when the bytes went out. A write that has to reconnect can take seconds.

There is no change to the protocol, the firmware, the timeouts, the retries or the locking. _cmd_lock still serialises senders, and the reader still does not take it to match a reply.

Tests

The new tests are in tests/control/test_microcontroller.py. They use a SimSerial subclass whose write() returns only after the reader thread has handled the reply. It waits on the packet callback, which runs after the reader's matching branches. That makes the race happen every time:

  • test_a_reply_handled_before_write_returns_completes_the_command fails on master:
    TimeoutError: Current mcu operation timed out after 0.5 [s]. Sent cmd 15 (MOVE_X); mcu reports cmd 15 status=COMPLETED_WITHOUT_ERRORS; 0.5 [s] since a valid packet. The mcu has gone quiet - check the serial connection.
    
  • test_an_execution_error_handled_before_write_returns_fails_the_command fails on master. The wait times out instead of raising CommandAborted:
    TimeoutError: Current mcu operation timed out after 0.5 [s]. Sent cmd 15 (MOVE_X); mcu reports cmd 15 status=CMD_EXECUTION_ERROR; 0.5 [s] since a valid packet. The mcu has gone quiet - check the serial connection.
    
  • test_a_failed_write_leaves_no_command_pending passes on master, where the state was only set after the write. It guards the rollback: with the state moved before the write but no rollback, it fails.

Results, under both PyQt5 and PyQt6:

  • The microcontroller, status-stream, firmware-sim, limit-switch, focus-wheel, startup-homing and filter-wheel test files: 442 passed, 1 skipped.
  • test_HighContentScreeningGui.py, run whole in one process with CI's config: 53 passed.

Still unverified

  • Not run on a real controller.
  • The race never hit in a local run, before or after the fix, so the HCS homing test's local duration is unchanged: about 4.6 s, of which roughly 4 s is building the GUI.
  • The rest of that test's time is a wait for the next heartbeat, which is by design. The test sets the host flag by hand, and a Z-only home's first wait in CephlaStage.home() waits on it. That wait varies by up to one heartbeat interval (2.5 s) from run to run. The fix removes only the extra heartbeat wait for each command the race hits, which is what pushed the test past 10 s under CI load.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved command handling when a reply arrives before a write completes, including execution-error responses.
    • Prevented failed writes from leaving a command marked as pending or overwriting the last successfully sent command.
    • Ensured acknowledgement timing starts after a successful write.

send_command set mcu_cmd_execution_in_progress (and last_command, the send
time, the retry count and the cleared abort error) only after the serial
write returned. A reply parsed before that - SimSerial answers inside
write(), and a fast link can too - found the flag still clear, and the flag
was then set with nothing left to clear it until another packet acked the
same id: in simulation the next command's reply, at worst the next
heartbeat. A CMD_EXECUTION_ERROR reply in that window was wiped the same
way, so the wait timed out instead of raising CommandAborted.

Everything the reader matches a reply against is now set before the write,
the in-progress flag last. A write that raises puts that state back as it
found it, flag first, so a failed write leaves no pending command for a
wait or an ack-timeout resend. The send time is taken again after the
write, so the ack timeout still counts from when the bytes went out.

Tests: a SimSerial whose write() returns only after the reader has handled
the reply (completion and execution error, both failed before), and a
failed write that leaves no command pending.

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

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

send_command prepares command state before writing, restores the prior state if writing fails, and resets the acknowledgement timeout after a successful write. New tests cover early replies and write failures.

Changes: Command send synchronization

Layer / File(s) Summary
Command state and write handling
software/control/microcontroller.py, software/tests/control/test_microcontroller.py
send_command sets command state and the in-progress flag before writing. If the write raises, it restores the previous state and re-raises. Tests cover early success and execution-error replies, plus write failure and preservation of the prior command.

Estimated code review effort: 2 (Simple) | ~12 minutes

Change: Bug fix

Possibly related issues

  • Issue 558 reports microcontroller.is_busy() staying True. This PR addresses a host-side race that can leave the in-progress flag set when a reply arrives before send_command sets it. The issue’s root cause is unconfirmed.

Suggested reviewers: ianohara, alpaca233

Merge Risk: Minimal · up to 3d687

This fixes a race where a fast reply could be processed before a command was marked pending, which could leave the busy flag set or clear an execution error. The new tests cover early success, early error, and failed-write rollback. It was not tested on real hardware, and an unusually slow serial write could in theory cause a duplicate command retransmission. That edge case does not warrant blocking the merge.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "fix(mcu): mark a command pending before its bytes are written" describes the main change. The summary shows Microcontroller.send_command now sets the in-progress flag and command state befo…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title "fix(mcu): mark a command pending before its bytes are written" describes the main change. The summary shows Microcontroller.send_command now sets the in-progress flag and command state before the write, restores prior state on write failure, and refreshes the ack timeout after the write. The title is specific, concise, and follows a conventional-commit style. It names the fix and its ordering change, which matches the PR objectives.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Team
  • Run ID: a56eb183-8da1-4524-82d8-7842b4fb742b
Commits

Reviewing files that changed from the base of the PR and between 8f3a879 and 3d68718.

Files selected for processing: 2

  • software/control/microcontroller.py
  • software/tests/control/test_microcontroller.py

Included review availability: This review used your included allowance. 3 included reviews remain after this review. Your included PR review attempts over the past 7 days set your current allowance at 4 reviews per hour.

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