Skip to content

docs(521): replace history-narrating comments with the rule they protect - #674

Open
bhattmanthan wants to merge 4 commits into
awslabs:devfrom
bhattmanthan:docs/521-comment-cleanup
Open

bhattmanthan wants to merge 4 commits into
awslabs:devfrom
bhattmanthan:docs/521-comment-cleanup

Conversation

@bhattmanthan

Copy link
Copy Markdown

Issue Reference

Closes #521

Description of Changes

Replaces history-narrating comments ("CRITICAL FIX", "PHASE 3 FIX", "Subtask N", "HYBRID APPROACH") with the invariant each one protects, and fixes the stale structured_object_evaluator/README.md. Comments, docstrings and Markdown only; no behavior change.

Changes Made

  • Rewrote flagged comments in aggregate_metrics_calculator.py, comparable_field.py, comparison_engine.py, comparison_helper.py, configuration_helper.py, derived_metrics_calculator.py, evaluator_format_helper.py, structured_list_comparator.py, structured_model.py, and trees/base.py to state the rule each one enforces, keeping the related issue links
  • Shortened _ClassGatedComparator's docstring to the gating rule and the warning-replay reason, dropping the 40-line before/after score table.
  • Fixed structured_object_evaluator/README.md: corrected the install name, relinked ANLSTree to [RFC]: Resolve the parallel evaluation paths — trees/ (ANLSTree) vs ComparisonEngine #135, dropped the 2025 changelog-style section, named DerivedMetricsCalculator correctly, replaced the hand-copied API section with a link to the mkdocs API reference, and corrected the Dict[str, Any] limitation note

Why These Changes Are Needed

Many comments narrated how the code got here (review history, ticket/subtask numbers) rather than what it does, making the module harder for a newcomer to read. The package README had also drifted from the current code (wrong install name, wrong location for ANLSTree, a changelog entry masquerading as documentation, and an incorrect limitations claim).

Testing

  • All existing tests pass
  • Unit tests added/updated - not applicable, behavior-preserving comment/docs change
  • Integration tests added/updated - not applicable
  • Manual testing completed - ran uv run --frozen pytest -q: 6751 passed,
    13 skipped, 1 xfailed, no test files edited

Rewrite "CRITICAL FIX", "PHASE 3 FIX", "Subtask N" and "HYBRID APPROACH"
comments across structured_object_evaluator as the invariant they enforce,
keeping the issue links. Shorten _ClassGatedComparator's docstring to the
gating rule and the warning-replay reason, dropping the before/after score table.
Fix the package README: relink ANLSTree, drop the 2025 changelog section,
name DerivedMetricsCalculator, replace the hand-copied API section with a docs link,
and correct the dict-field limitation.

No code changes; full suite passes unmodified.

@vawsgit vawsgit left a comment

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.

needs changes

Checked at 87a781bb. The merge base is dev 0a4820f4.

Required (1):

  1. src/stickler/structured_object_evaluator/README.md:425: the example still says # ❌ Not supported - will raise an error. That contradicts the new text at :416-418 and the code. #521 names "will raise an error" as the wrong claim, so Closes #521 would close the issue with it still in place. Change :425 to say what happens, for example # ⚠️ Warns once and scores 0.0. Also reword or drop :440 ("This limitation ensures reliable, predictable comparison results."). Details are in the inline comment.

Verified: no change in behavior

  • AST check: I parsed each of the 10 .py files on dev and on the PR head and compared ast.dump, which ignores comments. With docstrings removed, all 10 are identical. With docstrings kept, 7 are also identical. The other 3 change only docstrings: comparison_helper.py, structured_list_comparator.py and structured_model.py. Nothing in src/ reads __doc__.
  • Full suite on dev 0a4820f4, using dev's own src and tests: 6768 passed, 3 skipped, 1 xfailed.
  • Full suite on the PR head 87a781bb, using the PR's own src and tests: 6768 passed, 3 skipped, 1 xfailed.
  • tests/test_docs_build.py on the PR head: 77 passed. ruff check src/stickler/structured_object_evaluator passes on both trees.

Each rewritten comment checked against the code on the head:

  • _ClassGatedComparator: the wrapper is installed when either list holds a plain model (_holds_a_plain_model). _judges is _is_plain_model(gt) or _is_plain_model(pred). warn_for_selected replays the gate only on matched_pairs. The docstring states all three correctly.
  • structured_model.py docstring: "a mapping, a plain BaseModel, and a list of either" matches is_object_grade_annotation (is_dict_field_type, _is_list_of_mappings, is_plain_model_field_type, _is_list_of_plain_models). The model_fields / PEP 563 comment is now one paragraph and is correct. This hunk is inside _install_object_grade_comparators (:627), not the excluded __init_subclass__ (:770).
  • comparison_engine.py: field_comparisons is collected when it is missing, and ConfidenceCalculator.extract still raises ValueError("No field comparisons found ...") (confidence/calculator.py:53).
  • from_json_schema: validate_json_schema is a Draft7Validator check, so "Validate against the JSON Schema spec" is right.
  • structured_list_comparator.py, configuration_helper.py, comparable_field.py, the calculators, evaluator_format_helper.py and trees/base.py: each new comment describes the code next to it.

