Skip to content

Remove redundant deletion matches - #655

Draft
jtmaxwell3 wants to merge 5 commits into
masterfrom
removeRedundantDeletionMatches
Draft

jtmaxwell3 wants to merge 5 commits into
masterfrom
removeRedundantDeletionMatches

Conversation

@jtmaxwell3

@jtmaxwell3 jtmaxwell3 commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

This PR removes redundant deletion matches when a phonological deletion rule is unapplied. Redundant deletion matches occur when a deletion rule matches next to an optional node. Since the node is optional, the rule can match on either side of it. If the rule's context doesn't match the node, then one of these matches is redundant.

Each unapplication introduces an optional node, and some matching algorithms are exponential in the number of optional nodes, so eliminating a rule application can make a big difference in how long a word takes to parse. This is especially true if the grammar has a lot of phonological deletion rules, since phonological deletion rules produce optional nodes, and so later phonological deletion rules produce a lot of redundant matches. In the worst case, the number of redundant matches is exponential in the number of deletion rules that the grammar has. See RewriteTests.CascadedDeletionRules for an example. Note that when the left context and the right context don't filter, then there are a lot matches in the output.

This speeds up the slowest words in the Puguli project from minutes to seconds. The slowest word is now less than two seconds on my machine. (The Puguli project has 4763 words if you use Run Tests > Parse All Texts.)


This change is Reviewable

@jtmaxwell3
jtmaxwell3 marked this pull request as draft November 26, 2026 17:08
@claude

This comment has been minimized.

@claude

This comment has been minimized.

@codecov-commenter

codecov-commenter commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.43590% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 75.65%. Comparing base (c73ca66) to head (ca20ebe).
⚠️ Report is 6 commits behind head on master.

Files with missing lines Patch % Lines
...gy.HermitCrab/PhonologicalRules/RewriteRuleSpec.cs 96.87% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##           master     #655   +/-   ##
=======================================
  Coverage   75.64%   75.65%           
=======================================
  Files         456      456           
  Lines       38985    39022   +37     
  Branches     5435     5439    +4     
=======================================
+ Hits        29492    29522   +30     
- Misses       8347     8354    +7     
  Partials     1146     1146           

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

// Test with epenthesis rule.
Morphophonemic.PhonologicalRules.Clear();
CreateDeletionRule("rule1", "a");
var rule4 = new RewriteRule { Name = "rule4"};

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.

Major: F3. CI fails the format check on this line: Build on ubuntu-22.04 stops at dotnet csharpier check . with RewriteRuleTests.cs - Was not formatted. The cause is the missing space in { Name = "rule4"}. Run dotnet csharpier format . and push.

@claude

claude Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor
  1. Verdict: request changes. The new epenthesis case fixes F1, but the head fails CI's format check.
  2. Most important: F3 (tests/SIL.Machine.Morphology.HermitCrab.Tests/PhonologicalRules/RewriteRuleTests.cs:1944). { Name = "rule4"} is not CSharpier-formatted, so Build on ubuntu-22.04 fails before it builds or tests.
  3. Counts: 1 Critical (F3), 0 Important open, 0 Low open.
  4. Ran: gh pr checks 655 shows Build on ubuntu-22.04 failing at dotnet csharpier check ., comment hygiene passing, and Build on windows-latest and claude-review pending. Locally, dotnet test --filter CascadedDeletionRules on the HermitCrab suite passed 4/4, including the new ParseWord("sog") assertion. Since 3bf373c, only the test changed.
  5. Not verified: whether the epenthesis case fails with the filter turned off. The Puguli speedup is also unverified; there is still no benchmark.

