Skip to content

Add hc-whynot, a standalone why-not tool for the parser conformance suite - #651

Draft
johnml1135 wants to merge 1 commit into
masterfrom
feat/hc-whynot
Draft

johnml1135 wants to merge 1 commit into
masterfrom
feat/hc-whynot

Conversation

@johnml1135

@johnml1135 johnml1135 commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Start here: src/SIL.Machine.Morphology.HermitCrab.WhyNot/ adds hc-whynot, a standalone console tool that answers "why does HermitCrab reject this intended analysis?" for the why-not rows of the FieldWorks parser conformance suite (fieldworks-parser-conformance PR #51, PROTOCOL.md section 11, schema/whynot.schema.json). It uses only HermitCrab's public API and makes no HermitCrab source change.

What it does. hc-whynot why-not <grammar.xml> <queries.jsonl> <output.jsonl> reads one query per line (word plus the intended morphs, by morpheme id and allomorph id) and writes one answer per line. A single-word form, hc-whynot <grammar.xml> <word> --expect m[:allo],..., is there for humans. A capturing ITraceManager records the allomorph and failure object of each Failed event, which the stock TraceManager drops. The first failure matching the intended morphs is classified into the suite's kinds (adhoc_prohibition, stem_name, environment_unmet, feature_clash) with the HC reason and morphs. Output schema is whynot.v1, engine-neutral and compatible with pangloss.whynot.v1. Ids are the grammar.xml ids, recovered by cross-checking the XML against the loaded Language; FieldWorks and internal GUIDs are never written. A failure that cannot fill a schema-required field (for example an unmapped allomorph id) becomes result: unknown with a stop reason and a note, never an invalid row. A bad query yields an unknown row, not a crash.

Why standalone. The existing hc Tool is an interactive REPL that loads one grammar through -i; the suite contract is a one-shot batch command. Folding it in would also touch the Tool's Program, which #615 (hc-runner) is already editing.

HC limits found (no HC change made).

  • First failure only: HC short-circuits validity checks, so one failure per derivation is visible.
  • No environment.index: Allomorph.Environments is an unordered set and the check fails only when every alternative fails.
  • Mpr reasons are not attributable: Required/Excluded Mpr and rule-side syntactic gates arrive through MorphologicalRuleNotApplied, not as per-derivation Failed events, so they report as other_gate or unknown.
  • Compounding subrules are not mapped to grammar.xml allomorph ids.
  • Head and foot feature ids are per-process GUIDs; they appear as head and foot in feature paths.
  • Derivations that never reach word validity return unknown.
Evidence
  • WhyNotTests: 16 tests (adhoc, stem name, environment, feature clash, ids, unknown rows, CLI batch on a real grammar.xml copied from an fpc fixture). Full HermitCrab test project: 250 passed, 0 failed.
  • csharpier check . and scripts/comment-hygiene.ps1 clean. Machine.sln gains 7 lines only.
  • A smoke run on the fpc adhoc-prohibition-affix-environment-copies fixture validated against whynot.schema.json.
  • The solution-wide local_check.sh --agent-strict was not run to completion: cmake is missing, so the SentencePiece step fails.

Next: wire the suite runner to hc-whynot once fpc PR #51 lands.

🤖 Generated with Claude Code


This change is Reviewable

…an intended analysis, with whynot.v1 JSON

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

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.28571% with 138 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.75%. Comparing base (e7422c1) to head (48c7dac).

Files with missing lines Patch % Lines
...ine.Morphology.HermitCrab.WhyNot/WhyNotAnalyzer.cs 79.53% 44 Missing and 9 partials ⚠️
....Machine.Morphology.HermitCrab.WhyNot/WhyNotCli.cs 67.92% 28 Missing and 6 partials ⚠️
...Machine.Morphology.HermitCrab.WhyNot/WhyNotJson.cs 88.11% 12 Missing and 5 partials ⚠️
...phology.HermitCrab.WhyNot/CapturingTraceManager.cs 77.14% 15 Missing and 1 partial ⚠️
....Morphology.HermitCrab.WhyNot/FeatureStructDiff.cs 75.60% 5 Missing and 5 partials ⚠️
...Machine.Morphology.HermitCrab.WhyNot/GrammarIds.cs 90.14% 3 Missing and 4 partials ⚠️
...IL.Machine.Morphology.HermitCrab.WhyNot/Program.cs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #651      +/-   ##
==========================================
+ Coverage   75.53%   75.75%   +0.21%     
==========================================
  Files         455      463       +8     
  Lines       38933    39633     +700     
  Branches     5428     5527      +99     
==========================================
+ Hits        29407    30022     +615     
- Misses       8376     8433      +57     
- Partials     1150     1178      +28     

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

if (!TryCompile(language, out WhyNotSession session))
return 1;
using var output = new StreamWriter(outputPath, false, new UTF8Encoding(false));
foreach (string line in File.ReadLines(queriesPath).Where(l => l.Trim().Length > 0))

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. A missing queries file wipes the output file and then crashes: the StreamWriter on line 94 truncates out.jsonl before File.ReadLines throws FileNotFoundException, which nothing catches. If queries and output are the same path, the queries are erased before they are read. Open the queries file first, and return a documented exit code on IOException/UnauthorizedAccessException.

var expected = new List<ExpectedMorph>();
foreach ((string morpheme, string allomorph) in expect)
{
int? index = allomorph == null ? null : ids.AllomorphIndex(morpheme, allomorph);

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: F2. One bad query line crashes the whole batch, even though batch mode promises bad queries become unknown rows. A query whose expect entry has "morpheme": null and an allomorph passes a null key to AllomorphIndex, so Dictionary.TryGetValue(null) throws ArgumentNullException outside the try in Answer, and the filter in AnswerLine does not catch it. Reject null morpheme ids while parsing.

ids = GrammarIds.Load(grammar, language);
return true;
}
catch (Exception e)

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: F3. Common grammar errors crash the tool instead of printing cannot load grammar and exiting 1 as the usage text says. XmlLanguageLoader.Load also throws InvalidShapeException (derives from Exception), KeyNotFoundException for a dangling stem-name or class id, and FormatException from int.Parse(multipleApplication); none pass this filter. Catch non-fatal exceptions here, as HermitCrab.Tool/Program.cs:81 does.

foreach (Morpheme morpheme in morphemes.Distinct())
{
string id = MorphemeIds.Of(morpheme);
counts[id] = counts.ContainsKey(id) ? -1 : morpheme.AllomorphCount;

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: F4. A valid grammar crashes GrammarIds.Load: MorphemeId and Gloss are both optional in HermitCrabInput.dtd:280, so for a morpheme with neither, MorphemeIds.Of returns null and counts[id] throws ArgumentNullException, which TryLoad does not catch. Skip morphemes with a null id.

partners = others;
string verb = type == ConstraintType.Exclude ? "excludes" : "requires";
string plain =
$"{Label(culprit)} {verb} {string.Join(" or ", others.Select(Label))} ({adjacency}) in this word.";

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: F5. The explanation states the opposite logic for a rule with several partners. MorphCoOccurrenceRule.CoOccurs checks that all partners are present, so Require {X, Y} fails when the word has X but not Y, yet the text says "requires X or Y", which the word already satisfies. Join with " and ", for example "requires all of X and Y" or "excludes the combination X and Y".

public static IReadOnlyList<MorphRef> MorphsOf(Word word)
{
return word
.AllomorphsInMorphOrder.Select(a => new MorphRef(MorphemeIds.Of(a.Morpheme), a.Index, a.Morpheme.Gloss))

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: F6. A word with an affix applied twice gets the wrong verdict: AllomorphsInMorphOrder ends in .Distinct() (Word.cs:127), so two applications collapse to one morph, and Matches compares counts. With multipleApplication=2, expect [root, X, X] never matches and expect [root, X] is reported accepted. Build the list from word.Morphs through GetAllomorph. Unverified: from reading the code, not reproduced.

}

var stemNameCounts = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (XElement stemName in doc.Descendants().Where(e => e.Attribute("partsOfSpeech") != null && IsLive(e)))

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: F7. Inactive stem names are left out of the duplicate check, but XmlLanguageLoader.cs:280 loads every StemName whatever its isActive. If active snA and inactive snB are both named first, a failure caused by snB reports snA. Count stem names the way the loader does.

Array.Empty<MorphRef>(),
null,
null,
new[] { new FeatureMismatch(feature.ID, "specified", actual?.ToString()) }

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: F8. This feature path is the bare feature.ID, while FeatureStructDiff writes every other path as head/... or foot/.... A consumer cannot match tense here against head/tense from a stem-name diff on the same feature.


public class WhyNotTests
{
private sealed class Grammar

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: F9. AGENTS.md says the HermitCrab configuration "has no Grammar type - prefer Language or Stratum", but this test helper is a class named Grammar. Rename it, for example to LanguageFixture.

@claude

claude Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor
  1. Verdict: approve with fixes. The tool works on well-formed input, but several ordinary inputs crash it instead of producing the exit codes or unknown rows it promises.
  2. Most important: F1, WhyNotCli.cs:95. A mistyped queries path truncates the output file and then crashes with an unhandled exception.
  3. Counts: 0 Critical, 6 Important (F1-F6), 3 Low (F7-F9).
  4. Ran: /code-review high, then checked each finding against the source (XmlLanguageLoader, HermitCrabInput.dtd, MorphCoOccurrenceRule.CoOccurs, Word.AllomorphsInMorphOrder). Built the tool in Release: 0 errors. gh pr checks 651: Build on ubuntu-22.04 and windows-latest pass; Create NuGet package pending.
  5. Not verified: the sandbox would not let me run hc-whynot, so no finding was reproduced at runtime. F1-F5 follow directly from the code; F6 depends on HermitCrab reusing one Allomorph instance across repeated applications and is unverified.

Public API, target framework, package: none verified changed in the published libraries. The PR adds a new executable project (hc-whynot) to Machine.sln. No parity contract with sillsdev/machine.py applies.

Findings: F1 new, F2 new, F3 new, F4 new, F5 new, F6 new (unverified), F7 new, F8 new, F9 new.

Reviewed at 48c7dac

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