Skip to content

fix: one command in flight per axis; concurrent Stops join the pending one (bug-076) - #10

Merged
rafalmaciag merged 1 commit into
masterfrom
fix/bug-076-one-stop-in-flight
Nov 25, 2026
Merged

rafalmaciag merged 1 commit into
masterfrom
fix/bug-076-one-stop-in-flight

Conversation

@rafalmaciag

Copy link
Copy Markdown
Contributor

Defect (bug-076, MAJOR)

At Pamet, 73 STATION STOP presses in 1.5 s ran as 73 concurrent StopAsync calls on the carriage. AxisEngine.SendCommandAsync takes the next CommandSeq under _sync, writes [Command, CommandSeq] and waits up to 500 ms for CommandAck == seq. Nothing serialized two callers. Each later write replaced the earlier CommandSeq, and the PLC acknowledges only the sequence it last saw. Every earlier caller therefore failed with NotAcknowledged: Stop not accepted. CommandSeq 232 written, CommandAck 302 read, although the axis stopped. Each failing Stop then cleared its edge with its own older sequence. The PLC accepted that older sequence as a new command word, so the ack went backwards (CommandSeq 237 written, CommandAck 235 read).

Fix (AxisEngine only, plus one protocol paragraph)

  • A pending Stop is one shared task (_stop, guarded by the existing _sync). The first StopAsync writes the Stop edge at once. Callers that arrive while it is pending join it, write nothing and get its result. A StopAsync after it finished starts a new Stop. The Stop runs to its end under CancellationToken.None; one caller's cancellation ends only that caller's wait.
  • No other command word while a Stop is pending.
    • A new verb is refused by G2 (Busy: … refused: a Stop is in progress, nothing written). _running is read under the same lock that publishes the Stop, so a verb is either cancelled by the Stop or refused by G2.
    • A command already past its guards waits in SendCommandAsync. The check sits under the lock that takes the sequence. A verb the Stop pre-empted ends there with OperationCanceledException, as it does today. The disconnect's Enable 0 goes after the Stop.
  • A command pre-empted at its ack deadline no longer writes a stale edge clear after the Stop. The best-effort ClearEdgeAsync now uses the command's own token, which the Stop cancels, instead of CancellationToken.None. The NotAcknowledged branch throws the cancellation instead of reporting the Stop's ack as its own.
  • No new option, no new setting, no new timeout, no new lock.

docs/protocol.md

I added a paragraph, One command in flight, under § Command semantics. Decision: this belongs in the protocol, not only in the driver. It changes what the PLC sees on the wire: a command the Stop pre-empts no longer gets its edge cleared, which the Acknowledge bullet promises today, and a second Stop is never written while one is pending. The repo rule says the protocol file is the contract. protocol.pdf is not regenerated in this PR.

Red → green (StopStormTests, FakePlcChannel + DriverRig.BehaveLikePlc, which acks the last CommandSeq it saw, like the real PLC)

Test master branch
73 concurrent StopAsync on a moving axis: one Stop on the wire, every caller stopped FAIL: 73 Stop writes, 72 of 73 callers failed, 72 NotAcknowledged pass
concurrent StopAsync joining a Stop that fails: every caller gets that failure, one Stop on the wire FAIL pass
a StopAsync after the earlier Stop finished sends a new Stop pass pass
Stop while a move waits for its ack: the Stop is written at once and pre-empts the move pass pass
Stop during a move's ack-deadline read: the move writes nothing after the Stop FAIL: Stop not accepted. CommandSeq 2 written, CommandAck 1 read pass
Stop cancels a move's ack-deadline read: the move writes nothing after the Stop FAIL pass
the disconnect's Enable 0 while a Stop is pending goes after the Stop, never over it FAIL pass
a move commanded while a Stop waits for its ack is refused; nothing overwrites the Stop FAIL pass

Master: 6 failed, 2 passed. Branch: 8 passed. Whole ModelingEvolution.GenericAxis.Tests: 220 passed (212 existing + 8 new). ModelingEvolution.GenericAxis.Plugin.Tests: 69 passed. TestApp.Tests was not run locally; that is CI's job.

Mutation check, one change per mutant, StopStormTests re-run each time:

  • no join → 2 red
  • no G2 Stop refusal → 1 red
  • no wait loop in SendCommandAsync → 1 red
  • no ThrowIfCancellationRequested in the NotAck branch → 1 red
  • read-failed branch clears with None → 1 red
  • NotAck branch clears with None while ThrowIfCancellationRequested is kept → survives. The only window is between that check and the gate acquire, and the synchronous fake has no such window. I kept it as defence in depth.

Stop vs. a motion command whose handshake is waiting for its ack: what master does

Verified by the tests above on master.

  • During the 500 ms ack wait it is correct today. StopAsync cancels the running verb, the ack wait ends at once with OperationCanceledException, nothing is written for it, and the Stop is written immediately.
  • The collision is at the ack deadline. The deadline read, or the NotAcknowledged branch, clears the edge with CancellationToken.None. That writes [Enable, olderSeq] after the Stop; the PLC accepts it as a new command word and the Stop fails NotAcknowledged.
  • A new verb at Standstill during a pending Stop also overwrote the Stop's word. The same NotAcknowledged follows.
  • All three are fixed here.

Safety (owner's order: a STOP never gets slower or weaker)

  • No Stop pending → the Stop edge is on the wire before StopAsync returns. It goes on the Stop lane and never waits for a motion ack, with no debounce and no delay. The test asserts the write before any tick and before any fake time passes. Only one thing changed: the Stop is no longer aborted by a caller's cancellation token, which makes it stronger, not weaker.
  • A joined failure stays a failure. Every joiner awaits the same task and rethrows the same exception (test: 10 joiners, one identical NotAcknowledged).
  • A Stop after the earlier one finished is a new Stop. _stop is cleared before the result is published (test).
  • Could a joiner be told "stopped" although a motion command was written after the Stop it joined? No, by construction:
    • A verb that starts while the Stop is pending is refused by G2, under the lock that published the Stop.
    • A verb running when the Stop is created is cancelled. A sequence it had not taken waits and then throws.
    • Its frame already granted in the PriorityGate finishes before the Stop's frame, because the gate serializes and the Stop enqueues after the cancel. Its queued frame is dropped; the gate never grants a cancelled waiter (PriorityGate.Waiter.WaitAsync / TakeNext).
    • Its best-effort edge clear uses its cancelled token, so it is not written.

Deferred until observed (not built: no source)

  • The disconnect's Enable 0 (DisableForDetachAsync, token None) could take its sequence just before a Stop starts and still sit queued on the Move lane. The Stop lane would then overtake it, and Enable 0 would land after the Stop with the older sequence. That frame is not motion: it drops the drive. Reaching it needs a station STOP inside the few milliseconds of a disconnect's Enable 0. Not observed, not reproduced.
  • ReattachAsync (the PLC dropped the lease) writes the attach edge clear outside SendCommandAsync, and could overwrite a pending Stop's word. Not observed.
  • The rw2 half (StationHalt coalescing, the "may still be moving" verdict, the Handset sending 54 presses) belongs to the separate rw2 PR.

Release path into rw2 (not done here; no tag, no publish)

  • Next version: v0.2.1. The latest tag is v0.2.0 = 2d2da1d, this branch's base.
  • After merge: git tag v0.2.1 <merge sha> && git push origin v0.2.1. .github/workflows/publish-nuget.yml then:
    • builds and tests;
    • packs ModelingEvolution.GenericAxis 0.2.1 and ModelingEvolution.GenericAxis.Plugin 0.2.1;
    • attaches GenericAxis.Plugin-0.2.1.zip (layout plugins/ModelingEvolution.GenericAxis.Plugin/0.2.1/) to the GitHub release;
    • pushes to the org feed (best effort) and to nuget.org (Trusted Publishing).
  • rw2 source pins no version. git grep GenericAxis on rw2 origin/master finds only a comment in MotionRoster.cs.
  • The version lives per station, in the Plugins configuration section (PluginEntry[]). PluginService writes it on install/update (POST /api/plugins/update), stages the closure into plugins/<id>/<version>/, and reports restart-required. PluginLoader loads that folder at the next start.

🤖 Generated with Claude Code

…g one (bug-076)

At a station, 73 STATION STOP presses ran as 73 concurrent StopAsync calls on the carriage. Each wrote its own
[Stop, CommandSeq]; the PLC acknowledges only the sequence it last saw, so 72 callers failed NotAcknowledged
while the axis stopped.

- A pending Stop is one shared task: the first caller writes the edge at once, later callers join it and get its
  result (success or failure); a Stop after it finished is a new Stop. It runs to its end regardless of one
  caller's cancellation.
- While a Stop is pending no other command word is written: a new verb is refused (G2, Busy), a command already
  past its guards waits (a pre-empted verb ends with OperationCanceledException), the disconnect's Enable 0 goes
  after the Stop.
- A command pre-empted at its ack deadline no longer clears its edge with CancellationToken.None after the Stop
  (that stale CommandSeq made the PLC drop the Stop's ack).
- protocol.md § Command semantics: "One command in flight".

Tests: StopStormTests (8): 6 red on master (73 Stop writes, 72 of 73 callers NotAcknowledged), 8 green here.

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

Copy link
Copy Markdown
Contributor Author

Independent review: bug-076 axis half, MERGE. Binds to 15088be64f282b622b236c4b19d6317db8ddecb5 (base 2d2da1d)

Checked against docs/PRINCIPLES.md, docs/standards/dotnet.md, docs/standards/happy-path-first.md, the skills use-thread-safe-collection, writing-value-class and use-json-parsable-converter, the bug doc, both logs, docs/bugs/bug-076/test-scenarios.md, the repo CLAUDE.md and docs/protocol.md. I read the code in my own detached worktree.

The fix does what the bug asks:

  • N concurrent StopAsync calls put one Stop on the wire, and every caller gets the same result.
  • A joined failure stays a failure for every caller.
  • A Stop after the earlier one finished is a new Stop.
  • With no Stop pending, the Stop edge is written as it was on master: Stop lane, no wait for any ack, no lock held across an await.

I found no path where a caller is told "stopped" while the axis moves. The Stop succeeds only when a status read after its ack shows Standstill, Disabled or ErrorStop (AxisEngine.cs WriteStopAsync). Every residual write-ordering path below can therefore only produce a failure, never a false success.

Findings

S1 SHOULD (already on master, read only): a pre-empted verb's command frame can still be granted after its token was cancelled
PriorityGate.cs:61-80 and Waiter.WaitAsync :193-207, ModbusChannel.cs:150-180.

The steps:

  1. AcquireAsync checks ct on entry.
  2. It enqueues the waiter under the gate lock.
  3. Only later, in WaitAsync, does it register ct.

Suppose the Stop's running.Cancel() lands after step 1, and the Stop's own frame finishes before step 3. Then ReleaseOne → TakeNext claims the move waiter (TryClaim 0→1), and the registration that runs after it no longer cancels it. ExecuteAsync does not re-check ct once it holds the slot. The verb's [Move…, k] then reaches the PLC after [Stop, k+1]. The PLC treats k ≠ ack as a new command, so the axis moves after the Stop.

The Stop then fails, never false-succeeds: either NotAcknowledged (the ack reads k) or MotionFailed ("still moving" after StopTimeout). The window is sub-microsecond and the PR did not widen it. But the PR text says "the gate never grants a cancelled waiter", which holds only once the registration has run.

Fix: one line in ExecuteAsync, ct.ThrowIfCancellationRequested() right after the slot is acquired (dispose the slot, then throw). The fix is outside this diff, so I accept it as an immediate follow-up rather than a blocker.

N1 NOTE: deferred path (a), the disconnect's Enable 0 with a sequence taken just before a Stop, is acceptable to defer (read only)
ModbusAxisDevice.cs:307-320, AxisEngine.cs DisableForDetachAsync.

  • Worst case: [Stop,k+1] and then [0x0000,k]. The PLC accepts the second word as a command and drops the drive. That is not motion.
  • The Stop most likely reports NotAcknowledged, a false alarm in the safe direction. No caller is told "stopped" while the axis moves.
  • It needs a STATION STOP inside the few milliseconds of a disconnect's Enable 0. Not observed.
  • Deferred is fine. Put one line about it in the protocol paragraph (see N4).

N2 NOTE: deferred path (b), ReattachAsync's edge clear during a pending Stop, is acceptable to defer (read only)
AxisEngine.cs ReattachAsync/AttachAsync (:258-317).

  • The attach write is [Enable level, fresh.CommandAck]. It has no motion edge.
  • It can replace the Stop's word, and _seq restarts from a CommandAck read before the Stop. Worst case: the Stop reports a false failure, or the next command's sequence collides with the PLC's ack.
  • A false "stopped" is still impossible: success needs a later Standstill/Disabled read.
  • It only happens after the PLC dropped the lease (a PLC restart or release). Not observed. Deferred is fine.

N3 NOTE: the new Busy refusal is sourced, and rw2 will see it (read only)
AxisEngine.cs:1021-1022.

  • Source: the observed log (CommandSeq 237 written, CommandAck 235 read) plus the protocol (the PLC acks the last sequence it saw). On master, a verb during a pending Stop overwrote the Stop's word.
  • A move right after a Stop completes is not refused, because _stop is cleared before the result is published (verified by test).
  • rw2's Handset AxisPane shows MotionError.Busy as Devices.Mobile.ErrBusy (rw2 master AxisPane.razor:636). A jog re-pressed while the release-Stop still waits for Standstill now shows that word instead of silently failing the Stop. Please tell the rw2 lead and the tester.
  • MotionSafety.StopAxesAsync uses StopAsync(None).WaitAsync(deadline), so its behaviour is unchanged.
  • No Plugin code issues a verb after a Stop (grep of src/ModelingEvolution.GenericAxis.Plugin).

N4 NOTE: protocol paragraph (docs/protocol.md:71-76)

  • It is consistent with Handshake and Acknowledge, and it states the one exception to Acknowledge's "the driver clears the edge bit it set" (a pre-empted command).
  • But "While a Stop waits … the driver writes no other command word" is absolute, and N1/N2 are two known exceptions. Add one sentence naming them as deferred, or soften the wording. The repo rule is that the protocol file is the contract.

N5 NOTE: protocol.pdf
No script in the repo generates it. It is regenerated by hand, sometimes in the same commit (8f1f19f), sometimes later as "regenerated from master " (bf59723, bd9a5b7, 6f62ada). Name in the PR who regenerates it after the merge.

N6 NOTE: the shared Stop cannot be left dead, but only by argument (read only)
RunStopAsync catches every exception and clears _stop on both branches. Every await inside it is bounded:

  • the gate grants the waiter, or fails it on dispose;
  • a frame is bounded by IoTimeout 500 ms plus one retry;
  • AwaitAsync is bounded by AckTimeout/StopTimeout and throws on Detach.

The only statement between publishing _stop and starting the runner is running?.Cancel() (AxisEngine.cs:737). Running.Cancel swallows ObjectDisposedException. It could only throw through a throwing registration on a verb token, and there is none today. A try/finally that always starts or faults the runner would make this structural rather than argued.

The lead's questions

  1. Expected behavior: met. Verified by the tests below.
  2. Safety.
    • With no Stop pending, the edge goes out at once: no lock across an await, never behind a 500 ms ack wait, Stop lane in the gate. The test asserts the write before any tick.
    • A caller that joins a Stop told "stopped" while a motion word followed: impossible through this PR's paths, because success needs a post-ack Standstill read. S1 is an old path that can only produce a failure.
    • A joined failure stays a failure, and a later Stop is new.
    • A dead shared task: none (N6).
    • Busy: sourced, and it breaks no normal run (N3).
    • The deferred items do not block (N1, N2).
  3. Tests. The fake PLC (DriverRig.BehaveLikePlc, Support/DriverRig.cs:108-118) accepts any word whose seq differs from its ack and acks it, so an older seq written later moves the ack back. That is what the log shows (237 written, 235 read).
  4. Protocol. N4, N5.
  5. Conventions.
    • No new lock: _stop is guarded by the existing _sync (Lock).
    • The TaskCompletionSource uses RunContinuationsAsynchronously.
    • No new option, setting or timeout.
    • Logging uses ILogger, tests use no Moq.
    • B.0, identifiers and JSON: the diff touches no id, value type, event or command record.

Run evidence (all Debug, native ~/.dotnet/dotnet, -nodeReuse:false, foreground)

  • Head: ModelingEvolution.GenericAxis.Tests 220/220, ModelingEvolution.GenericAxis.Plugin.Tests 69/69.
  • Mutants, each run on StopStormTests with the test project rebuilt:
Mutant Result Tests that fail
fix reverted (AxisEngine.cs at 2d2da1d, tests kept) 6/8 fail join-failure, 73-callers, both ack-deadline tests, Enable-0-after-Stop, move-refused
(a) Stops serialized, each writes its own 2/8 fail 73 callers → one Stop; joined failure → one Stop
(b) joiners get success when the pending Stop failed 1/8 fail joined failure stays a failure
(c) shared task kept after completion 2/8 fail a later Stop sends a new Stop; Enable 0 after the Stop
  • Checkout restored to 15088be, clean.

Not verified

  • No real PLC and no simulator run.
  • TestApp.Tests not run.
  • S1, N1, N2 and N6 by reading only.

🤖 Generated with Claude Code

@rafalmaciag
rafalmaciag merged commit 90c2555 into master Nov 25, 2026
6 checks passed
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