Skip to content

Fix race condition in LanguageModelSession when streaming responses with NSLock#130

Closed
mattt wants to merge 4 commits intomainfrom
mattt/fix-race-condition-with-nslock
Closed

Fix race condition in LanguageModelSession when streaming responses with NSLock#130
mattt wants to merge 4 commits intomainfrom
mattt/fix-race-condition-with-nslock

Conversation

@mattt
Copy link
Collaborator

@mattt mattt commented Feb 17, 2026

Alternative to / extension of #126, but using NSLock instead of creating custom lock type (01be769).

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

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 MainActor dispatch and actor-based synchronization with NSLock for protecting mutable state
  • Converted isResponding and transcript from stored to computed properties backed by a locked State struct
  • 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.

@mattt
Copy link
Collaborator Author

mattt commented Feb 17, 2026

Closing in favor of #126. See #126 (comment)

@mattt mattt closed this Feb 17, 2026
@mattt mattt deleted the mattt/fix-race-condition-with-nslock branch March 24, 2026 11:57
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