Skip to content

HermitCrab: cut FeatureStruct clone and VariableBindings allocation - #633

Open
johnml1135 wants to merge 7 commits into
masterfrom
alloc-medium
Open

johnml1135 wants to merge 7 commits into
masterfrom
alloc-medium

Conversation

@johnml1135

@johnml1135 johnml1135 commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #632

Start here: FeatureStruct.Clone and the per-call VariableBindings clone are two of the largest allocation sources in HermitCrab parsing. This PR removes most of that traffic without changing semantics: Clone takes a map-free tree path for plain structures, and Unify/Subsumes/IsUnifiable snapshot the bindings lazily, only if something is written, and roll back on failure. Allocation falls 11-18% and paired wall time 4-19%, with identical parse output. Public API is unchanged.

What changed

  • FeatureStruct.Clone first tries a recursive tree clone with no copies dictionary. A thread-static 32-slot array records visited values. If any value is reachable twice (reentrance, Forward chains, cycles) or the structure has more than 32 nodes, it falls back to the existing map-based copy, so reentrant semantics are unchanged.
  • VariableBindings gains internal BeginTransaction/EndTransaction. The three operations write in place; the bindings shallow-snapshot their dictionary on the first write and restore it on failure. Binding values are only read, never mutated, so the shallow snapshot is equivalent.
  • Caveat: bindings are written in place during a call, so one VariableBindings must not be shared across threads. HermitCrab uses per-word bindings. Transactions do not nest; a nested call on the same thread does not own the rollback.

Behaviour change: a VariableBindings used by two threads at once now throws InvalidOperationException ("VariableBindings is not safe for concurrent use") instead of risking silent corruption. No caller shares one.

A/B (interleaved, alternating order, n=15 per workload, new process per sample, 1 warm + 2 timed passes, load average 8-13 on 20 cores)

workload alloc MB/pass base -> patch median ms base -> patch paired wall ratio (patch/base) patch faster GC pause ms process CPU s base -> patch paired CPU ratio CPU faster
Amharic 40 2747 -> 2251 (-18%) 2238 -> 1950 (-12.8%) 0.873 15/15 514 -> 412 10.96 -> 9.61 0.907 15/15
Aweti 15 492 -> 439 (-11%) 665 -> 638 (-4.0%) 0.930 12/15 90 -> 88 6.93 -> 6.82 0.965 12/15
Mbugwe 12 1419 -> 1216 (-14%) 1616 -> 1304 (-19.3%) 0.851 13/15 264 -> 220 11.27 -> 9.99 0.937 11/15

perf was unavailable, so CPU is getrusage child time (user+sys). It agrees in sign with wall everywhere.

Verification

  • HermitCrab.Tests: 181 passed, 0 failed. SIL.Machine.Tests FeatureModel: 20 passed, 0 failed (Release, net10.0). Earlier filtered run over FeatureModel|FiniteState|Matching|Rules: 30 passed.
  • New FeatureStructCloneTests (13 tests): Clone() against the map-based copy for a plain tree, a reentrant structure, a Forward chain, a cycle, nesting at 10/16/17/40 levels, and a large reentrant structure, checking equality, sharing and reentrance. Failed Unify, IsUnifiable and Subsumes that wrote mid-operation leave the bindings unchanged. The rollback tests fail when the rollback is disabled.
  • Parse output byte-for-byte identical to base (all parses, sorted, with shapes): Amharic 60 words, Aweti 30, Mbugwe 30.

Risks: measured on a loaded machine (wall noise is real; Amharic and Mbugwe are solid at 15/15 and 13/15, Aweti is a mild win). Parse equality checked on 60/30/30 words, not the full lists.

Next: re-measure with perf on a quiet machine before deciding on the larger copy-on-write rewrite; cheaper candidates are the remaining _definite dictionary per FeatureStruct and SymbolicFeatureValue flag clones.

🤖 Generated with Claude Code


This change is Reviewable

@claude

This comment has been minimized.

@claude

This comment has been minimized.

@codecov-commenter

codecov-commenter commented Nov 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.47619% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.65%. Comparing base (e7422c1) to head (e2912b1).

Files with missing lines Patch % Lines
src/SIL.Machine/FeatureModel/VariableBindings.cs 81.81% 6 Missing ⚠️
src/SIL.Machine/FeatureModel/FeatureStruct.cs 94.44% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #633      +/-   ##
==========================================
+ Coverage   75.53%   75.65%   +0.12%     
==========================================
  Files         455      455              
  Lines       38933    39022      +89     
  Branches     5428     5441      +13     
==========================================
+ Hits        29407    29523     +116     
+ Misses       8376     8355      -21     
+ Partials     1150     1144       -6     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@claude

This comment has been minimized.

@claude

This comment has been minimized.

@claude

This comment has been minimized.

johnml1135 and others added 7 commits November 20, 2026 09:25
…Bindings roll back lazily instead of cloning per call

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…al and restore tests plus comments on the scratch array and missing nested transactions

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… tree path

A node with more values than the remaining scratch slots now goes straight to the
map copy, so a wide structure (over 31 values) costs what master's Clone did
instead of about 1.5-1.8x. The check is one comparison per node; clones are
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nstead of corrupting a transaction

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ow on VariableBindings

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Verdict: approve. The rebase onto master left the PR's code as it was, and e2912b1 rewords the VariableBindings remark to match what the code detects. Nothing is open.

Most important: F6, src/SIL.Machine/FeatureModel/VariableBindings.cs:10, was addressed in e2912b1. The remark now limits the InvalidOperationException to overlapping Unify/IsUnifiable/Subsumes calls and says direct dictionary writes are not detected.

Counts: 0 Critical, 0 Important, 0 Low open. No new findings.

What I ran: The compare from e6852c4 to e2912b1 reports diverged because of the rebase, so I re-read the whole PR diff. TryCloneTree still dereferences values exactly as the map copy constructor does, and every write path still calls BeforeWrite. dotnet test tests/SIL.Machine.Tests --filter FullyQualifiedName~SIL.Machine.FeatureModel passed 28 of 28. gh pr checks 633: Build on ubuntu-22.04 passed, Build on windows-latest and claude-review are pending, and the advisory Comment hygiene checks passed.

Not verified: I was not permitted to run ./local_check.sh --agent-strict here. The new text is a /// remark, which is exempt from the 200-character budget. The Windows build had not finished.

API/parity: Public VariableBindings throws InvalidOperationException when two threads overlap Unify/IsUnifiable/Subsumes calls on it, and the remark now documents this. No signature, target framework, package, or sillsdev/machine.py parity contract changed.

F1 addressed · F2 addressed · F3 addressed · F4 withdrawn · F5 withdrawn, unverified · F6 addressed

Reviewed at e2912b1

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants