Skip to content

HermitCrab analysis re-matches the same rule against the same shape once per parent path #653

Backlog

Description

@johnml1135

HermitCrab analysis matches the same rule against the same shape again for every parent path that reaches that shape. On a real Tamil project, adding one N→V derivational suffix made analysis about ten times as expensive on 24 unrelated words. The repeats never change the results.

Mechanism. CombinationRuleCascade.ApplyRules recurses into every result Word. Two Words that reached one shape through different rules differ in _mruleApps, so each is a distinct state and gets its own full pass over the stratum's rules. In AnalysisAffixProcessRule.Apply, the per-path part is cheap: the rule selector, GetUnapplicationCount, the _outputFS gate, the FS restrict and unify, and MorphologicalRuleUnapplied. The expensive part, _rules[i].Apply(input), reads only the shape.

Measured at 1ddef2b with a grammar of k homophonous template suffixes, counting MorphologicalRuleUnapplied/NotUnapplied trace events:

k derivational rule on katit each other rule on kat
2 2 2
4 4 4
8 8 8

On the Tamil word அவ்விடம், analysis makes 4,128 rule attempts but reaches only 7 distinct shapes and 387 distinct (rule, shape) pairs. The new rule fires from 15 parent paths into one shape, and its noun stem then passes the gate of about 33 rules on each of them.

Proposed fix (results and their order unchanged). Per ParseWord, keep for each (rule, shape) the ordered list of (allomorph index, output shape) the pattern rules produced, keyed by the frozen shape's value equality. Apply runs its per-path gates as now, then reuses the list and builds each output Word from the input Word and the stored shape. The table is bounded by distinct shapes × rules.

The Rust port (PanGloss) is landing this in two steps:

On the 24 Tamil words, work fell from 722M to 112M units. Analyses were byte-identical on 5,000-word samples of three languages, and the table stayed under 80 KB per word.

Next: confirm the counts with the attached grammar, then port the per-word table to HermitCrab once PanGloss has validated it across all its grammars.

Reproduction

Generate grammars g2.xml, g4.xml and g8.xml with k homophonous suffix rules in one optional template slot, one derivational suffix and five other suffix rules. Run hc -i g4.xml with tracing on, parse katitm, parse tikitm, and count Morphological Rule Analysis lines by rule and input. The grammars, generator and full count tables are kept with the PanGloss research for #481 and can be attached on request.

