Skip to content

fix: a cancelled caller's frame never reaches the wire; the shared Stop always runs (bug-076 S1/N4/N5/N6) - #11

Merged
rafalmaciag merged 2 commits into
masterfrom
fix/bug-076-stop-frame-recheck
Nov 25, 2026
Merged

rafalmaciag merged 2 commits into
masterfrom
fix/bug-076-stop-frame-recheck

Conversation

@rafalmaciag

Copy link
Copy Markdown
Contributor

Follow-up to #10 (bug-076), from its review: S1, N4, N5, N6. The branch is cut from #10's head 15088be, so until #10 is merged this diff also shows #10.

S1: a cancelled caller's frame could still reach the PLC after the Stop (safety)

Verified in the code:

  • PriorityGate.ReleaseOne → TakeNext claims a waiter (TryClaim 0→1) and grants it.
  • The waiter's cancellation callback (Waiter.WaitAsync) cancels only an unclaimed waiter (CAS 0→2). So a waiter claimed before its token is cancelled is still granted, and the same holds when the token is cancelled while the waiter is enqueued but not yet registered.
  • ModbusChannel.ExecuteAsync did not check the token again once it held the slot.
  • Result: a verb that a Stop pre-empted could write [Move, k] after [Stop, k+1], and the PLC would take it as a new command.

Fix: ExecuteAsync checks the token right after it takes the slot; if it is cancelled, it releases the slot and throws before the frame starts. After that check, ordering holds:

  • The frame proceeds only if the token was not yet cancelled while this caller held the slot.
  • The Stop cancels first and only then asks for the slot, so this frame lands before the Stop's frame, or not at all.
  • A frame already in flight is still never cancelled, as before.

Test (Channel_SlotGrantedAfterTokenCancelled_NoFrameWrittenSlotReleased), deterministic:

  1. Hold the gate.
  2. Start a write with a cancellable token.
  3. Register a second callback on that token that releases the gate.
  4. Cancel.

Callbacks run newest first, so the gate claims the waiter before the waiter's own callback can cancel it; the token is already cancelled when the frame would start. The test asserts OperationCanceledException, that no TCP connection reached the test listener (so no frame), and that the slot was released.

  • Before the fix: red. A connection was opened and a frame written.
  • After: green.

N6: the shared Stop can never be left dead

  • In StopCoreAsync, the runner now starts in a finally after running.Cancel(). If a token callback makes Cancel() throw, the error is logged and the Stop still goes out. Before, _stop stayed published with no runner, and every later StopAsync joined a task that never completes.
  • In RunStopAsync, _stop is cleared and the result published in a finally.

Tests:

  • StopAsync_CancellingTheVerbThrows_StopStillRunsAndIsNotLeftPending: red before, because the first StopAsync threw AggregateException and no runner started. Green after: the Stop runs, and the next StopAsync writes a new Stop. It needs one test-only hook, FakePlcChannel.OnToken, to put a throwing callback on the verb's token.
  • StopAsync_RunThrows_CallersGetTheFailure_NextStopWritesANewOne: its caller gets the Stop's own failure, and the next StopAsync writes a new Stop. It passes both before and after; it pins the failure path.

N4: docs/protocol.md

"One command in flight" now names the two known exceptions, deferred until observed:

  • a disconnect's Enable 0 that took its CommandSeq just before the Stop;
  • the edge clear a re-attach writes after the PLC dropped the lease.

Either can land after the Stop's word; neither carries a motion edge.

N5: protocol.pdf regenerated in this PR

  • How it was made before: no script exists in the repo. Earlier commits (8f1f19f, bf59723, bd9a5b7, 6f62ada) only say "regenerated". The old PDF's metadata shows how: Creator HeadlessChrome/154, Producer Skia/PDF, title "generic-axis protocol".
  • How I made it, with tools already on this host (nothing installed):
    1. markdown-it-py (CommonMark + tables) → HTML with title "generic-axis protocol" and a plain print stylesheet.
    2. google-chrome --headless=new --no-pdf-header-footer --print-to-pdf.
  • The HTML contains the new paragraph, and I checked a screenshot of the render.
  • Difference: the old stylesheet is unknown, so the layout differs: 13 pages against 18 before. The content is docs/protocol.md at this commit.

Evidence (Debug, native ~/.dotnet/dotnet, foreground)

  • StopStormTests on this branch's tests against the code at 15088be: 2 red (S1, N6-cancel), 9 green.
  • After the fix: StopStormTests plus the channel and gate classes (PriorityGateTests, ChannelBlockingTests, ErrorMessageTests, ConnectMessageTests): 25/25.
  • Whole ModelingEvolution.GenericAxis.Tests: 223/223 (220 + 3 new).
  • ModelingEvolution.GenericAxis.Plugin.Tests: 69/69.

Not verified

  • No real PLC; TestApp.Tests not run locally.
  • From the review, N3 is still open for the rw2 side: the Handset will now show Busy for a jog re-pressed while a Stop is still pending. The rw2 lead and the tester should know.

🤖 Generated with Claude Code

rafalmaciag and others added 2 commits November 25, 2026 16:06
…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>
…op always runs (bug-076 S1/N6)

S1: PriorityGate grants a waiter it already claimed even when the waiter's token was cancelled meanwhile (the
cancellation callback loses to the claim). ModbusChannel.ExecuteAsync now re-checks the token right after it
takes the slot, releases the slot and throws, so a verb a Stop pre-empted can never write [Move, k] after
[Stop, k+1]. A frame that already started is not cancelled; it holds the slot, so the Stop comes after it.

