Skip to content

fix: wipe FixedSizeDictionary's slots when its version wraps - #704

Open
nadrummond wants to merge 1 commit into
Handlebars-Net:masterfrom
nadrummond:fix/fixed-size-dictionary-version-wrap
Open

nadrummond wants to merge 1 commit into
Handlebars-Net:masterfrom
nadrummond:fix/fixed-size-dictionary-version-wrap

Conversation

@nadrummond

@nadrummond nadrummond commented Nov 26, 2026 •

Copy link
Copy Markdown

Fixes #705.

FixedSizeDictionary clears cheaply: Reset() and OptionalClear() bump a byte version and leave
old entries in place, counting them as absent while their version differs. When the version wraps from
255 back to 1, an entry written 255 versions earlier matches the current version again. Pooled
BindingContexts go through OptionalClear() on every return (BindingContext.Pool.cs:61-62), so a
block param bound by one render comes back in a later, unrelated render, from another IHandlebars
instance, and shadows that render's own model. The issue has a repro.

Reset() and Clear() now move to the next version through NextVersion(), which wipes _entries
and _indexes when the version wraps, before reusing version 1, so no entry can outlive a full cycle
of versions. The cost is one clear of both arrays per 255 resets (112 slots for a binding context's
dictionaries); the per-return path is otherwise unchanged. EntryIndex values kept outside the
dictionary (BindingContext.WellKnownVariables, indexes into ContextDataObject) can still carry a
version from an earlier cycle; after the wipe such an index points at an empty slot or at an entry
written since the wipe, never at one left from before the wrap.

Tests

  • FixedSizeDictionaryTests.EntryFromAnEarlierUseStaysGoneOnceTheVersionWraps, a theory over Reset
    and OptionalClear: add a key, reset 255 times, add another key, and the first key must stay absent.
    Deterministic.
  • BindingContextPoolTests.BlockParamBoundInOneRenderIsNotSeenByLaterRenders, in a non-parallel
    collection: 20 renders bind x, then a second template renders up to 100,000 times and must never
    print it. It reads x in two nested frames, so the pool's rotation can't hand the context holding
    the old binding only to the root frame, where nothing is read. It depends on the state other tests
    leave the shared pool in, so the dictionary theory is the deterministic check.

On master (11a2daa), with only the tests added, the dictionary theory fails on every run, and the
pool test fails both alone (5 of 5) and in the full suite (15 of 15). With the fix, the full suite
passes on net10.0: 2,352 tests (2,349 on master, plus the three new ones). The issue's console repro
prints the first render's value on renders 509, 1019, 1529, … before the fix, and nothing in 100,000
renders after it.

Reset() and OptionalClear() bump a byte version and leave old entries in
place, counting them as absent while their version differs. Once the
version wraps from 255 back to 1, an entry written 255 versions earlier
matches again, so a pooled BindingContext could hand a block param bound
by one render to a later, unrelated render. When the version wraps, the
entries and indexes are now wiped before version 1 is reused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@rexm

rexm commented Nov 27, 2026

Copy link
Copy Markdown
Member

/harness adopt

See if you can reconcile fixing the bug with not introducing the performance regression.

@nadrummond

Copy link
Copy Markdown
Author

Good catch on the benchmark alert, it was worth digging into. It turns out the slowdown comes from the machines the benchmarks ran on rather than from this change: run on the same machine, #704 is as fast as master.

The benchmark job compares each PR with the most recent master run. That master run (11a2daa) happened to land on the fastest machine type in recent runs, and #704's run happened to land on the slowest. The same master code runs about twice as fast on one as on the other, which on its own is enough to trip the 2× alert. That would also explain why benchmarks this PR doesn't touch, such as template compilation, were flagged as well, and why #708 received the same 18 alerts on the same machine type, while #706, which carried the identical change, received none on a faster one.

To rule the hardware out, I ran master, #704, and a variant that moves the wipe into a separate non-inlined method on a single runner, one after another. Across all 32 benchmarks, #704 comes out at 1.000× master, and master's own two runs differ from each other by 0.8%, so I couldn't find any difference between them. The non-inlined variant comes out at 1.001×, so it doesn't seem to gain anything, and I've left #704 as it is. If you'd like it measured another way, or you see something I've missed, I'm happy to look again.

Technical detail

Why the change shouldn't cost anything. On the hot path, Reset() and Clear() do what they did before: increment the byte version and compare it with zero. The only new work is the wipe, Array.Clear over _entries and _indexes (112 slots each for a binding context's dictionaries), and it runs once every 255 resets of a dictionary, which means once per 255 returns of a pooled BindingContext. Nothing new is allocated: BenchmarkDotNet's allocated bytes match across variants, apart from CompileMany's usual run-to-run variation and a 2–4 byte rounding difference on LargeArray.

