Reviewer · Algorithms
Avoid fragile algorithmic assumptions
When implementing pattern matching, tree/graph traversal, or conditional control-flow logic, avoid relying on incidental properties that happen to hold for today's inputs but are not structurally guaranteed. Make the algorithm's correctness independent of implementation details that are not part of its contract, and generalize special-case handling to cover...
When implementing pattern matching, tree/graph traversal, or conditional control-flow logic, avoid relying on incidental properties that happen to hold for today’s inputs but are not structurally guaranteed. Make the algorithm’s correctness independent of implementation details that are not part of its contract, and generalize special-case handling to cover the full equivalence class of inputs it is meant to address.
Concretely:
- For alternation/regex-style matching, don’t depend on leftmost-first ordering accidentally producing correct results (e.g.
sudomatching beforesuonly because of list order and a trailing boundary check). Sort or structure alternatives so the match outcome is order-independent, e.g."|".join(sorted(words, key=len, reverse=True)). - For recursive traversal over structured data (e.g. stripping a key from a JSON schema), identify the actual class of “name-keyed maps” (
properties,$defs,definitions,patternProperties, etc.) your algorithm must skip over, rather than special-casing a single observed instance. A fix that only coverspropertiesleaves the same bug reachable through$defswith a differently-named model. - When refactoring conditional guards (e.g. merging two independent
ifchecks into a nested one), explicitly enumerate the input domain (including non-standard values likemax_loops == "auto") and confirm every previously-reachable branch is still reachable after the change. - When sharing or duplicating data structures (e.g. schema dictionaries) across instances, be explicit about shallow vs. deep copies; aliasing a nested mutable object across two “distinct” structures reintroduces global mutable state and can cause cross-instance corruption.
Before merging an algorithmic fix, ask: “Does this generalize to the full class of inputs it claims to handle, or does it only patch the one example in the test?” Document any invariant the algorithm’s correctness depends on, and prefer approaches that remain correct even if that invariant is later violated (e.g., list reordering, new schema keywords, new conditional branches).</description> </invoke>