Skip to content

SemanticContext.AND and OR equality depends on the order their operands were combined in #4990

Open
moderneinc/rewrite-mainframe
#256

Description

@knutwannheden

SemanticContext.and(a, b) and SemanticContext.and(b, a) are unequal and hash differently whenever a and b share a bucket of the HashSet the constructor collects them in. Configurations that differ only in that order then coexist in the prediction cache, and each copy's predicates are evaluated separately. In a 600-rule COBOL grammar, a change that only renumbered rules made 192,356 of the cache's 753,719 configurations such copies, where there had been none. Building the cache over 94 programs went from 0.74 s to 1.11 s.

Reproduction, Java target, 4.13.2 and dev at 7d57703:

SemanticContext a = new SemanticContext.Predicate(0, 0, false);
SemanticContext b = new SemanticContext.Predicate(0, 2, false);
SemanticContext.and(a, b).equals(SemanticContext.and(b, a)); // false: {0:0}?&&{0:2}? vs {0:2}?&&{0:0}?
SemanticContext.or(a, b).equals(SemanticContext.or(b, a));   // false

Of 25,440 ordered pairs of predicates with rule index below 40 and predicate index below 4, 1,578 give unequal ANDs.

Expected: equal. The constructors deduplicate operands through a set, and AND.eval documents operand evaluation as "short-circuiting, but unordered". Actual: AND and OR keep operands.toArray() in the set's iteration order, compare it with Arrays.equals, and hash it with MurmurHash.hashCode(opnds, …), both order-sensitive (runtime/Java/src/org/antlr/v4/runtime/atn/SemanticContext.java).

The C#, Python 3, JavaScript and Dart runtimes also build the operand list from a set and compare it in order, and Swift builds it the same way. I have not checked Go or C++.