Which machine each run landed on. Execution.CallHelperWithoutParameters on recent ci.yml runs, with the CPU BenchmarkDotNet reports:

Run Runner CPU Mean
master 11a2daa (the alert's baseline) AMD EPYC 9V45 60 ns
master 1cc7339 Intel Xeon 6973P-C 67 ns
master 2c78546, 39e91b2, f6e613b, dcbe4af AMD EPYC 9V74 86–89 ns
master 74bf99f, a1d79e9, 47960fa, db664c0, 92a86d0 AMD EPYC 7763 109–113 ns
#704 AMD EPYC 7763 113 ns
#706 (same FixedSizeDictionary.cs blob as #704) Intel Xeon Platinum 8573C 93 ns

Against the median of those five master runs on the EPYC 7763, #704's CI run has a geometric mean of 1.015× across all 32 benchmarks. The action compares against the latest gh-pages entry whatever runner produced it, so for as long as that entry comes from a 9V45, any PR that lands on a 7763 is likely to trip the threshold the same way.

Same-runner A/B. One job on an AMD EPYC 9V74 built master (11a2daa), #704 (ddb1260) and #704 with the wrap moved into a [MethodImpl(MethodImplOptions.NoInlining)] method. It then ran the full suite with the same Program.cs job and --filter '*' as ci.yml, six times in the order master, #704, variant, variant, #704, master. Averaging each variant's two passes cancels any drift over the hour, and master's pass 6 against its pass 1 shows the noise floor. Workflow and results:
https://github.com/nadrummond/Handlebars.Net/actions/runs/46386568299

All 32 benchmarks
Benchmark master mean (ns) #704 / master no-inline / master master pass 6 / pass 1
Compilation.Template 4,254,947.4 0.997 0.999 0.996
Execution.CallHelperWithoutParameters 86.3 1.014 1.056 0.993
EndToEnd.Default(N: 5, DataType: "dictionary") 46,329.8 1.015 1.013 0.994
EndToEnd.Default(N: 5, DataType: "object") 46,296.3 0.995 1.002 1.001
RenderNested.Render(RowsPerSection: 5, DataType: "dictionary") 6,128.2 0.991 1.003 0.971
RenderNested.Render(RowsPerSection: 5, DataType: "object") 6,803.2 0.966 0.935 1.046
RenderNested.Render(RowsPerSection: 20, DataType: "dictionary") 18,375.4 0.987 1.010 1.007
RenderNested.Render(RowsPerSection: 20, DataType: "object") 18,995.0 0.973 0.962 1.057
RenderList.Render(N: 10, DataType: "dictionary") 2,483.0 0.988 0.998 1.006
RenderList.Render(N: 10, DataType: "object") 2,774.6 0.965 0.955 1.005
RenderList.Render(N: 100, DataType: "dictionary") 21,671.7 1.022 1.003 1.050
RenderList.Render(N: 100, DataType: "object") 23,883.7 1.001 1.004 1.030
RenderList.Render(N: 1000, DataType: "dictionary") 225,950.4 1.003 1.009 1.048
RenderList.Render(N: 1000, DataType: "object") 227,845.2 0.998 1.011 0.954
CompileMany.Compile(N: 10) 16,478,184.0 0.965 0.992 1.016
CompileMany.Compile(N: 100) 180,896,111.7 0.988 1.001 1.015
LargeArray.Default(N: 20000) 794,271.4 1.012 1.005 0.995
LargeArray.Default(N: 40000) 1,630,583.7 1.045 0.982 1.045
LargeArray.Default(N: 80000) 3,268,326.9 0.978 0.966 1.019
RenderToString.Render(Content: "clean") 13,005.2 1.024 1.051 0.994
RenderToString.Render(Content: "html") 20,080.9 0.987 0.979 1.008
RenderSimple.Render(DataType: "dictionary") 753.0 0.969 0.969 1.048
RenderSimple.Render(DataType: "expando") 643.4 1.009 1.003 0.995
RenderSimple.Render(DataType: "object") 785.1 1.016 1.027 0.988
Execution.CallHelperWithOneParameter 90.8 1.011 1.001 0.983
Execution.CallHelperWithTwoParameter 90.2 1.020 1.013 0.962
Execution.LateCallHelperWithoutParameters 86.5 1.015 1.017 0.987
Execution.LateCallHelperWithOneParameter 89.6 1.022 1.005 0.984
Execution.LateCallHelperWithTwoParameter 89.6 1.064 1.021 0.983
Execution.CallBlockHelperWithoutParameters 91.0 1.003 1.087 0.978
Execution.CallBlockHelperWithOneParameter 93.9 1.014 1.008 1.010
Execution.CallBlockHelperWithTwoParameter 99.7 0.962 0.950 1.093

This branch has not been deployed

No deployments
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.

A render can print a block param bound by an earlier, unrelated render (pooled context reuse)

2 participants