Activity

  1. johnml1135 commented on Nov 25, 2026

    @johnml1135
    CollaboratorAuthor

    The two algorithms, explained

    This comment explains both fixes in full: the interim per-word memo (PanGloss#480) and the per-word shape graph that replaces it (PanGloss#481). Neither changes any parse result or the order of results. The shape graph is the one proposed for HermitCrab.

    Why the work repeats

    Analysis is a depth-first search over Words. A Word is a shape plus a label: syntactic FS, realizational FS, the ordered list of rules unapplied so far (_mruleApps), and template state. Two Words with the same shape and different rule histories are different search states. CombinationRuleCascade.ApplyRules therefore gives each of them its own full pass over the stratum's rules.

    For each rule on each Word, AnalysisAffixProcessRule.Apply does two kinds of work:

    1. Label work (cheap). The rule selector, GetUnapplicationCount (max applications), the _outputFS unifiability gate, the FS restrict and unify on each result, template state, and MorphologicalRuleUnapplied.
    2. Shape work (expensive). _rules[i].Apply(input) matches each allomorph's pattern against the shape lattice. It reads the rule, the allomorph and the shape only, never the label.

    The search therefore pays for one shape match per (shape, label, rule) that passes the gate. The answer depends only on (shape, rule).

    Tamil has many zero and homophonous allomorphs, so shapes stay few while labels multiply. One word reaches 7 distinct shapes but makes 4,128 rule attempts, only 387 of them distinct (rule, shape) pairs. A new N→V suffix sets the stem's FS to noun, which lets about 33 noun rules through the gate on each of 15 arrivals at the same shape. Each of those arrivals repeats the same pattern matches.

    Fix 1, interim: per-word match memo (PanGloss#480, landing now)

    This is a cache in front of the shape work.

    • Key: (allomorph, the prune_disagreeing_copies flag, the exact shape by value). This is everything the pattern match reads.
    • Value: the ordered list of output shapes, plus a "no match at all" flag.
    • Use: every arrival still runs all of its label work. Only the pattern match is replaced by the stored list, in the same order with the same deduplication. Each output Word is then rebuilt from the arriving Word and the stored shape.
    • Admission:
      • an entry is stored on the second miss of the same key; the first miss records only a 64-bit fingerprint, so one-off matches never allocate;
      • only matches that cost more than a hit are stored;
      • nothing is stored from a search that the work cap stopped.
    • Hit cost: a hit is charged one work unit, plus one per output. This keeps the work cap meaningful and means a hit never costs more than the search it replaces.
    • Hard cap: 10 MiB of real heap bytes per word, with fewest-hits eviction.
      • Shapes are measured with Shape::heap_bytes.
      • Hash tables are counted at their real capacity times 1.5, which covers a resize.
      • The memo fills only to 5/6 of the cap, and the rest is margin.
      • The cap also shrinks to fit the word's memory allowance, so the memo can never cause a memory-cap outcome that would not otherwise happen.
      • With a counting allocator, the real peak was 8.4 MiB.
    • Cost of this design: it needs an admission rule, a fingerprint set, a ceiling and eviction. It also pays each repeated match twice before storing it. That is why it is interim.

    Fix 2, structural: per-word shape graph (PanGloss#481, next; proposed for HermitCrab)

    This makes the word's unapplication graph an explicit, bounded table that the search reads. It is still a table keyed by shape, but it is complete and needs no policy.

    • Nodes: each distinct shape the word's analysis reaches is interned once per ParseWord. Equal shapes share one node, using the frozen shape's value equality.

    • Rows: row(node, rule) is the ordered list of (allomorph index, output node) edges, exactly what _rules[i].Apply returns on that shape. A rule with no match on that shape gets an empty row.

    • Search: unchanged. It is the same depth-first walk over Words in the same order. On each arrival, Apply runs all label work as today, then:

      • if the row exists, it reads it;
      • otherwise it runs the pattern match once and stores the row.

      Each output Word is built from the arriving Word plus the edge's allomorph and output shape.

    • Why results are identical: the match is a pure function of (shape, rule). The row is exactly that function's return value, in the same order. Everything that depends on the path still runs on every arrival:

      • gates;
      • max-application counts;
      • FS unification;
      • template state;
      • the _mruleApps trail;
      • recursion into the cascade.

      The only thing removed is recomputing a pure function.

    • Bounded without eviction:

      • Rows are at most distinct shapes × stratum rules, and edges are at most distinct matches.
      • Measured worst case over 5,000-word samples: 19 KB per word for Tamil, 74 KB for Cebuano, 11 KB for Swahili. The mean is 3–6 KB.
      • Shapes are already kept alive by the search, so interning them makes them share memory rather than adding to it.
      • PanGloss charges row bytes to its existing per-word memory meter, so there is one limit, not a second ceiling.
      • The table can be dropped at any point without changing results.
    • Result: every repeated (rule, shape) match is gone, including the first repeat that Add a conformance suite for HermitCrab, with its adequacy argument #480 still pays. What remains, 92–98% of Tamil's work, is first-time matches: real search, not repetition.

    24 Tamil words, one grammar work units largest word
    no fix 722.2M 59.0M
    #480 memo 157.6M 11.9M
    shape graph (prototype) 112.2M 8.2M

    The prototype's analyses were byte-identical to the unfixed engine on these 24 words and on 5,000-word samples: Tamil (both grammars), Swahili and Cebuano.

    For HermitCrab

    1. Keep a per-ParseWord dictionary keyed by (rule, Shape) using the frozen shape's value equality, or by (rule, interned shape id).
    2. Store the ordered list of (allomorph index, output shape).
    3. In AnalysisAffixProcessRule.Apply and the realizational equivalent, run the per-path gates as now. (Leave compounding rules out: their match also depends on the non-head root filter, not only the shape.) Replace _rules[i].Apply(input) with a row lookup that fills the row on a miss.
    4. Build each output Word from the input Word and the stored shape.

    Nothing else in the search changes, so trace output and result order stay the same.

    Alternatives rejected

    • Sharing whole subtrees by full state. The key would have to ignore rules that cannot fire later, which is unknown until the subtree has been explored. That needs a large memo, and it would save at most 2–6% more than the shape graph.
    • Expanding each shape once and carrying label sets. It needs the same rows anyway, and it changes the visiting order, which risks result order and work-cap snapshots.
    • A lexicon reachability prune. It is complementary, but a sound prune is the FST prefilter's job and is out of scope here.
    • Moving the phonological cascade. It already runs once per stratum input, not once per rule firing, so there is nothing to save.

    The PanGloss SHA, the safety invariant and the before/after C# counts at 1ddef2b will follow here when #481 lands, as the hand-off for the HermitCrab port.

    🤖 Generated with Claude Code

  2. johnml1135 commented on Nov 26, 2026

    @johnml1135
    CollaboratorAuthor

    Hand-off: PanGloss landed the per-word (rule, shape) table as sillsdev/PanGloss#488 (main 18ed10635, released in PanGloss v0.35.0). Analyses byte-identical to the prior engine on Tamil, Swahili and Cebuano samples and the full conformance suite. The HermitCrab port is draft PR #654.

    🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    • Status
      📋 Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions