Skip to content

feat(sequencer): SEQ_RUN selects one channel of the uploaded program (wire v3) - #792

Open
hongquanli wants to merge 16 commits into
feat/hardware-sequencer-z-firstfrom
feat/hardware-sequencer-run-channel
Open

hongquanli wants to merge 16 commits into
feat/hardware-sequencer-z-firstfrom
feat/hardware-sequencer-run-channel

Conversation

@hongquanli

Copy link
Copy Markdown
Contributor

Stacked on #790 (feat/hardware-sequencer-z-first). Host and firmware: the sequencer wire version goes from 2 to 3.

What

SEQ_RUN now selects a channel of the committed program. Byte 6 of the command: 0 runs every channel (today's run, and what a zero-filled command means), n runs channel n minus 1 alone.

#790 made a Z FIRST acquisition one single-channel burst per channel, and had to re-upload a one-channel program before every burst, because the controller holds one program: 16 acked SEQ_WRITE words plus SEQ_COMMIT per channel per FOV. With the selector the program is uploaded once per acquisition for both orders, and each Z FIRST burst selects its channel of it.

Compatibility

The program layout is unchanged, but kWireVersion / WIRE_VERSION are now 3, so firmware without the selector refuses the new host's programs at commit (BadProgram, detail version) and the acquisition fails at preparation with a clear reason, instead of running every channel and failing three bursts later. New host plus old firmware and old host plus new firmware both fail that way. The pairing rule, host and firmware from the same tree, is unchanged. The reported firmware version number is untouched.

Firmware

  • SeqEngine::start() takes the channel (kAllChannels by default). Step count, the step-to-layer mapping (one step per layer; the channel's z offset applies), the range check and the reported channel count follow the selection. A selector past the last channel fails BadChannel with the index as detail before anything moves, next to the BadDuration and StackOutOfRange refusals.
  • seq_start(stack_start, channel); callback_seq_run() decodes byte 6; the self-test runs every channel.
  • Native tests: a selected channel runs alone (its three planes with its offset, its exposure, then the return to start); a selector past the last channel fails before any DAC write; the golden program bytes and CRC are re-pinned at v3 (0xEB4E) in the firmware test and the host mirror.

Host

  • Microcontroller.seq_run(stack_start, channel=None).
  • SequencerProgram.n_frames_for(), step_to_layer_channel() and check_stack_range() take the channel; SimulatedSequencer runs the selected channel alone and refuses a bad index like the engine.
  • Worker: one upload per acquisition; a Z FIRST burst of one channel of a multi-channel program selects it; _ensure_uploaded and build_bursts from feat(sequencer): hardware-sequenced Z FIRST, one single-channel burst per channel #790 are gone; the burst timeout is sized for the selected channel.
  • tools/sequencer_transport_check.py: two bench checks between the existing run checks, "run channel 1 alone: Done, 3 frames fired" and "a channel past the program is refused before anything moves (BAD_CHANNEL)".

Tests

Native: 293 passed. Teensy build (teensy41_newctrl): success. Host: the sequencer program, simulator, controller and firmware-sim files, the worker-level Z FIRST file, the end-to-end file and the worker files, all green; collect-only clean; the simulation GUI driver boots and runs the microcontroller and stage.

Bench: the transport check's two new checks, then the Z FIRST sample run of #790 without the per-burst uploads. Flashing is Hongquan's call.

🤖 Generated with Claude Code
Claude-Session: https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod

…(wire v3)

Hongquan, 2026-11-01: "let's do channel selector". A hardware Z FIRST stack is one
single-channel burst per channel; until now each burst re-uploaded a one-channel
program, because the controller holds one program and SEQ_RUN ran all of it: 16 acked
SEQ_WRITE words plus the commit per channel per FOV.

Wire: SEQ_RUN byte 6 selects a channel - 0 = every channel of the committed program
(today's run; what a zero-filled command means), n = channel n-1 alone. The program
layout is unchanged; the wire version goes 2 -> 3 so firmware without the selector
refuses the new host's programs at commit and the acquisition fails at preparation
with a clear reason, instead of running every channel and failing three bursts later.

Engine: start() takes the channel; step count, the step-to-layer mapping (one step per
layer, the channel's z offset applies), the range check and the reported channel count
follow the selection; a selector past the last channel fails BadChannel with the index
as detail before anything moves. seq_start() and callback_seq_run() carry it.

Host: Microcontroller.seq_run(stack_start, channel=None); the program mirror's
n_frames_for / step_to_layer_channel / check_stack_range take the channel; the
simulator runs the selected channel alone and refuses a bad index like the engine.
The worker uploads the program once per acquisition for both orders and a Z FIRST
burst selects its channel of it; the per-burst upload and build_bursts are gone. The
transport check gains "run channel 1 alone: Done, 3 frames" and "a channel past the
program is refused" for the bench.

Tests: native (a selected channel runs alone with its planes, offset, exposure and
the return; a bad selector fails before any DAC write; golden bytes and CRC re-pinned
at v3), host (run command byte, simulator run and refusal, range check of a selected
channel, golden + word split), worker-level (each channel of the one uploaded program
with its own settings; a single-channel acquisition runs the whole program), end to
end (Z FIRST: one upload, one run per channel selecting it).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod
@coderabbitai

coderabbitai Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

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: dc636adb-a32b-4b95-be39-437ac328ff31

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

hongquanli added a commit that referenced this pull request Nov 2, 2026
…he burst

The controller returns the piezo to the stack START after a burst, which for From
Center is the stack bottom that prepare_z_stack() moved to. The sequenced path
returned there without the climb back that the software stack does in
move_z_back_after_stack(), and the next FOV's From Center move started from the
cached (bottom) position: with autofocus off, every FOV began half a stack below
the previous one (three planes at 1.5 um: FOV 2 started at 17 um instead of 18.5).

acquire_at_position() now climbs back to the centre after a sequenced From Center
stack, exactly as after a software one. The e2e test compares the per-image piezo
z and the final piezo position of a two-FOV From Center acquisition between the
sequenced and the software path.

Found by an external review of the #656 / #790 / #792 stack.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod
hongquanli added a commit that referenced this pull request Nov 2, 2026
…etry

After a burst failed, the retry paired its captures with whatever frame arrived
first. A frame the controller fired in the failed attempt can still be on its way
(a late frame is one of the ways a burst fails), and a frame carries nothing that
tells it from the retry's first frame: it was saved under the retry's z = 0 and
every later frame shifted by one, while the retry's count and consecutive-id
checks still passed. A silent mislabel, the one class of error validate-before-
save exists to rule out.

_run_sequenced_burst() now goes through _discard_failed_burst() on every failure
path, which restarts the camera stream before returning: the drivers lose
in-flight frames with the stream (ToupCam Stop(); Hamamatsu cap_stop +
buf_release), so the retry starts from a quiet camera. Worker-level tests with a
fake camera that holds a frame in flight: the late frame of attempt 1 is not
paired with attempt 2, and a burst the controller refused resynchronizes too.

Found by an external review of the #656 / #790 / #792 stack.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod
hongquanli added a commit that referenced this pull request Nov 2, 2026
Master's ENABLE_TOUPCAM_GLOBAL_RESET (#705) and this branch's
HARDWARE_TRIGGER_GLOBAL_RESET each put the sensor in global reset, through two
writers with one cache. With only the branch's opt-in on, _apply_global_reset_mode()
wrote the option without updating _global_reset_enabled, and on the way back to
software trigger _set_global_reset() skipped the write-off because its cache said
the mode was already off: the sensor stayed in global reset under software
trigger, where the illumination is on through the readout and shades the image.

_set_global_reset() is now the only writer and enables the mode for either opt-in
(with the stream paused, as #705 does); _apply_global_reset_mode() only verifies
(the write was refused, or the read-back is not 1) and raises, as before. Each
opt-in keeps its own strobe model until the bench settles which one is right.

The merge of master (4a00afc) also left the branch's ToupCam test helper without
the #705 attributes, which failed 15 tests in CI (AttributeError on
_global_reset_enabled); the helper now models the post-startup state. New test:
the mode is written on and written off again across a hardware -> software
trigger round trip.

Found by an external review of the #656 / #790 / #792 stack.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod
hongquanli added a commit that referenced this pull request Nov 2, 2026
…esident

The eligibility rule budgeted for two bursts, but the burst dispatcher holds one
in flight and queues one behind it (submit() blocks only beyond that), and the
worker collects the next burst meanwhile: three 400 MB bursts could occupy
1.2 GB under a 1 GB budget. The rule now requires three bursts to fit, and says
so in its reason.

Found by an external review of the #656 / #790 / #792 stack.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod
hongquanli and others added 2 commits November 1, 2026 17:21
… no channel selected

The three-argument _run_sequenced_burst() of the channel selector takes the
selected channel; the worker-level retry tests from the base branch run the
whole program (channel None).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod
hongquanli added a commit that referenced this pull request Nov 2, 2026
…the retry

7c2e772 restarted the camera stream after a failed burst so a late frame of that
burst could not be paired with the retry. That covers frames still in the camera
or its SDK, not a frame the driver had already read: the Hamamatsu read thread
takes a batch out of DCAM's ring under the capture lock and publishes it after
releasing the lock, one callback at a time, so a frame held by a callback ahead
of the worker's (a display) survives the restart and is delivered during the
retry - with an id that continues into the new capture, since _frame_id_base is
rebased from the newest frame read. Count and id order pass; the frame is saved
under the retry's z = 0. (The driver's constructor comment claimed the lock
covered publication; it does not, and now says so.)

Every frame now carries the run of the camera stream it was READ in
(CameraFrame.stream_generation; AbstractCamera.stream_generation() is the
current run, bumped by each start of the capture). The Hamamatsu stamps it under
the capture lock, the ToupCam reads it at the top of its frame callback before
the pull, the simulated camera in its frame generator; a driver that does not
stamp reports 0 for both. The worker's frame callback refuses a frame whose run
is not the camera's current one, before any pairing.

Tests: the Hamamatsu case end to end over the real read loop and a fake DCAM
ring (a display callback holds frame 3 across the restart; the retry gets 4, 5,
6 and frame 3 is logged and dropped); frames carry their capture's run across a
restart; the ToupCam callback stamps the run read before the pull and starting
the raw stream begins a new run; the worker-level fake camera no longer assumes
the restart drops what the driver had read.

Found by the external review's second pass of the #656 / #790 / #792 stack.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod
hongquanli and others added 2 commits November 1, 2026 18:03
…annel selected

The three-argument _run_sequenced_burst() of the channel selector takes the
selected channel; the driver-level restart test from the base branch runs the
whole program (channel None).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod
hongquanli added a commit that referenced this pull request Nov 2, 2026
Master's ENABLE_TOUPCAM_GLOBAL_RESET (#705) and this branch's
HARDWARE_TRIGGER_GLOBAL_RESET each put the sensor in global reset, through two
writers with one cache. With only the branch's opt-in on, _apply_global_reset_mode()
wrote the option without updating _global_reset_enabled, and on the way back to
software trigger _set_global_reset() skipped the write-off because its cache said
the mode was already off: the sensor stayed in global reset under software
trigger, where the illumination is on through the readout and shades the image.

_set_global_reset() is now the only writer and enables the mode for either opt-in
(with the stream paused, as #705 does); _apply_global_reset_mode() only verifies
(the write was refused, or the read-back is not 1) and raises, as before. Each
opt-in keeps its own strobe model until the bench settles which one is right.

The merge of master (4a00afc) also left the branch's ToupCam test helper without
the #705 attributes, which failed 15 tests in CI (AttributeError on
_global_reset_enabled); the helper now models the post-startup state. New test:
the mode is written on and written off again across a hardware -> software
trigger round trip.

Found by an external review of the #656 / #790 / #792 stack.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod
(cherry picked from commit 5a1118e)
…uencer-run-channel

# Conflicts:
#	software/tests/control/test_camera_hamamatsu_stream_restart.py
hongquanli added a commit that referenced this pull request Nov 11, 2026
…camera stream it comes from

eafc652 pinned every batch of pending captures to the run of the camera stream it was queued in, so
that a frame callback still on its way to pairing when a hardware-sequenced burst is given up cannot
take the retry's captures. That broke the AION/NL5 path: a stalled confocal scan is aborted inside
send_trigger(), the camera re-armed (stop + start streaming, a new run) and the scan retried. The
retried scan's frame then came from the new run, the ordinary capture's batch refused it, the worker
never became ready for the next trigger and the acquisition aborted after the frame timeout
(tests/control/test_aion_hw_trigger.py::test_a_stall_during_an_acquisition_does_not_abort_it, red
on CI for #656, #790 and #792).

Only a batch the worker itself gives up and retries after a stream restart needs the pin, and that is
the hardware-sequenced burst. An ordinary capture's batch is now queued for no particular run
(expect(..., stream_generation=None)) and follows the camera: the worker never restarts the stream
under it, and the confocal unit retries only a scan that had not exposed the camera, so one capture
never meets two frames. This is the pairing behaviour master has for ordinary captures.

PendingCaptures.stream_generation says which run the queued batch is for, and the worker's
unpaired-frame warning uses it to name a stream restart under a queued burst (the camera recovered on
its own; the burst times out and is retried) instead of calling the capture given up.

Tests: the any-run batch and the queued run on PendingCaptures; worker-level, an ordinary capture
pairing its frame after the trigger restarted the stream, and the warning for a restart under a
burst. The AION file passes again with the sequenced, retry and Hamamatsu restart sets (123 tests).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod
@hongquanli

Copy link
Copy Markdown
Contributor Author

Updated with #790 6f570f7 (master merged, firmware 2.0): clean merge, head 76d3931. All three firmware images build, 978 tests passed in the controller, sequencer, calibration and worker files, collect-only clean, simulation GUI driver ok. The bench image built from this tree is now firmware 2.0 (wire v3) and still needs its own flash.

🤖 Generated with Claude Code
Claude-Session: https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod

hongquanli and others added 2 commits November 13, 2026 20:48
… into feat/hardware-sequencer-run-channel

# Conflicts:
#	software/control/core/multi_point_worker.py
#	software/control/sequencer_sim.py
#	software/tests/control/test_MultiPointWorker_sequenced_z_first.py
…s, not every channel of the program

Finding of the 2026-11-13 Codex review of the stack, verified against the code.

With the SEQ_RUN channel selector one uploaded program serves every Z FIRST
burst, but the binding decided "this program uses a laser TTL" once per program,
at load. A run of an LED-only channel of a program that also holds a laser
channel was therefore aborted with InterlockOpen when the interlock was open,
although the run lit no laser. The engine now answers run_uses_ttl() for the
run in flight (the selected channel's mask, or any channel's when every channel
runs), and seq_tick aborts on that. The host builds TTL channels only, so no
acquisition reached this; a hand-built mixed program did.

Merged from the layers below: the worker builds the one program when it is
about to upload it, after the camera is set up for the burst, so a burst whose
strobe delay differs (the ToupCam's depends on the exposure in global reset)
uploads again and the others upload nothing; the burst time bound counts the
selected channel's own step time; the abort is checked before SEQ_RUN; a run
the host gives up on is cancelled and waited out before the camera restarts;
a failed burst puts the piezo back at the stack start.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod
@hongquanli

Copy link
Copy Markdown
Contributor Author

External review round (Codex, 2026-11-13) and fix: 5ab1523 (plus the merge of the updated #790 head)

Codex reviewed this layer's diff against the #790 head; both findings were verified against the code. One (the combined program's limits) is an ineligibility now in #656. The other is fixed here:

  • Interlock per run: the binding decided "this program uses a laser TTL" once per program at load, so a run that selected an LED-only channel of a program that also holds a laser channel was aborted with InterlockOpen when the interlock was open. The engine now answers run_uses_ttl() for the run in flight (the selected channel's mask, or any channel's when every channel runs). No host-built program reached this; every host channel is a TTL channel.

Merged from below and adapted to the selector: the one program is rebuilt when a burst is about to run, with the camera's current strobe delay, and uploaded again only when it differs; the burst time bound counts the selected channel's step time.

Evidence: native suites pass (new engine test); teensy41, teensy41_newctrl and the self-test image build; host sequencer test files pass; collection clean; simulation GUI driver ok. Wire v3 unchanged.

🤖 Generated with Claude Code
Claude-Session: https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod

@hongquanli
hongquanli marked this pull request as ready for review November 15, 2026 12:26
… into feat/hardware-sequencer-run-channel

# Conflicts:
#	firmware/controller/src/sequencer/seq_engine.cpp
#	software/control/microcontroller.py
#	software/tests/control/test_microcontroller_sequencer.py
@hongquanli

Copy link
Copy Markdown
Contributor Author

Why shard 1 failed three attempts running on ba60ed3, and what fixes it.

Both failing tests are master's, and neither touches this stack's code: tests/squid/test_stage.py::test_pi_focus_sub_window_settle_does_not_hold_the_stage_lock (5 to 7 extra sleep entries) and tests/control/test_aion_hw_trigger.py::test_a_stall_during_an_acquisition_does_not_abort_it[0.2] (its 0.2 s trigger timeout fired for a healthy scan). The shard balance differs per branch, and on this branch tests/squid/test_prior_stage.py runs in shard 1 before both of them. Each Prior stage starts a daemon that polls the position every 250 ms and had no way to stop; the Prior tests build a stage per test and never closed one. Reproduced locally with this shard's file list and a thread probe placed before test_stage.py: 48 threads named prior-pos-polling, all sleeping 0.25 s in a loop for the rest of the process.

Fixes, both from master: #826 gives PriorStage a close() that stops the poller and makes the Prior tests close their stages; #825 makes the stage test count only its own thread's sleeps. Once they merge and master is merged into the stack, shard 1 stops needing re-runs. Nothing in this PR changes for it.

🤖 Generated with Claude Code
https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod

… into feat/hardware-sequencer-run-channel

# Conflicts:
#	firmware/controller/src/sequencer/seq_bind.cpp
#	software/control/core/multi_point_worker.py
@hongquanli

Copy link
Copy Markdown
Contributor Author

Codex round 2 on this PR's own commit since round 1 (5ab1523) and on the merge resolution ba60ed3: no findings at any severity. Codex checked that the interlock fix follows the selected channel's TTL mask and keeps the all-channel behaviour, and that the three merge resolutions kept channel selection alongside the camera timing retention, the int32 payload check and their tests.

Carried up in fdb68c7: the round-2 fixes of #654 (camera rollbacks), #655 (an abort before a queued trigger fires leaves no cooldown) and #656 (no retry under a controller that did not stop, the piezo goes back before an abort, a sub-count z step falls back), through #790. Two resolutions by hand: the selected-channel interlock check now passes the timestamp the engine's abort takes, and the per-burst retry loop keeps this PR's channel argument inside the new try/except. This PR's own stack-range refusal in the engine gained the same timestamp. Native 22/22, host sequencer and worker sets 424 passed, collection and the simulation GUI fine.

The bench image moves with this: firmware 2.0, wire v3, now from fdb68c7.

🤖 Generated with Claude Code
https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod

hongquanli added a commit that referenced this pull request Nov 15, 2026
…s close their stages (#826)

## Why

`PriorStage` starts a daemon that polls the stage position every 250 ms,
and nothing could stop it: every stage object kept a poller for the life
of the process. `tests/squid/test_prior_stage.py` builds a stage per
test and never closed one, so by the end of the file 48 pollers were
alive, each calling `time.sleep` and talking to its fake controller four
times a second for the rest of the pytest process.

Seen in CI on the hardware-sequencer stack, where the shard balance put
`test_prior_stage.py` and `tests/squid/test_stage.py` in the same shard
(#792 run 43718535759, three attempts, all failed the same way):

- `test_pi_focus_sub_window_settle_does_not_hold_the_stage_lock` counted
the pollers' sleeps (5 to 7 extra entries). #825 makes that test count
only its own thread's sleeps; this PR removes the threads it was
counting.
-
`test_aion_hw_trigger.py::test_a_stall_during_an_acquisition_does_not_abort_it[0.2]`
saw its 0.2 s trigger timeout fire for a healthy scan on the same loaded
runner.

Reproduced locally by running the shard's file list with a thread probe
placed before `test_stage.py`: 48 threads named `prior-pos-polling`, all
sleeping 0.25 s in a loop.

## What

- `PriorStage.close()` stops the poller, joins it and releases the
serial handle. The polling loop waits on an `Event` instead of
`time.sleep`, so it ends within one period, and
`_ensure_pos_polling_thread()` does not restart polling after `close()`.
`Microscope.close()` already calls `stage.close()`, so a real Prior
stage now releases its thread and port on shutdown too.
- The test fixture closes every stage it built; the fake controller
records the close.
- Two new tests: `close()` ends the thread and releases the serial and
nothing restarts it; and, last in the file, no `prior-pos-polling`
thread outlives the file.

## Checks

- `tests/squid/test_prior_stage.py` and
`tests/control/test_preferences_dialog.py`: 210 passed locally.
- Simulation GUI starts, the microcontroller and stage work; collection
unchanged.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_0152Tv35xKhniRMRq2Xywaod


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Stage shutdown now stops position updates and closes the hardware
connection, helping prevent polling from continuing after the stage is
closed.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
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