Activity

  1. ericvergnaud commented on Oct 30, 2026

    @ericvergnaud
    Contributor

    @knutwannheden Thanks for this.
    May I ask how this issue affects the parsing?
    Does it produce unexpected errors, incorrect trees, or performance issues?

  2. knutwannheden commented on Oct 30, 2026

    @knutwannheden
    Author

    @ericvergnaud This was only a performance concern, no parse errors. It is a bit hidden in my issue description:

    Building the cache over 94 programs went from 0.74 s to 1.11 s.

  3. ericvergnaud commented on Oct 30, 2026

    @ericvergnaud
    Contributor
  4. knutwannheden commented on Oct 30, 2026

    @knutwannheden
    Author

    That was a again out of context:

    In a 600-rule COBOL grammar, a change that only renumbered rules made 192,356 of the cache's 753,719 configurations such copies, where there had been none. Building the cache over 94 programs went from 0.74 s to 1.11 s.

    So I made a small innocent change and that caused the parser to end up being much slower. That is how I stumbled over this. I can do some more measurements, if you like

  5. ericvergnaud commented on Oct 31, 2026

    @ericvergnaud
    Contributor

    Yes please.
    Although your findings seem logical, some numbers would help prove the usefulness of this change.
    Also, applying them across all targets would be required such that the algorithm behaves identically across them (it does today).

  6. knutwannheden commented on Oct 31, 2026

    @knutwannheden
    Author

    Here are the numbers, and the change now covers every target.

    In short: the targets don't behave identically today. An AND's or OR's operand order comes from hash buckets in Java, Python and JavaScript, from insertion order in C#, C++, Dart and PHP, and from chance in Go and Swift. So the cost depends on the target and on the grammar's rule numbering. The change gives every target one order.

    Numbers

    The reproducer is a generated grammar of about 15 rules: block statements with optional terminators, each terminator an empty alternative guarded by a plain predicate, so SLL prediction meets those predicates in both orders. A seed shuffles the rule definitions without changing them. It has a harness for each of the eight runtimes: https://github.com/knutwannheden/antlr-semantic-context-order

    The same grammar and input build a cache of a different size in every target on dev, and the same one everywhere with the change (6 block kinds, 200 generated programs, rule orders 0 and 11, median of 3 interleaved runs):

                 cached configurations           building the cache            warm pass
                 dev                     fix     dev            fix            dev            fix
    Java         15,206 / 33,226         15,206  35 / 144 ms    25 / 20 ms     21 / 31 ms     20 ms
    JavaScript   18,374 / 15,206         15,206  406 / 287 ms   65 / 67 ms     60 / 51 ms     50 ms
    Python       20,972 / 17,590         15,206  942 / 685 ms   399 / 407 ms   3.7 / 3.1 s    2.7 s
    Swift        21,334 – 36,064 by run  15,206  0.4 / 1.0 s    60 ms          360 / 333 ms   243 ms
    C#           313,184                 15,206  16.5 s         25 – 56 ms     710 ms         61 – 88 ms
    C++          313,184                 15,206  23.4 s         17 ms          360 / 383 ms   39 ms
    Dart         313,184                 15,206  103 – 107 s    21 ms          0.9 s          55 ms
    Go           573,260 – 580,984 by run 15,206 58 – 60 s      19 – 23 ms     1.6 s          46 – 49 ms
    

    With the change every target also evaluates exactly the same number of predicates, 1,514,026 per pass for rule order 0. On dev that ranges from 1,518,433 in Java to 53.6 million in Go.

    In real grammars the effect is smaller, and it moves with rule numbering (Java):

    grammar                    cached configurations   differing only in order   building the cache, dev → fix
    JavaScript (grammars-v4)   1,922,859               82,851                    1,728 → 1,654 ms
    600-rule COBOL             643,999                 52,633                    0.92 → 0.65 s
    Java (grammars-v4)         475,119                 0                         388 → 391 ms
    

    The 192,356 duplicates in the issue came from an earlier version of the COBOL grammar, after a change that only renumbered rules. grammars-v4's PL/SQL, MySQL, C# and Go grammars have no such duplicates, even with insertion order. In PL/SQL every predicate stands in front of a token, so prediction never combines two of them.

    The change

    AND and OR keep their operands in one order in every runtime: plain predicates by rule and predicate index, then precedence predicates by precedence, then nested operators. The constructors merge two already-sorted operand lists and compute the hash once. Equality, toString and evaluation follow that order, so every target builds the same cache and evaluates predicates in the same order.

    The public API and the serialized ATN are unchanged, and a grammar without such duplicates costs the same, as the Java grammar above shows. Three other differences between the targets go away:

    • Python, Go and JavaScript never reduced several precedence predicates to one, as Java does.
    • Go's equality ignored the operand count, so an AND whose operands were a prefix of another's compared equal.
    • Go and Swift no longer build a different cache on every run.

    I also measured the set comparison this PR started with. It removes the duplicates too, but building the cache took up to 2.5× longer than with sorted operands, and it leaves the evaluation order different in every target.

    Tests

    A new runtime test, SemPredEvalParser/PredicatesCombinedInEitherOrder, counts the predicate evaluations of a prediction that combines two predicates in both orders. Without the change it fails in Java, Python, JavaScript, Go, C#, Dart and C++, and in Swift some of the time. With the change it passes in every target. Java, Python, JavaScript, C++, Swift and Dart also get unit tests.

    #4991 now holds this change, one commit per runtime. PHP lives in its own repository and keeps insertion order too, so I'll open a PR there once this one is settled.

  7. knutwannheden commented on Oct 31, 2026

    @knutwannheden
    Author
  8. added a commit that references this issue on Nov 2, 2026
    89e984d
  9. knutwannheden commented on Nov 2, 2026

    @knutwannheden
    Author

    I've updated the PR now. The various runtimes handled this quite differently, but are now aligned.

  10. ericvergnaud commented on Nov 2, 2026

    @ericvergnaud
    Contributor

    Thanks for this.
    How do you explain the Java slowdown:
    Java (grammars-v4) 475,119 0 388 → 391 ms

  11. knutwannheden commented on Nov 4, 2026

    @knutwannheden
    Author

    It isn't a slowdown, it's run-to-run noise. The three runs behind that row took 383 to 389 ms on dev and 366 to 398 ms with the change, so one run with the change was faster than every dev run.

    There is also nothing for the change to cost on that grammar, because it hardly reaches the code it touches. With counters in the AND and OR constructors and their equals, a whole run (four passes over the 174 files, building the cache twice) creates no AND and 40 ORs, and never compares two of them, in both builds.

    To check, I measured again in 45 interleaved rounds, with a second copy of the dev build as a control:

    building the cache   median     middle 50%
    dev                  373.9 ms   372 – 380 ms
    dev, second copy     374.1 ms   367 – 382 ms
    #4991                374.4 ms   368 – 379 ms
    

    Round by round, #4991 was slower than dev in 21 rounds and faster in 24 (sign test p ≈ 0.8). The second copy of dev, running identical code, split 21 to 24 against dev as well.

  12. knutwannheden commented on Nov 4, 2026

    @knutwannheden
    Author

    A follow-up, because the Java grammar was a poor test of what the change costs: it hardly reaches the changed code at all. A better test is a grammar that combines many predicates but never makes contexts that differ only in operand order, so the change has nothing to deduplicate.

    Here are two such cases in Java, 30 interleaved rounds each. Every round also runs the dev build a second time, as a separate arm, so the gap between the two dev columns shows the run-to-run noise:

                                  ANDs / ORs        building the cache (median)
                                  built per run     dev        dev again  #4991
    C# (grammars-v4, 25 files)    2,832 / 134,022   1,247 ms   1,245 ms   1,233 ms
    reproducer, rule order 0      3,060 / 21,326    36.1 ms    36.3 ms    21.4 ms
    

    With the change, building the cache was faster in 24 of 30 rounds for C# (sign test p ≈ 0.001) and in all 30 for the reproducer. It also allocated less: 2,656 → 2,645 MB and 36.5 → 24.4 MB. Each constructor merges two sorted arrays and computes the hash once, where dev fills a HashSet.

    Parsing with the cache already built shows no clear difference. For C# the change was faster in 20 of 30 rounds. For the reproducer, #4991 takes a steady 17.8 ms per pass, while dev takes about 17.2 ms or about 20 ms depending on the run.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions