Skip to content

apps/ios: fix the FlashTeXPad crash — CaptureQueue.records is lock-protected, hosted tests don't start a second PadModel (#359) - #372

Merged
GoKubar merged 2 commits into
mainfrom
agent/daniel-parent/pad-capturequeue-race
Sep 14, 2026
Merged

GoKubar merged 2 commits into
mainfrom
agent/daniel-parent/pad-capturequeue-race

Conversation

@d-q222

@d-q222 d-q222 commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

Fixes #359, the owner-visible FlashTeXPad SIGSEGV. Implemented by a Cursor worker (Grok 4.6 high), reviewed by daniel-parent. Split out of the e2e branch (#364) so it can be reviewed and merged on its own.

Cause

CaptureQueue (FlashTeXPadKit) kept records as a bare Array. Its async send/refreshOutcome resume off the main actor after await and mutated the array, while PadModel (main actor) copied it into @Published captures. With one poller per capture, two captures raced, corrupting the array's buffer. That's the swift_release_dealloc crash in PadModel.captures.setter. Strict concurrency is minimal, so the compiler didn't flag it.

Fix

  • CaptureQueue: _records sits behind an NSLock. records and record(_:) return atomic snapshots, and update, draft, discard and persistLocked mutate under the lock, as does lastStoreError. store.save runs under the lock so a reader never sees a torn list; CaptureStore has its own lock and no callback runs under ours. No lock is held across an await.
  • PadModel: the pollOutcome task doesn't hold self strongly across await.
  • Hosted XCTest (XCTestConfigurationFilePath set): the app's own @StateObject PadModel doesn't load the Keychain or disk, and doesn't start polling or auto-reconnect. Before this, a second model polled leftover captures alongside the test's model, which is a second source of concurrent access.

Evidence (iPad Pro 11-inch M5 simulator, iOS 26.5, Xcode 26.6)

Follow-up (not here)

SWIFT_STRICT_CONCURRENCY = minimal / Swift 5 mode hid this. Turning on complete checking for FlashTeXPadKit would surface any sibling races. That deserves its own lane.

🤖 Generated with Claude Code

https://claude.ai/code/session_012c9XLkHjePPGBuarrmE2mz

d-q222 and others added 2 commits September 14, 2026 01:46
…s without a lock

CaptureQueueTests.testConcurrentRefreshSendAndRecordsRead hammers refreshOutcome/send/draft
plus tight records reads from Task.detached on two received captures (FakeMac + temp CaptureStore).

Ran against unfixed CaptureQueue (HEAD 304120c, iPad Pro 11-inch M5 947A8CC1-07E2-4AA2-9363-FA389B569E8D):
control unit suite first: Executed 25 tests, with 1 test skipped and 0 failures (0 unexpected) / ** TEST SUCCEEDED **
race test: Crash: FlashTeXPad at closure #1 in closure #1 in closure #2 in CaptureQueueTests.testConcurrentRefreshSendAndRecordsRead(); ** TEST FAILED **
(Restarting after unexpected exit, crash, or test timeout)

Next: lock CaptureQueue._records and lastStoreError; isolate hosted XCTest PadModel; re-run this test then the suite.

Implementation-Agent: cursor-agent cursor-grok-4.6
Commit-Executor: cursor-agent (this session, git commit)
Lane-Owner: daniel-parent (mac-m5pro-dq222)
Co-authored-by: Cursor <[email protected]>
…ychain/disk/polling

CaptureQueue.records/lastStoreError/redeliveries are NSLock snapshots; update/draft/persistLocked
run under the lock (store.save included). pollOutcome is @mainactor [weak self]. Hosted
XCTestConfigurationFilePath PadModel() does not attach Keychain or CaptureStore and does not
poll leftovers; FlashTeXPadApp skips auto-reconnect in that environment.

