Repository navigation
fix: make SerializationContext immutable to stop concurrent parses corrupting each other - #361
Merged
Merged
Conversation
`serialize()` declared `context=SerializationContext()` as a default
argument. Python evaluates a default once, at import, so every rule in
the process shared a single mutable context -- and expressions.py,
functions.py and indexing.py mutate it in place through
`context.modify(inside_dollar_string=True)`.
Nothing supplies a context at any public entry point: `api.serialize`
calls `tree.serialize()`, and `NodeView.to_dict` calls
`self._node.serialize(options=...)`. Both landed on that shared object.
So a thread serializing a function call set `inside_dollar_string` for
every other thread, and any tuple or object those threads were
serializing came back as its inline HCL source -- `[1, 2, 3]` as the
string `'[1, 2, 3]'`, `{a = 1}` as `'{a = 1}'`. No exception, just a
different type, which a caller doing schema validation downstream then
reports as a type error in the user's configuration.
The structural rules in base.py now build a fresh context when called
without one, and thread the context they were given into every child
call -- eight sites that were dropping it and re-defaulting to the
shared object. The rules below them already threaded it.
The regression test interleaves 800 parses across 8 threads. Before this
change, 400 of the 400 plain parses came back corrupted; the effect needs
roughly 400 interleaved parses to show at all, which is why the count is
what it is rather than a token handful.
Other `serialize()` signatures keep the mutable default. They are no
longer reachable with it -- every caller passes a context now -- but the
defaults remain a trap for a future call site and would be worth removing
separately.
Threading a context through the four structural rules fixed every parse the public API performs, because all of them enter at `StartRule`. It left the same declaration standing on 46 other methods: a default argument is evaluated once at import, `SerializationContext.modify` mutates in place, and so a caller serializing a rule directly -- not through `loads` -- still shared one object with every other thread doing the same. Nothing reachable from `loads` used those defaults, so this changes no value the library returns; it removes a trap rather than a live defect. Each of them now takes `context=None` and builds its own when it is not given one. The nine methods that never read the context keep the parameter but skip the construction. The new test walks the shipped rule modules and asserts every `context` parameter defaults to None, so a rule added later is covered without anyone remembering, and a second test asserts the walk actually found methods rather than passing over an empty list.
The existing regression test submits 800 parses and trusts that their critical sections overlap. That is how the defect was found and it is worth keeping, but it can only ever be evidence: on a single-core or differently-scheduled worker the same run passes over unfixed code because the two halves never meet. These force the overlap. One thread holds a mutated context open on a barrier while another serializes, and a second test asserts two serializations are handed different context objects at all. Both fail against the unfixed structural rules rather than depending on the scheduler to reveal it. Also pins why `options` may keep the shared default the context could not: nothing in the package assigns to it. If something ever does, the new test fails rather than the default quietly becoming a second cross-thread channel.
`options=SerializationOptions()` is the same construct as the context was, in the same position: one object evaluated at import and handed to every caller that omits the argument. It was not a live defect, because nothing in the package assigns to a `SerializationOptions` -- but that is a property of today's code, not of the design, and it is reachable by any subclass or hook a consumer writes. Keeping it meant defending a distinction that rests on nobody ever writing to it. The earlier tests here asserted exactly that distinction. They are replaced by the guard the context already has: a walk over the shipped rule modules asserting every `options` parameter defaults to None. It immediately earned it, catching one the change had missed -- `NewLineOrCommentRule.to_list` declares its default with an annotation, which the mechanical pass did not match.
The walk backing both guards missed three things. It used `iter_modules`, so a future subpackage would have been invisible; it looked at `hcl2.rules` alone, though the pattern is package-wide; and it tested `inspect.isfunction` against what `vars(cls)` returns, which is the descriptor for a staticmethod or classmethod rather than a function. That last one was not hypothetical: `StringRule._serialize_part_as_value` takes a context and was never inspected. It walks `hcl2` recursively and unwraps `__func__` now, taking the count from 50 to 51 and 59. The floors were `> 30` against real counts of 51 and 59, so a 40% loss of coverage would have passed. They now sit just under the true numbers. Defaulting to None was also only half the invariant: a rule that takes `None` and dereferences it without constructing one passes every guard and then raises `AttributeError` for exactly the direct caller this protects. Both parameters are annotated `Optional[...]`, which makes that a mypy error -- confirmed by deleting a guard and watching three `union-attr` errors appear -- and a test asserts the annotation is there, for the parameters that default to None rather than the required ones. Finally, thirteen test doubles still declared the mutable defaults. They are the nearest template anyone copies, so they now match.
Removing the shared default fixed the contexts the package builds for itself. A consumer that builds one and hands it to concurrent calls still had several writers: modify() was a context manager that set fields on whatever context it was given and restored them on exit, so two threads sharing one object raced on it and produced the same silent corruption -- a tuple or object serialized as its inline HCL source -- with nothing to warn them. A traversal now descends by building a child with replace(), the dataclass is frozen, and modify() is gone. The post-block checks are unchanged in meaning: they already read the outer value, which is now simply the context that was never written to. Racing two threads does not demonstrate the old defect -- modify() restored the field within a single call, so a repetition test came back green against the unfixed code. The regression test reads the caller's own context from inside the scope that used to mutate it, and sees True there before this change.
…ontext-shared-between-threads
With SerializationContext frozen, the shared `context=SerializationContext()` default can no longer be mutated, so the None defaults, per-method guards and signature-walking tests are unnecessary. Restore main's serialize() signatures, keep the base.py context threading and the modify -> replace rebinds, and trim the thread-safety tests to the regression plus a deterministic check that the shared default is never written. Co-Authored-By: Claude Opus 5.5 <[email protected]>
SerializationOptions stays a mutable shared default because it is public API; assert no rule writes to it. Move the caller-supplied context threading note under Changed, since a non-default context passed to StartRule.serialize() now affects output. Co-Authored-By: Claude Opus 5.5 <[email protected]>
kkozik-amplify
marked this pull request as ready for review
November 9, 2026 12:07
mluhovyi
approved these changes
Nov 9, 2026
rddimon
approved these changes
Nov 9, 2026
This was referenced Nov 9, 2026
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.
Caused by
loads()calls silently corrupt each other's values #327SerializationContext.modifymutates in place, so a caller-supplied context cannot be shared across threads #344Builds on #334 by @livingstaccato. Their commits are kept as they are, with one refactor commit on top.
Why
All
serialize()methods shared one defaultSerializationContext, and the rules mutated it in place throughcontext.modify(...). Under concurrentloads()calls, one thread'sinside_dollar_stringleaked into another's, so tuples and objects came back as inline HCL strings ('[1, 2, 3]') with no error (#327). A context a caller built and shared across threads had the same problem (#344).#334 fixes this two ways: it freezes the context, and it replaces every
context=/options=default withNoneplus a guard (~50 signatures, 25 files). Once the context is frozen, though, a shared default instance can no longer be mutated by anyone. The None defaults add no safety, so the top commit here removes them.What changes against
mainSerializationContextis@dataclass(frozen=True)andmodify()is removed. Eachwith context.modify(...)becomesinner = context.replace(...), passed to the children.StartRule,BodyRule,BlockRuleandAttributeRulenow pass the context they receive down to their children (8 call sites used to drop it). This is a small behaviour change: a non-default context passed toStartRule.serialize()now affects the output, where before it was ignored. It is noted under Changed in the CHANGELOG.serialize()signatures are unchanged frommain.optionstoo.SerializationOptionsstays a mutable shared default: it is exported and used indocs/, so freezing it would break the public API. Nothing in the library writes to it, and a test asserts the default still equalsSerializationOptions()after serializing.test/unit/test_thread_safety.py:SerializationOptions.test_utils.py: themodify()tests are replaced withreplace()and frozen-assignment tests.Breaking (listed under Changed in the CHANGELOG):
SerializationContext.modify()is gone, assigning a field now raisesFrozenInstanceError, and subclasses must be declared@dataclass(frozen=True).SerializationContextisn't exported fromhcl2or mentioned indocs/, so the documented API is unaffected.Test plan
main.mainfor every golden.tfundertest/integration/, across 1767SerializationOptionscombinations.loads()calls silently corrupt each other's values #327 gives 0 of 1000 corrupted (93 of 1000 onmain);SerializationContext.modifymutates in place, so a caller-supplied context cannot be shared across threads #344 gives 0 of 3000 (2769 of 3000 onmain).main, the new test file fails both the concurrency regression and the default-context test.🤖 Generated with Claude Code