Repository navigation
Make tokenization thread-safe when a grammar is shared by several threads - #133
Merged
Merged
Conversation
When several threads tokenize with a grammar that is not compiled yet, all of them compile it at the same time and some get null results. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The grammar is compiled lazily on the first tokenization, and its rules cache and mutate their compiled patterns (RegExpSourceList.SetSource for back-referenced end patterns) while tokenizing. When several threads used the same grammar, they compiled it concurrently, got null results or hit 'Collection was modified' exceptions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
🟢 Approval recommended
The locking scope covers both tokenization paths, and the regression test exercises the reported race.
0 open findings
What changed in this PR
Serializes tokenization per grammar instance to prevent races during lazy compilation and mutable rule-cache access.
Changes:
- Adds a private tokenization lock around both tokenization APIs.
- Adds a concurrent first-tokenization regression test.
| File | Description |
|---|---|
src/TextMateSharp/Internal/Grammars/Grammar.cs |
Serializes tokenization through TokenizeCore. |
src/TextMateSharp.Tests/Internal/Grammars/GrammarTests.cs |
Verifies concurrent tokenization produces consistent results without errors. |
🧠 Review effort: Balanced
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Related to #131 (follow-up to #132).
Problem
Grammaris not thread-safe, but the sameIGrammarinstance is often used from several threads: for example, several AvaloniaEdit editors with the same language, or the old and newTMModeltokenizer threads when the editor document is replaced (the scenario in #131).Tokenizecompiles the grammar on first use (if (_rootId == null) GenerateRootId()). Two threads can compile at the same time, both registering rules into a plainDictionaryand callingSetIdon the shared raw rules. A thread can then get a root id whose rule is not registered yet, andTokenizeLinereturnsnull.RegExpSourceList/CompiledRulecaches lazily, andBeginEndRule/BeginWhileRulecallSetSourceon the shared list on every scan with a back-referenced end pattern. Concurrent use throwsInvalidOperationException: Collection was modified.So a lock around
GenerateRootIdalone is not enough: with only that lock, the new test still fails with the second error.Fix
Serialize
Grammar.Tokenizeper grammar instance with a private lock. The uncontended cost is negligible compared to tokenizing a line. The grammar never calls back into the caller while holding the lock (TMModelcalls the tokenizer outside its own lock), so this does not introduce lock-ordering issues.IsCompilingis kept for API compatibility;TMModelstill uses it (with the polling fix from #132).Tests
Concurrent_First_Tokenization_Should_Compile_Grammar_Once_And_Generate_Same_Tokens: 8 threads behind aBarriertokenize the same line with a fresh C# grammar, 20 iterations, comparing against single-threaded tokens. It fails on master on the first iteration (nullresults).🤖 Generated with Claude Code