Ran (iPad Pro 11-inch M5 947A8CC1-07E2-4AA2-9363-FA389B569E8D, iOS 26.5, Xcode 26.6):
- unfixed race test: Crash: FlashTeXPad ... testConcurrentRefreshSendAndRecordsRead; TEST FAILED
- after lock: race + hosted Executed 2 tests, with 0 failures; TEST SUCCEEDED
- FlashTeXPadTests: Executed 27 tests, with 1 test skipped and 0 failures (control was 25 / 1 skip)
- TSan -enableThreadSanitizer YES on race test and full suite: Executed 27 tests, 1 skipped, 0 failures; no ThreadSanitizer data-race reports
- swift test in FlashTeXPadKit: Build complete! then error: no tests found (package has no test target by design)

Next: lane-owner review / PR. Not switching CaptureQueue to actor/@mainactor (would hop off-main callers; current tests are @mainactor so it is feasible).

Implementation-Agent: cursor-agent cursor-grok-4.6
Commit-Executor: cursor-agent (this session, git commit)
Lane-Owner: daniel-parent (mac-m5pro-dq222)
Co-authored-by: Cursor <[email protected]>
@d-q222

d-q222 commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

GH-PADKIT-CONCURRENCY checkpoint

SHA: 5796c27521664d8b90e238b787c9e49722125920 on agent/daniel-parent/padkit-strict-concurrency (stacked on this PR's d401d2e8; not pushed to pad-capturequeue-race).

Done

Enabled .enableExperimentalFeature("StrictConcurrency") on the FlashTeXPadKit target only in Package.swift (tools 5.9, no .unsafeFlags). Simulator: iPad Pro 11-inch (M5) 947A8CC1-07E2-4AA2-9363-FA389B569E8D, Xcode 26.6 / Swift 6.3.3.

Control on unmodified d401d2e8: Executed 27 tests, with 1 test skipped and 0 failures / ** TEST SUCCEEDED **.

PadKit-flag build: ** BUILD SUCCEEDED **; compile line has -enable-experimental-feature StrictConcurrency and -swift-version 5.

Warning inventory (file:line, unique)

FlashTeXPadKit (Sources/FlashTeXPadKit/*.swift) — 0 warnings

Flag stays ON. Swift 6.3 region isolation does not diagnose class mutation after await, which is why #359 was invisible under minimal.

Classification of checker-missed PadKit state (no compiler warning):

  • (a) none remaining after the FlashTeXPad crashes (EXC_BAD_ACCESS/SIGSEGV) in PadModel.pollOutcome → @Published captures setter — data race on CaptureQueue.records #359 NSLock on CaptureQueue._records / _lastStoreError / _redeliveries. send/refreshOutcome resume off-main after await; readers copy snapshots under that lock. Interleaving that used to EXC_BAD_ACCESS is the existing testConcurrentRefreshSendAndRecordsRead.
  • MacLink.onTranscript is a public stored property not taken under lock. Production writes it once in PadModel.init before connect; network log() reads it later. Not a currently reachable race (write-once-before-readers). Checker-missed, not (a) in the live app.
  • (b) pending annotations (next commit): CaptureQueue: @unchecked Sendable (justified by lock); MacLink.TranscriptLine: Sendable (immutable value type, cross-module). These are the PadKit roots of some app-target warnings below.

NearbyClient (REPORT ONLY — Mac-owned symlink) — 21

Grouped:

  • static non-Sendable: NearbyReconnector.swift:31 ReconnectPolicy.immediate
  • sending / @sendable capture: NearbyReconnector.swift:217 budget, :246 pair+onLine, :168 capture; NearbyClient.swift:122/124 pair/policy/onLine/p; NearbyBrowser.swift:81 results; NearbyResolver.swift:31 $0, :70 Result<Resolved, Error>
  • CLI (not used by the iPad): NearbyCLI.swift:299,300,305,307,329 emit/pair/lineLogger/CaptureReceived
    Root cause is mostly PairedMac / ReconnectPolicy / NearbyWire.CaptureReceived not Sendable (public structs, no inferred Sendable across modules). PairFile.pairs is @unchecked Sendable but mutated without a lock — possible (a) if the CLI store is used concurrently; not edited here.

FlashTeXProtocol (REPORT ONLY — Mac-owned symlink) — 3

  • LayoutNegotiation.swift:17 static legacy / non-Sendable LayoutNegotiation
  • RenderingV2.swift:115 static black / non-Sendable Paint
  • RenderingV2.swift:497 ValidationError.source is RuntimeV1.SourceRange (not Sendable)
    All (b) — immutable-looking value types missing Sendable.

App target (REPORT ONLY — PRs #348 #349 #352) — 13 unique, under command-line SWIFT_STRICT_CONCURRENCY=complete (pbxproj still minimal)

  • PadModel.swift:80 sending line (TranscriptLine not Sendable across modules)
  • PadModel.swift:247,277,292 sending self.queue (CaptureQueue not Sendable)
  • PadModel.swift:186,198,489 sending pair (PairedMac — NearbyClient)
  • PadModel.swift:193 sending (DiscoveredMac) -> Bool
  • PadModel.swift:235 sending mac (DiscoveredMac — NearbyClient)
  • ContentView.swift:400 NearbyWire.CaptureReceived not Sendable; :3 hint to @preconcurrency import NearbyClient
  • CaptureView.swift:57 cameraAvailable MainActor from Sendable closure
  • PadModel.swift:454 unused try? (not concurrency)
    Baseline minimal already had PadModel.swift:108 maxRecentInstructions (that one did not reproduce under complete in this inventory build).

Next

(b) annotations in PadKit sources only; then xcodebuild test FlashTeXPadTests + TSan vs control 27/1 skip.

@d-q222

d-q222 commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

GH-PADKIT-CONCURRENCY checkpoint

SHA: dcfcfbf1adc24a5c447453902af251f90c5e425c

Done

(b) annotations only (no (a) races left in PadKit after #359):

  • CaptureQueue: @unchecked Sendable — comment names lock (_records, _lastStoreError, _redeliveries)
  • MacLink.TranscriptLine / Direction: Sendable
  • PairingStore: Sendable (both conformers already were)

Build: ** BUILD SUCCEEDED **; 0 PadKit-owned warnings. App PadModel sending-queue/line warnings gone; leftover app warnings are PairedMac/DiscoveredMac (NearbyClient, report-only).

Next

xcodebuild test FlashTeXPadTests vs control 27/1 skip, then -enableThreadSanitizer YES.

d-q222 added a commit that referenced this pull request Sep 14, 2026
…ringStore

(b) checker-only; no runtime behaviour change.
- CaptureQueue: @unchecked Sendable — lock serializes _records/_lastStoreError/_redeliveries
- MacLink.TranscriptLine (and Direction): Sendable (immutable value type)
- PairingStore: Sendable (PairFile and KeychainPairStore already are)

Rebuild with PadKit StrictConcurrency + SWIFT_STRICT_CONCURRENCY=complete: ** BUILD SUCCEEDED **;
still 0 warnings in Sources/FlashTeXPadKit. App PadModel sending-queue/line warnings gone;
remaining app warnings are NearbyClient PairedMac/DiscoveredMac (report-only).

Next: FlashTeXPadTests control-vs-after and -enableThreadSanitizer YES.

Implementation-Agent: cursor-agent cursor-grok-4.6
Commit-Executor: cursor-agent (this session, git commit)
Lane-Owner: daniel-parent (mac-m5pro-dq222)
Co-authored-by: Cursor <[email protected]>
@d-q222

d-q222 commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

GH-PADKIT-CONCURRENCY checkpoint

SHA: dcfcfbf1adc24a5c447453902af251f90c5e425c (lane agent/daniel-parent/padkit-strict-concurrency; last code change). Flag stays ON (PadKit warning-clean).

Gates (iPad Pro 11-inch M5 947A8CC1-07E2-4AA2-9363-FA389B569E8D, iOS 26.5, Xcode 26.6)

Control on unmodified d401d2e8:
Executed 27 tests, with 1 test skipped and 0 failures / ** TEST SUCCEEDED **

After (dcfcfbf1):
Executed 27 tests, with 1 test skipped and 0 failures / ** TEST SUCCEEDED **

TSan -enableThreadSanitizer YES after:
Executed 27 tests, with 1 test skipped and 0 failures / ** TEST SUCCEEDED **
No ThreadSanitizer: / data-race lines.

Remaining vs acceptance

@GoKubar
GoKubar merged commit e03e48d into main Sep 14, 2026
20 checks passed
@GoKubar
GoKubar deleted the agent/daniel-parent/pad-capturequeue-race branch September 14, 2026 14:49
d-q222 added a commit that referenced this pull request Sep 14, 2026
…h-merged

CaptureQueue.swift conflict: main has #372's lock without the Sendable
annotation; kept this branch's `@unchecked Sendable` + lock comment.

Claude-Session: https://claude.ai/code/session_012c9XLkHjePPGBuarrmE2mz
d-q222 added a commit that referenced this pull request Sep 14, 2026
… main

Restored CaptureQueue.swift, PadModel.swift and FlashTeXPadApp.swift to
origin/main (#372's reviewed version). What remains is the opt-in real-Mac UI
test, its project/scheme wiring, the Paste accessibility identifier and the
evidence pack.

Claude-Session: https://claude.ai/code/session_012c9XLkHjePPGBuarrmE2mz
GoKubar pushed a commit that referenced this pull request Sep 14, 2026
…rning-clean (follow-up to #359/#372) (#375)

* wip(#359): regression test that concurrent CaptureQueue access crashes without a lock

CaptureQueueTests.testConcurrentRefreshSendAndRecordsRead hammers refreshOutcome/send/draft
plus tight records reads from Task.detached on two received captures (FakeMac + temp CaptureStore).

Ran against unfixed CaptureQueue (HEAD 304120c, iPad Pro 11-inch M5 947A8CC1-07E2-4AA2-9363-FA389B569E8D):
control unit suite first: Executed 25 tests, with 1 test skipped and 0 failures (0 unexpected) / ** TEST SUCCEEDED **
race test: Crash: FlashTeXPad at closure #1 in closure #1 in closure #2 in CaptureQueueTests.testConcurrentRefreshSendAndRecordsRead(); ** TEST FAILED **
(Restarting after unexpected exit, crash, or test timeout)

Next: lock CaptureQueue._records and lastStoreError; isolate hosted XCTest PadModel; re-run this test then the suite.

Implementation-Agent: cursor-agent cursor-grok-4.6
Commit-Executor: cursor-agent (this session, git commit)
Lane-Owner: daniel-parent (mac-m5pro-dq222)
Co-authored-by: Cursor <[email protected]>

* wip(#359): lock CaptureQueue records; hosted XCTest PadModel skips Keychain/disk/polling

CaptureQueue.records/lastStoreError/redeliveries are NSLock snapshots; update/draft/persistLocked
run under the lock (store.save included). pollOutcome is @mainactor [weak self]. Hosted
XCTestConfigurationFilePath PadModel() does not attach Keychain or CaptureStore and does not
poll leftovers; FlashTeXPadApp skips auto-reconnect in that environment.

Ran (iPad Pro 11-inch M5 947A8CC1-07E2-4AA2-9363-FA389B569E8D, iOS 26.5, Xcode 26.6):
- unfixed race test: Crash: FlashTeXPad ... testConcurrentRefreshSendAndRecordsRead; TEST FAILED
- after lock: race + hosted Executed 2 tests, with 0 failures; TEST SUCCEEDED
- FlashTeXPadTests: Executed 27 tests, with 1 test skipped and 0 failures (control was 25 / 1 skip)
- TSan -enableThreadSanitizer YES on race test and full suite: Executed 27 tests, 1 skipped, 0 failures; no ThreadSanitizer data-race reports
- swift test in FlashTeXPadKit: Build complete! then error: no tests found (package has no test target by design)

Next: lane-owner review / PR. Not switching CaptureQueue to actor/@mainactor (would hop off-main callers; current tests are @mainactor so it is feasible).

Implementation-Agent: cursor-agent cursor-grok-4.6
Commit-Executor: cursor-agent (this session, git commit)
Lane-Owner: daniel-parent (mac-m5pro-dq222)
Co-authored-by: Cursor <[email protected]>

* wip(#372): enable StrictConcurrency on the FlashTeXPadKit target

Package.swift: .enableExperimentalFeature("StrictConcurrency") on FlashTeXPadKit
only (no .unsafeFlags; NearbyClient / FlashTeXProtocol flags not committed).

What was run (iPad Pro 11-inch M5 947A8CC1-07E2-4AA2-9363-FA389B569E8D, iOS 26.5, Xcode 26.6 / Swift 6.3.3):
- control on unmodified d401d2e: Executed 27 tests, with 1 test skipped and 0 failures / ** TEST SUCCEEDED **
- FlashTeXPad build with PadKit flag: ** BUILD SUCCEEDED **; -enable-experimental-feature StrictConcurrency on FlashTeXPadKit.swiftc; 0 warnings in Sources/FlashTeXPadKit/*.swift
- inventory build with temporary sibling flags + SWIFT_STRICT_CONCURRENCY=complete (not in this commit): ** BUILD SUCCEEDED **; 0 PadKit-owned, 21 NearbyClient, 3 FlashTeXProtocol, 13 app-target (report-only)

PadKit sources are already warning-clean under complete checking (Swift 6.3 region isolation no longer diagnoses class mutation after await). Flag stays ON.

Next: classify (a)/(b); annotate CaptureQueue (@unchecked Sendable, lock) and TranscriptLine (Sendable) as (b); no (a) remaining in PadKit after #359 lock. Then unit + TSan gates.

Open questions: none on the flag spelling; experimental still maps to complete on this frontend.

Implementation-Agent: cursor-agent cursor-grok-4.6
Commit-Executor: cursor-agent (this session, git commit)
Lane-Owner: daniel-parent (mac-m5pro-dq222)
Co-authored-by: Cursor <[email protected]>

* wip(#372): Sendable annotations for CaptureQueue, TranscriptLine, PairingStore

(b) checker-only; no runtime behaviour change.
- CaptureQueue: @unchecked Sendable — lock serializes _records/_lastStoreError/_redeliveries
- MacLink.TranscriptLine (and Direction): Sendable (immutable value type)
- PairingStore: Sendable (PairFile and KeychainPairStore already are)

Rebuild with PadKit StrictConcurrency + SWIFT_STRICT_CONCURRENCY=complete: ** BUILD SUCCEEDED **;
still 0 warnings in Sources/FlashTeXPadKit. App PadModel sending-queue/line warnings gone;
remaining app warnings are NearbyClient PairedMac/DiscoveredMac (report-only).

Next: FlashTeXPadTests control-vs-after and -enableThreadSanitizer YES.

Implementation-Agent: cursor-agent cursor-grok-4.6
Commit-Executor: cursor-agent (this session, git commit)
Lane-Owner: daniel-parent (mac-m5pro-dq222)
Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
GoKubar pushed a commit that referenced this pull request Sep 14, 2026
…sample image and drawing reach the Captures inbox, provider none (#355) (#364)

* wip(#355): isolate hosted unit tests and add opt-in real-Mac UI test

Xcode 26.6 / iOS 26.5 full `xcodebuild test` crashed once in
FluidCaptureTests.testSendNowDraftsSendsAndRemembersTheInstruction
(EXC_BAD_ACCESS in PadModel.captures.setter vs CaptureStore.save). Isolated
3/3 and a control unit rerun were 25/25; the race is CaptureQueue.records
mutated off-main after await while a retain-cycled pollOutcome copied the
array into @published. Lock the list, keep poller self weak, and skip the
TEST_HOST PadModel's Keychain/disk/auto-reconnect. Add CaptureFlowRealMacUITests
(skipped unless FLASHTEX_PAD_E2E_MAC=1) that types host/port and pastes the
bootstrap URL.

Ran: unit 25/25 PASS twice after the fix; UI 5 passed + 1 skipped, 0 failures
(iPad Pro 11-inch M5, 947A8CC1-07E2-4AA2-9363-FA389B569E8D).

Next: launch FlashTeXMac with provider none / keychain off, write pairing
info JSON, run the gated UI test, collect evidence.

Implementation-Agent: cursor-agent cursor-grok-4.6
Commit-Executor: cursor-agent (this session, git commit)
Lane-Owner: daniel-parent (mac-m5pro-dq222)
Co-authored-by: Cursor <[email protected]>

* wip(#355): drive real-Mac UI test via TEST_RUNNER_ env and Form scroll

The XCUITest runner is in the simulator, so host env and /tmp JSON paths
do not reach it; inject host/port/bootstrap with TEST_RUNNER_FLASHTEX_PAD_E2E_*.
pair.port lives below the fold in the Mac-link Form and is not in the
accessibility tree until scrolled — first gated run failed there
(Executed 1 test, with 1 failure, 10.962s) after pair.qr.text was found.

Ran: that gated test-without-building against FlashTeXMac pid 52883 /
port 49884 (pairing then expired). Next: relaunch Mac with a fresh 120s
code, rebuild-for-testing, rerun CaptureFlowRealMacUITests.

Implementation-Agent: cursor-agent cursor-grok-4.6
Commit-Executor: cursor-agent (this session, git commit)
Lane-Owner: daniel-parent (mac-m5pro-dq222)
Co-authored-by: Cursor <[email protected]>

* wip(#355): avoid Allow Paste idle so pairing beats the 120s code

Second gated run filled host/port and the bootstrap URL but Pair from
payload ran at t=76s, ~1s after the Mac code expired (08:33:34Z). Cause:
tapping Paste blocked 60s on the system Allow Paste banner
(app event loop idle notification not received). Type the bootstrap
into pair.qr.text, fill port first, and wait for Connected to on Capture.

Ran: Executed 1 test, with 1 failure (0 unexpected) in 98.210s;
pairs.json still empty. Next: rebuild, relaunch Mac, rerun.

Implementation-Agent: cursor-agent cursor-grok-4.6
Commit-Executor: cursor-agent (this session, git commit)
Lane-Owner: daniel-parent (mac-m5pro-dq222)
Co-authored-by: Cursor <[email protected]>

* wip(#355): record simulator real-Mac e2e evidence (provider none)

Gated CaptureFlowRealMacUITests passed against FlashTeXMac: sample +
synthetic drawing both landed in Captures with durable=false /
has_proposal=false. Evidence README + app-only screenshots; omit the
Mac-link frame that showed the pairing URL.

Ran: Executed 1 test, with 0 failures in 36.472s (TEST EXECUTE SUCCEEDED);
skip without env: 1 skipped, 0 failures. Mac pairs.json capture_count=2.

Next: none for this lane's acceptance path unless Commander asks for a PR.

Implementation-Agent: cursor-agent cursor-grok-4.6
Commit-Executor: cursor-agent (this session, git commit)
Lane-Owner: daniel-parent (mac-m5pro-dq222)
Co-authored-by: Cursor <[email protected]>

* apps/ios: drop this branch's copy of the #359 fix now that #372 is on main

Restored CaptureQueue.swift, PadModel.swift and FlashTeXPadApp.swift to
origin/main (#372's reviewed version). What remains is the opt-in real-Mac UI
test, its project/scheme wiring, the Paste accessibility identifier and the
evidence pack.

Claude-Session: https://claude.ai/code/session_012c9XLkHjePPGBuarrmE2mz

---------

Co-authored-by: Cursor <[email protected]>
d-q222 added a commit that referenced this pull request Sep 14, 2026
Fixes GH-NEARBY-PAIRFILE (found by #375's strict-concurrency audit):
PairFile declares @unchecked Sendable but mutated its `pairs` array with no
synchronisation, and read it unlocked from pair(fingerprint:)/
pair(matching:). A real data race, not just a compiler technicality --
confirmed below.

Follows the exact CaptureQueue.records shape from #372: private `_pairs`
backing storage, `private let lock = NSLock()`, a public computed `pairs`
property that reads under the lock, and every mutating method (upsert,
remove) taking the lock once around its whole read-modify-write-and-persist
sequence via a new saveLocked() (caller must hold lock). pair(fingerprint:)
and pair(matching:) now read under the lock too. Public API surface
(method signatures, pairs' type and read-only-ness from outside) is
unchanged -- behavior-neutral for every existing caller.

Also adds Sendable to PairedMac, PairFile.Contents, DiscoveredMac
(NearbyBrowser.swift), and NearbyWire.CaptureReceived -- all plain
immutable value types with already-Sendable fields. NearbyWire.Destination
(referenced by PairedMac.lastDestination) is NOT yet Sendable, which is why
PairedMac: Sendable currently compiles with a Swift-6-mode warning rather
than an error; fixing Destination is out of this slice's scope
(NearbyWire.swift changes were limited to CaptureReceived) and is a natural,
one-word follow-up before any Swift 6 migration.

New testConcurrentUpsertRemoveKeepsStoreConsistent (125 concurrent tasks:
50 upserts, 50 reads, 25 removes on one PairFile instance) asserts no
duplicate fingerprints and disk/memory agreement afterward.

Verification, measured (not inferred), by the reviewer outside the Muse
sandbox:
- BEFORE (unpatched source, same new test applied on top): `swift test
  --sanitize=thread` reports multiple real "ThreadSanitizer: Swift access
  race" warnings in PairFile.remove(fingerprint:), and the process crashes
  with "Fatal error: Index out of range" in ContiguousArrayBuffer -- a real,
  severe race, not a false positive.
- AFTER (this fix): `swift test --filter PairFileTests --sanitize=thread`:
  2 tests, 0 failures, zero TSan reports. Re-run again after rebasing onto
  current main: still clean.
- `swift build` in nearby-client: exit 0 (only the anticipated Destination
  warning, expected and explained above).

Implementation-Agent: muse-spark-1.3-contributor (Muse Code, lane nearby-pairfile-lock, slice 1)
Commit-Executor: daniel-muse-lead (Claude Sonnet)
Reviewed-by: daniel-muse-lead (Claude Sonnet)
Muse-Lane-Head: 2aa90d0e
Co-authored-by: d-q222 <[email protected]>
d-q222 added a commit that referenced this pull request Sep 14, 2026
Fixes GH-NEARBY-PAIRFILE (found by #375's strict-concurrency audit):
PairFile declares @unchecked Sendable but mutated its `pairs` array with no
synchronisation, and read it unlocked from pair(fingerprint:)/
pair(matching:). A real data race, not just a compiler technicality --
confirmed below.

Follows the exact CaptureQueue.records shape from #372: private `_pairs`
backing storage, `private let lock = NSLock()`, a public computed `pairs`
property that reads under the lock, and every mutating method (upsert,
remove) taking the lock once around its whole read-modify-write-and-persist
sequence via a new saveLocked() (caller must hold lock). pair(fingerprint:)
and pair(matching:) now read under the lock too. Public API surface
(method signatures, pairs' type and read-only-ness from outside) is
unchanged -- behavior-neutral for every existing caller.

Also adds Sendable to PairedMac, PairFile.Contents, DiscoveredMac
(NearbyBrowser.swift), and NearbyWire.CaptureReceived -- all plain
immutable value types with already-Sendable fields. NearbyWire.Destination
(referenced by PairedMac.lastDestination) is NOT yet Sendable, which is why
PairedMac: Sendable currently compiles with a Swift-6-mode warning rather
than an error; fixing Destination is out of this slice's scope
(NearbyWire.swift changes were limited to CaptureReceived) and is a natural,
one-word follow-up before any Swift 6 migration.

New testConcurrentUpsertRemoveKeepsStoreConsistent (125 concurrent tasks:
50 upserts, 50 reads, 25 removes on one PairFile instance) asserts no
duplicate fingerprints and disk/memory agreement afterward.

Verification, measured (not inferred), by the reviewer outside the Muse
sandbox:
- BEFORE (unpatched source, same new test applied on top): `swift test
  --sanitize=thread` reports multiple real "ThreadSanitizer: Swift access
  race" warnings in PairFile.remove(fingerprint:), and the process crashes
  with "Fatal error: Index out of range" in ContiguousArrayBuffer -- a real,
  severe race, not a false positive.
- AFTER (this fix): `swift test --filter PairFileTests --sanitize=thread`:
  2 tests, 0 failures, zero TSan reports. Re-run again after rebasing onto
  current main: still clean.
- `swift build` in nearby-client: exit 0 (only the anticipated Destination
  warning, expected and explained above).

Implementation-Agent: muse-spark-1.3-contributor (Muse Code, lane nearby-pairfile-lock, slice 1)
Commit-Executor: daniel-muse-lead (Claude Sonnet)
Reviewed-by: daniel-muse-lead (Claude Sonnet)
Muse-Lane-Head: 2aa90d0e
Co-authored-by: d-q222 <[email protected]>
GoKubar pushed a commit that referenced this pull request Sep 15, 2026
…#410)

Fixes GH-NEARBY-PAIRFILE (found by #375's strict-concurrency audit):
PairFile declares @unchecked Sendable but mutated its `pairs` array with no
synchronisation, and read it unlocked from pair(fingerprint:)/
pair(matching:). A real data race, not just a compiler technicality --
confirmed below.

Follows the exact CaptureQueue.records shape from #372: private `_pairs`
backing storage, `private let lock = NSLock()`, a public computed `pairs`
property that reads under the lock, and every mutating method (upsert,
remove) taking the lock once around its whole read-modify-write-and-persist
sequence via a new saveLocked() (caller must hold lock). pair(fingerprint:)
and pair(matching:) now read under the lock too. Public API surface
(method signatures, pairs' type and read-only-ness from outside) is
unchanged -- behavior-neutral for every existing caller.

Also adds Sendable to PairedMac, PairFile.Contents, DiscoveredMac
(NearbyBrowser.swift), and NearbyWire.CaptureReceived -- all plain
immutable value types with already-Sendable fields. NearbyWire.Destination
(referenced by PairedMac.lastDestination) is NOT yet Sendable, which is why
PairedMac: Sendable currently compiles with a Swift-6-mode warning rather
than an error; fixing Destination is out of this slice's scope
(NearbyWire.swift changes were limited to CaptureReceived) and is a natural,
one-word follow-up before any Swift 6 migration.

New testConcurrentUpsertRemoveKeepsStoreConsistent (125 concurrent tasks:
50 upserts, 50 reads, 25 removes on one PairFile instance) asserts no
duplicate fingerprints and disk/memory agreement afterward.

Verification, measured (not inferred), by the reviewer outside the Muse
sandbox:
- BEFORE (unpatched source, same new test applied on top): `swift test
  --sanitize=thread` reports multiple real "ThreadSanitizer: Swift access
  race" warnings in PairFile.remove(fingerprint:), and the process crashes
  with "Fatal error: Index out of range" in ContiguousArrayBuffer -- a real,
  severe race, not a false positive.
- AFTER (this fix): `swift test --filter PairFileTests --sanitize=thread`:
  2 tests, 0 failures, zero TSan reports. Re-run again after rebasing onto
  current main: still clean.
- `swift build` in nearby-client: exit 0 (only the anticipated Destination
  warning, expected and explained above).

Implementation-Agent: muse-spark-1.3-contributor (Muse Code, lane nearby-pairfile-lock, slice 1)
Commit-Executor: daniel-muse-lead (Claude Sonnet)
Reviewed-by: daniel-muse-lead (Claude Sonnet)
Muse-Lane-Head: 2aa90d0e

Co-authored-by: muse-spark-1.3-contributor <[email protected]>
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.

FlashTeXPad crashes (EXC_BAD_ACCESS/SIGSEGV) in PadModel.pollOutcome → @Published captures setter — data race on CaptureQueue.records

2 participants