Skip to content

Match each affix rule once per shape in HermitCrab analysis - #654

Draft
johnml1135 wants to merge 1 commit into
masterfrom
hc-shape-table-653
Draft

johnml1135 wants to merge 1 commit into
masterfrom
hc-shape-table-653

Conversation

@johnml1135

@johnml1135 johnml1135 commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Quick summary

HermitCrab analysis now matches each affix or realizational rule allomorph once per shape in a parse, instead of once per path that reaches the shape. Results, their order and every trace event are unchanged; each path still runs its own gates and builds its own output words. Compounding rules and the public API are untouched.

Ports PanGloss PR #488 (sillsdev/PanGloss) to C#. Spec: #653 (comment). Refs #653 (not closing it).

Where to look

  • MorphologicalRules/ShapeMatchTable.cs -- the table, keyed by (grammar rule, allomorph index, frozen Shape by value). A row is the output shapes after RemoveDuplicates; an empty row is "no match".
  • AnalysisAffixProcessRule.Apply and AnalysisRealizationalAffixProcessRule.Apply -- only the _rules[i].Apply(input).RemoveDuplicates() call changed. Selector, unapplication count, _outputFS, edge prefilter, Restrict/Unify, template state, MorphologicalRuleUnapplied and trace calls run before and after it exactly as before.
  • Stored shapes are frozen and shared; Word.CloneWithShape builds each hit's word from the input and the stored shape. A later clone still copies the shape, so nothing mutates a stored one (StoredShapesAreFrozenAndNotMutatedByTheWordsBuiltFromThem).
  • Slot rules go through the same Apply, so every slot gate stays outside the row (TemplateSlotsWithRequiredAndExcludedFeatures_AreUnchanged). AnalysisCompoundingRule never reads the table (CompoundingRules_AreNotReadFromTheTable).
  • The table lives on the input Word and is copied by Clone, so it is per ParseWord, dropped with it, and safe under maxDegreeOfParallelism above 1 (ConcurrentDictionary; shapes are frozen).