N6: the Stop's runner is started in a finally, after the running verb is cancelled; a throwing callback on the
verb's token is logged and the Stop goes out regardless. RunStopAsync clears _stop and publishes the result in a
finally.

N4: protocol.md "One command in flight" names the two deferred exceptions (a disconnect's Enable 0, a re-attach's
edge clear); neither carries a motion edge. N5: protocol.pdf regenerated from this protocol.md (markdown-it-py ->
HTML -> headless Chrome, as the previous PDF's metadata shows).

Tests (StopStormTests +3): S1 and N6-cancel red before the fix, green after; N6-run-throws pins the failure path.

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

Copy link
Copy Markdown
Contributor Author

Independent review: bug-076 follow-up (S1/N4/N5/N6), MERGE. Binds to 53c890e10861f7359dcbad896ba9a2128251c960

I reviewed only 15088be..53c890e, in my own detached worktree. I checked it against docs/standards/dotnet.md, docs/standards/happy-path-first.md, the skill use-thread-safe-collection, and the repo CLAUDE.md and docs/protocol.md. All four of my findings are closed.

S1: the frame of a cancelled caller is not written. Closed.

  • The slot is always released on that path. ModbusChannel.cs:163-167 calls slot.Dispose() and then throws, before using (slot) takes ownership. Release.Dispose is idempotent (Interlocked.Exchange). The test also takes the gate again afterwards.
  • The re-check never drops the STOP's own frame.
    • The driver's Stop writes under CancellationToken.None (AxisEngine.cs:781-782, WriteStopAsync), and so does its edge clear.
    • The other driver writers on the Stop lane are the heartbeat's release writes (AxisHeartbeat.cs:319/323, None) and the watchdog-fault clear (:165, the caller's token).
    • So no caller's token can cancel a STOP frame. The STOP is not weakened.
    • For any other token, the re-check only drops a frame whose token was cancelled while it queued. The waiter's own registration already meant to drop such a frame; the claim simply beat it. Nothing that used to go out on purpose is now dropped.
  • The test is deterministic. It relies on cancellation callbacks running last-registered-first, which is the long-standing .NET behaviour: the test's release runs before the waiter's own callback, so the gate claims the waiter first.
  • Mutant: re-check removed → only Channel_SlotGrantedAfterTokenCancelled_NoFrameWrittenSlotReleased fails (verified by running).

N6: the shared Stop cannot be left without a runner. Closed.

AxisEngine.cs:729-744 wraps running.Cancel() in try/catch/finally and always starts RunStopAsync. RunStopAsync (:759-777) clears _stop and publishes the result in a finally.

Mutant (StopStormTests, project rebuilt) Result
try/catch/finally around Cancel removed (old order) 1/11 fail: StopAsync_CancellingTheVerbThrows_StopStillRunsAndIsNotLeftPending
RunStopAsync's finally body emptied 10/11 fail, including both N6 tests
RunStopAsync put back as it was at 15088be 11/11 pass

The last row shows the RunStopAsync rewrite behaves exactly like 15088be, which already caught every exception. The new StopAsync_RunThrows_… test guards behaviour that already existed; that is fine.

FakePlcChannel.OnToken is test-only and harmless. It lives in src/ModelingEvolution.GenericAxis.Tests/Support, defaults to null, and is invoked before the fake's own ThrowIfCancellationRequested. Product code is untouched.

N4: the protocol sentence is accurate. Closed.

docs/protocol.md:76-79 matches the code:

  • Disconnect: DisableForDetachAsync writes the Enable level only.
  • Re-attach: AttachAsync writes [Enable level, CommandAck], which carries no edge bit.

Both can land after the Stop's word, and neither carries a motion edge. With S1 closed, these are the only two exceptions left.

N5: the regenerated protocol.pdf is complete and legible. Keep it.

I compared it with the old PDF (git show 15088be:docs/protocol.pdf), extracting text with pypdf and rendering pages with PyMuPDF.

  • Complete. All 17 headings and all 87 register-table rows of protocol.md are present.
  • Legible.
    • Register tables have ruled rows. A table split across a page repeats its header row (Command block, pages 1–2), and no row is cut.
    • No text span reaches past the right margin (checked on every page). The long example messages wrap inside their grey block.
  • Differences a reader may notice; none is worse in a way that matters.
    • The paper size is now A4, not Letter.
    • The code font in tables and message blocks is smaller than before, but still readable at 100 %.
    • 13 pages instead of 18.
  • The render is not reproducible from the repo. No script; markdown-it-py plus headless Chrome by hand. Committing the stylesheet and command next time would let anyone regenerate it. NOTE, not blocking.

Q5: invented constraints and conventions

None.

  • No new option, timeout or setting.
  • No new lock.
  • The catch-all around Cancel logs at Error and is sourced by N6.
  • B.0, identifiers and JSON: no id, value type, event or command record touched.
  • No Moq.

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

  • 53c890e: ModelingEvolution.GenericAxis.Tests 223/223, ModelingEvolution.GenericAxis.Plugin.Tests 69/69.
  • Mutants as above, each run on StopStormTests with the project rebuilt. Checkout restored and clean at 53c890e.

Not verified

  • No real PLC and no simulator run.
  • TestApp.Tests not run.
  • PDF checked on screen renders, not printed.

🤖 Generated with Claude Code

@rafalmaciag
rafalmaciag merged commit bd460ad 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