Fix race condition in LanguageModelSession when streaming responses with NSLock#130
Fix race condition in LanguageModelSession when streaming responses with NSLock#130
LanguageModelSession when streaming responses with NSLock#130Conversation
- Fix race condition when streaming responses.
There was a problem hiding this comment.
Pull request overview
This PR fixes race conditions in LanguageModelSession by replacing the previous combination of MainActor dispatching and an actor-based RespondingState with a unified NSLock-based synchronization approach. The implementation introduces a private State struct that encapsulates both the transcript and the responding count, protected by a single NSLock. Properties are exposed as computed properties that properly integrate with Swift's Observation framework using access(keyPath:) for reads and withMutation(keyPath:) for writes.
Changes:
- Replaced
MainActordispatch and actor-based synchronization withNSLockfor protecting mutable state - Converted
isRespondingandtranscriptfrom stored to computed properties backed by a lockedStatestruct - Added comprehensive observation tests to verify that property changes correctly trigger observation notifications
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| Sources/AnyLanguageModel/LanguageModelSession.swift | Implemented NSLock-based synchronization, converted properties to computed properties with Observation framework integration, replaced RespondingState actor with State struct |
| Tests/AnyLanguageModelTests/ObservationTests.swift | Added comprehensive tests for observation behavior including transcript and isResponding tracking, with ThreadSafeValue helper for thread-safe test assertions |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
Closing in favor of #126. See #126 (comment) |
Alternative to / extension of #126, but using
NSLockinstead of creating custom lock type (01be769).