README checked against dev (PYTHONPATH=<dev>/src):

  • A Dict[str, Any] field with LevenshteinComparator: the class builds with no error. Comparing two identical dicts scores 0.0 and gives one warning ("Field 'attributes' holds a mapping, but its comparator (LevenshteinComparator) scores scal..."). The same field with no comparator gets ANLSStarComparator. The new prose at :416-418 is right.
  • DerivedMetricsCalculator.add_derived_metrics_to_result exists (derived_metrics_calculator.py:49). anls_score does take threshold. docs/docs/API-Reference/api.md exists, so the link has a page. #135 is the RFC about trees/ vs ComparisonEngine.
  • The install line already read pip install stickler-eval on dev, so the PR needed no change there.

#521's done-when grep on the head returns only configuration_helper.py:82 and field_converter.py:746. Both are lines the ticket excludes. #516 has removed field_comparator.py:133. The net reduction is 167 lines (the ticket expects about 120). None of the excluded sections are touched.

Optional, not blocking:

  • README.md API Reference: "both missing from this section previously" describes history, which is what this ticket removes. "See the generated API reference for StructuredModel, anls_score, and compare_json." would be enough.
  • comparison_helper.py _ClassGatedComparator docstring: "see #321" now sits next to the pair-population rule. #321 is about whether a refused element should pair at all, which is a different question.
  • comparison_engine.py:337 has a trailing space after "here.". Ruff does not flag it.

No CI checks are reported on this head.

