fix(camera): prevent intermittent all-zero ToupCam frames from read-buffer realloc race#585
Open
Alpaca233 wants to merge 1 commit into
Open
fix(camera): prevent intermittent all-zero ToupCam frames from read-buffer realloc race#585Alpaca233 wants to merge 1 commit into
Alpaca233 wants to merge 1 commit into
Conversation
…zero frames _on_frame_callback read self._internal_read_buffer twice non-atomically: PullImageV2 fills it, then np.frombuffer re-reads it. _update_internal_settings — called on every set_exposure_time, i.e. every channel switch, from the acquisition thread — reassigns it to a fresh zero-filled bytes() without holding _raw_frame_callback_lock. A reassignment landing between the two reads made np.frombuffer view the new all-zero buffer while PullImageV2 had filled the old one, producing intermittent all-zero saved frames across channels (misread as dim/dark FOVs). Snapshot the buffer reference once inside the lock so fill and read use the same object; a concurrent reassignment can no longer split them. The local reference also keeps that buffer alive for the SDK's write. Adds tests/control/test_camera_toupcam_buffer_race.py, which drives the real _on_frame_callback and deterministically forces the reallocation-during-pull interleaving (fails with an all-zero frame before the fix). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
facd0f5 to
8691aad
Compare
Contributor
There was a problem hiding this comment.
Pull request overview
This PR addresses an intermittent Toupcam frame corruption issue where saved/delivered frames can become entirely zero due to a race between the SDK callback thread reading self._internal_read_buffer and the acquisition thread reallocating that buffer during exposure/channel switches.
Changes:
- Snapshot
self._internal_read_bufferonce insideToupcamCamera._on_frame_callbackand use that reference for bothPullImageV2andnp.frombuffer, preventing split-buffer reads. - Add a regression test that deterministically forces the “realloc during pull” interleaving and asserts the delivered frame is not all-zero.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| software/control/camera_toupcam.py | Prevents all-zero frames by ensuring the callback uses a consistent read-buffer object for both SDK fill and NumPy view. |
| software/tests/control/test_camera_toupcam_buffer_race.py | Adds a targeted regression test to reproduce and guard against the buffer-realloc race. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Comment on lines
+46
to
+48
| cam._config = types.SimpleNamespace(rotate_image_angle=None, flip=None, crop_width=None, crop_height=None) | ||
| cam._diag_frame_log_every = 30 # keep high so the per-frame diagnostic branch never runs | ||
| cam._log = squid.logging.get_logger("test_toupcam_buffer_race") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes intermittent all-zero saved frames in multi-channel acquisitions (a scattered ~1–2% of FOVs across channels — first noticed as "dim"/dark 405 tiles in a mosaic, but the raw TIFFs are exactly zero). A real exposure is never all-zero, so this is a data-path defect, not a light/laser/firmware issue.
Root cause — a thread race on the camera read buffer
ToupcamCamera._on_frame_callback(SDK callback thread) readsself._internal_read_buffertwice, non-atomically:PullImageV2(self._internal_read_buffer, …)fills it, thennp.frombuffer(self._internal_read_buffer, …)re-reads it.Meanwhile
_update_internal_settings— invoked byset_exposure_timeon every channel switch (set_microscope_mode→set_exposure_time) from the acquisition thread — reassignsself._internal_read_buffer = bytes(buffer_size)(a fresh zero-filled buffer) without holding_raw_frame_callback_lock. InMultiPointWorker.acquire_camera_image, the channel setup (_select_config→ the realloc) runs before the wait on the previous frame's callback, so the next channel's reallocation is not gated by the in-flight callback.If that reassignment lands between the callback's two reads,
PullImageV2filled the old buffer butnp.frombufferviews the new all-zero one → the delivered/saved frame is entirely zeros. It's channel-agnostic (the buffer is re-zeroed before every frame) and intermittent (the store must land in the pull window — observed 0.5–45.8 ms per callback in production logs).Fix
Snapshot the buffer reference once inside the callback lock and use it for both the fill and the read, so a concurrent reassignment can no longer split them. The local reference also keeps that buffer alive for the SDK's C-level write. Minimal, localized, and correct regardless of the async triggering pipeline.
Test
tests/control/test_camera_toupcam_buffer_race.pydrives the real_on_frame_callback/_process_raw_frame(faking only the SDK boundary + ROI getters) and deterministically forces the reallocation-during-pull interleaving:Plus a no-realloc sanity case.
black-clean; camera-layer tests pass locally.Notes / follow-ups
_update_internal_settingsto only run whenbuffer_sizeactually changes. Exposure changes don't change the buffer size, so today it needlessly allocates+zeroes the full frame buffer on every channel switch — a perf win and defense-in-depth that narrows the race window further. Deserves its own test.🤖 Generated with Claude Code