Skip to content

fix: make SerializationContext immutable to stop concurrent parses corrupting each other - #361

Merged
kkozik-amplify merged 10 commits into
mainfrom
review/pr334-frozen-default
Nov 9, 2026
Merged

kkozik-amplify merged 10 commits into
mainfrom
review/pr334-frozen-default

Conversation

@kkozik-amplify

@kkozik-amplify kkozik-amplify commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Caused by

Builds on #334 by @livingstaccato. Their commits are kept as they are, with one refactor commit on top.

Why

All serialize() methods shared one default SerializationContext, and the rules mutated it in place through context.modify(...). Under concurrent loads() calls, one thread's inside_dollar_string leaked 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 with None plus 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 main

  • SerializationContext is @dataclass(frozen=True) and modify() is removed. Each with context.modify(...) becomes inner = context.replace(...), passed to the children.
  • StartRule, BodyRule, BlockRule and AttributeRule now 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 to StartRule.serialize() now affects the output, where before it was ignored. It is noted under Changed in the CHANGELOG.
  • serialize() signatures are unchanged from main.
  • The None defaults are dropped for options too. SerializationOptions stays a mutable shared default: it is exported and used in docs/, so freezing it would break the public API. Nothing in the library writes to it, and a test asserts the default still equals SerializationOptions() after serializing.
  • New test/unit/test_thread_safety.py:
    • A check that no rule writes to the shared default SerializationOptions.
    • An 800-parse concurrent regression test.
    • A deterministic check that the shared default context is never written and can't be assigned to.
    • Tests that a context the caller passes in stays unchanged, including when it is shared across threads.
  • test_utils.py: the modify() tests are replaced with replace() and frozen-assignment tests.

Breaking (listed under Changed in the CHANGELOG): SerializationContext.modify() is gone, assigning a field now raises FrozenInstanceError, and subclasses must be declared @dataclass(frozen=True). SerializationContext isn't exported from hcl2 or mentioned in docs/, so the documented API is unaffected.

Test plan

🤖 Generated with Claude Code

livingstaccato and others added 10 commits September 1, 2026 14:51
`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.
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
kkozik-amplify marked this pull request as ready for review November 9, 2026 12:07
@kkozik-amplify
kkozik-amplify requested a review from a team as a code owner November 9, 2026 12:07
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.

4 participants