Skip to content

Server: claim subscription expiry without the manager semaphore - #5228

Merged
marcschier merged 5 commits into
masterfrom
romanett/sb4-sweep-semaphore-c60b03
Dec 1, 2026
Merged

marcschier merged 5 commits into
masterfrom
romanett/sb4-sweep-semaphore-c60b03

Conversation

@romanett

@romanett romanett commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Fixes SB-4 from the 2026-11-15 server architecture review: TransferSubscriptions held SubscriptionManager.m_semaphoreSlim across await PrepareSessionTransferAsync, while the publish sweep's expiry path took the same semaphore with a synchronous Wait() inside Parallel.For. One slow transfer could stall the publish threads.

Changes

  • Per-subscription expiry claim. ISubscriptionPublishPipeline.TryClaimExpiration / ReleaseExpirationClaim / IsExpirationClaimed, decided under Subscription.m_lock and mutually exclusive with TryBeginTransfer.
    • Queued subscriptions: SessionPublishQueue.TryClaimForExpiration claims and removes the exact queue entry under the queue lock (same lock order as TryClaimForTransfer).
    • Abandoned subscriptions: claim, remove from the abandoned set, release the claim if removal fails.
    • The sweep no longer touches m_semaphoreSlim. m_expiringSubscriptions is removed; StoreSubscriptionsAsync checks the claim flag.
  • Three-phase transfer. (1) validate and reserve under the semaphore, recorded in m_transfersInFlight; (2) PrepareSessionTransferAsync with no lock; (3) commit under the semaphore. On failure RollbackAsync runs outside the semaphore and only the restore bookkeeping runs under it.
  • Ordering preserved. Closing the source or destination session, deleting the subscription, a second transfer of the same id, and shutdown wait for the in-flight transfer itself (EnterSemaphoreAfterTransfersAsync, which releases the semaphore while waiting) instead of on the semaphore.
  • Documented invariants and lock order at m_semaphoreSlim: semaphore → SessionPublishQueue.m_lock → Subscription.m_lock → status-messages lock.

Invariants

  • A subscription is never both expired and transferred.
  • A subscription is never transferred twice concurrently.
  • A failed transfer leaves the original owner intact (source entry is only claimed until commit; source session close waits for the transfer).

Behaviour change

None visible to clients. The sweep, other transfers, and create/delete of other subscriptions no longer wait behind a slow transfer.

The (SubscriptionManager) downcast in SessionPublishQueue is left as is (SB-1; the queue needs SubscriptionExpired/CleanupSubscriptions on the manager).

Tests

  • 7 new deterministic (TaskCompletionSource-gated) tests in SubscriptionTests.cs: blocked transfer does not stall the sweep; expiry-first wins (queued and abandoned); transfer-first wins over a stale sweep snapshot; second transfer of the same id waits and gets BadNothingToDo; failed transfer restores the source before the source session closes; claim and reservation exclude each other. The stall test fails against the old code.
  • Server.Tests net10.0: 12549 passed, 8 failed (pre-existing local symlink-permission tests).
  • Stress Conformance 154/154, Contract + Integration 45/45. net48 build clean.

🤖 Generated with Claude Code

The publish sweep claimed expirations with a synchronous Wait() on the
subscription manager semaphore, from inside Parallel.For, while
TransferSubscriptions held that semaphore across the awaited
PrepareSessionTransferAsync. One slow monitored item transfer stalled
the publish threads.

- Expiry is claimed per subscription (TryClaimExpiration under the
  subscription lock, exclusive with the TryBeginTransfer reservation);
  a queued subscription is claimed under the queue lock together with
  the removal of its exact entry. The sweep no longer takes the manager
  semaphore. m_expiringSubscriptions is replaced by the claim flag.
- TransferSubscriptions runs in three phases: reserve under the
  semaphore, prepare without it, commit or roll back under it.
  Transfers in flight are registered; closing either session, deleting
  the subscription, a second transfer of it and shutdown wait for them,
  keeping the ordering they had while the transfer held the semaphore.
- Lock order and invariants are documented at m_semaphoreSlim.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings December 1, 2026 05:06
@romanett romanett changed the title Server: claim subscription expiry without the manager semaphore (SB-4) Server: claim subscription expiry without the manager semaphore Dec 1, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The same-session transfer shortcut bypasses the expiry check, returning BadNothingToDo instead of BadSubscriptionIdInvalid for an expired subscription awaiting cleanup.

1 open issue
What changed in this PR

This PR removes subscription-expiry processing’s dependency on the manager semaphore, allowing publish sweeps and unrelated requests to proceed while a transfer is waiting.

Changes:

  • Adds per-subscription expiry claims that exclude concurrent transfer reservations.
  • Splits transfers into reserve, prepare, and commit phases, with explicit waiting for conflicting operations.
  • Documents locking invariants and adds seven deterministic concurrency tests.
File Description
tests/​Opc.Ua.Server.Tests/​SubscriptionTests.cs Tests blocked transfers, expiry ordering, rollback, and competing reservations.
src/​Opc.Ua.Server/​Subscription/​SubscriptionManager.cs Separates transfer phases and removes semaphore acquisition from expiry claims.
src/​Opc.Ua.Server/​Subscription/​Subscription.cs Makes expiry claims and transfer reservations mutually exclusive.
src/​Opc.Ua.Server/​Subscription/​SessionPublishQueue.cs Claims expiry and removes the exact queue entry under the queue lock.
src/​Opc.Ua.Server/​Subscription/​ISubscriptionPublishPipeline.cs Defines the expiry-claim operations and state.