Deliberately not included

  • No public API. Morpher.ShapeMatchTableEnabled (default on) and ShapeMatched are internal, for tests.
  • No memory cap: rows are at most distinct shapes x rule allomorphs per word, and go with the parse. PanGloss charges a word budget; Machine has none to charge.
  • No change to the conformance runner or gates (Run the FieldWorks parser conformance suite against HermitCrab in CI #615).

Validation

  • ./local_check.sh --agent-strict -- PASSED (csharpier, Release build, all tests, comment hygiene clean).
  • dotnet test tests/SIL.Machine.Morphology.HermitCrab.Tests -- 275 passed, 0 failed (10 new).
  • Conformance replay, fieldworks-parser-conformance main at 1fc36fe (has all 8 convergent-*): 268 fixtures (252 conformance + 16 stress), 17,729 words, each run with and without tracing, hc built from master c73ca66 versus this branch, both with maxDegreeOfParallelism: 1. 264 fixtures byte-identical (trace text included). simultaneous-epenthesis-cascade is a pinned crash with identical output except the source path in the stack trace. truncate-morphotactic and truncate-morphotactic-identity give different output from run to run on master itself (7 and 10 distinct outputs in 12 runs); over 40 runs per branch every per-word parse set from this branch also appears on master. -copy-u and -subsumption varied the same way earlier but agreed here. All 8 convergent-* fixtures are identical.

Rule-allomorph matches per parse (probe grammars, k homophonous template suffixes; counted at _rules[i].Apply, trace events are unchanged by design):

grammar word without table with table most matches of one (rule, shape)
g2 katitm 7 5 2 -> 1
g2 tikitm 13 8 2 -> 1
g4 katitm 13 7 4 -> 1
g4 tikitm 25 10 4 -> 1
g8 katitm 25 11 8 -> 1
g8 tikitm 49 14 8 -> 1

Timings are small and noisy, because hc re-parses in a few milliseconds: 300 parses of g4 took 2.1 s before and 1.5 s after (medians of 5); g2 and g8 were within noise. On conformance fixtures, deep-optional-affix-nesting 4.8 s -> 4.2 s, syncope-redup-optional-vowel-lattice 3.5 s -> 2.7 s, others within noise.


Decisions, and why
  • Keyed per allomorph, not per rule, so the edge prefilter still skips an allomorph before it reaches the table and no match is computed that master would not compute.
  • Keyed by the grammar rule, so a rule compiled for a stratum and for a template slot shares rows.
  • Unfrozen input shapes (no value hash) fall back to matching directly.
  • A miss freezes the freshly built output shapes and continues with those very words, so the miss path is master's code path.
Paths not taken

Sharing whole subtrees by state, carrying label sets per expanded shape, and a lexicon reachability prune were rejected in the #653 comment: they change visiting order or belong to the FST prefilter.

🤖 Generated with Claude Code


This change is Reviewable

Matching an affix or realizational rule allomorph reads only the input shape,
yet the analysis search matched it again for every path that reached the same
shape. Each parse now keeps a table keyed by (rule, allomorph, frozen shape)
holding the output shapes, and every path still runs its own gates and builds
its own output words from the stored shape. Compounding rules are not stored,
because their match also reads the non-head root.

Refs #653

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

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.55172% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.74%. Comparing base (c73ca66) to head (277435b).

Files with missing lines Patch % Lines
...y.HermitCrab/MorphologicalRules/ShapeMatchTable.cs 92.85% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #654      +/-   ##
==========================================
+ Coverage   75.64%   75.74%   +0.09%     
==========================================
  Files         456      457       +1     
  Lines       38985    39039      +54     
  Branches     5435     5442       +7     
==========================================
+ Hits        29492    29570      +78     
+ Misses       8347     8326      -21     
+ Partials     1146     1143       -3     

☔ 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.

_finalTemplateState = word._finalTemplateState;
_isPartial = word._isPartial;
CurrentTrace = word.CurrentTrace;
MatchTable = word.MatchTable;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: F1. Parse results keep the whole table alive, so it is not "dropped with" the parse as the description says. This line copies MatchTable into every clone, and lexical lookup builds results with input.Clone() (Morpher.cs:580, :652); Source (Word.cs:85, never cleared) also reaches back to the input word. So every Word that ParseWords returns holds every row its parse stored, and a caller keeping results over a corpus keeps all of them. Since ParseWord is eager and synthesis never reads the table, clearing its rows right after _analysisRule.Apply(input) would release them.

return Compute(rule, patternRule, input, matched);

var key = new Key(rule, allomorph, input.Shape);
if (table._rows.TryGetValue(key, out Shape[] shapes))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI: F2. Two threads can match the same (rule, allomorph, shape), so "computed once per parse" (line 13) does not hold under the default maxDegreeOfParallelism: 0. This TryGetValue and the TryAdd at line 71 are not atomic, and AnalysisAffixTemplateRule.ParallelApplySlots (:186) runs slots in parallel inside one parse. Results stay correct; only the saving and the ShapeMatched count change. GetOrAdd with a Lazy<Shape[]> would make it once; otherwise reword the doc.

@claude

claude Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Approve with fixes.

The main issue is F1 at src/SIL.Machine.Morphology.HermitCrab/Word.cs:104: every returned Word keeps its parse's whole match table alive, which contradicts the description's claim that the table is dropped with the parse.

Findings: 0 Critical, 1 Important (F1), 1 Low (F2).

Ran /code-review high 654 and checked each candidate against the source (Word.Source is never cleared; ParseWord is eager; ParallelApplySlots runs slots in parallel within one parse). gh pr checks 654: builds on ubuntu-22.04 and windows-latest pass, and the advisory comment-hygiene report passes. Create NuGet package and claude-review are still pending.

Not verified: how much memory the retained rows cost on a real corpus; the conformance replay and timings in the description, which I did not rerun; and whether --agent-strict passes, since the green hygiene check is advisory and does not stand in for it.

Public API, target framework, package, and sillsdev/machine.py parity: none changed. The new members are internal, and this ports PanGloss, not machine.py.

F1 new, F2 new.

Reviewed at 277435b

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.

2 participants