Dictionary fields (`Dict[str, Any]`) with text-based comparators like `LevenshteinComparator` are not supported as they would produce unpredictable results.
A `Dict[str, Any]` field given a text comparator like `LevenshteinComparator` warns once and
scores 0.0 rather than comparing meaningfully (see [#297](https://github.com/awslabs/stickler/issues/297)).
A dict field with no comparator named gets `ANLSStarComparator` instead.

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.

Required. This new text is right, but the example 7 lines below still says # ❌ Not supported - will raise an error (:425). #521 names that exact claim as wrong, and the PR says Closes #521.

Measured on dev 0a4820f4 (PYTHONPATH=<dev>/src), with a field attributes: Dict[str, Any] = ComparableField(comparator=LevenshteinComparator(), threshold=0.7):

class def: ok, warnings at def: 0
score identical dicts: 0.0 {'attributes': 0.0}
warnings total: 1 ["Field 'attributes' holds a mapping, but its comparator (LevenshteinComparator) scores scal..."]

Please change :425 to something like # ⚠️ Warns once and scores 0.0 -- not a meaningful comparison. :440 ("This limitation ensures reliable, predictable comparison results.") also no longer fits, because no error is raised. Drop it or reword it.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ac57e13

@sromoam sromoam left a comment

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.

Thanks @bhattmanthan, and thanks for the quick turnaround. I checked ac57e13 against current dev (ce0f710b), and tests/structured_object_evaluator (3723 passed) and tests/test_docs_build.py (77 passed) pass at this head.

vawsgit's required item is resolved: README.md:425 now says what happens, :440 is gone, and the new wording still holds on current dev (one warning, 0.0 against an identical copy). Their three optional notes are still open. I'd take the first two, since "previously" is the kind of text #521 removes and #321 is a different question from the pair rule. Smaller 2 and the inline suggestion on comparison_helper.py:36-38 cover them.

Must fix

  1. The rewritten _install_object_grade_comparators docstring states a rule the code doesn't keep (structured_model.py:655-658). "None is substituted at read time alone" is false for a field whose annotation resolves only after the class is defined, and get_comparison_info keeps a read-time copy of the substitution for exactly that case (configuration_helper.py:757-778). A forward-referenced plain-model field, completed by model_rebuild(), scores with ANLSStarComparator and clip off but exports LevenshteinComparator with clip on, and its round trip scores 0.0 where the original scores 0.5. Someone who trusts the docstring could delete that fallback as dead code. Repro and suggestion inline.

Smaller

  1. (#316) should be (#319) (structured_model.py:677). Suggestion inline.
  2. The API Reference link sends StructuredModel readers to the wrong page (README.md:392-395). Suggestion inline.

One heads-up: we're not merging anything outside the 1.1.0 milestone until 1.1.0 lands, so this will wait until after that even once it's ready. It also conflicts with dev now, in structured_model.py at the #316 comment, where #670 added a list-of-tuples branch under it. #688 and #690 in 1.1.0 touch that file too, so please bring dev in after 1.1.0 lands rather than now. When you do, keep dev's tuple paragraph and its object_grade / ExactComparator code as they are, and replace only the #316 paragraph.

Comment on lines +655 to +658
All four object-grade shapes (a mapping, a plain `BaseModel`, and a
list of either) take this one path (#319); none is substituted at
read time alone, which would let the exported schema disagree with
the engine for that shape.

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.

Must fix 1. This holds for every field whose annotation has resolved when the class is defined, but not for one that resolves later. get_comparison_info substitutes at read time for that case (configuration_helper.py:757-778), and the export then disagrees with the engine. At this head:

class Outer(StructuredModel):
    item: "Inner" = ComparableField()

class Inner(BaseModel):
    a: str
    b: int

Outer.model_rebuild()

class Direct(StructuredModel):
    item: Inner = ComparableField()
        get_comparison_info                to_json_schema()
Outer   ANLSStarComparator, clip False     LevenshteinComparator, clip True
Direct  ANLSStarComparator, clip False     ANLSStarComparator, clip False

Round-tripping Outer through to_json_schema() and from_json_schema() then scores item {"a": "alpha", "b": 1} against {"a": "alpha", "b": 2} 0.0 with a "holds a mapping" warning, where Outer itself scores the same pair 0.5. dev behaves the same, so the PR doesn't need to change the behaviour, only describe it:

Suggested change
All four object-grade shapes (a mapping, a plain `BaseModel`, and a
list of either) take this one path (#319); none is substituted at
read time alone, which would let the exported schema disagree with
the engine for that shape.
All four object-grade shapes (a mapping, a plain ``BaseModel``, and a
list of either) take this one path (#319) when the annotation has
resolved by class definition. A field whose annotation resolves only
later, such as a forward reference completed by ``model_rebuild()``,
misses it and is substituted at read time by
``ConfigurationHelper.get_comparison_info`` instead.

# comparator at definition time changes what `to_json_schema()` exports
# for that shape -- which is exactly the reader alignment this branch is
# for. All four object-grade shapes now take the one path.
# All four object-grade shapes take this one path (#316): installing

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.

#316 is the threshold PR that deferred this widening. The four shapes took one path in #319, which the docstring above now cites.

Suggested change
# All four object-grade shapes take this one path (#316): installing
# All four object-grade shapes take this one path (#319): installing

Comment on lines +392 to +395
See the generated [API reference](https://awslabs.github.io/stickler/API-Reference/api/) for
`StructuredModel`, `anls_score`, and `compare_json` with their full signatures and options —
including `compare_with`'s options and `anls_score`'s `threshold` parameter, both missing from
this section previously.

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.

StructuredModel and compare_with render on the Models page. API-Reference/api/ has only compare_structured_models, anls_score and compare_json, and its own tip sends readers on to Models. This also drops the "previously" clause:

Suggested change
See the generated [API reference](https://awslabs.github.io/stickler/API-Reference/api/) for
`StructuredModel`, `anls_score`, and `compare_json` with their full signatures and options —
including `compare_with`'s options and `anls_score`'s `threshold` parameter, both missing from
this section previously.
See the generated API reference for full signatures and options:
[Models](https://awslabs.github.io/stickler/API-Reference/models/) for `StructuredModel`
(including `compare_with`), and [API](https://awslabs.github.io/stickler/API-Reference/api/)
for `anls_score` and `compare_json`.

Comment on lines +36 to +38
at least one element of EITHER list is a plain model; `_judges` below
decides which PAIRS it then applies to (a pair with a plain model on at
least one side, #327's cross-class rule otherwise left alone, see #321).

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.

For vawsgit's #321 note, a wording that keeps #321 apart from the pair rule and says which pairs are delegated untouched:

Suggested change
at least one element of EITHER list is a plain model; `_judges` below
decides which PAIRS it then applies to (a pair with a plain model on at
least one side, #327's cross-class rule otherwise left alone, see #321).
at least one element of EITHER list is a plain model; `_judges` below
then judges only a pair with a plain model on at least one side. A pair
with neither (dict against dict, `StructuredModel` against
`StructuredModel`) is delegated untouched, so #327's open cross-class
rule is not applied to it. See #321 for whether a refused element should
pair at all.

- structured_model: document that a forward-referenced plain-model field (resolved via model_rebuild()) misses the definition-time install and is substituted at read time by get_comparison_info
- structured_model: correct comment reference awslabs#316 -> awslabs#319
- README: point StructuredModel/compare_with to the Models API page and drop the "previously" wording
- comparison_helper: clarify which pairs _ClassGatedComparator delegates untouched and keep awslabs#321 separate from the pair rule
@bhattmanthan

Copy link
Copy Markdown
Author

Thanks @sromoam, applied all four suggestions as written in 856406d: the forward-reference docstring caveat, #316 -> #319, the API Reference links, and the ClassGatedComparator wording. ruff and the structured_object_evaluator and docs-build tests pass locally.

I'll bring dev in after 1.1.0 lands and keep dev's tuple paragraph as you described.

@vawsgit vawsgit left a comment

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.

✅ LGTM!

Checked at 856406d8 (full SHA 856406d8a4258035c975db2eb3283067c79ba7ba). Merge base is dev 0a4820f4. dev is now 2cde48fa (1.1.0).

Earlier findings, all cleared

  • My required item (README.md:425, "will raise an error"): the line now reads # ⚠️ Warns once and scores 0.0 -- not a meaningful comparison, and the "reliable, predictable comparison results" sentence is gone. At this head, a Dict[str, Any] field with LevenshteinComparator builds with no warning, scores two identical dicts 0.0, and gives one warning in total.
  • My optional notes: the "previously" wording is gone (README.md:392-395), and #321 is now separate from the pair rule in comparison_helper.py:36-41.
  • sromoam's must-fix (structured_model.py:655-658): the docstring now says a forward-referenced field completed by model_rebuild() is substituted at read time by ConfigurationHelper.get_comparison_info. I ran the Outer / Inner / Direct example from that thread at this head. Outer gives ANLSStarComparator from get_comparison_info and LevenshteinComparator from to_json_schema(). Direct gives ANLSStarComparator from both. So the docstring now matches the code.
  • sromoam's smaller items: #316 is now #319 (structured_model.py:679), and the README links the Models page for StructuredModel and compare_with. Both pages exist (docs/docs/API-Reference/models.md, api.md).

No change in behavior

  • AST comparison of the 10 changed .py files, merge base against head: with docstrings removed, all 10 are identical. With docstrings kept, 7 are identical and 3 differ only in docstrings (comparison_helper.py, structured_list_comparator.py, structured_model.py). No code under src/ reads __doc__.
  • Full suite at the PR head with its own src: 6751 passed, 13 skipped, 1 xfailed. This matches the PR body. The skips are optional extras that were not installed here.
  • tests/test_docs_build.py: 77 passed. ruff check src/stickler/structured_object_evaluator: all checks passed.
  • #521's done-when grep (CRITICAL FIX, PHASE 3, Subtask N, HYBRID APPROACH) in .py files returns only configuration_helper.py:82 and field_converter.py:746. #521 excludes both lines, and the PR leaves them untouched.

Merge conflict with dev (not a reason to hold the approval)
GitHub reports the PR as conflicting. A trial merge onto dev 2cde48fa conflicts in one file, models/structured_model.py, in two hunks inside _install_object_grade_comparators. The other 10 files merge cleanly. Per the maintainer's note, bring dev in after 1.1.0 lands.

  1. First hunk (PEP 563 / model_fields comment): keep this PR's shorter comment and keep dev's added note_deferred_clip_fields(...) paragraph and code.
  2. Second hunk (the #316 comment): dev replaced the continue below it with a List[StructuredModel] clip-only branch (#415) and a tuple/set ExactComparator branch (#659). Do not paste "All four object-grade shapes take this one path (#319)" above code that now branches into other shapes. Reword it for what dev does, and keep dev's code as is.

Optional, not blocking

  • comparison_engine.py:338: trailing space after "here." (git diff --check flags it).
  • comparison_helper.py:40-41: #321 is closed, and its closing comment says the open question now lives in #327, which the docstring already cites two lines earlier. "See #327" would avoid the redirect.

@sromoam sromoam added the anytime Non-breaking improvement off the release critical path: merge whenever it's ready label Dec 4, 2026
@bhattmanthan

Copy link
Copy Markdown
Author

Merged dev after 1.1.0 (3772fa4). Conflicts were in structured_model.py and
structured_list_comparator.py: I kept dev's code as-is (including the tuple
paragraph and the object_grade / ExactComparator path), replaced only the
#316 comment paragraph, and dropped the "PHASE 3 FIX" docstring prefix.

The diff against dev is comments, docstrings and README only (AST-identical
once docstrings are ignored). ruff and the tests pass locally. This should be
ready for another look, @sromoam.

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

anytime Non-breaking improvement off the release critical path: merge whenever it's ready

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Replace history-narrating comments with the rule they protect, and fix the stale structured_object_evaluator README

3 participants