Review effort: Balanced

The same-session BadNothingToDo shortcut ran before TryBeginTransfer saw
the expiry claim, so the owner got BadNothingToDo for a subscription that
was already expiring. Treat an expiry-claimed subscription as gone for
every caller, and cover the same-session request in the expiry-first test.

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

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Code coverage

✅ Coverage gate passed.

Check Result Threshold
✅ Project line rate 89.51% (515452/575860 lines) >= 70.00%
✅ Project branch rate 80.16% >= 60.00%
✅ Patch coverage 86.13% (149/173 changed lines) >= 75.00% (> 100 changed lines)
ℹ️ Baseline delta (advisory) +15.91 pp 73.60% recorded
Uncovered changed lines
  • src/Opc.Ua.Server/Subscription/SubscriptionManager.cs: 1410, 1411, 1473, 1474, 1475, 1476, 1477, 1479, 1480, 1481, 1497, 2175, 2179, 2231, 2232, 2233, 2234, 2258, 2266, 2267, 2268, 2269
  • src/Opc.Ua.Server/Subscription/SessionPublishQueue.cs: 782, 783

Coverage is above the recorded baseline - consider ratcheting coverage-thresholds.json.

Thresholds live in coverage-thresholds.json. Whole report before exclusions: line 89.06%, branch 79.67%.

@codecov

codecov Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.76879% with 35 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.86%. Comparing base (aa5f140) to head (f92670b).
⚠️ Report is 7 commits behind head on master.

Files with missing lines Patch % Lines
.../Opc.Ua.Server/Subscription/SubscriptionManager.cs 78.08% 21 Missing and 11 partials ⚠️
.../Opc.Ua.Server/Subscription/SessionPublishQueue.cs 70.00% 2 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #5228      +/-   ##
==========================================
- Coverage   83.87%   83.86%   -0.01%     
==========================================
  Files        3879     3879              
  Lines      575722   575860     +138     
  Branches    99270    99294      +24     
==========================================
+ Hits       482903   482962      +59     
- Misses      60122    60186      +64     
- Partials    32697    32712      +15     
Flag Coverage Δ
actions 83.86% <79.76%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/Opc.Ua.Server/Subscription/Subscription.cs 91.84% <100.00%> (+0.06%) ⬆️
.../Opc.Ua.Server/Subscription/SessionPublishQueue.cs 87.94% <70.00%> (-1.69%) ⬇️
.../Opc.Ua.Server/Subscription/SubscriptionManager.cs 86.31% <78.08%> (+0.28%) ⬆️

... and 76 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The documented lock hierarchy reverses the implemented order of the status-messages and subscription locks, which could lead future changes to introduce a deadlock.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Low severity Correct the documented status-message and subscription lock order

src/​Opc.Ua.Server/​Subscription/​SubscriptionManager.cs:3765

The last two locks are documented in the opposite order to the implementation: SubscriptionExpired holds m_statusMessagesLock while calling PublishTimeout, which acquires Subscription.m_lock; the transferred-status path does the same through SubscriptionTransferred. Following the hierarchy documented here in future changes could therefore introduce a deadlock. Please place the status-messages lock before the subscription lock in this hierarchy.

1 resolved since last review

Review effort: Balanced

SubscriptionExpired and the transferred status take Subscription.m_lock
under m_statusMessagesLock; document that order instead of the reverse.

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The transfer releases its reservation before initializing and filtering the destination status queue, creating an expiry race that can lose BadTimeout notifications and needs a gated regression test.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Initialize the destination status queue before releasing the reservation

src/​Opc.Ua.Server/​Subscription/​SubscriptionManager.cs:2155

CompleteTransfer releases the reservation before the destination status queue is initialized and filtered. If the subscription is due to expire at this point, the semaphore-free sweep can enqueue BadTimeout that the filter then removes, or drop it because the status queue does not exist yet. Move the status-queue initialization/filtering block before CompleteTransfer, and add a gated regression test for expiry during commit.

Review effort: Balanced

…fer reservation

CompleteTransfer released the reservation before the destination status
queue was created and filtered, so a sweep-side expiry in that window
could drop its BadTimeout (no queue yet) or have it filtered away. Build
the queue first; the reservation keeps the sweep out until it exists.
Adds a test that holds the status-messages lock to stop the commit there.

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Filtering the destination status queue before the fallible monitored-item commit can permanently delete pending transfer notifications when the commit fails, because rollback does not restore them.

1 open issue

Review effort: Balanced

A failing CommitMonitoredItemEffects rolled the transfer back after the
destination status queue had already dropped the subscription's pending
messages (e.g. GoodSubscriptionTransferred from an earlier transfer).
Run the fallible commit first; the reservation is still held until the
filtered queue exists.

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The three-phase transfer and semaphore-free expiry changes alter ordering across callbacks, session closure, deletion, and shutdown, warranting human concurrency review with gated and stress tests not independently executed.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@marcschier
marcschier merged commit 6bf4c52 into master Dec 1, 2026
144 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.

3 participants