Skip to content

Fix ExternalSessionScanner cache thread safety#407

Merged
PureWeen merged 1 commit intomainfrom
fix/scanner-cache-thread-safety
Mar 18, 2026
Merged

Fix ExternalSessionScanner cache thread safety#407
PureWeen merged 1 commit intomainfrom
fix/scanner-cache-thread-safety

Conversation

@PureWeen
Copy link
Owner

Replace Dictionary with ConcurrentDictionary for _cache in ExternalSessionScanner. The cache is read/written from a Timer callback (ThreadPool thread) in Scan(), and Dictionary is not thread-safe for concurrent operations.

Found during PR #405 code review — the scanner code is from PR #370.

Replace Dictionary with ConcurrentDictionary for _cache. The cache
is read/written from a Timer callback (ThreadPool thread) in Scan(),
and Dictionary is not thread-safe for concurrent operations. This
could cause corruption or crashes during disposal or test scenarios.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@PureWeen
Copy link
Owner Author

🤖 Multi-Model Consensus Review

CI: ⚠️ No checks configured
Tests: 2792/2794 pass (2 pre-existing flaky WsBridgeIntegrationTests timing failures — unrelated to this change)


✅ No Findings

5/5 models reviewed this PR and found no bugs. The fix is correct and complete.

Verified:

  • All _cache access patterns (TryGetValue, indexer write [key]=, ContainsKey, Keys, TryRemove) are individually atomic on ConcurrentDictionary
  • The stale-key eviction pattern (_cache.Keys.Where(...).ToList()TryRemove) is the standard correct approach — snapshot avoids collection-modified exceptions, TryRemove handles already-gone keys ✓
  • The TOCTOU gap (TryGetValue miss → [key]= write) is benign: the timer is one-shot and re-arms only after Scan() completes, so concurrent self-invocation can't occur. Even if it could, last-write-wins with identical values is harmless ✓
  • _sessions (the public Sessions property) uses a separate volatile field — correctly handled pre-PR ✓

Recommended Action: ✅ Approve

@PureWeen PureWeen merged commit 025c975 into main Mar 18, 2026
@PureWeen PureWeen deleted the fix/scanner-cache-thread-safety branch March 18, 2026 16:04
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