Public API: unchanged since the last round (RewriteRuleSpec's protected constructor gains an optional parameter). Target framework, package, and machine.py parity: none verified.

Findings: F1 addressed; F2 addressed; F3 new.

Reviewed at e40e1d2

@johnml1135

johnml1135 commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Removing redundant deletion matches (#655) drops some analyses the parser finds today

With #655's filter, HermitCrab no longer finds some analyses it finds without it. In the smallest case, one deletion rule with an alpha variable becomes unrecoverable, because the gap #655 keeps binds the variable from an optional node rather than from the consonant before the deleted segment.

Grammar (case A), two deletion rules applied in this order:

  • prD: C[α voice] → ∅ / (C) C[α voice] _ i
  • prE: g → ∅ / _ i

Root tapti surfaces as tapi through prD alone (t agrees in voicing with p). Parsing tapi:

Why: unapplying prE gives t a p g? i. prD can re-insert at the gap after p (α bound from p, which restores t) or at the gap after g? (α bound from g). #655 drops the gap after p, because its right context i fails when g? is mandatory. The remaining gap cannot restore a voiceless consonant.

Checked two ways: hc built from a recent tree with and without #655's src/ changes (rows below), and the attached unit test on the PR, which passes on its base f9294f9 and fails on head ca20ebe. Two shorter cases with the same pattern are in the details: one with no variables and two left-to-right rules, and one with a right-to-left rule. Across 46 small random deletion grammars, #655 removed analyses in 7 grammars (52 words) and never added one.

Next: is the extra gap intended to produce these analyses? If it is, could the filter keep both gaps when the rule binds variables in its left context, or when the deleted segment could form a run? A unit test reproducing cases B and A is attached (Repro655Tests.cs).

Case B: no variables, both rules left-to-right (4 segments)
  • r0: a → ∅ / t _ V (iterative, left to right)
  • r1: p → ∅ / _ i (simultaneous)

Root taai → t a i → ti (r0 twice). Parsing ti: without #655 the analyses include taai; with #655 taai is lost. With only the root taai in the lexicon, the unit test returns taai on the base and nothing on the head.

Unapplying r1 gives t p? i. Without the filter, r0 re-inserts a? on both sides of p? (t a? p? a? i), which spells t a a i. With the filter, the gap before p? is kept (the guard), the gap after p? is dropped (its left context t fails when p? is mandatory), and one a? cannot spell a a.

The same grammar loses taai-type roots for pti, tti, tip, tit, tia, tii, ati and iti.

Case C: a right-to-left rule
  • prD: t → ∅ / _ i (iterative, right to left)
  • prE: g → ∅ / _ i

Parsing pai: without #655 the analyses are pagi, pati, patti; with #655 they are pagi, pati. patti is lost. There is no left context, so the guard does not apply and the gap before g? is dropped.

Rows and method
grammar word without #655 with #655
A tapi tapgi, tapi, tapti tapgi, tapi
B ti includes taai taai missing
C pai pagi, pati, patti pagi, pati
cascaded chain e/o/u/i → ∅ / _ t pt 2 analyses the same 2

Built with dotnet publish of the conformance driver project from tree ba6dfa1, with and without git apply of #655's src/ hunks. Words were parsed with the hc tool and compared on root glosses.

Random grammars: 2 to 4 one-segment deletion rules over {p, t, a, i} with random contexts and modes. The lexicon holds every string of length 1 to 5, and all 340 words of length 1 to 4 were parsed. Seeds 1 to 46 were run; the rest was not run.

No analysis was gained with #655 in any grammar.

What the filter assumes

The PR description says a deletion match next to an optional node is redundant with the match on the node's other side, provided the rule's context does not match the node. That holds as a set of strings when both gaps re-insert the same segment and analysis is otherwise complete.

Here neither holds. A left-context variable binds per gap (case A). With DeletionReapplications 0, analysis restores one copy per gap, so two adjacent copies spell a run of deleted segments that a single copy cannot (cases B and C).

Unit test (RewriteRuleTests style). Base f9294f9: 2 passed. Head ca20ebe: 2 failed.

Base returned ti: taai and tapi: tapgi, tapti. Head returned ti: nothing and tapi: tapgi.
Save as tests/SIL.Machine.Morphology.HermitCrab.Tests/PhonologicalRules/Repro655Tests.cs.

using NUnit.Framework;
using SIL.Machine.Annotations;
using SIL.Machine.FeatureModel;
using SIL.Machine.Matching;

namespace SIL.Machine.Morphology.HermitCrab.PhonologicalRules;

public class Repro655Tests : HermitCrabTestBase
{
    // Smallest case: two rules, four segments (t, a, p, i), no variables, no right-to-left rule.
    //   r0: a -> 0 / t _ V   (iterative, left to right)
    //   r1: p -> 0 / _ i     (simultaneous)
    // Root taai: r0 deletes both a's (t a a i -> t a i -> t i), r1 does not apply, so the surface is "ti".
    // Analysing "ti" unapplies r1 first (t p? i). Without #655, r0 re-inserts a? on both sides of p?
    // (t a? p? a? i), which spells t a a i. With #655 the gap after p? is dropped (its left context t fails when
    // p? is mandatory), one a? remains, and taai is not found.
    [Test]
    public void DeletionNextToOptionalNode_KeepsRunOfDeletedSegments()
    {
        FeatureStruct vowel = FeatureStruct
            .New(Language.PhonologicalFeatureSystem)
            .Symbol(HCFeatureSystem.Segment)
            .Symbol("cons-")
            .Value;

        var r0 = new RewriteRule
        {
            Name = "r0",
            Lhs = Pattern<Word, ShapeNode>.New().Annotation(Character(Table3, "a")).Value,
        };
        r0.Subrules.Add(
            new RewriteSubrule
            {
                LeftEnvironment = Pattern<Word, ShapeNode>.New().Annotation(Character(Table3, "t")).Value,
                RightEnvironment = Pattern<Word, ShapeNode>.New().Annotation(vowel).Value,
            }
        );
        var r1 = new RewriteRule
        {
            Name = "r1",
            ApplicationMode = RewriteApplicationMode.Simultaneous,
            Lhs = Pattern<Word, ShapeNode>.New().Annotation(Character(Table3, "p")).Value,
        };
        r1.Subrules.Add(
            new RewriteSubrule
            {
                RightEnvironment = Pattern<Word, ShapeNode>.New().Annotation(Character(Table3, "i")).Value,
            }
        );
        Morphophonemic.PhonologicalRules.Add(r0);
        Morphophonemic.PhonologicalRules.Add(r1);

        LexEntry root = AddEntry("taai", Pos("N"), Morphophonemic, "taai");
        try
        {
            var morpher = new Morpher(TraceManager, Language, 1);
            IEnumerable<string> glosses = Glosses(morpher.ParseWord("ti"));
            TestContext.Out.WriteLine("ANALYSES ti: " + string.Join(", ", glosses.OrderBy(g => g)));
            Assert.That(glosses, Does.Contain("taai"));
        }
        finally
        {
            RemoveEntry(root);
        }
    }

    // Case A: a single deletion, made unrecoverable because the surviving gap binds the variable from an optional node.
    //   prD: C[a vd] -> 0 / (C) C[a vd] _ i   (a consonant agreeing in voicing with the one before it is lost before i)
    //   prE: g -> 0 / _ i
    // Root tapti surfaces as "tapi" through prD alone (t agrees with p). Root tapgi surfaces as "tapi" through prE.
    // Analysing "tapi" unapplies prE first: t a p g? i. Without #655, prD re-inserts at the gap after p (voicing bound
    // from p, giving t) and after g? (voicing bound from g). With #655 the gap after p is dropped (its right context i
    // fails when g? is mandatory, and the gap after g? is not left-redundant), so tapti is not found.
    [Test]
    public void DeletionNextToOptionalNode_KeepsVariableBindingFromLeftContext()
    {
        FeatureStruct cons = FeatureStruct
            .New(Language.PhonologicalFeatureSystem)
            .Symbol(HCFeatureSystem.Segment)
            .Symbol("cons+")
            .Value;
        FeatureStruct alphaCons = FeatureStruct
            .New(Language.PhonologicalFeatureSystem)
            .Symbol(HCFeatureSystem.Segment)
            .Symbol("cons+")
            .Feature("vd")
            .EqualToVariable("a")
            .Value;

        var prD = new RewriteRule { Name = "prD", Lhs = Pattern<Word, ShapeNode>.New().Annotation(alphaCons).Value };
        prD.Subrules.Add(
            new RewriteSubrule
            {
                LeftEnvironment = Pattern<Word, ShapeNode>.New().Annotation(cons).Optional.Annotation(alphaCons).Value,
                RightEnvironment = Pattern<Word, ShapeNode>.New().Annotation(Character(Table3, "i")).Value,
            }
        );
        var prE = new RewriteRule
        {
            Name = "prE",
            Lhs = Pattern<Word, ShapeNode>.New().Annotation(Character(Table3, "g")).Value,
        };
        prE.Subrules.Add(
            new RewriteSubrule
            {
                RightEnvironment = Pattern<Word, ShapeNode>.New().Annotation(Character(Table3, "i")).Value,
            }
        );
        Morphophonemic.PhonologicalRules.Add(prD);
        Morphophonemic.PhonologicalRules.Add(prE);

        LexEntry tapti = AddEntry("tapti", Pos("N"), Morphophonemic, "tapti");
        LexEntry tapgi = AddEntry("tapgi", Pos("N"), Morphophonemic, "tapgi");
        try
        {
            var morpher = new Morpher(TraceManager, Language, 1);
            IEnumerable<string> glosses = Glosses(morpher.ParseWord("tapi"));
            TestContext.Out.WriteLine("ANALYSES tapi: " + string.Join(", ", glosses.OrderBy(g => g)));
            Assert.That(glosses, Does.Contain("tapti").And.Contain("tapgi"));
        }
        finally
        {
            RemoveEntry(tapti);
            RemoveEntry(tapgi);
        }
    }

    private FeatureStruct Pos(string symbol) => FeatureStruct.New(Language.SyntacticFeatureSystem).Symbol(symbol).Value;

    private static IEnumerable<string> Glosses(IEnumerable<Word> words) =>
        words.Select(w => string.Join(" ", w.AllomorphsInMorphOrder.Select(a => a.Morpheme.Gloss))).ToList();

    private void RemoveEntry(LexEntry entry)
    {
        Morphophonemic.Entries.Remove(entry);
        Entries.Remove(entry.Gloss);
    }
}

@johnml1135

Copy link
Copy Markdown
Collaborator

Thanks for this; the speedup is substantial. We ran #655 (head ca20ebe) against its merge base on 23 real and calibration grammars (two with heavy deletion cascades) and all 155 conformance-suite grammars. Analyses are identical in every case, and the slowest words in the two deletion-heavy grammars are 6x to 12x faster in total time.

The filter is not result-preserving in general, though. Two small grammars lose analyses that base finds (Repro655Tests.cs, posted earlier in this thread: base passes, head fails):

  • Rules prD: C[alpha voice] -> 0 / (C) C[alpha voice] _ i and prE: g -> 0 / _ i: parsing tapi finds tapgi, tapi, tapti on base but not tapti on head. The surviving gap binds the variable from an optional node instead of the preceding consonant.
  • Rules a -> 0 / t _ V (iterative) and p -> 0 / _ i: parsing ti loses taai, because dropping the gap after the optional node leaves too few copies to spell a run.

A fuzz of 46 small random deletion grammars lost analyses in 7 and never gained one. Could the filter keep both gaps when the rule's left context binds variables or when the deleted segment can form a run? If these analyses are considered spurious, a test pinning that decision would help. A case comparing full analysis sets with and without the filter would also help.

@johnml1135

Copy link
Copy Markdown
Collaborator

For comparison: PanGloss (the Rust port of HC) is landing an exact filter aimed at the same blowup, sillsdev/PanGloss#585 (design in sillsdev/PanGloss#579). Before searching an affix allomorph it checks cheaply whether the allomorph can match the input at all. Analyses are identical on every finished word across our lists, and Tamil does 4-8x less work. The cost is +6% work on Mbugwe and +1.6% on Swahili, where it rarely rejects anything. Next we will measure a corrected version of this PR's gap filter (keeping both gaps when the left context binds variables or the deleted segment can form a run) on its own and combined with #585, and report the numbers here.

@johnml1135

Copy link
Copy Markdown
Collaborator

Follow-up on our earlier report: we ported this change to the Rust port (PanGloss) and measured it three ways. Instruction counts are Windows hardware counters, 100 random words per grammar. Grammar names are withheld; "grammar A" is the slow agglutinative grammar from our earlier comment.

Exactness. A faithful port reproduces the lost-analysis repro (Repro655Tests.cs, earlier in this thread) and loses analyses on 68 of 300 fuzzed grammars. We tried two corrections:

  • Per rule: apply the skip only when the deletion rule has no alpha variables, no reapplication, applies left to right, and its right environment cannot start with the deleted segment. This still loses on 10 of 300, because another rule can rescue the deleted segment.
  • Grammar-wide: apply the skip only when every deletion rule in the grammar passes that test. This lost nothing on 1,000 fuzz seeds. But grammar A has a deletion rule that can apply in runs, so the skip never fires there and the gain is gone.

So in our measurements, making it exact removes the speedup on the grammar that needs it.

Speed, faithful port (instructions): grammar A -83% (-90% on its heaviest words); grammar B -61%. On every word that finished in both builds, analyses matched the unmodified build. The losses show up only on fuzzed grammars.

What we're doing: we're landing an exact prefilter instead (sillsdev/PanGloss#585, grammar A -69%; heaviest words -82%). If this PR merges, we'll port it at our next Machine pin and stack it on #585. We think the exact route to the remaining gain is enumerating optional runs (#635).

@johnml1135

Copy link
Copy Markdown
Collaborator

The code behind our results is in sillsdev/PanGloss#589. It's a closed PR, kept only as evidence and never to be merged.

What we tried. We implemented this PR's redundant-match filter in PanGloss's deletion un-application (rust/crates/pg-rules/src/rewrite.rs, ana_narrow_deletion) in three versions, selected by an environment switch:

  1. Raw: a line-for-line port of the two-sided test here.
  2. Per rule: the filter only for a deletion rule with no alpha variables, no reapplication, left-to-right direction, and a right environment that cannot start with the deleted segment.
  3. Grammar-wide: the per-rule version, applied only when every deletion subrule in the grammar qualifies.

The PR also includes our earlier one-sided version of the same idea, which we rejected before this PR was opened.

Why. On our slowest deletion grammar, un-application re-inserts the deleted segment at every gap, up to 2^N optional copies per gap. That's the blowup this PR targets. We wanted to know whether the change keeps the oracle's analyses, whether a corrected version could, and what it gains on its own and combined with our own exact prefilter.

What we found (summarised in our previous comment): the raw and per-rule versions drop analyses against the pinned hc.dll on fuzzed grammars, 68 of 300 and 10 of 300. The grammar-wide version is exact on 1,000 seeds, but it never fires on the grammar that needs it, because that grammar has a deletion rule that can apply in runs. On every real word that finished, all versions gave the same analyses as the unmodified build.

Records:

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