Skip to content

docs(288): state which confusion-matrix rollup node answers which question - #295

Merged
sromoam merged 13 commits into
devfrom
docs/288-overall-vs-aggregate
Sep 9, 2026
Merged

sromoam merged 13 commits into
devfrom
docs/288-overall-vs-aggregate

Conversation

@sromoam

@sromoam sromoam commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Closes the documentation half of #288.

The problem

confusion_matrix.overall and confusion_matrix.aggregate were described only mechanically:

overall reflects this node's own direct classification.
aggregate sums all primitive-field classifications beneath this node.

Both accurate, and no help. Nothing said which to read for which question, or that they diverge on any model with nesting. So consumers picked by guessing, and the AWS Solutions Library IDP Accelerator picked overall, which scores 100% on any document whose line items merely paired (their #625, surfacing as a parent field showing a tick while its own drilldown showed a cross).

What the nodes actually are

They are the two stages of the evaluation:

  • overall is detection. Unit is the object. Did we find the right things?
  • aggregate is extraction. Unit is the leaf. Among objects established to be the same object, were the values right?

match_threshold is the handoff, and it is really the definition of "the same object". Above it, grading the fields is meaningful. Below it, grading them would be scoring the fields of a different object, so such an object is one FD and is not descended into.

Five line items of six fields each, one field wrong. The item scores 5/6 and is comparable:

overall_score   0.9667

cm['overall']     tp=5   fd=0   P=1.0000  R=1.0000  F1=1.0000
cm['aggregate']   tp=29  fd=1   P=0.9667  R=1.0000  F1=0.9831

Five objects found, none spurious. Thirty leaves, one wrong. Both numbers correct for their own question.

Drop the same item to 4/6 and it is no longer the same object:

cm['overall']     tp=0   fd=1
cm['aggregate']   tp=0   fd=1

The nodes now agree, because there is no accepted subtree to expand. They coincide in exactly two situations: a flat model, and a subtree rejected outright.

Grounding this in mAP rather than arguing it

This is the same match-then-score structure as mean Average Precision, which this repo already implements for bounding boxes. docs/docs/Advanced/bbox-map-metrics.md:191 already states the same rule for IoU:

A below-threshold detection counts as both a false positive and a false negative (the prediction is in the wrong place, and the ground-truth box is left unmatched).

So the rule is not new and not specific to objects; the objects path was simply the one without an explanation. Both new sections cross-link to bbox-map-metrics.md#iou-thresholds instead of re-arguing it. Nobody expects an unmatched detection to contribute per-attribute errors, and the reasoning is identical.

Getting leaf detail for a marginal object

The knob is match_threshold itself, which the docs now say and a test pins:

match_threshold   comparable?   aggregate
0.70              no            tp=0 fd=1
0.66              yes           tp=4 fd=2

What changed

file change
docs/docs/Guides/Evaluation/understanding-results.md rewrote the overall vs aggregate section: both examples, the remedy table, a which-node-for-which-question table, the two-node failure check
docs/docs/Advanced/aggregate-metrics.md new "Which node answers which question" section under the existing mechanical note
docs/docs/Advanced/classification-logic.md one paragraph noting the derived metrics are per node, so the node choice changes the precision you report
compare_with() docstrings structured_model.py and comparison_engine.py, both published to the API reference
tests/structured_object_evaluator/test_rollup_node_semantics.py new, 9 tests

Tests

The new file pins the numbers this PR publishes, so the pages cannot go stale, plus the behaviour they describe:

  • the worked example's counts and all three derived metrics on both nodes
  • that overall_score tracks aggregate and not overall (the claim the docs rest on)
  • that a rejected object reports itself and not its leaves, and that leaf rows stop as soon as an object drops below the threshold
  • that lowering match_threshold exposes those leaves, which is the documented remedy
  • the flat-model case where the nodes converge, which is why this is easy to miss

Not in scope

EvalResult.precision, .recall, .f1 and .accuracy read overall.derived, so they are the object-level metrics. On the example above result.precision is 1.0 beside an overall_score of 0.9667 on the same object. That is two correct answers to two different questions, and it is documented here rather than changed.

What #288 still leaves open for 1.0 is naming. overall reads as "everything" when it means "one level, one unit". by_object / by_field or detection / extraction would carry the distinction that the current names actively hide. Renaming is breaking, so it is a 1.0 decision and not this PR.

Whether aggregates should also count the leaves of below-threshold objects is a separately deferred question, and is deliberately not treated here as a defect.

Verification

  • 1975 passed, 2 skipped
  • ruff check clean
  • mkdocs build --strict adds no new warnings (it already fails on 9 pre-existing griffe and autorefs findings in untouched files, count identical to dev)
  • both new cross-links verified to resolve against the #iou-thresholds anchor in the built site

Merge order

Please land #290 first. Both branches edit understanding-results.md in adjacent sections, so git should merge them cleanly, but I would rather reread the merged page as a whole than trust the diff. I will rebase this onto dev once #290 is in.

@sromoam
sromoam requested a review from vawsgit August 28, 2026 00:28
@github-actions

github-actions Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-09-09T18:29:13+00:00
  • Time since scan: 2 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-09-09T18:26:21+00:00
  • ASH version: 3.1.2

Summary

Scanner Results

The table below shows findings by scanner, with status based on severity thresholds and dependencies:

  • Severity levels:
    • Suppressed (S): Findings that have been explicitly suppressed and don't affect scanner status
    • Critical (C): Highest severity findings that require immediate attention
    • High (H): Serious findings that should be addressed soon
    • Medium (M): Moderate risk findings
    • Low (L): Lower risk findings
    • Info (I): Informational findings with minimal risk
  • Duration (Time): Time taken by the scanner to complete its execution
  • Actionable: Number of findings at or above the threshold severity level that require attention
  • Result:
    • PASSED = No findings at or above threshold
    • FAILED = Findings at or above threshold
    • MISSING = Required dependencies not available
    • SKIPPED = Scanner explicitly disabled
    • ERROR = Scanner execution error
  • Threshold: The minimum severity level that will cause a scanner to fail
    • Thresholds: ALL, LOW, MEDIUM, HIGH, CRITICAL
    • Source: Values in parentheses indicate where the threshold is set:
      • global (global_settings section in the ASH_CONFIG used)
      • config (scanner config section in the ASH_CONFIG used)
      • scanner (default configuration in the plugin, if explicitly set)
  • Statistics calculation:
    • All statistics are calculated from the final aggregated SARIF report
    • Suppressed findings are counted separately and do not contribute to actionable findings
    • Scanner status is determined by comparing actionable findings to the threshold
Scanner Suppressed Critical High Medium Low Info Actionable Result Threshold
bandit 0 3 0 0 5321 0 3 FAILED MEDIUM (global)
cdk-nag 0 0 0 0 0 0 0 PASSED MEDIUM (global)
cfn-nag 0 0 0 0 0 0 0 MISSING MEDIUM (global)
checkov 0 0 0 0 0 0 0 PASSED MEDIUM (global)
detect-secrets 0 1 0 0 0 0 1 SKIPPED MEDIUM (global)
grype 0 0 0 0 0 0 0 MISSING MEDIUM (global)
npm-audit 0 0 0 0 0 0 0 PASSED MEDIUM (global)
opengrep 0 0 0 0 0 0 0 MISSING MEDIUM (global)
semgrep 3 0 0 0 0 0 0 PASSED MEDIUM (global)
syft 0 0 0 0 0 0 0 MISSING MEDIUM (global)

Top 2 Hotspots

Files with the highest number of security findings:

Finding Count File Location
2 tests/comparators/test_anls_leaf_semantics.py
2 tests/structured_object_evaluator/test_rollup_node_semantics.py

Detailed Findings

Show 4 actionable findings

Finding 1: SECRET-HEX-HIGH-ENTROPY-STRING

  • Severity: HIGH
  • Scanner: detect-secrets
  • Rule ID: SECRET-HEX-HIGH-ENTROPY-STRING
  • Location: tests/comparators/test_anls_leaf_semantics.py:89

Description:
Secret of type 'Hex High Entropy String' detected in file 'tests/comparators/test_anls_leaf_semantics.py' at line 89

Code Snippet:

Secret of type Hex High Entropy String detected

Finding 2: B108

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B108
  • Location: tests/comparators/test_anls_leaf_semantics.py:210-212

Description:
Probable insecure usage of temp file/directory.

Code Snippet:

uuid.UUID(int=1),
            pathlib.Path("/tmp/x"),
            b"bytes",

Finding 3: B307

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B307
  • Location: tests/structured_object_evaluator/test_rollup_node_semantics.py:1343-1349

Description:
Use of possibly insecure function - consider using safer ast.literal_eval.

Code Snippet:

def published_label(node: dict, section: str, object_lists: set) -> str:
            counts_objects = eval(  # noqa: S307
                cond.group(1),
                {},
                {"data": node, "section": section, "OBJECT_LISTS": object_lists},
            )
            return eval(unit.group(1), {}, {"counts_objects": counts_objects})  # noqa: S307

Finding 4: B307

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B307
  • Location: tests/structured_object_evaluator/test_rollup_node_semantics.py:1348-1350

Description:
Use of possibly insecure function - consider using safer ast.literal_eval.

Code Snippet:

)
            return eval(unit.group(1), {}, {"counts_objects": counts_objects})  # noqa: S307

Report generated by Automated Security Helper (ASH) at 2026-09-09T18:29:14+00:00

@sromoam
sromoam force-pushed the docs/288-overall-vs-aggregate branch from 53c57f1 to 972e70d Compare September 3, 2026 17:58
@sromoam

sromoam commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current dev (972e70d), now mergeable. Only CHANGELOG.md conflicted.

Re-verified after #285, #301 and #308 landed, since the whole point of this PR is a table of numbers:

one bad leaf inside a paired list item
  overall     tp=1  fd=0     pairing succeeded
  aggregate   tp=1  fd=1     the leaf failure is here

2048 passed, 12 skipped, ruff clean, mkdocs warnings unchanged from dev, and the 9 tests in test_rollup_node_semantics.py all pass.

One thing worth knowing while reviewing: this PR's explanation is what resolves #275 as well. I ran that issue's downstream scenario on dev and the leaf failure is reported, on aggregate. The "self-contradictory report" the IDP Accelerator hit was reading overall for a question only aggregate answers. So this is not only documentation, it is the answer to an open downstream bug.

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

This is the explanation the two rollup nodes have needed, and the framing is the right one. Naming them detection and extraction and then grounding the gate in the mAP structure the repo already implements turns "why does aggregate skip those leaves" from an argument into a citation, and the cross-link to bbox-map-metrics.md#iou-thresholds is a much better answer than re-deriving it. Pinning the published numbers in test_rollup_node_semantics.py so the pages cannot drift is exactly right, and the EvalResult.precision note (precision 1.0 beside overall_score 0.9667) is the single most useful paragraph here for anyone in the IDP Accelerator's position. Scope discipline is good too: the rename and the "should aggregates descend anyway" question are named and deferred rather than smuggled in.

I checked the numbers against the code rather than reading them, and three of the published artefacts do not hold. The blocker is the clean snippet, because it is copy-paste guidance that answers "did anything fail" with no on a document containing a hallucinated value — the exact failure mode this PR exists to prevent, one node over. The two worked-example tables print numbers from a different document than the prose describes; both are label fixes, but they are the numbers a reader reproduces first, and they are also the two tables the new tests do not pin.

Verified locally on this branch: 2048 passed, 12 skipped; the 9 new tests pass; ruff check's 16 findings are all pre-existing in examples/notebooks/, none from this diff; the #iou-thresholds and #which-node-answers-which-question anchors both resolve.

Everything below is markdown-only except the last two, and none of it touches the argument — happy to re-approve as soon as the snippet and the two tables agree with the engine.

Comment on lines +149 to +156
```python
clean = (
cm['aggregate']['fd'] + cm['aggregate']['fn'] == 0
and cm['overall']['fd'] + cm['overall']['fn'] + cm['overall']['fa'] == 0
)
```

`overall` is the only node carrying `fa`, the fields the prediction invented, since those correspond to no ground truth leaf.

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.

This check reports clean on a document with an invented value. aggregate does carry fa: AggregateMetricsCalculator.calculate_aggregate_metrics sums "fa" along with the other five counts, both when rolling child aggregates into a parent (aggregate_metrics_calculator.py:144) and at leaves (:169). And a leaf whose ground truth is null while the prediction supplies a value is scored fa=1 at that leaf (confusion_matrix_calculator.py:226) — so an invented value does correspond to a ground-truth leaf, and lands on aggregate, not on the root overall.

Ran this against the branch: one line item, ground truth total=None, prediction total="INVENTED", remaining five leaves exact:

overall     tp=1  fp=0  fn=0  fa=0  fd=0
aggregate   tp=5  fp=1  fn=0  fa=1  fd=0
leaf total  tp=0  fp=1  fn=0  fa=1  fd=0

clean -> True        # aggregate['fa'] == 1

The pairing survives at 5/6, so the root overall never sees the hallucination, and the snippet skips aggregate['fa']. A reader who adopts this as their gate ships hallucinated fields as clean — the same shape of miss as reading overall alone, which is what the page is here to stop.

Smallest fix is to sum fp, which is fa + fd by construction and cannot go stale if a new class is added:

clean = (
    cm['aggregate']['fp'] + cm['aggregate']['fn'] == 0
    and cm['overall']['fp'] + cm['overall']['fn'] == 0
)

That also retires the closing sentence, which reads the wrong way round: overall is the only node carrying fa for a field the prediction invented wholesale, while aggregate is the only node carrying it for an invented value inside a matched object. test_a_complete_failure_check_reads_both_nodes (line 233) passes only because its fixture has no FA at all, so it pins the snippet's shape without exercising the case that breaks it — worth adding the null-ground-truth pair there.

Comment on lines +126 to +135
#### Asking whether anything failed

Because the nodes scope different things, a complete check reads both. `overall` is also the only node carrying `fa`, since an invented field corresponds to no ground truth leaf:

```python
clean = (
cm['aggregate']['fd'] + cm['aggregate']['fn'] == 0
and cm['overall']['fd'] + cm['overall']['fn'] + cm['overall']['fa'] == 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.

Same snippet and same fa claim as understanding-results.md:149-156 — see the detail there. Both copies need the fix, and this one states it as "overall is also the only node carrying fa", which is the stronger and equally untrue form. A leaf with null ground truth and a populated prediction is fa=1 at the leaf and rolls into aggregate; the root overall shows fa=0.

Comment thread docs/docs/Advanced/aggregate-metrics.md Outdated
Comment on lines +107 to +114
Drop the same item below the threshold (two fields wrong, so 4/6) and it becomes a rejected object:

```
cm['overall'] tp=0 fd=1
cm['aggregate'] tp=0 fd=1
```

The two nodes now agree, because there is no accepted subtree to expand. They coincide in exactly two situations: a model with no nesting, and a subtree that was rejected outright.

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.

"Drop the same item" prints a different document's numbers. Taking the five-item invoice from directly above and pushing item 2 to 4/6 gives, on this branch:

overall_score   0.9333
overall     tp=4  fd=1  fn=0   P=0.8000  R=1.0000  F1=0.8889
aggregate   tp=24 fd=0  fn=0   P=1.0000  R=1.0000  F1=1.0000

tp=0 fd=1 on both nodes is a one-item document (which is what test_a_rejected_object_reports_itself_and_not_its_leaves builds). So the conclusion drawn from it inverts on the stated data: the nodes do not "now agree" — they diverge further, and aggregate reports a flawless P=1.0000 precisely because the rejected item contributes no leaf rows.

That divergence is a better illustration than the one printed, and it is the same trap as the overall-only reading at one level down. Either say the document is a single item, or keep the five and print 4/1 against 24/0 and note that aggregate alone now looks clean. The follow-on sentence needs a matching narrowing too: they coincide when there is no nesting, or when every subtree is rejected.

Comment on lines +126 to +136
#### Getting leaf detail for a marginal object

If you want those leaves counted, lower `match_threshold` so the object qualifies as comparable. Same data as above:

```
match_threshold comparable? overall aggregate
0.70 no tp=0 fd=1 tp=0 fd=1
0.66 yes tp=1 fd=0 tp=4 fd=2
```

At `0.66` the object is comparable, so its six leaves are scored individually and the two bad ones appear as `fd`. This is the knob for how much leaf detail you get: `match_threshold` decides what counts as the same object, and leaf reporting follows from that.

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.

"Same data as above" is not the same data. The example above is two items of six fields with the second at 4/6. Re-running that pair at both thresholds:

0.70   overall tp=1 fd=1     aggregate tp=6  fd=0
0.66   overall tp=2 fd=0     aggregate tp=10 fd=2

The table's tp=0 fd=1 / tp=1 fd=0 / tp=4 fd=2 is the one-item document, and the sentence after it ("its six leaves are scored individually") only holds there — the two-item document has twelve. The 0.70 row also contradicts the block six lines up, which correctly prints overall tp=1 fd=1 for this data.

The remedy itself is right and is the useful part; it just needs its own setup named ("one item of six fields, two wrong"), or the numbers recomputed for two. Worth pinning whichever you choose in test_rollup_node_semantics.py, since this table and the one in aggregate-metrics.md:107 are the only published figures the new tests do not cover — the gap both errors came through.

The `aggregate` field exists at every node in the confusion matrix hierarchy, making it easy to get field-level granularity at any depth.
`match_threshold` is the handoff, and it is really the definition of "the same object". Above it, the pair is the same thing, so grading its fields is meaningful. Below it, it is not the same thing, so grading its fields would be scoring the fields of a *different* object. Such an object is classified as a single **false discovery** and is not descended into.

If that split is familiar, it should be: it is the structure of mean Average Precision, which Stickler also implements for bounding boxes. An IoU threshold decides whether a detection matched, and only matched pairs are scored further. See [Bounding Box mAP Metrics](../../Advanced/bbox-map-metrics.md#iou-thresholds).

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.

The mAP analogy is the right move, but it is worth a half-sentence on where the objects path stops matching it, because the difference cuts against the reader. bbox-map-metrics.md:191 — quoted in the PR description — has a below-threshold detection count as both FP and FN, so recall falls. Here a rejected pairing is FD only:

five items, one rejected
  recall_with_fd=False   overall tp=4 fd=1 fn=0  R=1.0000
  recall_with_fd=True    overall tp=4 fd=1 fn=0  R=0.8000

So by default the ground-truth item that went unmatched leaves no trace in recall, and overall's recall reads 1.0 on a document with a spurious pairing. A reader who accepts "the reasoning here is identical" will expect recall to drop and it will not. Naming recall_with_fd=True here — it is already a compare_with parameter and the closest thing to the mAP convention — makes the parallel hold and points at the knob.

The `confusion_matrix` object has four keys:

- **`overall`** -- Object-level metrics for the current hierarchical level.
- **`overall`** -- Object-level metrics for the current hierarchical level. Counts item pairings, not leaves.

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.

"Counts item pairings, not leaves" is true only where there is a list. overall is the sum of this node's direct children's classifications (comparison_engine.py:165), so on a flat model the root overall counts leaves — which is what test_the_nodes_converge_when_there_is_no_list asserts with overall tp == aggregate tp == 5. As written, the bullet contradicts the convergence case the page later leans on. "Counts this level's direct classifications — item pairings where the field is a list" keeps it accurate in both shapes.

- **`fields`** -- Field-by-field breakdown, with nested structure for objects and lists.
- **`non_matches`** -- Populated when `document_non_matches=True` (empty otherwise).
- **`aggregate`** -- Sum of all primitive field metrics recursively below this node.
- **`aggregate`** -- Primitive field metrics summed recursively below this node, for the subtrees the traversal reached. See the caveat below.

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.

Nit: "See the caveat below" has no landing spot — no heading or admonition below is labelled as the caveat, and the thing being pointed at (rejected subtrees are not descended into) is three paragraphs into the next section. Either link the section by anchor or state it inline: "...below this node, excluding subtrees rejected at match_threshold". Given the caveat is the whole point of the page edit, it is worth not making the reader hunt for it.

Comment on lines +217 to +230
def test_overall_score_agrees_with_aggregate_and_not_with_overall(
self, one_bad_leaf_of_thirty
):
"""The claim the docs rest on.

`overall_score` is a weighted mean over the whole tree, so it tracks the
leaf view. Reporting `overall.derived` precision beside `overall_score`
puts two numbers in the same report that disagree by construction.
"""
cm = one_bad_leaf_of_thirty["confusion_matrix"]
score = one_bad_leaf_of_thirty["overall_score"]

assert score == pytest.approx(0.9667, abs=1e-4)
assert score == pytest.approx(cm["aggregate"]["derived"]["cm_precision"])

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.

The != half of this is the load-bearing claim and it is solid. The == half is incidental to this fixture rather than a property: overall_score is a weighted mean of leaf scores, while cm_precision is tp/(tp+fp), and they coincide here only because every leaf is exact-match, weights are uniform and there are no FN. The page's own second example separates them — two items with the second at 4/6 gives overall_score=0.8333 against aggregate precision 1.0000.

Worth either asserting the documented figure directly (score == approx(0.9667), which the line above already does) or noting in the docstring that the equality is a coincidence of this fixture. As it stands the test name asserts a general relationship ("agrees with aggregate") that a maintainer could reasonably rely on and that does not hold once a subtree is rejected.

Comment thread CHANGELOG.md Outdated
under review for 1.0 in
[#288](https://github.com/awslabs/stickler/issues/288).


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.

Nit: two blank lines before ## [0.7.0]; every other release heading in the file has one. Moving ### Performance below ### Changed to sit beside the new ### Documentation matches the 0.6.0 ordering, so no objection to the reshuffle itself.

`confusion_matrix.overall` and `confusion_matrix.aggregate` were described only
mechanically ("this node's own direct classification" / "sums all
primitive-field classifications beneath"). Accurate, and no help: nothing said
which to read for which question, or that they diverge on any model with
nesting.

They answer two different questions. `overall` gives object verdicts: was this
pairing genuine, or spurious. `aggregate` gives leaf detail for the objects that
were comparable. `match_threshold` is the line between them, and the gating is
deliberate: an object scoring below it is one FD, a spurious non-match, and is
not descended into, because reporting the leaves of an object already rejected as
a whole would score something declared not comparable.

    5 items x 6 leaves, one leaf wrong, item scores 5/6 -> comparable
      overall     tp=5   fd=0    P=1.0000     5 comparable objects, none spurious
      aggregate   tp=29  fd=1    P=0.9667     30 leaves, one wrong

    same item at 4/6 -> rejected
      overall     tp=0   fd=1
      aggregate   tp=0   fd=1                 no accepted subtree to expand

The knob for leaf detail on a marginal object is `match_threshold` itself, which
the docs now say and a test now pins:

    match_threshold   comparable?   aggregate
    0.70              no            tp=0 fd=1
    0.66              yes           tp=4 fd=2

The two nodes coincide only where there is no accepted subtree: a flat model, or
a subtree rejected outright. Documented across the three pages a reader lands on,
plus both `compare_with()` docstrings, with a which-node-for-which-question table
and the conjunction that a complete "did anything fail" check needs (`overall` is
the only node carrying `fa`, since an invented field maps to no ground truth
leaf).

Also documents that `EvalResult.precision`, `.recall`, `.f1` and `.accuracy` are
the object-level metrics, read from `overall.derived`. A `precision` of 1.0 beside
an `overall_score` of 0.9667 on the same object is two correct answers to two
different questions, not a contradiction. The naming is what #288 leaves open for
1.0.

`test_rollup_node_semantics.py` pins the published numbers, the gating, the
`match_threshold` remedy, and the flat-model case where the nodes converge.

Whether aggregates should also count the leaves of below-threshold objects is a
deliberately deferred question and is not treated here as a defect.

1975 passed, ruff clean, mkdocs adds no new warnings (strict mode already fails
on 9 pre-existing findings in untouched files).
Names the two stages rather than describing them: `overall` is detection (unit =
the object, did we find the right things), `aggregate` is extraction (unit = the
leaf, among objects established to be the same object, were the values right).
`match_threshold` is the handoff, and it is really the definition of "the same
object": above it, grading the fields is meaningful; below it, grading them would
be scoring the fields of a different object.

That is the structure of mAP, which this repo already implements for bounding
boxes, and `bbox-map-metrics.md` already documents the same rule for IoU: a
below-threshold detection is a failure at the matching stage, not a source of
per-attribute errors. So both pages now cross-link to it rather than arguing the
point from scratch. It also answers the "is the gating a hole" question by
reference to a standard the audience already accepts.

Cross-links verified to resolve against the `#iou-thresholds` anchor.

1975 passed, ruff clean, mkdocs adds no new warnings.
Review found three published artefacts that did not hold, all verified
against the engine.

The `clean` snippet reported clean on a document containing a hallucinated
value. It read `fa` on `overall` alone, but a leaf whose ground truth is
null and whose prediction supplies a value is `fa` at that leaf and rolls
into `aggregate`, while `overall` stays clean because the item still pairs:

    one item, GT total=None, prediction total="INVENTED"
    overall     tp=1  fp=0  fn=0  fa=0  fd=0
    aggregate   tp=5  fp=1  fn=0  fa=1  fd=0

Both nodes carry `fa`, for different kinds of invention. The check now sums
`fp`, which equals `fa + fd` by construction and cannot go stale if a class
is added. The snippet was published in four places, two of which were not
in the original diff: `threshold-gated-evaluation.md` and a second copy
earlier in `understanding-results.md`.

Both worked-example tables printed a one-item document's numbers under
prose describing five and two items:

    5 items, third at 4/6   overall tp=4 fd=1   aggregate tp=24 fd=0
    2 items, second at 4/6  overall tp=1 fd=1   aggregate tp=6  fd=0

The conclusion drawn from the first inverted on its own data: the nodes do
not converge when an item is rejected, they diverge further, and
`aggregate` reports a flawless P=1.0000 precisely because the rejected item
contributes no leaf rows. They coincide only when *every* subtree is
rejected, which is now stated and pinned.

Also names where the mAP analogy stops: a below-threshold detection counts
as both FP and FN so mAP recall falls, while a below-threshold object is
`fd` only, so `overall` recall reads 1.0 unless `recall_with_fd=True`.

Corrects the `overall` bullet, which claimed it counts pairings and not
leaves; on a flat model it counts leaves, which the convergence test
already asserted. Gives the dangling "see the caveat below" a target.

Tests: both tables are now pinned, which is the gap both errors came
through, plus the null-ground-truth FA case, the rejected-subtree case that
separates `overall_score` from `aggregate` precision, and a guard walking
all three pages to confirm none has drifted from the executable snippet.
Narrows the docstring claiming `overall_score == aggregate` precision as a
property; it holds only while leaf scores are binary, weights uniform,
there are no FN and nothing was rejected.

CHANGELOG: de-duplicates the "Replacements" block, which shipped twice in
blank line before the 0.7.0 heading.
`### Changed` carried the `json-schema-to-pydantic` delegation entry and the
NumPy statistics entry twice each. Both arrived on dev through earlier
conflict resolutions, not from this branch: I checked the counts both ways
before touching them.

Folded in here rather than opened as its own PR because this branch is
already correcting the duplicated `Replacements` block for the same reason,
and the two fixes are one class of defect.
@sromoam
sromoam force-pushed the docs/288-overall-vs-aggregate branch from 58ff2a5 to 60f8165 Compare September 4, 2026 15:48
@sromoam

sromoam commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

All nine fixed, each reproduced against the engine before I touched it. Nothing disputed. Rebased past #289, #312 and #313; now at 60f8165.

2335 passed, 12 skipped     ruff check clean
mkdocs 9 warnings (dev baseline)     0 broken anchors

The blocker was worse than the two sites you flagged

Reproduced exactly as you described:

one item, ground truth total=None, prediction total="INVENTED"
overall     tp=1  fp=0  fn=0  fa=0  fd=0
aggregate   tp=5  fp=1  fn=0  fa=1  fd=0

published clean check -> True        your fp-based fix -> False

After fixing the two you cited I grepped, and found the same snippet in two more places: threshold-gated-evaluation.md:184 and a second copy earlier at understanding-results.md:55. Four copies, all reporting clean on a hallucinated value.

Summing fp is now used in all four, and test_every_page_publishes_the_current_clean_check walks the pages and fails if any drifts from the single executable definition. A snippet nothing executes is how this got in, so the fix is a test that executes the pages.

The tables

I took your framing rather than relabelling, because you were right that the divergence is the better illustration:

5 items, third at 4/6    overall tp=4 fd=1    aggregate tp=24 fd=0   P=1.0000
2 items, second at 4/6   overall tp=1 fd=1    aggregate tp=6  fd=0
                 at 0.66 overall tp=2 fd=0    aggregate tp=10 fd=2

So the page now says the nodes diverge further when an item is rejected, and that aggregate reads a spotless P=1.0000 for exactly the reason the page exists to explain. I also verified your narrowing on when they coincide: reject all five and both read tp=0 fd=5; reject one of five and they part company. Both tables are pinned, and I confirmed the pin fails against the old published numbers.

One refinement on the == assertion

It is not quite arbitrary. A weighted mean of leaf scores equals tp/(tp+fp) whenever leaf scores are binary, weights are uniform, there are no FN, and nothing was rejected. The docstring now names those four conditions and points at a new test that breaks the last one, rather than calling it a coincidence. Your point that the test name overpromised stands, and that is what changed.

Also folded in

Two release notes shipped twice each on dev, the json-schema-to-pydantic delegation entry and the NumPy statistics entry, alongside the duplicated Replacements block you flagged on #290. All three are corrected here. I checked the counts in both directions first: they arrived through earlier conflict resolutions, not from this branch, and no bullet is lost either way.

The threshold-gated-evaluation.md anchor you flagged on #290 resolves as a side effect, since this PR introduces the ## Which node answers which question heading it pointed at. That was a cross-PR ordering artefact rather than a defect in #290.

Still outstanding from that review, and not in scope here: the CHANGELOG does not name that all_fields_matched also disappeared from nested nodes' overall and from three compare_json error dicts.

@sromoam
sromoam requested a review from vawsgit September 4, 2026 15:48

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

Requesting changes: 3 medium, 4 low. Nothing here is a code-behaviour bug — the src diff is docstrings only — but the central claim the new prose is built on is true for List[StructuredModel] items and false for a single nested StructuredModel field, and one of the pages contradicts itself on exactly that point.

What I verified first, so the findings below are narrow. On a worktree of this branch: full suite 2335 passed, 12 skipped; the 13 new tests pass; mkdocs build --strict aborts on the same 9 pre-existing griffe/autorefs warnings as dev, none from the new docstrings. Every published figure that no test pins re-derives correctly — the recall_with_fd table (R=1.0000 / R=0.8000), tp=0 fd=5 for five rejected items, and overall tp=1 fp=0 fn=0 fa=0 fd=0 beside aggregate tp=5 fp=1 fn=0 fa=1 fd=0 for the invented-on-null example. FP = FA + FD does hold at every site that assigns fp (comparison_helper.py:169, confusion_matrix_calculator.py:82-133, comparison_engine.py:181-182), and EvalResult.precision does read overall.derived (auto/facade.py:46-52), so the new fp-based clean check and the EvalResult.precision admonition are both correct. The CHANGELOG de-duplication is genuine: dev lines 107-126 and 144-163 were byte-identical, and the surviving copy is intact.


medium 1 — docs/docs/Advanced/aggregate-metrics.md:92: "is not descended into" is contradicted by the example 30 lines above it

Such an object is classified as a single false discovery and is not descended into.

The gating is a property of StructuredListComparator, not of objects. threshold-gated-evaluation.md:162 says so in its own table ("List[StructuredModel] with threshold-gated recursion"), while FieldComparator handles "single nested StructuredModel fields" with no such gating.

The counter-example is this page's own worked output at lines 45-77: contact is a nested object, not a list item, it scores 0.5 and is "overall": {"fd": 1} — rejected — and its leaves are still reported, "aggregate": {"tp": 1, "fd": 1}, and still roll into the root aggregate (tp=2 fd=1). Reproduced against this branch:

class Contact(StructuredModel):
    match_threshold = 0.7
    a/b/c: Optional[str] = ComparableField(ExactComparator(), threshold=1.0)

class Doc(StructuredModel):
    contact: Optional[Contact]; name: Optional[str]

# c wrong -> contact scores 0.667
overall    tp=1 fd=1        # contact rejected
aggregate  tp=3 fd=1        # all four leaves reported anyway

A reader with a nested-object schema (the common non-line-item case) takes away that aggregate hides their failing leaves, when it is showing them.

medium 2 — docs/docs/Guides/Evaluation/understanding-results.md:104: the structure bullet states the exclusion unconditionally

aggregate -- Primitive field metrics summed recursively below this node, excluding subtrees rejected at match_threshold.

This is the reference bullet a consumer reads before anything else, and for a nested object field neither half holds: nothing is excluded, and match_threshold is not the threshold that rejected it (the field's own threshold is). Same for :61 ("An object scoring below match_threshold ... not descended into"), :113, and classification-logic.md:122. Scoping the claim to list items — the word understanding-results.md:101 already uses correctly ("Where the field is a list, those children are item pairings") — fixes all four.

medium 3 — src/stickler/structured_object_evaluator/models/structured_model.py:1553: the published remedy is a no-op for nested objects

An object below match_threshold is one FD and is not descended into, so lowering match_threshold is how you get leaf detail for a marginal object.

For a nested non-list object, match_threshold is never consulted. Same model as above, sweeping the nested class's declaration:

match_threshold=0.9  overall tp=1 fd=1   aggregate tp=3 fd=1
match_threshold=0.7  overall tp=1 fd=1   aggregate tp=3 fd=1
match_threshold=0.5  overall tp=1 fd=1   aggregate tp=3 fd=1

Identical at every value. A user following this docstring turns a knob that cannot move their result; the knob there is the field's threshold. comparison_engine.py:217 carries a shorter form of the same claim. This one matters more than the pages because it ships in the API reference, where there is no surrounding "five line items" context to signal that the statement is list-scoped.

low 4 — docs/docs/Advanced/aggregate-metrics.md:120: when every subtree is rejected, aggregate silently stops counting leaves

tp=0 fd=5 is correct, but it is not the leaf view converging on the object view — aggregate is reporting objects. aggregate_metrics_calculator.py:191-215 falls back to summing children's overall whenever the recursive leaf sum comes out all-zero, so the unit switches with the data:

items=2 rejected=1   aggregate tp=6 fd=0  P=1.0000   # 6 leaf rows
items=2 rejected=2   aggregate tp=0 fd=2  P=0.0000   # 2 object rows, though 12 leaves exist

Line 90 promises "aggregate is extraction. The unit is the leaf", and understanding-results.md:104 promises "primitive field metrics"; anyone dividing aggregate counts by a leaf total, or labelling that derived block "leaf-level precision" (as the new admonition invites), gets object-level numbers on an all-rejected document with no signal. test_a_rejected_object_reports_itself_and_not_its_leaves pins this shape ("The object is the unit of report here") but no page says it. One sentence at 120 would close it.

low 5 — docs/docs/Advanced/aggregate-metrics.md:94 and understanding-results.md:115: the cross-link points at the wrong section

Both link bbox-map-metrics.md#iou-thresholds to support "a below-threshold detection is likewise a failure at the matching stage" / "counts as both a false positive and a false negative". #iou-thresholds (bbox-map-metrics.md:167) is about configuring the COCO IoU range and says nothing of the sort; the sentence you are citing — the one the PR description quotes as bbox-map-metrics.md:191 — is under ### IoU calculation. The anchor resolves, so --strict stays quiet and a reader lands on a section that does not support the claim. #iou-calculation is the intended target.

low 6 — tests/auto/test_risk_surface.py:1098: the superseded check survives in the suite, labelled "reliable"

# So the reliable question is the conjunction of both nodes.
clean = (
    aggregate["fd"] + aggregate["fn"] == 0
    and overall["fd"] + overall["fn"] + overall["fa"] == 0
)

This is the exact form test_the_clean_check_catches_a_value_invented_on_a_null_leaf now pins as returning True on a hallucinated value. The new drift guard walks only the three doc pages, so the form this PR retires stays in the repo as a worked example with a comment recommending it. Worth updating alongside, or the next person greps for clean = ( and copies the wrong one.

low 7 — docs/docs/Advanced/threshold-gated-evaluation.md:188: the stated reason for the change is not the reason

Read fp, not fa + fd. The two are equal by construction, and fp also catches the mirror-image case ...

fa + fd on aggregate catches the invented-on-null value perfectly well (aggregate fa=1). What the old snippet missed was reading fa on aggregate at all — it summed aggregate['fd'] and took fa only from overall. So the fix is the node, not the field, exactly as the two sibling pages put it ("A check that names only one node reports clean on a hallucinated value"). As written, this page tells a reader that fa + fd is unsafe, which is a false lesson about the classes.


Happy to re-approve on a pass that scopes the "not descended into" claim to list items (findings 1-3) and retargets the anchor; 4, 6 and 7 are cheap to fold in while you are in these files.

Addresses Vincil's second review of #295. All seven reproduced before
changing anything; nothing disputed.

The central claim the new prose was built on is true for
List[StructuredModel] items and false for a single nested StructuredModel
field, and aggregate-metrics.md contradicted itself on exactly that point:
its own worked output 30 lines above showed a rejected nested object whose
leaves were still reported.

Gating is a property of StructuredListComparator, which pairs items and
then accepts or rejects them. A nested object field goes through
FieldComparator, which has no such stage. Measured on a three-leaf nested
object with one leaf wrong:

  field threshold=0.9    overall tp=1 fd=1    aggregate tp=3 fd=1
  field threshold=0.5    overall tp=2 fd=0    aggregate tp=3 fd=1
  match_threshold 0.9 / 0.7 / 0.5 / 0.1  ->  identical at every value

So two things the pages got wrong for that shape: the leaves are always
reported, not excluded, and match_threshold is not the knob -- which made
the published "lower match_threshold to get leaf detail for a marginal
object" remedy a no-op. That remedy shipped in the API reference via two
docstrings, where no surrounding line-item context signals that it is
list-scoped, so it is corrected there too.

Six doc sites and two docstrings now scope the claim. Confirmed the list
case does gate and does respond to match_threshold (2 items 1 rejected ->
aggregate tp=6 fd=0; at 0.5 -> tp=10 fd=2), so the narrowed claim is
accurate rather than merely hedged.

Also folded in:

- On an all-rejected document, aggregate stops counting leaves.
  AggregateMetricsCalculator falls back to summing children's overall when
  the recursive leaf sum is all-zero, so the unit changes with the data:
  two rejected items of six fields give aggregate tp=0 fd=2, two object
  rows where twelve leaves exist. Documented as a warning admonition,
  because the page promises "the unit is the leaf".

- The mAP cross-link pointed at #iou-thresholds, which is about
  configuring the COCO IoU range. The sentence being cited is under
  #iou-calculation. Both links retargeted; the old anchor resolved, so
  --strict never noticed.

- The retired clean check survived in tests/auto/test_risk_surface.py
  under a comment calling it "the reliable question", so the form this PR
  retires was still in the repo for the next person to copy. Fixed, and
  the drift guard now walks every .py and .md in the tree rather than only
  the three doc pages -- verified it fails when the retired form is
  reintroduced and passes when it is not.

- threshold-gated-evaluation.md told readers "read fp, not fa + fd", which
  teaches a false lesson about the classes. FP = FA + FD by construction,
  and fa + fd on a node works fine; what the old snippet missed was
  reading fa on aggregate AT ALL. The fix is the node, not the field, as
  the two sibling pages already said.

Nine new tests pin the corrected claims, including match_threshold's
inertness for a nested object, so the retired remedy cannot be
re-published silently.

2346 pass, ruff clean, mkdocs at the 9-warning dev baseline with no new
anchor warnings.
@sromoam

sromoam commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

All seven fixed — 6c2cfbf. Nothing disputed; every one reproduced before I touched anything.

You were right, and the page was worse than self-contradictory — it was self-refuting. aggregate-metrics.md asserted "not descended into" 30 lines below its own worked output showing a rejected nested object whose leaves are reported. I wrote both and didn't connect them.

1–3: the claim is list-scoped

Measured on a three-leaf nested object with one leaf wrong:

field threshold=0.9    overall tp=1 fd=1    aggregate tp=3 fd=1
field threshold=0.5    overall tp=2 fd=0    aggregate tp=3 fd=1
match_threshold  0.9 / 0.7 / 0.5 / 0.1  ->  identical at every value

Sharper than your version in one respect: aggregate is tp=3 fd=1 in both rows. So it is not merely that leaves are reported when rejected — the aggregate view is completely insensitive to the verdict for this shape.

And I confirmed the list case really does gate, so the narrowed claim is accurate rather than just hedged: 2 items with 1 rejected gives aggregate tp=6 fd=0, and at match_threshold=0.5 it becomes tp=10 fd=2.

Six doc sites and both docstrings now scope it. You were right that the docstrings matter more — structured_model.py:1553 and comparison_engine.py:217 ship in the API reference with no surrounding line-item context, so a reader has nothing to signal the statement is list-scoped.

4: the unit switches, and it is now a warning admonition

two items of six fields
  1 of 2 rejected    aggregate tp=6 fd=0   P=1.0000    6 leaf rows
  2 of 2 rejected    aggregate tp=0 fd=2   P=0.0000    2 OBJECT rows, though 12 leaves exist

Stated on the page with the explicit consequence you named: an aggregate count is not a safe denominator for a leaf total, and a derived block from an all-rejected document is not leaf-level precision.

5: retargeted

#iou-thresholds is line 167 and about configuring the COCO range; the sentence I was citing is at 191 under #iou-calculation. Both links fixed. Worth noting the failure mode: the anchor resolved, so --strict stayed quiet and the check I added for broken anchors could never have caught this.

6: fixed, and the guard now covers it

You were right that the page walk couldn't see it — it matches on the docs' quoting style and that copy used different variable names. So rather than just fix the one file, the drift guard now walks every .py and .md in the tree, finds each clean = (, and checks the block under it. Verified it fails when the retired form is reintroduced and passes when it is not, because a guard I can't see fail is how the < 1.0 assertion on #319 got through.

7: the reason was wrong

Correct — fa + fd on aggregate catches it fine. What the old snippet missed was reading fa on aggregate at all; it took fa from overall only. The page now says the fix is the node, not the field, and that fp is preferred merely for being one term instead of two — not because the classes are unsafe to read.

Tests

Nine new, pinning the corrected claims — including match_threshold's inertness for a nested object parametrised over four values, so the retired remedy cannot be re-published silently.

2346 passed, 12 skipped, ruff clean, mkdocs --strict at the same 9 pre-existing warnings with no new anchor warnings, 18/18 CI.

Thanks for re-running the figures rather than taking the prose at face value — finding 3 in particular was shipping a knob that cannot move the result.

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

Request changes — the new guidance is right for a list-only document and wrong for the ordinary one

I verified every published number on this branch and they all hold: the tp=5/29, tp=4 fd=1 / 24, both match_threshold tables, the recall_with_fd pair, the INVENTED-on-null block, the contact claim against the pre-existing worked output, the tp=0 fd=5 all-rejected line, and result.precision == 1.0 beside overall_score == 0.9667. mkdocs build --strict gives the same 9 pre-existing warnings as dev, all four new cross-links resolve to real ids in the built site (#iou-calculation, #which-node-answers-which-question, #overall-vs-aggregate), the full suite is green (2346 passed, 12 skipped), and the CHANGELOG deletions are genuine de-duplication — both blocks exist twice on dev. The clean-check change is also strictly stronger than the form it retires, not merely equivalent.

The problem is the document shape every example uses. All of them are a model whose only field is the list, and cm['overall'] is the sum of the node's direct children — which the PR itself now says at understanding-results.md:103. Add the header fields a real invoice has and the object-verdict framing stops being true at the root.

class Doc(BaseModel):
    invoice_id: Optional[str] = None
    vendor: Optional[str] = None
    date: Optional[str] = None
    lines: List[Line] = Field(default_factory=list)   # Line has 6 leaves

Everything correct, 5 line items:

root  overall  tp=8      <- 3 header leaves + 5 item pairings
lines overall  tp=5

Three header fields right and all list items rejected (2 of 6 leaves wrong each):

root  overall    tp=3 fd=2
root  aggregate  tp=3 fd=2   derived.cm_precision = 0.6   <- 15 leaves exist
lines aggregate  tp=0 fd=2

Three consequences, listed as findings below. None of them is a code defect — the source change is docstrings only — but this PR's whole job is telling a consumer which node to read, and on the shape they actually have it currently tells them the wrong one. That is the same failure the linked IDP Accelerator issue hit.

Findings

1. docs/docs/Guides/Evaluation/understanding-results.md:168 (medium) — "How many list items did the model find? | overall" is wrong on any model with fields beside the list. On the Doc above, cm['overall']['tp'] is 8, not 5; a reader following this row reports 8 line items found. The node that answers it is cm['fields']['lines']['overall']. Same overstatement in the framing at understanding-results.md:112 ("For a list of 5 line items that each paired above match_threshold, tp = 5" — true of the list node, not of cm['overall'], which is where every worked example in the section prints), at aggregate-metrics.md:89, at classification-logic.md:122 ("overall gives object verdicts at that level"), and in both new docstrings (structured_model.py:1550, comparison_engine.py:214) which are published to the API reference. Please scope the claim to the list field's own node, or add a header field to one example so the mixing is visible.

2. docs/docs/Advanced/aggregate-metrics.md:129 (medium) — the all-rejected warning is scoped too narrowly to protect the reader it is for. The fallback in AggregateMetricsCalculator fires per node whenever that node's recursive leaf sum is all-zero, but the warning conditions it on the whole document ("On an all-rejected document", "a document in which every subtree was rejected") and demonstrates it on a list-only model. On the Doc above the document is not all-rejected — the three header leaves matched — yet cm['aggregate'] is tp=3 fd=2, five rows where fifteen leaves exist, and cm['aggregate']['derived']['cm_precision'] is 0.6. The reader checks whether the whole document was rejected, correctly concludes it was not, and divides by 15 anyway. The closing advice ("Read overall to know how many objects were rejected before dividing") does not help either, since here overall reads tp=3 fd=2 as well. Condition the warning on a list whose items were all rejected, not on the document.

3. docs/docs/Advanced/aggregate-metrics.md:127 (medium) — "The two nodes coincide only where there is no accepted subtree to expand at all: a model with no nesting, or a document in which every subtree was rejected" is falsified by that same shape. Root overall and root aggregate are both tp=3 fd=2 there, with an accepted subtree present (the header leaves) and a list subtree that was expanded. CHANGELOG.md:520 and the new module docstring at tests/structured_object_evaluator/test_rollup_node_semantics.py:14 repeat the rule verbatim, so the wrong invariant now lands in three places — and the adjacent CHANGELOG sentence "One rejected subtree among several makes them diverge further, not converge" is wrong on the same example. Worth a test, since this is the kind of claim the new file exists to keep honest.

4. docs/docs/Guides/Evaluation/understanding-results.md:106 (low) — the aggregate reference bullet promises a unit it does not always have, with no pointer to the caveat. "Primitive field metrics summed recursively below this node, excluding list items rejected at their element class's match_threshold" is the description a reader lands on before computing a leaf rate, and on an all-rejected list the counts are object rows rather than primitive-field metrics. aggregate-metrics.md carries the warning; this page does not link to it. A cross-link would close the gap.

5. docs/docs/Advanced/aggregate-metrics.md:82 (low) — two pages now state two different rules for overall, four lines apart from the new section. This line still reads "reflects this node's own direct classification", while understanding-results.md:103 now correctly says "Metrics for this node's direct children". At the root the second is right and the first is not (root overall is tp=1 fd=1 in this page's own worked example, i.e. name + contact, not any classification of the root itself). Since the section right below it is about exactly this, fixing the old line here costs one edit.

6. tests/structured_object_evaluator/test_rollup_node_semantics.py:494 (low) — the repo-wide scan flags on an 8-line window, which overruns the block it means to inspect. block = "\n".join(lines[number : number + 8]) starts at clean = (; the retired form is 4 lines, so the window reads 4 lines past the closing paren. In tests/auto/test_risk_surface.py the updated check ends at line 1106 and the window reaches into the next test — adding a natural assert overall["fa"] == 0 after that block would fail this test, in another file, for a reason unrelated to the change being made. Stopping at the first line containing ) (or scanning only until the parens balance) would keep the guard without the false positive. Runtime is fine (0.31 s), and .venv is the only env name .gitignore knows, so the exclusion is adequate.

Findings 1-3 are the ones I would want addressed before merge; 4-6 are cheap while you are in the files. The structure, the two-stage framing, the mAP grounding, the recall caveat, and the executable _documented_clean_check are all a clear improvement over what is on dev — this is a scoping fix, not a rethink.

Addresses Vincil's second review of #295. All six reproduced; every number
he published matched.

The findings share one root: every example in the section was a model whose
ONLY field is the list, and `overall` sums a node's DIRECT children -- which
this PR itself now states. Add the header fields a real invoice has and the
object-verdict framing stops holding at the root.

  5 items, everything correct
    root  overall                     tp=8      3 header leaves + 5 pairings
    cm['fields']['lines']['overall']  tp=5      the item count

So "How many list items did the model find? -> overall" overstates by the
number of header fields. Corrected in the lookup row, in the framing on both
pages, in classification-logic.md, and in both docstrings -- which matter
most, since they publish to the API reference where no surrounding
line-item context signals that the claim was list-scoped. Added a worked
example with header fields so the mixing is visible rather than described.

The all-rejected warning was scoped to the document and needed to be scoped
to the list. The fallback fires per node whenever THAT node's leaf sum is
all-zero, so with three correct header fields beside a fully rejected list
the document is plainly not all-rejected and the root still reads

    root  overall    tp=3 fd=2
    root  aggregate  tp=3 fd=2    cm_precision 0.6000

five rows where fifteen leaves exist. A reader checking the document
condition concluded correctly that it did not apply and divided by 15
anyway, and the closing advice to read `overall` did not help either since
it reports the same numbers. The condition that actually holds is
`tp == 0` on the list field's own `overall`, which is what the warning now
says.

That same shape falsifies "the two nodes coincide only where there is no
accepted subtree to expand". They coincide there WITH an accepted subtree
present. The rule was stated in three places -- the page, the CHANGELOG,
and this test file's own module docstring -- and all three are corrected,
with `TestCoincidingNodesAreNotEvidenceOfAgreement` pinning the
counter-example, since it is exactly the kind of claim that file exists to
keep honest.

Also folded in: the `aggregate` reference bullet now links to the caveat
rather than promising a unit it does not always have; aggregate-metrics.md's
older "reflects this node's own direct classification" line agreed with
neither the engine nor the new section four lines below it; and the
repo-wide clean-check scan read a fixed 8-line window past the closing
paren, so an ordinary assertion written after a corrected block would have
failed this test in another file for an unrelated reason. It now stops when
the parentheses balance, verified still to fail on the retired form.

9 new tests, 33 in the file. 2355 pass, ruff clean, mkdocs at the 9-warning
dev baseline.

Refs #288
…s cited

Round three fixed the six sites Vincil named. Grepping for the claim itself
rather than the line numbers finds four more, one of them in the file whose
whole job is keeping this honest.

  tests/.../test_rollup_node_semantics.py:3   "overall gives object verdicts at
                                              its own level" -- the exact wording
                                              finding 1 retires, in the module
                                              docstring, three paragraphs above
                                              the test that falsifies it
  CHANGELOG.md:510                            this PR's own release note, still
                                              saying "an object below it is a
                                              single FD ... a caller wanting leaf
                                              detail for a marginal OBJECT lowers
                                              match_threshold" -- the round-two
                                              medium-3 claim, fixed in the
                                              docstring and left in the note
  understanding-results.md:59                 "overall gives the object verdicts",
                                              two lines above the :61 already
                                              corrected
  aggregate-metrics.md:192                    the #288 rename rationale quotes
                                              "object verdicts at this level" as
                                              the intended meaning

Also fixes an anchor of exactly the kind flagged as low-5 last round. The new
cross-link from the `aggregate` reference bullet pointed at
`#getting-leaf-detail-for-a-marginal-list-item`, which begins immediately AFTER
the warning it was sent to show, so the anchor resolved and --strict stayed quiet
while the reader landed past the paragraph. attr_list is enabled, so the warning
now carries its own id and the link targets it.

  2355 passed, 12 skipped        ruff: 16 findings, all pre-existing in
                                 examples/notebooks, none in this diff
  mkdocs --strict: same 9 pre-existing griffe/autorefs warnings as dev
  new id present in the built HTML, directly above the admonition
@sromoam

sromoam commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

All six fixed in 3477a69, and a self-audit afterwards found four more sites of the same claim plus an anchor defect of the kind you flagged as low-5 last round -- 182d720.

Nothing disputed. Every number you published reproduced, including the ones that made me wrong.

1-3, the root mixes units. You were right that the shape was the problem, not the wording. Pinned:

5 items, everything correct
  cm['overall']['tp']                     8      3 header leaves + 5 pairings
  cm['fields']['lines']['overall']['tp']  5      the item count

Corrected in the lookup row, the framing on both pages, classification-logic.md, and both docstrings. Added a worked section with header fields so the mixing is visible rather than described, and TestTheRootMixesHeaderLeavesWithItemPairings pins it.

2, the all-rejected warning. Rescoped from the document to the list. Your counter-example is now in the warning itself: 3 correct header fields beside 2 rejected items reads root overall tp=3 fd=2, root aggregate tp=3 fd=2, cm_precision 0.6000 -- five rows where fifteen leaves exist. The advice is now to check each list field's own overall for tp == 0, since neither the document condition nor the root overall protects the reader.

3, the invariant. Replaced with "coincide wherever the node being read has no accepted subtree left to expand", plus an explicit paragraph that coinciding is not evidence nothing was hidden. Fixed in all three places, and TestCoincidingNodesAreNotEvidenceOfAgreement pins your falsifying shape, since this is exactly what that file exists to catch.

4, 5, 6 all folded in. The scan now stops when the parens balance, so the window cannot overrun the block.

What the self-audit found

Round three fixed the six sites you named. Grepping for the claim found four you had not:

site what it still said
test_rollup_node_semantics.py:3 "overall gives object verdicts at its own level" -- in the module docstring, three paragraphs above the test that falsifies it
CHANGELOG.md:510 this PR's own note, still carrying the round-two medium-3 claim ("a caller wanting leaf detail for a marginal object lowers match_threshold") that I fixed in the docstring and left here
understanding-results.md:59 "overall gives the object verdicts", two lines above the :61 already corrected
aggregate-metrics.md:192 the #288 rename rationale quotes "object verdicts at this level" as the intended meaning

CHANGELOG.md:309 also carries it, correctly scoped to list items, and is a shipped historical entry -- left alone.

And the anchor. My new cross-link from the aggregate reference bullet pointed at #getting-leaf-detail-for-a-marginal-list-item, which begins immediately after the warning it was sent to show. Same failure as low-5: the anchor resolved, --strict stayed quiet, the reader landed past the paragraph. attr_list is enabled, so the warning now carries its own id and the link targets it -- verified in the built HTML, directly above the admonition.

2355 passed, 12 skipped
ruff: 16 findings, all pre-existing in examples/notebooks, none in this diff
mkdocs --strict: same 9 pre-existing griffe/autorefs warnings as dev

On the wider point: the recurring failure here is that I fix the cited sites and not the claim. Grepping for the assertion's wording across the repo, and treating every cross-link as suspect until the built HTML shows where it lands, is what caught this round's four. The drift guard covers that discipline for the clean check specifically but not for this phrasing, which is what let the four survive -- happy to extend it if you think it is worth the test.

@sromoam
sromoam requested a review from vawsgit September 8, 2026 20:09
The clean-check guard covers one published snippet. It did not cover the claim
that actually kept recurring, which is why the phrasing survived three review
rounds: each round corrected the sites that were cited, not the assertion.

Bans "object verdict", "verdicts at" and "own direct classification" across
src/, docs/ and tests/. Verified it fails rather than passing for free -- putting
the old wording back into classification-logic.md reports:

    docs/docs/Advanced/classification-logic.md:122

CHANGELOG.md is exempt: shipped release notes record what was said at the time.
This file is exempt of necessity, since the banned tuple spells the phrases out,
and that exemption is load-bearing -- the module docstring says a list field's
`overall` "reads as an object verdict", the one context where it is accurate.
Noted in the test so the gap is stated rather than discovered.

2356 passed, 12 skipped
@sromoam

sromoam commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

Went ahead and added the guard -- 6d2c6e4. Bans "object verdict", "verdicts at" and "own direct classification" across src/, docs/ and tests/.

I checked it fails rather than passing for free: putting the old wording back into classification-logic.md reports docs/docs/Advanced/classification-logic.md:122.

Two exemptions, both stated in the test. CHANGELOG.md, because shipped notes record what was said at the time. And this file, of necessity, since the banned tuple spells the phrases out -- that one is load-bearing rather than a formality: the module docstring says a list field's overall "reads as an object verdict", which is the single context where the phrase is accurate. That is the boundary the guard cannot police.

2356 passed, 12 skipped.

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

Reviewed the full diff against origin/dev (rebased, #290 already in, so the merge-order caveat is resolved). I verified the substance rather than trusting the prose:

  • Every published number reproduces. I ran the recall_with_fd table (R=1.0000 / R=0.8000) and the "reject all five items → tp=0 fd=5" claim independently, since those two are not pinned by a test — both correct.
  • FP = FA + FD holds at every construction site (hungarian.py:328, confusion_matrix_calculator.py:82-133/223-235), so the new fp-based clean check is strictly stronger than the retired fd/fa form, not merely equivalent.
  • The AggregateMetricsCalculator all-zero fallback the new warning describes is real (aggregate_metrics_calculator.py:191-215).
  • EvalResult.precision/.recall/.f1/.accuracy do read cm['overall']['derived'] (auto/facade.py:46-53).
  • The {: #aggregate-counts-objects-for-an-all-rejected-list } anchor renders (attr_list is enabled) and every new cross-link resolves in the built site (bbox-map-metrics/#iou-calculation, #which-node-answers-which-question).
  • mkdocs build --strict produces the same 9 pre-existing warnings as dev; ruff check is clean on all touched files; the new 33 tests and test_risk_surface.py pass. The CHANGELOG hunk that looks like it deletes two release notes is a genuine de-duplication — dev carries both entries twice inside ### Changed.

So the new material is accurate. What blocks this is that three older passages the PR did not touch now contradict it, two of them on the same page as the new text. For a PR whose whole purpose is to remove this ambiguity, a self-contradicting page is the defect being fixed: a reader who lands on the older section acts on the statement this PR set out to retire.


1. docs/docs/Advanced/aggregate-metrics.md:198 — ## Calculation Logic still states the rule the new warning disproves (medium)

  1. Parent nodes: aggregate is the sum of all child aggregate values.

Sixty-five lines above, the new warning documents that when the child aggregates are all zero the calculator instead sums the children's overall (aggregate_metrics_calculator.py:191-215), which is exactly why aggregate tp=0 fd=2 appears where twelve leaves exist. A reader who skips the narrative and reads "Calculation Logic" as the normative spec — a reasonable thing to do with a section by that name — comes away with the model the PR is correcting, and will divide an aggregate count by a leaf total. ## Key Features line 12 ("Parent nodes sum metrics from all child primitive fields") has the same problem. One clause each, pointing at the new warning.

2. docs/docs/Guides/Evaluation/understanding-results.md:455 — ## Field-Level Aggregate Metrics contradicts the new bullet at line 106 (medium)

Every node in the confusion matrix automatically includes an aggregate field that sums all primitive field metrics recursively below that node.

Line 106 on this same page now says the opposite for a list whose items were all rejected. Worse, the snippet at line 468 is the precise misuse the new warning warns against:

errors = data['aggregate']['fd'] + data['aggregate']['fa'] + data['aggregate']['fn']

On a section whose list items were all rejected that yields object rows, so the "which sections have the most extraction issues" ranking the section promises is computed across two different units. Commit 182d720 is titled "retire the unscoped claim everywhere, not only where it was cited" — this is the copy that survived, 350 lines below the corrected one.

3. docs/docs/Advanced/threshold-gated-evaluation.md:197 — re-publishes the remedy this PR pins as a no-op (medium)

So match_threshold is also the knob for how much leaf detail you get. If you want a marginal object's leaves scored individually, lower it until that object qualifies as comparable.

Three lines above this, the PR rewrote the snippet and added two new paragraphs, and the CHANGELOG entry says the unqualified form "made the published 'lower match_threshold' remedy a no-op for that shape". test_match_threshold_is_inert_for_this_shape pins it as inert at 0.9/0.7/0.5/0.1, with the docstring "The retired remedy, pinned as a no-op so it cannot be re-published" — yet it is still published here, in a paragraph the diff is adjacent to. understanding-results.md:175/177 has the same wording ("Getting leaf detail for a marginal object" / "lower match_threshold so the object qualifies"), which reads as unscoped even though line 115 of that file scopes it correctly. Swapping "object" for "list item" in both places is enough.

4. docs/docs/Guides/Evaluation/understanding-results.md:148 — the sentence undercuts the number it is explaining (low)

The root number is not wrong, it is a different question: it classifies the root's own four fields.

The block immediately above reports tp=8 and explains it as "3 header leaves + 5 item pairings". If the root classified four fields, tp could not exceed 4 — the list field contributes 5 rows, not 1. This is the one passage in the PR whose point is that the root mixes units, so the phrasing works against it. "…it classifies the root's own fields, and the list field contributes one row per item pairing rather than one row for the field" would say it.

5. tests/structured_object_evaluator/test_rollup_node_semantics.py:480 — the repo-wide guard is fragile in two ways (low)

test_no_file_anywhere_publishes_the_superseded_form globs **/*.py across the whole repo and skips only .venv. A contributor whose environment lives in venv/, env/, or .tox/ gets a failure naming third-party files, with a message about Stickler's clean check. Secondly, the heuristic flags any clean = ( block containing both fa and overall, so a correct future check such as cm['overall']['fp'] == 0 and cm['aggregate']['fa'] == 0 fails it. Matching overall and fa inside one subscript pair, and restricting the walk to src/, tests/, docs/, and examples/, would keep the guard without the false positives.

Also worth noting: neither guard covers CHANGELOG.md or *.md outside docs/ (test_every_page_publishes_the_current_clean_check names three pages; the repo walk covers *.py and docs/**/*.md). The CHANGELOG copy of the snippet is correct today but can drift silently — adding CHANGELOG.md to _PAGES_PUBLISHING_THE_CLEAN_CHECK costs nothing.


None of this touches the new prose, the tests, or the docstrings, all of which I checked and found sound. Items 1-3 are the ones I would want fixed before merge, since each leaves a page that disagrees with itself about the exact thing the PR is disambiguating.

Addresses Vincil's third review. All five reproduced by reading the cited lines;
he is right that a page disagreeing with itself about this is the defect.

1 `aggregate-metrics.md` stated the parent-node rule twice as an unconditional
  sum of child `aggregate` values -- in `## Calculation Logic`, 65 lines below
  the new warning that documents the all-zero fallback, and in `## Key Features`.
  A reader treating a section called "Calculation Logic" as the normative spec
  got exactly the model this PR corrects. Both now name the fallback and link to
  it, and the derived-metrics line says those inherit whichever unit came out.

2 `understanding-results.md` repeated it 350 lines below the bullet 182d720
  corrected, and its snippet ranked sections by `aggregate` error counts -- the
  precise misuse the new warning warns against, since an all-rejected list
  contributes object rows to that ranking. The snippet now reports which unit it
  got, and switches to `fp` for the reason the rest of the page already gives.

3 The "lower `match_threshold` for a marginal OBJECT" remedy survived in
  `threshold-gated-evaluation.md` and in two headings, while
  `test_match_threshold_is_inert_for_this_shape` pins it inert at 0.9/0.7/0.5/0.1
  under the docstring "The retired remedy, pinned as a no-op so it cannot be
  re-published". Now scoped to list items, both places, and both say what the
  knob is for a single nested model instead.

4 My own new prose worked against its own point: "it classifies the root's own
  four fields" cannot yield tp=8. Reworded to say the list field contributes one
  row per pairing.

5 The repo-wide guard, both fragilities. It globbed `**/*.py` and skipped only
  `.venv`, so a contributor with `venv/`, `env/` or `.tox/` got third-party paths
  reported under a message about stickler's clean check -- now scoped to the trees
  we author. And it flagged any block containing both `fa` and `overall`, which
  would condemn a correct future check reading `fa` off `aggregate`; it now
  matches the two in one subscript chain. Verified both directions:

      RETIRED  cm['overall']['fa'] + cm['aggregate']['fd'] == 0     flagged
      RETIRED  overall["fa"] == 0 and aggregate["fd"] == 0           flagged
      OK       cm['overall']['fp'] == 0 and cm['aggregate']['fa'] == 0   not
      OK       cm["aggregate"]["fa"] + cm["aggregate"]["fd"] == 0        not

  and end to end: reintroducing the retired form into test_risk_surface.py still
  fails the guard, naming the line. `CHANGELOG.md` is now in the page list too --
  its copy is correct today and nothing was watching it.

  2356 passed, 12 skipped        ruff check clean
  mkdocs --strict: same 9 pre-existing warnings as dev
  every anchor verified in the built HTML, including that no link still points at
  the heading I renamed
@sromoam

sromoam commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

All five fixed -- f699344. You are right that the self-contradiction is the defect and not a cosmetic gap; a reader who lands on the older section acts on the claim this PR set out to retire.

1, aggregate-metrics.md. The unconditional parent-node rule was stated twice and I had only added the warning. ## Calculation Logic now names the all-zero fallback and links to it, and the derived-metrics line says those inherit whichever unit step 2 produced. ## Key Features likewise.

2, understanding-results.md:455. Corrected, and the snippet with it -- it ranked sections by aggregate error counts, which is the misuse the new warning describes, since an all-rejected list contributes object rows to that ranking. It now reports which unit it got, and reads fp for the reason the rest of the page already gives. That is the copy 182d720 missed.

3, the no-op remedy. Scoped to list items in threshold-gated-evaluation.md:197 and in both understanding-results.md headings, each now saying what the knob does for a single nested model instead. test_match_threshold_is_inert_for_this_shape was pinning it inert while the page still published it.

4. My own prose worked against its own point: "the root's own four fields" cannot yield tp=8. Reworded to the phrasing you suggested.

5, the guard, both fragilities. Scoped to src/, tests/, docs/, examples/, so nobody with venv/, env/ or .tox/ gets third-party paths reported under a message about stickler's clean check. And the heuristic now matches overall and fa in one subscript chain rather than "both words appear in the block":

RETIRED  cm['overall']['fa'] + cm['aggregate']['fd'] == 0          flagged
RETIRED  overall["fa"] == 0 and aggregate["fd"] == 0                flagged
OK       cm['overall']['fp'] == 0 and cm['aggregate']['fa'] == 0    not flagged
OK       cm["aggregate"]["fa"] + cm["aggregate"]["fd"] == 0         not flagged

Checked end to end as well: reintroducing the retired form into test_risk_surface.py still fails the guard, naming the line. CHANGELOG.md is in the page list now -- its copy is correct today and nothing was watching it.

2356 passed, 12 skipped        ruff check clean
mkdocs --strict: same 9 pre-existing warnings as dev

Anchors verified in the built HTML, including that no link still points at the heading I renamed.

The pattern across these rounds has been that I fix the lines you cite rather than the claim behind them. Grepping for the assertion's wording repo-wide, and testing each guard in both directions instead of only the failing one, is what turned up this round's set.

@sromoam
sromoam requested a review from vawsgit September 8, 2026 20:34

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

Requesting changes. No high-severity blockers, and nothing here is a runtime risk — the only source edits are docstrings. I reproduced everything below against the engine on f699344; 2356 passed, 12 skipped, mkdocs --strict at the same 9-warning dev baseline, and the new anchor is present in the built HTML. The findings are all one class: the round-four framing landed in the sites that were cited, and the sibling statements of the same claim were left behind — which is the defect this PR defines itself against ("a page that disagrees with itself about this is the defect being fixed").

Medium

1. docs/docs/Guides/Evaluation/understanding-results.md:474 — the published ranking snippet applies the list-only unit check to every field, and mislabels a failing primitive.

Line 458 is careful: "The check is cm['fields'][name]['overall']['tp'] == 0 on a list field." The snippet 16 lines below drops the qualifier and runs it over every entry in cm['fields']. A primitive header field that failed has tp == 0, so it is reported as object rows. Ran the snippet verbatim on a 5-item document with a wrong vendor:

  invoice_id: F1=1.000, Errors=0 (leaves)
  vendor:     F1=0.000, Errors=1 (objects)     <-- one leaf, labelled objects
  date:       F1=1.000, Errors=0 (leaves)
  lines:      F1=1.000, Errors=0 (leaves)

So the annotation added to stop a reader mixing units is itself wrong on exactly the rows a reader is scanning for — the failing ones. It also fires for a list that is null on both sides (tp=0, tn=1), where no leaves exist either way. Gate it on the field actually being a list, or on 'fields' in data and not data['fields'], which is the condition the engine really uses (see 3).

2. docs/docs/Advanced/aggregate-metrics.md:89 — "The unit is the object", unscoped, on the page every cross-link points at.

understanding-results.md:112 was corrected to "The unit is whatever this node's direct children are ... Read it on the list field, not at the root". The corresponding bullet here still reads "overall is detection. The unit is the object." That is the claim TestTheRootMixesHeaderLeavesWithItemPairings falsifies (tp=8 at the root of a 3-header + 5-item document), and this page — #which-node-answers-which-question — is the target of the cross-links from classification-logic.md, threshold-gated-evaluation.md and both docstrings. Line 82 of the same page already says the units mix, 7 lines above.

3. docs/docs/Advanced/aggregate-metrics.md:134 and :198 — the newly documented mechanism is not the mechanism, and step 2 as written predicts the wrong numbers for its own example.

The warning says "When a node's recursive leaf sum comes out all-zero, aggregate falls back to summing its children's overall", and Calculation Logic step 2 restates it as normative. Neither is what happens. When every item of a list is rejected, the list node has no child fields at all:

rejected=1  lines overall tp=1 fd=1   agg tp=6 fd=0   children ['sku','desc','qty','unit','tax','total']
rejected=2  lines overall tp=0 fd=2   agg tp=0 fd=2   children []

With fields == {}, AggregateMetricsCalculator takes the leaf branch (aggregate_metrics_calculator.py:153-170, aggregate = overall); the all-zero fallback at :191 is then skipped because the counts are no longer zero. Read step 2 literally and "the children's overall values are summed" is a sum over an empty set — it predicts tp=0 fd=0 where the engine reports fd=2, i.e. the rule contradicts the worked output it links to. The observable claim (the unit changes) is right; the causal story and the derived rule are not, and the rule is what finding 1 inherits.

4. docs/docs/Guides/Evaluation/understanding-results.md:219 and CHANGELOG.md:556 — EvalResult.precision is characterised with the framing this PR retires.

Both say these are "the object-level metrics" answering "how many objects were comparable rather than spurious". facade.py:46-52 reads cm["overall"]["derived"] at the root, so on any document with fields beside the list it is a precision over header leaves and item pairings mixed — 8 rows, not 5. The note is otherwise the most useful paragraph on the page; it just needs the same scoping the bullet above it got.

5. docs/docs/Guides/Evaluation/understanding-results.md:192 — first table row still sends an object question to the unscoped node.

Row 3 was scoped in round three ("that list field's own overall, e.g. cm['fields']['lines']['overall']"). Row 1 — "Were the objects comparable, and how many were spurious? | overall" — was not, and a reader consulting the lookup table rather than the prose gets the root, where the answer is inflated by the header-field count. Rows 1 and 2 want the same cm['fields'][...] treatment.

Low

6. CHANGELOG.md:309 — "overall carries the object verdict", in [Unreleased].

This is the exact phrase test_no_file_describes_overall_as_an_object_verdict bans repo-wide, and 182d720 names this very line (CHANGELOG.md:510 at the time) as fixed. The guard's exemption is justified as "shipped release notes record what was said at the time" — but line 309 is inside [Unreleased] (10-561) and is a line this PR authors, so the rationale does not cover it. Relatedly, exempt = {Path("CHANGELOG.md")} at tests/structured_object_evaluator/test_rollup_node_semantics.py:521 is dead code: the walk is src/**/*.py + docs/**/*.md + tests/**/*.py, so CHANGELOG.md is never a candidate. Worth either dropping the dead set and saying plainly that the changelog is unscanned, or adding it with a ## [Unreleased]-only rule.

7. docs/docs/Guides/Evaluation/understanding-results.md:219 — attribute syntax attributed to a compare_with() example.

"On the first example above result.precision is 1.0 while result.overall_score is 0.9667" — the first example (156-163) is a compare_with() result, which is a dict; .precision / .overall_score only exist on EvalResult from stickler.evaluate(). Copying the line raises. Say "the same document under stickler.evaluate()", or switch to result['overall_score'].

8. docs/docs/Guides/Evaluation/understanding-results.md:113 — the aggregate bullet lost the caveat its sibling kept.

aggregate-metrics.md:90 reads "The unit is the leaf, except where noted in the warning below." Here it is a flat "The unit is the leaf." The caveat does appear at 106 and 458 on this page, so this is the one statement of it that promises a unit the node does not always have — the same shape as the aggregate reference bullet corrected in 182d720.

Verified sound

For the record, since these were the load-bearing new claims: FP = FA + FD holds at both sites that produce it (hungarian.py:328, confusion_matrix_calculator.py), so the fp rewrite is a strict strengthening of the retired check; the recall_with_fd table at understanding-results.md:124-125 reproduces exactly (R=1.0 / R=0.8); #iou-calculation is the right anchor and the cited sentence is under it (bbox-map-metrics.md:191); the {: #... } id renders; all five match_threshold tables and the 5-items-all-rejected tp=0 fd=5 claim reproduce; and the three CHANGELOG de-duplications are real (two copies each on origin/dev, one after).

…iblings

Addresses Vincil's fourth review. Eight findings, all one class again: round four
landed where it was cited and left the sibling statements of the same claim.

Finding 3 is the serious one and it was mine. The previous round documented
"`aggregate` falls back to summing its children's `overall`" as the mechanism and
derived a rule from it. That is not what happens. When every item of a list is
rejected the node has NO child fields:

    rejected=1  lines overall tp=1 fd=1  agg tp=6 fd=0  children [6 leaves]
    rejected=2  lines overall tp=0 fd=2  agg tp=0 fd=2  children []

With `fields == {}` the calculator takes the LEAF branch (`aggregate = overall`);
the all-zero fallback is never reached, because by then the counts are not zero.
So `Calculation Logic` step 2 as published summed an empty set and predicted
`tp=0 fd=0` where the engine reports `fd=2` -- contradicting the worked output it
linked to. Instrumented the calculator across the suite to be sure rather than to
assume: 85,297 calls, the empty-`fields` leaf branch fired 16,731 times, the
all-zero fallback was entered ONCE and never changed a number. It is therefore
described nowhere; documenting an inert branch is what caused this finding.

Finding 1 inherited that wrong rule. The published ranking snippet labelled units
with `overall['tp'] == 0`, which is true of any FAILING PRIMITIVE, so the
annotation added to stop a reader mixing units mislabelled exactly the rows they
scan for:

    vendor:  F1=0.000, Errors=1 (objects)      <- one leaf, called objects

Checked the suggested replacement before adopting it: a primitive leaf has no
`fields` key at all, a structured node always has one, and it is empty exactly
when nothing was descended into. `'fields' in data and not data['fields']` is
therefore exact where `tp == 0` over-fires. A list null on both sides is childless
too, and has no leaves either way, which a test names.

2, 4, 5 scope the remaining unscoped statements: "The unit is the object" on the
page every cross-link targets, `EvalResult.precision` (root `overall`, so mixed
units), and the lookup table's rows 1 and 2. 8 restores the caveat its sibling
kept.

6 was two things. `CHANGELOG.md:309` carried the banned phrase inside
`[Unreleased]`, which this PR authors, so the "shipped notes record what was said"
exemption did not cover it -- and `exempt = {Path("CHANGELOG.md")}` was dead code,
since the walk never reached the changelog. Replaced with a shared
`_authored_prose()` walker that scans the `[Unreleased]` section and nothing else,
tested in both directions.

7 the page read `result.precision` off a `compare_with()` result, which is a dict,
so copying the line raised. Now binds `stickler.evaluate()` explicitly.

Five new guards, each verified to FAIL on the pre-fix content at the exact lines,
including one that `eval`s the page's own snippet against the helper over five node
shapes and asserts the labels are not all identical.

  2368 passed, 12 skipped (+12)      ruff check clean
  mkdocs --strict: 9 warnings, the dev baseline
  both anchors verified in the built HTML, no unresolved fragments
`test_no_file_describes_overall_as_an_object_verdict` banned `object verdict`
and friends, and `aggregate-metrics.md` went on saying "The unit is the object"
for another review round -- on the page every cross-link targets. The guard
passed the whole time. Banning the concept in one spelling and not the other is
how that happens.

Verified it fires on the reintroduced wording (`aggregate-metrics.md:89`) and is
quiet after.

  2368 passed, 12 skipped        ruff check clean
All nine findings. Three were substantive and two of those were mine.

1 The page published `tp=3 fd=2` and "15 leaves" for what the prose called "that
  list" -- the FIVE-item list established two lines above. Measured:

      2-item list, all rejected   overall tp=3 fd=2   15 leaves in doc
      5-item list, all rejected   overall tp=3 fd=5   33 leaves in doc

  The pinning test uses `item_count=2`, so the guard could not see the mismatch.
  The prose now says two items, matching the test and the numbers.

2 "equal, with an accepted subtree present" was FALSE, so the example did not
  falsify the rule stated one paragraph above. Measured: the three header fields
  are primitive leaves with no `fields` key, and `lines` is childless because every
  item was rejected. No accepted subtree anywhere.

  Worse, `test_and_an_accepted_subtree_is_present` asserted only
  `overall['tp'] == 3` -- three matched LEAVES -- so it did not test its own name.

  Found the shape that does falsify it: a nested object holding exactly ONE leaf.
  The object is one row on `overall`, its leaf is one row on `aggregate`, they
  coincide, and the subtree is accepted AND expanded.

      overall tp=1   aggregate tp=1   kid children ['a']

  So the rule is not "coincide only where nothing is left to expand"; it is
  "coincide whenever every child contributes the same number of rows to each".
  Rewritten on both pages, in the CHANGELOG and in the module docstring, with the
  two claims separated: this shape is evidence about HIDING, not a counter-example
  to the coincidence rule. Conflating them is what put a false claim on the page.

3 The prose guards matched PER LINE, so a phrase split across a hard wrap passed --
  and one already had. `CHANGELOG.md` is wrapped at ~80 columns and carried
  "this node's own direct / classification" across two lines, so the guard I have
  been treating as the safety net was passing while the claim was present.
  `_phrase_hits` now joins each file's authored lines, collapses whitespace, and
  reports the line the match starts on. Verified it catches a deliberately wrapped
  phrase and reports `CHANGELOG.md:538`. The historical quote that tripped it is
  reworded rather than exempted, so the guard stays strict.

4 "Nothing sums a node's children's `overall`" is contradicted by live source. The
  block exists; it just cannot produce the all-rejected behaviour, since a
  childless node never reaches step 2, and instrumented across the suite it
  contributes to nothing. Stated that way instead of denying it exists.

5 "`contact` scores 0.5" -- running the page's own example gives
  `field_scores['contact'] == 0.0`, clipped below the field's `threshold=1.0`. The
  0.5 is the subtree mean before clipping; said so.

6 "Run the first example above" was ambiguous and not runnable: no
  `ground_truth`/`prediction`, no `import stickler`, and the quoted numbers belong
  to a different example than the page's first. Names the example and binds it.

7 The two worked examples publish root counts valid only for a list-only model,
  immediately after teaching that the root reads `tp=8` with header fields. They
  now say which model they use.

8 The clean-check walk read the WHOLE changelog, forbidding the retired form
  anywhere in it -- including a future shipped note quoting it as history, which
  contradicts the `[Unreleased]`-only policy the walker states. Same window now.

9 `line == "## [Unreleased]"` disagreed with the walker's `startswith` and a bare
  `next()` died with `StopIteration` instead of a diagnosis. Both fixed.

  2371 passed, 12 skipped        ruff check clean
  mkdocs --strict: 9 warnings, the dev baseline
  every number the corrected paragraphs publish re-measured against the engine
… copy of it

Round five's finding 1: the ranking snippet ran the list-only unit check over every
field, so a failing primitive was labelled "object rows". Reproduced verbatim, a
five-item document with a wrong vendor:

    vendor:  F1=0.000, Errors=1 (objects)     <- one leaf
    vendor:  F1=0.000, Errors=1 (leaves)      <- now

I did NOT adopt the suggested remedy of gating on
`'fields' in data and not data['fields']`, because that form is wrong too, in the
other direction. A `List[str]` with one element wrong is childless with non-zero
counts, exactly like an all-rejected object list, and its rows are element
comparisons, which are leaves:

    tags   List[str],  one of two elements wrong   fields={}  aggregate tp=1 fd=1
    rows   List[Line], its only item rejected      fields={}  aggregate tp=0 fd=1

A scalar null on both sides carries `fields == {}` as well. The two shapes are
indistinguishable in the confusion matrix, so the unit cannot be derived from it at
all: the caller has to say which fields are `List[StructuredModel]`, and
`overall['tp'] == 0` then means every item in that list was rejected.

    OBJECT_LISTS = {'lines'}
    counts_objects = section in OBJECT_LISTS and data['overall']['tp'] == 0

Both retired forms mislabel a row in one ordinary document: `overall['tp'] == 0`
calls the failing `vendor` an object count, and the childless form calls the
`tags` list one.

A sweep for sibling copies of the claim found a THIRD site the review did not
name, which is the defect this PR defines itself against: CHANGELOG.md still
published `'fields' in node and not node['fields']` as "the condition to test".
Fixed, along with the same statement in aggregate-metrics.md, which had it as the
closing advice of the all-rejected warning.

Guards, all reverse-verified by breaking each site in turn:

- the snippet is EXECUTED, not pattern-matched. Its case list now includes a
  failing primitive and a primitive list, which are the two discriminating shapes.
  `_header_doc` grew a `vendor_wrong` flag because every header field was correct
  before, so dropping `section in OBJECT_LISTS` from the published snippet left
  every assertion passing.
- the prose guard matches the full phrase "cannot be derived from the confusion
  matrix" rather than "cannot be", which `aggregate-metrics.md` also contains in an
  unrelated sentence about the all-zero fallback, so deleting the real claim had
  left the guard green.

Five deliberate breakages, five caught, no gaps. Round five's other seven findings
were already addressed in 22a84e9; verified individually against the current tree.

2373 passed, 12 skipped; ruff clean and formatted; mkdocs --strict at the same 9
pre-existing warnings as dev, with the new cross-link resolving to a real anchor in
the built site. Every published number re-derived: precision 1.0 beside
overall_score 0.9667, aggregate precision 0.9667, root overall tp=8.
@sromoam

sromoam commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 0d020c3. Finding 1 was the only one still open from round five; the other seven were addressed in 22a84e9 and I re-verified each against the current tree rather than assuming. 18/18 CI green, 2373 passed, 12 skipped, ruff clean, mkdocs --strict at the same 9-warning dev baseline.

Finding 1

Your repro, before and after:

5-item document, wrong vendor
  vendor:  F1=0.000, Errors=1 (objects)     <- one leaf, labelled objects
  vendor:  F1=0.000, Errors=1 (leaves)      <- now

I did not take the suggested remedy, and I want to be explicit about why rather than quietly doing something else. Gating on 'fields' in data and not data['fields'] is wrong too, in the other direction. A List[str] with one element wrong is childless with non-zero counts, exactly like an all-rejected object list, and its rows are element comparisons, which are leaves:

tags   List[str],  one of two elements wrong   fields={}   aggregate tp=1 fd=1   leaves
rows   List[Line], its only item rejected      fields={}   aggregate tp=0 fd=1   object rows

A scalar null on both sides carries fields == {} as well. So the two shapes are indistinguishable in the confusion matrix, and the unit cannot be derived from it at all. The caller has to supply what only the model knows, and overall['tp'] == 0 then means every item in that list was rejected:

OBJECT_LISTS = {'lines'}
counts_objects = section in OBJECT_LISTS and data['overall']['tp'] == 0

Both retired forms mislabel a row in one ordinary document: overall['tp'] == 0 calls the failing vendor an object count, and the childless form calls the tags list one. That is now stated on both pages, with the two-row table above.

A third copy of the claim, which the review did not name

Sweeping for sibling statements — since that is the class this whole round was about — turned up CHANGELOG.md, which still published 'fields' in node and not node['fields'] as "the condition to test". Same statement, third site, and it was in [Unreleased]. Fixed there and in the closing advice of the all-rejected warning in aggregate-metrics.md.

Two holes in my own guards, found by reverse-verifying them

I broke each published site in turn to check the guards actually fire. Two did not, and both would have let the defect back in:

  • The snippet test passed with section in OBJECT_LISTS deleted. Its case list had no failing primitive, because _header_doc built vendor="v" on both sides, so every header leaf had tp == 1 — and the failing primitive is the only node where the published condition and the retired overall['tp'] == 0 form disagree. _header_doc now takes vendor_wrong, and the case list includes both discriminating shapes, the failing leaf and the primitive list.
  • The prose guard passed with the claim deleted. It matched "cannot be", and aggregate-metrics.md contains that string in an unrelated sentence about the all-zero fallback. It now matches the full phrase "cannot be derived from the confusion matrix".

Five deliberate breakages, five caught, no gaps. The snippet is executed rather than pattern-matched, as before.

The other seven, re-verified rather than assumed

# finding state
2 "overall is detection. The unit is the object"` unscoped scoped on both pages, with the tp = 8 example
3 the all-zero fallback presented as the mechanism step 2 now says a childless node never reaches it, and that the fallback contributes to no result in this repo's suite
4 EvalResult.precision framed as an object rate now "they inherit the root's unit ... so it is not an object rate at all"
5 lookup table row 1 unscoped scoped to cm['fields']['lines']['overall'], with why the root differs
6 "carries the object verdict" in [Unreleased], and the dead exempt set phrase gone; _authored_prose now scans ## [Unreleased] and the dead set is removed
7 attribute syntax on a compare_with() example the block now calls stickler.evaluate() and says why .precision raises on a dict
8 the aggregate bullet lost its caveat caveat restored, with the cross-link

Numbers

Every published figure on the pages I touched re-derived, not read: result.precision 1.0 beside overall_score 0.9667, aggregate precision 0.9667, root overall tp = 8 for three header fields beside a five-item list. The new cross-link from aggregate-metrics.md resolves to a real anchor in the built HTML.

@sromoam
sromoam requested a review from vawsgit September 9, 2026 18:31

@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!

Docs, docstrings and tests only -- no behaviour change -- and I could not find a blocker. I verified the review claims independently rather than taking the PR body's word for them.

Verified on the merged state (this branch merged into current origin/dev @ 420645f, since it is based on 1c4b28f and adds repo-wide prose guards that could have caught a newer commit):

  • Full suite: 2383 passed, 12 skipped. The 45 new tests and the touched test_risk_surface.py all pass.
  • ruff check: the 16 remaining errors are all pre-existing import-sort findings in examples/; the three files this PR touches are clean.
  • mkdocs build --strict: 9 warnings, the same 9 pre-existing griffe/autorefs findings, none in the changed pages.
  • Every cross-page anchor on all four changed pages resolves in the built site, including the attr_list anchor {: #aggregate-counts-objects-for-an-all-rejected-list } (renders as a real id=, and the three inbound links from understanding-results.md land on it) and bbox-map-metrics.md#iou-calculation.

Published numbers, re-derived against the engine rather than read off the page. Every figure I could execute matched exactly:

  • five items / one wrong leaf: overall tp=5 fd=0 P=1.0, aggregate tp=29 fd=1 P=0.9667 F1=0.9831, overall_score 0.9667
  • one item rejected: overall tp=4 fd=1 P=0.8 R=1.0 F1=0.8889, aggregate tp=24 fd=0 P=1.0, overall_score 0.9333
  • the recall_with_fd table, which is the one published figure no test pins: False -> R=1.0, True -> R=0.8. Correct.
  • the null-leaf invention: overall tp=1 fp=0 fa=0, aggregate tp=5 fp=1 fa=1
  • the EvalResult note, run through stickler.evaluate() with plain pydantic models: precision 1.0, overall_score 0.9667, aggregate.cm_precision 0.9667
  • an item invented wholesale: overall fa=1 fp=1, aggregate untouched -- which independently justifies reading both nodes

The fd/fa -> fp change in the clean check is safe. I grepped every "fp": assignment in src/: structured_list_comparator.py:154, structured_model.py:1021, field_comparator.py:72,141, confusion_matrix_calculator.py:89,234,243, primitive_list_comparator.py:116, result_helper.py:43,102 and comparison_engine.py:174 all maintain fp == fa + fd. Notably comparison_engine.py:173-174 increments fp alongside fa for hallucinated extra fields, so the shorter check does not lose the extra-field case either. FP = FA + FD by construction holds, and the new form is strictly more complete than the one it replaces.

The match_threshold-is-inert claim holds under a stronger test than the one in the file. test_match_threshold_is_inert_for_this_shape mutates _Contact.match_threshold after class definition, which would also pass if the value were simply captured at definition time. I re-ran it with match_threshold declared on the nested class at definition (0.9 / 0.7 / 0.5 / 0.1) and with it declared on the containing Doc: (overall tp=2 fd=0, aggregate tp=3 fd=1) at every value. Inert either way, so the documented claim and the retired-remedy guard are both sound.

CHANGELOG. The first hunk looks alarming in the diff -- it deletes the json-schema-to-pydantic and AUROC bullets -- but those are duplicated at the merge base (lines 107/122 and 144/159, from an earlier bad merge), and this removes the second copy. Same for the doubled all_fields_matched block. Net effect is a de-duplication; nothing is lost.

Three nits, none worth another round:

  • _TREES_WE_AUTHOR includes examples, but _authored_prose walks only src/docs/tests. So the phrase guards do not cover examples/ while test_no_file_anywhere_publishes_the_superseded_form does. Harmless today; the constant's name promises more than the walk delivers.
  • _phrase_hits computes its char offsets before re.sub(r"\s+", " ", joined) collapses whitespace, so a reported line number can drift on a file with internal whitespace runs (the doc tables have them). Message-only -- it cannot cause a false pass or fail.
  • The "How many list items did the model find?" row points at the list field's overall; strictly that answer is tp + fd, since a rejected pairing lands in fd. The worked tables right below make it unambiguous.

Non-blocking, and I agree with the call: EvalResult.precision reading the root overall while overall_score is a leaf-weighted mean will keep generating this same question. Documenting it here and holding the rename for 1.0 (#288) is right, but the note under "Not in scope" is doing a lot of load-bearing work for a name that actively misleads.

@sromoam
sromoam merged commit a7cdb6a into dev Sep 9, 2026
18 checks passed
@sromoam
sromoam deleted the docs/288-overall-vs-aggregate branch September 9, 2026 19:29
sromoam added a commit that referenced this pull request Nov 2, 2026
…475)

* refactor(anls)!: rename tau to leaf_threshold so `threshold` means one thing

`ANLSStarComparator` used the inherited `threshold` slot for tau, the
per-leaf cutoff applied during the recursion. That made `threshold` mean
two different things depending on the comparator: a verdict about a field
everywhere else, an algorithm parameter here.

Tau changes the SCORE the comparator returns. A verdict threshold decides
whether a score counts as a match. Those are different jobs and now have
different names:

    ANLSStarComparator(threshold=0.9)        verdict, as on every comparator
    ANLSStarComparator(leaf_threshold=0.85)  tau, the internal cutoff

`threshold` now defaults to 0.7 rather than 0.5, matching the value the
dict branch of ConfigurationHelper already supplied, because a mapping is
judged as an object.

Behavior-neutral: nothing reads a comparator's `threshold` during
evaluation today, so moving tau to its own attribute changes no score.
1999 passed, 2 skipped.

`config` now emits `leaf_threshold` instead of `threshold`, so a schema
exported before this change and re-imported after it would read a
non-default tau as a verdict threshold. Only affects non-default values,
which nothing in the repo exports.

* fix: address the five findings from reviewing the dict work

Every one reproduced before fixing; each has a test that fails without its fix.

1. ANLS* applied edit distance to every leaf, so character overlap between two
   numbers read as partial correctness. `{"amount": 1000}` vs
   `{"amount": 9000}` scored 0.75, cleared the 0.7 field threshold and reported
   a nine-fold error as a TRUE POSITIVE. Worse than the ranking failure this
   work exists to fix, because it corrupts the confusion matrix rather than
   flattening it. Dates were worse still (0.80), and self-inflicted: a `date`
   reaches the leaf already serialised to ISO by this library, so the type
   signal was destroyed here. Non-string leaves and ISO timestamp pairs are now
   right or wrong; text keeps its partial credit.

2. `Mapping[str, str]` and the rest of the family fell through to the exotic
   branch and were canonicalised to a JSON string, so the auto path disagreed
   with the explicit path about the same annotation, and with three docs
   surfaces. Both call sites now use `ConfigurationHelper.is_mapping_annotation`.

3. `_install_mapping_comparators` read raw `__annotations__`, which hold the
   STRING "Dict[str, Any]" under PEP 563, so it skipped every field. The engine
   still got ANLS* via the read-time fallback while `to_json_schema()` reported
   Levenshtein: precisely the divergence the method exists to prevent. Moved to
   `__pydantic_init_subclass__` over `model_fields`, whose annotations are
   resolved and whose FieldInfo is the object every reader consults. Writing to
   the pre-copy FieldInfo was silently discarded, which is how this hid.

4. The `handles_mappings` gate zeroed comparators that work. `ExactComparator`
   now canonicalises a mapping, so identical content is 1.0 regardless of key
   order -- it used `str(dict)` before, returning 0.0 or 1.0 depending only on
   how the JSON arrived. `StructuredModelComparator` was already correct.
   Levenshtein and Fuzzy stay excluded: the first raises, the second scores a
   changed value (0.944) above a mere reordering (0.667).

5. The substitution mutated the shared `json_schema_extra` closure, which
   pydantic does not clone, so one `ComparableField(...)` bound to a `str` field
   and a `Dict` field put ANLS* and clip=False on the string field, dependent on
   class definition order. Now copies.

Fixing 3 also restored `clip_under_threshold=True` being honoured, so the sixth
finding needed no separate change.

Also rebased onto dev (adopting #226's removal of `aggregate` while keeping the
clip sentinel), merged the duplicate `### Changed` heading, and cleaned two
editing artifacts: a mangled continuation indent in `builder.py` and a stray
empty comment in `facade.py`.

Two limits recorded rather than fixed, both pre-existing and identical on dev:
a dict field exports as `type: "string"` and re-imports as `Optional[str]`, so
a round-tripped model cannot hold a mapping (the comparator does survive); and
a numeric STRING is still text, deliberately, because the annotation is the
signal.

2088 passed, 12 skipped, ruff clean on src and tests.

* fix: keep ANLS* leaves canonical, and fix the two structural findings

Reverts the type-aware leaf comparison added in the previous commit, and
addresses the two findings that are independent of it.

## Why the leaf typing is reverted

It amounted to a SECOND inference table that contradicted the first:

    value            auto (declared field)                  typed leaf (as written)
    amount: float    NumericComparator@0.95, tol 0.001      exact equality
    issued: date     DateComparator@0.95                    string equality
    total: Decimal   NumericComparator@0.95, tol 0.001      edit distance
    vendor: str      Levenshtein@0.85                       Levenshtein@tau 0.5

So `1000.0` vs `1000.0001` was a match as a declared field and a miss as a dict
leaf, decided only by whether the author happened to declare the field. That is
the divergence #239 exists to remove; adding a fifth answer while writing the
contract that says there should be one is not a trade worth making.

It was also wrong in three ways review caught: `1000` vs `1000.0` scored 0.0
(a PERFECT extraction read as a total miss, and a regression in the public
`anls_score`), `Decimal` took the string branch because pydantic serialises it
to a string, and `datetime.time` was not covered by the date regex. Those are
symptoms of classifying on the post-normalisation value; the regex was treating
symptoms.

## What canonical means, and its cost

Every leaf is compared as text. ANLS came from scene-text VQA where every answer
is a string; what ANLS* generalises is the STRUCTURE -- key alignment, union
normalisation, Hungarian pairing.

The cost is documented rather than patched, in the comparator docstring, the
comparators guide, the CHANGELOG, and a test that asserts the numbers so nobody
"corrects" them:

    wrong IBAN, one character        0.9545
    date one day off                 0.9000
    amount 2x wrong                  0.8571
    "Acme Corporation"/"Acme Corp"   0.5625

No `leaf_threshold` separates those, and a test proves it rather than claiming
it. The remedy for a caller is to declare the field.

A future `infer_types=True` is described where someone would look for it,
including that it must delegate to `stickler.auto.inference` rather than define
its own rules, and that #49 (which side's type is authoritative) blocks it.

## The two findings that survive the revert

`can_score_mapping` is now a DENYLIST. It gated on a new `handles_mappings`
attribute no out-of-tree comparator could carry, so a user who wrote a mapping
comparator and asked for it by name got 0.0 -- reproducing #297's symptom for a
different population, and overriding an explicit `comparator=`, which is consent
by definition. Only Levenshtein (raises) and Fuzzy (ranks a changed value 0.944
above a reordering at 0.667) are refused, on measured evidence.
`handles_mappings` is deleted rather than documented, since nothing reads it.

`List[Dict[...]]` is routed on the explicit path, keyed on the element type. The
element kept Levenshtein, whose canonical-JSON fallback compared edit distance
over a blob: 0.7667 on one path (clearing a 0.7 threshold) against 0.0 on the
other for the same annotation. Both now compute the same raw score.

Also corrected two comments that claimed declaring Levenshtein on a dict
"raises" when it warns and scores 0.0.

Net: -39 lines of leaf logic, -121 lines of tests pinning it, +14 tests pinning
the canonical contract instead. 2084 passed, 12 skipped, ruff clean.

* fix: one annotation, one answer, on the two branches that disagreed

Three defects, all introduced earlier on this branch, all found by review
rather than by tests. The suite was 2084 green before and after the fixes,
which is the finding behind the findings.

## Declaring ComparableField changed which comparator a field got

`List[Dict[str, str]]` routing was added to the no-metadata fallback but not to
the read-time substitution beside it, so the same annotation resolved two ways:

    rows: List[Dict[str, str]] = ComparableField(threshold=0.7)
        -> LevenshteinComparator, edit distance over a canonical JSON blob,
           0.7667 for a near-miss, which CLEARS a 0.7 threshold

    rows: List[Dict[str, str]] = None
        -> ANLSStarComparator, 0.5625

Whether a field carries `ComparableField(...)` is not information about how its
values should be compared, so it must not select the comparator.

## Naming the comparator re-enabled clipping

The clip default rode along with the comparator substitution, which is skipped
when the caller named a comparator. So the form the new docs RECOMMEND for
setting the leaf cutoff turned clipping back on and zeroed the partial credit
ANLS* exists to produce:

    ComparableField(threshold=0.9)                              -> 0.8542
    ComparableField(comparator=ANLSStarComparator(), ...)       -> 0.0

The clip default now follows the annotation, applied whether or not the
comparator was named, on a copied descriptor for the same reason the
substitution copies. An explicit `clip_under_threshold=` still wins.

## ExactComparator canonicalised a lone mapping

Testing `isinstance(a, Mapping) or isinstance(b, Mapping)` made a dict equal to
its own JSON-string spelling, so `compare()` returned 1.0 while `compare_with()`
classified the same pair as a false discovery, its dict branch requiring two
dicts. A mapping and a string are different shapes; both sides must be mappings.

## Tests

Five added, including one that asserts the declared and bare spellings of
`List[Dict[...]]` produce the SAME score rather than each being independently
plausible. Every one of these three passed review-free because the suite only
ever checked one spelling at a time.

Also corrected the "Zero-config routing" paragraph, which claimed an
`Any`-annotated dict is a false discovery with a warning; on that path it is
canonicalised to JSON and scored by ExactComparator with no warning. Removed an
orphaned comment and stray blank lines left by the previous commit.

2089 passed, 12 skipped, ruff clean on src and tests.

* fix: refuse values with no JSON form, and rewrite the comparator docs

## Values with no JSON form are refused rather than scored

`to_jsonable_python(fallback=str)` invented a text form for values outside this
comparator's domain. For an object without a value-based `__repr__` that text is
`<module.Class object at 0xADDRESS>`, and two of those share a long prefix, so
edit distance was comparing memory addresses:

    two UNRELATED objects   0.8684   -> reported as a true positive
    two EQUAL objects       0.8857   -> reported as a miss
    longer class name       0.9315   -> a longer shared prefix scores HIGHER

It failed in both directions, and got worse the more specific the surrounding
code was. Nothing about the values participated.

The fix is scope, not equality semantics. ANLS* scores JSON values, and only
types pydantic cannot represent reach the fallback at all -- `date`, `datetime`,
`time`, `Decimal`, `UUID`, `Enum`, `set`, `tuple`, `bytes` and `Path` are all
handled natively. So such a value is refused: 0.0, whether or not the two sides
are equal, with a `warn_once` per type so a refusal is distinguishable from a
wrong extraction. Neighbouring keys keep their credit.

The refusal keys on JSON-representability, not on repr quality. An object with a
good `__repr__` is refused too, because sniffing whether a repr "looks
value-based" would be a heuristic about someone else's code and would make our
domain depend on how their class happens to be written.

Note the marker cannot be a plain string flowing into the metric: two identical
markers would score 1.0, making every out-of-domain value match every other. The
leaf short-circuits on it instead.

## Docs rewritten for someone deciding whether to use this

The section had grown to 103 lines against ~27 for every sibling, was the only
one in the file carrying issue links, and opened with the mechanism rather than
the problem. Now it opens with what the comparator is for, gains a "when NOT to
use", and leads with a runnable example whose printed numbers are real.

Removed: issue links, micro-benchmarks, zero-config-routing internals, and the
design argument for not typing leaves. That reasoning belongs in the docstring
and CHANGELOG, where maintainers look, and both already carry it.

Added: eight real scorings against one ground truth, showing that a renamed key
scores WORSE than a missing one; a before/after for `leaf_threshold`; and the
text-comparison table rebuilt to show ground truth against prediction with the
differing character bolded, so the failure is visible rather than described.

Every number and both code samples are verified by execution, not written from
memory.

Also: sibling comparators are linked following this file's own convention,
`StructuredModel` links to the API reference and opens in a new tab, and "IBAN"
is replaced with "22-character account number" -- an undefined acronym that also
hid the point, which is that length drives the false score.

11 new tests. 2105 passed, 12 skipped, ruff clean, mkdocs warnings unchanged
from dev.

* docs: answer why a reader would tune leaf_threshold

The parameter was documented by what it does and by a warning not to set it to
0.0, but never by why anyone would change it. The answer is concrete once
measured: character similarity scales with length, so one cutoff is lenient for a
short value and strict for a long one. At the default, a wholly wrong short code
still earns half credit.

    kind         truth              prediction        0.5      0.7      0.85
    state code   CA                 CO                0.5000   0.0000   0.0000
    status       PAID               PEND              0.5000   0.0000   0.0000
    vendor name  Acme Corporation   Acme Corp         0.5625   0.0000   0.0000
    description  blue widget, 3in   blue widget 3in   0.7895   0.7895   0.0000

So: raise it toward 0.7 for short codes, where one wrong character means wrong
rather than close; keep the default for names and free text, where a genuine
abbreviation should still count.

The most useful line is that the two columns disagree. 0.7 correctly rejects the
wrong status and also discards the correct vendor abbreviation, so a dict holding
both kinds has no single right value and the answer is to declare the fields that
matter. That is the same limit the text-comparison warning above reaches from the
other direction, which makes the section argue one thing end to end rather than
listing properties.

Numbers verified by execution.

* docs: show that numerically equal values can score below 1.0

The text-comparison warning only showed one direction, wrong values scoring
high. The opposite is likelier to bite:

    5                  vs 5.0                -> 0.0000
    1000               vs 1000.0             -> 0.6667
    Decimal("10.50")   vs Decimal("10.5")    -> 0.8000

A ground truth loaded from a database as an integer, against a prediction parsed
from JSON as a float, is a perfect extraction scored as a miss. Two identical
numbers scoring 0.0 is the kind of thing a reader should not have to derive from
"compared character by character".

Review raised this as a blocker and it is being answered as documented behaviour
rather than fixed, so the documentation has to actually document it, and the
remedy has to be named: declare the field with NumericComparator.

Five tests, including one asserting the named remedy works, so the docs cannot
recommend something untrue.

2105 passed, ruff clean, mkdocs warnings unchanged.

* docs: restore the BBoxIoUComparator section the ANLS* rewrite overwrote

Review caught that the entire `### BBoxIoUComparator` section was gone while the
summary table still linked `#bboxioucomparator`, so that link was dead.

Cause: I rewrote the ANLS* section by replacing everything between
`### ANLSStarComparator` and `### SemanticComparator`. BBoxIoU sat between them,
so a slice intended to touch one section silently consumed two.

Restored verbatim from `dev`, in its original position.

Also ran the check that would have caught it, which is mechanical: every heading
and bolded label present in `dev`'s version of the file is present here (0
missing), and every same-page anchor the document links resolves to a heading
that exists (0 broken). Same check across the other docs this PR touches shows
sections added and none removed.

Third loss of this shape across #290 and #300, all from index-based slicing or
conflict resolution, and none catchable by the test suite because nothing tests
prose. The check is three lines and belongs in the workflow, not in hindsight.

2110 passed, 12 skipped, mkdocs warnings unchanged from dev.

* feat: add normalized text comparator

* fix(210): reject unrecognized x-aws-stickler-* keys instead of dropping them

A misspelled extension key was silently discarded, leaving a model that built,
ran, and reported numbers wrong in the direction of over-reporting accuracy. The
sharpest shape was a typo beside a correctly-spelled sibling:

    x-aws-stickler-comparitor: ExactComparator   (typo, dropped)
    x-aws-stickler-threshold:  1.0               (honoured)
    -> LevenshteinComparator at threshold 1.0

Levenshtein at threshold 1.0 is the arithmetic product of one silent drop plus
one honoured key, and nobody would choose it.

The asymmetry this closes: a bad extension VALUE already raised a clear,
actionable error, so the schema path taught users it validated their input and
then said nothing about the case that actually bites.

Raising rather than warning, unlike the mapping-comparator gate elsewhere in this
codebase. A schema is read deterministically at import, so there is no risk of
failing on document N of a corpus after succeeding on N-1; the author is present
and the mistake is in a file they can edit.

Suggestions compare the SUFFIX after the prefix, not the whole key. Every valid
key starts with `x-aws-stickler-`, so whole-string similarity is dominated by
that shared prefix and returned a confident match for anything at all --
`x-aws-stickler-zzzzzzzz` scored as a near-miss on `-weight`. Found by a test I
wrote expecting no suggestion, which is why it is pinned. A wrong suggestion is
worse than none.

Accepted but never advertised: `x-aws-stickler-aggregate` (removed in #226, so
schemas already on disk keep importing) and the internal examples key. Offering
either as a correction would send an author somewhere useless.

`structured_object_evaluator/README.md` and `examples/scripts/json_schema_demo.py`
both used `x-stickler-*` and lowercase comparator names. Neither works: the
prefix was dropped and `"fuzzy"` is not a registered comparator, so the README's
own example applied NONE of its settings and raised nothing. With this change it
would have raised, so correcting it is part of the fix rather than a follow-up.
The example now applies all three of its settings, verified by running it.

Two of this issue's acceptance criteria are deliberately not here:

- `explain()` reporting a schema fallback as `source: "explicit"` needs a marker
  recording whether a setting was actually read. That is `_comparator_explicit`,
  which #300 introduces and `dev` does not have. Criterion 1 also removes the
  harmful case, since a typo can no longer produce a built model at all.
- The auto-versus-schema divergence table belongs to #239, whose numbers changed
  when #285 merged. Current measurements are on #239 and #186.

`nullable: true` (criterion 4) was fixed by #285 and now yields `Optional[str]`.

14 new tests. 2053 passed, 12 skipped, ruff clean, demo script exits 0.

Refs #210

* fix(210): make extension-key rejection reach every position

Review found the guarantee stopped at field level. `_reject_unknown_extensions`
ran only from `_extract_extensions`, which is per-field, so a typo on the
root object, on `items`, or on a list-form `["object", "null"]` node was
still dropped in silence while the identical typo one level down raised.

The check now runs from the walk in `_validate_supported_shapes`, which
visits every node of the RAW schema before `_prepare_schema` rewrites
list-form types into `anyOf`. Running after normalization was how the
list-form cases escaped: the node the author wrote no longer existed in the
shape being inspected.

Position is now part of validity, because the two key sets are not
interchangeable. Measured against dev, which of the two is read depends
entirely on where the key sits:

    position           model keys   field keys
    root object        read         not read
    object property    read         weight read
    array items        read         none read
    scalar property    not read     read

Allowlisting both sets everywhere meant the check passed on keys that do
nothing, and worse, let the suggester answer a field-position typo of
`-match-threshold` with "did you mean `x-aws-stickler-match-threshold`",
where applying that advice imported cleanly and changed nothing. That is the
exact silent drop this module exists to prevent, reached by following our own
error message. Suggestions are now scoped to the position, and a valid key in
a position that does not read it says so and names where it belongs.

An object-typed property reads both sets, so it is checked against their
union; `_extract_extensions` keeps a permissive backstop for entry points
that never walk a raw schema, rather than re-deciding position from an
annotation and disagreeing with the walker.

Docs: the README example was already corrected to `FuzzyComparator`, but the
key list below it still documented the lowercase aliases, which now raise, so
correcting the prefix alone would have turned a double no-op into a hard error
for anyone copying the page. The list now gives class names, separates
field-level from object-level keys, states that position matters, and fixes
the `clip-under-threshold` default, which it had recorded as `false` rather
than `true`. A test asserts the README's example applies every setting it
documents, verbatim.

22 new tests. The demo script keeps only its prefix corrections: it was
already unformatted on dev, so running the formatter over it would have added
about 290 lines of unrelated churn.

* feat(comparators)!: warn when compare() shadows the None policy (#215)

Removing the 0.7.0 shim outright left the one shape that still misbehaves
with no diagnostic at all. A subclass of a concrete comparator that supplies
compare() inherits _compare through the MRO, so it constructs and silently
bypasses the None policy -- str(None).lower() launders None into "none"
before the template method ever runs. On 0.7.0 that shape at least got a
DeprecationWarning naming the rename.

__init_subclass__ now reports exactly that shape, and only that shape:

- no _compare anywhere (extends BaseComparator, or a mixin over it):
  ABCMeta already raises TypeError at construction naming _compare, so no
  warning is emitted. A warning ahead of a hard failure is only noise.
- _compare inherited from a concrete comparator: constructs, so a
  UserWarning fires at class-definition time.

The signal is a warning rather than a TypeError because the condition is not
decidable at class-definition time. An override that forwards both values to
super().compare() unchanged keeps the policy intact and is correct code, and
nothing at class creation can distinguish it from one that transforms the
values first; a TypeError would reject both. Defining _compare opts out, and
the MRO-owner lookup keeps ordinary subclasses of a deliberate override
quiet.

UserWarning rather than DeprecationWarning so it is visible without -W, and
stacklevel=4 to skip the ABCMeta.__new__ frame so the warning points at the
user's class statement.

Restore _reset_deprecation_sentinels in the comparators conftest: the guard
warns through warn_once, which dedupes per process, so the new assertions
would silently rot without the reset.

Restore the published 0.7.0 CHANGELOG prose verbatim and append the version
and behaviour corrections to the existing correction note, matching the
convention used by the ComparableField(aggregate=) entry in the same section.
Update the Comparators guide, which documented only the TypeError half.

* docs(288): state which rollup node answers which question

`confusion_matrix.overall` and `confusion_matrix.aggregate` were described only
mechanically ("this node's own direct classification" / "sums all
primitive-field classifications beneath"). Accurate, and no help: nothing said
which to read for which question, or that they diverge on any model with
nesting.

They answer two different questions. `overall` gives object verdicts: was this
pairing genuine, or spurious. `aggregate` gives leaf detail for the objects that
were comparable. `match_threshold` is the line between them, and the gating is
deliberate: an object scoring below it is one FD, a spurious non-match, and is
not descended into, because reporting the leaves of an object already rejected as
a whole would score something declared not comparable.

    5 items x 6 leaves, one leaf wrong, item scores 5/6 -> comparable
      overall     tp=5   fd=0    P=1.0000     5 comparable objects, none spurious
      aggregate   tp=29  fd=1    P=0.9667     30 leaves, one wrong

    same item at 4/6 -> rejected
      overall     tp=0   fd=1
      aggregate   tp=0   fd=1                 no accepted subtree to expand

The knob for leaf detail on a marginal object is `match_threshold` itself, which
the docs now say and a test now pins:

    match_threshold   comparable?   aggregate
    0.70              no            tp=0 fd=1
    0.66              yes           tp=4 fd=2

The two nodes coincide only where there is no accepted subtree: a flat model, or
a subtree rejected outright. Documented across the three pages a reader lands on,
plus both `compare_with()` docstrings, with a which-node-for-which-question table
and the conjunction that a complete "did anything fail" check needs (`overall` is
the only node carrying `fa`, since an invented field maps to no ground truth
leaf).

Also documents that `EvalResult.precision`, `.recall`, `.f1` and `.accuracy` are
the object-level metrics, read from `overall.derived`. A `precision` of 1.0 beside
an `overall_score` of 0.9667 on the same object is two correct answers to two
different questions, not a contradiction. The naming is what #288 leaves open for
1.0.

`test_rollup_node_semantics.py` pins the published numbers, the gating, the
`match_threshold` remedy, and the flat-model case where the nodes converge.

Whether aggregates should also count the leaves of below-threshold objects is a
deliberately deferred question and is not treated here as a defect.

1975 passed, ruff clean, mkdocs adds no new warnings (strict mode already fails
on 9 pre-existing findings in untouched files).

* docs(288): ground the two rollup nodes in the mAP structure

Names the two stages rather than describing them: `overall` is detection (unit =
the object, did we find the right things), `aggregate` is extraction (unit = the
leaf, among objects established to be the same object, were the values right).
`match_threshold` is the handoff, and it is really the definition of "the same
object": above it, grading the fields is meaningful; below it, grading them would
be scoring the fields of a different object.

That is the structure of mAP, which this repo already implements for bounding
boxes, and `bbox-map-metrics.md` already documents the same rule for IoU: a
below-threshold detection is a failure at the matching stage, not a source of
per-attribute errors. So both pages now cross-link to it rather than arguing the
point from scratch. It also answers the "is the gating a hole" question by
reference to a standard the audience already accepts.

Cross-links verified to resolve against the `#iou-thresholds` anchor.

1975 passed, ruff clean, mkdocs adds no new warnings.

* docs(288): correct the published rollup numbers and the clean check

Review found three published artefacts that did not hold, all verified
against the engine.

The `clean` snippet reported clean on a document containing a hallucinated
value. It read `fa` on `overall` alone, but a leaf whose ground truth is
null and whose prediction supplies a value is `fa` at that leaf and rolls
into `aggregate`, while `overall` stays clean because the item still pairs:

    one item, GT total=None, prediction total="INVENTED"
    overall     tp=1  fp=0  fn=0  fa=0  fd=0
    aggregate   tp=5  fp=1  fn=0  fa=1  fd=0

Both nodes carry `fa`, for different kinds of invention. The check now sums
`fp`, which equals `fa + fd` by construction and cannot go stale if a class
is added. The snippet was published in four places, two of which were not
in the original diff: `threshold-gated-evaluation.md` and a second copy
earlier in `understanding-results.md`.

Both worked-example tables printed a one-item document's numbers under
prose describing five and two items:

    5 items, third at 4/6   overall tp=4 fd=1   aggregate tp=24 fd=0
    2 items, second at 4/6  overall tp=1 fd=1   aggregate tp=6  fd=0

The conclusion drawn from the first inverted on its own data: the nodes do
not converge when an item is rejected, they diverge further, and
`aggregate` reports a flawless P=1.0000 precisely because the rejected item
contributes no leaf rows. They coincide only when *every* subtree is
rejected, which is now stated and pinned.

Also names where the mAP analogy stops: a below-threshold detection counts
as both FP and FN so mAP recall falls, while a below-threshold object is
`fd` only, so `overall` recall reads 1.0 unless `recall_with_fd=True`.

Corrects the `overall` bullet, which claimed it counts pairings and not
leaves; on a flat model it counts leaves, which the convergence test
already asserted. Gives the dangling "see the caveat below" a target.

Tests: both tables are now pinned, which is the gap both errors came
through, plus the null-ground-truth FA case, the rejected-subtree case that
separates `overall_score` from `aggregate` precision, and a guard walking
all three pages to confirm none has drifted from the executable snippet.
Narrows the docstring claiming `overall_score == aggregate` precision as a
property; it holds only while leaf scores are binary, weights uniform,
there are no FN and nothing was rejected.

CHANGELOG: de-duplicates the "Replacements" block, which shipped twice in
blank line before the 0.7.0 heading.

* docs: de-duplicate two release notes that shipped twice

`### Changed` carried the `json-schema-to-pydantic` delegation entry and the
NumPy statistics entry twice each. Both arrived on dev through earlier
conflict resolutions, not from this branch: I checked the counts both ways
before touching them.

Folded in here rather than opened as its own PR because this branch is
already correcting the duplicated `Replacements` block for the same reason,
and the two fixes are one class of defect.

* fix(246)!: honour a threshold set on a comparator

`Comparator(threshold=...)` was accepted everywhere and read almost nowhere.
The only functional reader outside ANLS* is `binary_compare()`, which has no
callers in `src/`, so

    ComparableField(comparator=LevenshteinComparator(threshold=0.95))

produced a field whose verdict threshold was 0.5. The value sat on the
comparator, showed up in its repr, and was never consulted.

A threshold is only meaningful beside the metric that produced the score:
0.85 means one thing on edit distance and another on a semantic embedding.
So a threshold the caller put on the comparator is a statement about the
field, and discarding it in silence is the wrong default.

`ComparableField(threshold=...)` now defaults to None meaning "not
specified". Precedence: a threshold on the field wins; else one explicitly
set on the comparator is adopted; else 0.5 stands in until inference owns
that case (#239).

A comparator's own DEFAULT is deliberately not adopted, because those
defaults were never audited as verdict thresholds and several are wrong for
the job. `DateComparator` defaults to 1.0 while awarding 0.7 for a match
with no year, so adopting it would clip that comparator's own feature to
zero. Explicitness is recovered by comparing against the default declared on
the concrete class, since each subclass resolves its own before calling
`super().__init__`. One documented consequence: passing a value equal to the
class default reads as not set.

Reimplemented against current dev rather than rebased. The original branch
predated #212's delegation to json-schema-to-pydantic, which cut
`json_schema_field_converter.py` from ~570 lines to 239, so its conflicts
were against a structure that no longer exists. The semantic change is small
and dev already carried `_comparator_explicit` and `_clip_explicit` from
#300, so only the threshold half was missing.

Also records `_threshold_explicit`, which is what #210's remaining
acceptance criterion needs to tell a configured field from a defaulted one.

20 tests. 7 fail against dev's logic, including the verdict flip: a 0.9
similarity is a true positive at the old 0.5 and a false discovery at an
adopted 0.95, so the classification moves rather than just the reported
number. Full suite 2342 passed with no other test touched.

* fix(318): score a nested plain BaseModel instead of calling it a mismatch

`ComparisonDispatcher` routed on `isinstance(value, StructuredModel)`. A plain
pydantic `BaseModel` is not one, so a nested one fell through to the
mismatched-types branch and scored 0.0 against an IDENTICAL object, reported
as `fd=1`: a perfect match that is also a failure, the contradiction #287
removed elsewhere.

The asymmetry is what makes it a defect rather than an unsupported shape,
because the list form of the same type was already correct:

    Optional[Plain]        identical -> 0.0   and fd=1
    Optional[List[Plain]]  identical -> 1.0

CASE 2 already sends any non-StructuredModel element to the primitive list
comparator, so the singular and list forms of one shape disagreed.

Both now compare the model's canonical string through the field's declared
comparator, which is the same routing CASE 4 uses for a dict and for the same
reason: that method is only "primitive" in name, and it calls the field's
comparator, classifies against the field threshold, and honours clip.

Measured, singular and list now identical at every input tested:

    identical   1.0000 / 1.0000
    one char    0.8571 / 0.8571

Deliberately NOT scoring a plain BaseModel field by field here. That is what
`StructuredModel` is for, and what `stickler.evaluate()` does by wrapping one.
Doing it in the dispatcher would make a nested plain model behave differently
from the same model inside a list, trading this inconsistency for another;
the general question is #135.

A nested `StructuredModel` is unaffected and keeps its per-field detail. The
new branch sits after that one, which is load-bearing because
`StructuredModel` subclasses `BaseModel`, and a test asserts the ordering did
not swallow it.

16 tests, 9 of which fail against dev. Also covers that the canonical form is
independent of keyword order at construction, since order sensitivity there
would be the #276 bug in a new place.

* fix(318): pass the models to the comparator unconverted, and require one class

Adversarial review found three defects, all reproduced. Two of them were worse
than the bug this PR fixes.

Stringifying in the dispatcher defeated any comparator that reads structure.
`ANLSStarComparator` scored 0.9091 on a stringified model against 0.5000 on
the same model in a list, which is exactly the asymmetry this PR exists to
remove, reintroduced one comparator over. The tests could not see it because
they used Levenshtein and Exact, which coerce internally anyway. The models
now pass through unconverted, as CASE 4 already does for a dict: the
comparator decides its own coercion, the dispatcher does not decide for it.

That also restores the invariant `compare_field_raw` documents in its own
comment, that `compare()` and `compare_with()` agree on a field.
`compare_field_raw` passes raw models, so stringifying on one side only made
them disagree, 0.9091 against 0.5000, and `compare()` is what the Hungarian
cost matrix reads.

Both sides must now be the same class. Pydantic's `__str__` omits the class
name, so `Cat(name="rex")` and `Dog(name="rex")` both render as `name='rex'`
and compared equal: 1.0 with tp=1 where dev reported fd=1. Turning a genuine
type mismatch into a perfect match is worse than the 0.0 this PR set out to
fix. Reachable through `Any` and through a union of models, where pydantic
keeps the concrete class.

Two further findings are NOT fixed here, because they are pre-existing and not
introduced by this branch: a `repr=False` or `SecretStr` field is invisible to
scoring, and a dict-valued field inside the plain model makes key order
significant (0.8095 for identical content). Both measured identical on clean
dev via the list path, so this PR extends them to the singular case rather
than creating them. Filing separately.

Adds the documentation the shape had none of: the comparators guide now states
that a nested StructuredModel is compared field by field while a nested plain
BaseModel is compared as one value, and how to get the former.

Also corrects a stale "CASE 5" reference left by the renumbering.

23 tests, up from 16. The new ones use a comparator that can tell the
difference, which is what the original set could not.

* fix(318): settle the subclass case, and declare the rendering limitation

The class check was `type(gt) is type(pred)`, taken from review without
deciding what it means for a subclass. Deciding it: a subclass renders its own
fields, so even with the extra field unset the renderings differ,

    str(Base(a="x"))  ->  "a='x'"
    str(Sub(a="x"))   ->  "a='x' b=None"

so loosening to `isinstance` would score a schema mismatch by edit distance and
report a near-match. Exact class is the better answer, and it is now documented
and tested rather than incidental.

Also declares in the CHANGELOG the limitation this branch inherits rather than
introduces, now tracked as #320: a plain BaseModel is compared by its rendered
form, so a custom `__str__`, a `repr=False` field or a `SecretStr` hides data
from scoring, and extra-field or dict key ordering makes identical content score
below 1.0. Measured identical on dev via the list path, so this change makes the
singular case consistent with the existing behaviour rather than fixing it. It
was wrong to leave that unstated when it is measurable and known.

2349 passed, ruff clean.

* fix!: tell a named comparator threshold from a default one

Review of the previous revision found three defects in how explicitness
was inferred, and one place where a fix was needed and not made.

The inference was `resolved value != class default`. That cannot work:
every comparator resolves its own default before calling
`super().__init__`, so `DateComparator()` and `DateComparator(threshold=1.0)`
both arrive holding 1.0. Consequences:

  - The effective threshold was not monotonic. `Lev(threshold=0.69)` gave
    0.69 and a stricter 0.70 gave 0.50, because 0.70 is Levenshtein's
    default. `Exact(threshold=1.0)`, `Numeric(threshold=1.0)` and
    `Date(threshold=1.0)` -- the strictest and most natural spelling, and
    the one used in Custom_Comparator_Demo.ipynb -- all collapsed to 0.5.
  - A comparator forwarding `**kwargs` to `super().__init__` was missed
    entirely, so the bug stayed live for out-of-tree comparators, which
    are a documented extension point.

`BaseComparator.__init__` now takes `Optional[float] = None` and records
`threshold_was_set`; each comparator declares `DEFAULT_THRESHOLD`.
`.threshold` reads back the same number as before. This keeps the rule
that a comparator's *default* is never adopted -- `DateComparator`'s 1.0
would clip its own `allow_partial_year` credit of 0.7 to zero -- while
honouring any threshold the caller actually named.

Separately, the previous revision broke models that work on dev:

    items: List[Item] = ComparableField(comparator=Lev(threshold=0.9))

raised at class-definition time, blaming a `threshold` parameter absent
from the call site. The `List[StructuredModel]` guard in
`__init_subclass__` used `threshold != 0.5` as its proxy for "the caller
set one", and adopting a comparator threshold trips that proxy. It now
reads the `_threshold_explicit` marker this change already added but did
not consume. Two follow-on sites stopped passing a 0.5 placeholder for
list-of-model fields, and `to_json_schema()` stopped emitting
`x-aws-stickler-threshold` for them: it was never read there, and import
now rejects it, so such a model could be exported and not imported back.

Docs said in five places that evaluation ignores the comparator
threshold. Corrected, with the precedence chain (field, then comparator,
then 0.5) stated in both the thresholds guide and the comparators guide,
and every number in the new table verified against the engine. The
CHANGELOG no longer says "nothing else changes": `clip_under_threshold`
defaults to True, so an adopted threshold also zeroes the field score
(measured 0.9 -> 0.0), and it no longer claims `_threshold_explicit`
powers `explain()`, which is still #210's work.

Refs #246, #210

* fix!: score a nested plain BaseModel as an object, not as its string

Addresses Vincil's four review findings on #319. All four reproduced
before changing anything; three were mine.

The previous revision moved the ROUTING for a plain BaseModel to the dict
code path but not the CONFIGURATION, so the field kept the primitive
default of Levenshtein at 0.5: edit distance over `str(model)`. Field
names are identical on both sides, so that put a floor under every score
and a wholly wrong prediction classified as a match.

  LineItem(quantity=2, unit_price=10.5, currency='USD')
    vs LineItem(quantity=9, unit_price=99.9, currency='EUR')
                                   before  0.8293  tp=1
                                    after  0.0000  fd=1

A plain BaseModel field now gets what a Dict[...] field gets: ANLS* at
object grade, clip_under_threshold=False, the class's match_threshold.
Keyed on the element for List[plain BaseModel] too, so the singular and
list forms read one configuration rather than two.

Two plain models of different classes are a false discovery, whatever
their field names carry. That rule now lives in one place,
ConfigurationHelper.values_are_same_model_class, because four readers ask
it -- compare_with, compare, and the list form of each -- and they had
already drifted: compare() returned 1.0 for Cat/Dog and 0.4167 for
Base/Sub where compare_with() returned 0.0/fd=1, breaking the invariant
#233 states. compare() feeds the Hungarian cost matrix, so a list paired
those items at zero cost and then called the field a mismatch.

In a list a wrong-class element is one FD; it still pairs and scores 0.0.
[Cat(a), Cat(b)] vs [Cat(a), Dog(b)] was 1.0/tp=2 and is now 0.5/tp=1
fd=1. Whether it should pair at all is #321.

Warns rather than raises, following can_score_mapping: which class
arrives is prediction data. A correctly annotated field cannot reach the
mismatch at all, since pydantic refuses a Dog for an Optional[Cat] field
at construction.

Two tests of mine were too weak to catch any of this and are replaced:
test_a_different_nested_plain_model_still_fails asserted only `< 1.0`,
which passes at 0.8293, and the singular-vs-list parametrisation used the
same class on both sides in all three cases.

Two of #320's three limitations fall out as fixed, since scoring no
longer reads the rendered string: a custom __str__ and a repr=False field
no longer hide data, and dict key ordering no longer drops the score.
SecretStr remains, masked to a constant by to_jsonable_python so any two
secrets compare equal; a bare Dict[str, SecretStr] already did that on
dev, so this widens it rather than introducing it.

Refs #318, #320, #321, #233, #135

* fix: refuse an object the field cannot score, and memoise the lookup

Self-review of 0efc87c, before sending #319 back. Two real defects in my
own fix.

1. An 18% performance regression on the shape whose comment warns about
   exactly this. `get_comparison_info` runs once per field per pairwise
   comparison -- 60x60 objects of 20 fields is 72,000 calls -- and the
   four annotation predicates that select the object-grade path each
   destructure the annotation again. Measured 2.285s on dev against
   2.699s here, next to the 23% regression
   `ComparisonHelper.compare_field_raw` already records for adding work
   to this path.

   The classification is now memoised per (class, field) in `cls.__dict__`,
   which also removes work dev was repeating: 1.951s, 14% faster than dev.
   Only the annotation is cached. `match_threshold` is a plain class
   attribute a caller can reassign and `evaluate(match_threshold=...)`
   overrides it per call, so caching the resolved config would serve a
   stale number.

2. The fix was annotation-keyed, so it missed every annotation that
   declares no model type -- which is precisely the set that makes a class
   mismatch reachable in the first place. `Any`, `object`,
   `Union[Model, str]` and `List[Any]` all kept the scalar default and so
   kept the original bug:

     LineItem(quantity=2, unit_price=10.5, currency='USD')
       vs LineItem(quantity=9, unit_price=99.9, currency='EUR')  0.8293 tp=1

   These are now refused: 0.0, fd=1, and a warning naming both remedies.
   That is what a mapping in the same position has always got -- dev
   scores two IDENTICAL dicts in an `Any` field 0.0 with fd=1 -- so this
   makes plain models agree with mappings rather than inventing a third
   behaviour. They now agree in every case measured, down to a model
   holding an arbitrary_types_allowed value scoring the same 0.5 a dict
   holding one does.

   `can_score_mapping` becomes a thin wrapper over a shared
   `can_score_object` so the two cannot drift, and the refusal is applied
   in both the singular path (dispatcher CASE 5) and the element path
   (`_ClassGatedComparator`), which had disagreed: singular refused while
   `List[Any]` silently matched at 0.8293.

Five of my own tests were passing for the wrong reason. They used a bare
`Any` field to get two classes to one field, but a bare `Any` is now
refused in its own right, so both refusals return 0.0 and the tests could
not show which fired. They now declare the comparator to isolate the class
gate, and a new `Inherited` model covers the case needing no `Any` at all:
`Optional[Base]` accepts a `Sub` by ordinary subtyping and gets ANLS* from
its annotation, so the class gate is the only thing between
`Base(a="x")`/`Sub(a="x")` and a reported 1.0.

Also verified with no change: the primitive-list path (0.717s vs dev
0.722s), the cache not leaking across a subclass boundary, `False` being
remembered rather than recomputed, an explicit comparator still winning,
None elements in a gated list, StructuredModel pairs never reaching the
plain-model gate, and the warning firing once per field rather than per
pair.

Refs #318, #321

* fix: honour an explicit clip_under_threshold on a plain-model field

Found while writing the #314 tests for the clip provenance note, which
could not fire because the engine had already discarded the setting.

Installing the object-grade comparator also turns clipping off, because a
container keeps its partial score. Right as a default, wrong as an
override: the substitution set `clip_under_threshold=False` outright, so
an explicit `clip_under_threshold=True` was dropped in silence.

`_install_mapping_comparators` already gates the same amendment on
`_clip_explicit`, so a `dict` field carrying an explicit True never
reached the line that clobbers it. A plain-model annotation is not
handled there, so it did:

  declared clip_under_threshold=True, threshold=0.9, half-right value
    Dict[str, str] field      clip=True   score 0.0
    plain-model field         clip=False  score 0.5   <- setting dropped

The same declared setting honoured on one shape and dropped on the other
is the divergence between mappings and plain models this PR exists to
remove, so it is fixed here rather than filed.

Defaults are unchanged: an unstated clip still resolves to False for a
plain model, a dict, and a bare annotation of either, and a half-right
nested model still keeps its 0.5.

Refs #318

* fix(317): read x-aws-stickler-threshold on an object-typed property

`from_json_schema` read `weight` and `clip-under-threshold` from an
object-typed property's extensions and used a hardcoded literal for the
threshold, so one node honoured two field-level keys and discarded the
third, silently:

  declared threshold=0.88  ->  0.7    (the default)
  declared weight=3.0      ->  3.0    (honoured)

Carried rather than refused, because the key is not inert there. A
nested-model field's threshold gates the subtree mean: measured on a
two-leaf child scoring 0.5, a threshold of 0.6 with clipping on reports
0.0, and 0.0 keeps the 0.5. It worked set through a StructuredModel class
and not set in a schema, so the two configuration paths disagreed about
what is configurable, which is what #210 and #211 are about.

Scores can move for any imported schema that set the key, in the
direction the schema asked for. A to_json_schema() round-trip now
preserves the value where it previously came back as 0.7.

Probing the other positions found the same key one over, on an
array-of-objects property, ending somewhere a schema author cannot act on.
It is refused there, correctly -- array pairing reads the element's own
threshold, so a field threshold does nothing -- but the refusal came out
of ModelFactory naming ComparableField and a Python class attribute,
wrapped in "Error creating dynamic model". The schema path now translates
it:

  Could not import JSON Schema: 'x-aws-stickler-threshold' has no effect
  on array property 'f' and is refused. Pairing of array elements is gated
  by the element's own threshold, so put
  'x-aws-stickler-match-threshold': 0.88 inside that property's 'items'
  instead.

Translated at the from_json_schema seam, not in ModelFactory, which is
shared by both configuration paths -- a model_from_json caller keeps the
Python-flavoured advice that is correct for them. Tested that following
the new advice actually works, that the Python path's message is
unchanged, and that an unrelated import error is not mistranslated.

2337 pass, ruff clean, mkdocs at the dev baseline.

Closes #317

* docs(288): scope the threshold-gating claim to list items

Addresses Vincil's second review of #295. All seven reproduced before
changing anything; nothing disputed.

The central claim the new prose was built on is true for
List[StructuredModel] items and false for a single nested StructuredModel
field, and aggregate-metrics.md contradicted itself on exactly that point:
its own worked output 30 lines above showed a rejected nested object whose
leaves were still reported.

Gating is a property of StructuredListComparator, which pairs items and
then accepts or rejects them. A nested object field goes through
FieldComparator, which has no such stage. Measured on a three-leaf nested
object with one leaf wrong:

  field threshold=0.9    overall tp=1 fd=1    aggregate tp=3 fd=1
  field threshold=0.5    overall tp=2 fd=0    aggregate tp=3 fd=1
  match_threshold 0.9 / 0.7 / 0.5 / 0.1  ->  identical at every value

So two things the pages got wrong for that shape: the leaves are always
reported, not excluded, and match_threshold is not the knob -- which made
the published "lower match_threshold to get leaf detail for a marginal
object" remedy a no-op. That remedy shipped in the API reference via two
docstrings, where no surrounding line-item context signals that it is
list-scoped, so it is corrected there too.

Six doc sites and two docstrings now scope the claim. Confirmed the list
case does gate and does respond to match_threshold (2 items 1 rejected ->
aggregate tp=6 fd=0; at 0.5 -> tp=10 fd=2), so the narrowed claim is
accurate rather than merely hedged.

Also folded in:

- On an all-rejected document, aggregate stops counting leaves.
  AggregateMetricsCalculator falls back to summing children's overall when
  the recursive leaf sum is all-zero, so the unit changes with the data:
  two rejected items of six fields give aggregate tp=0 fd=2, two object
  rows where twelve leaves exist. Documented as a warning admonition,
  because the page promises "the unit is the leaf".

- The mAP cross-link pointed at #iou-thresholds, which is about
  configuring the COCO IoU range. The sentence being cited is under
  #iou-calculation. Both links retargeted; the old anchor resolved, so
  --strict never noticed.

- The retired clean check survived in tests/auto/test_risk_surface.py
  under a comment calling it "the reliable question", so the form this PR
  retires was still in the repo for the next person to copy. Fixed, and
  the drift guard now walks every .py and .md in the tree rather than only
  the three doc pages -- verified it fails when the retired form is
  reintroduced and passes when it is not.

- threshold-gated-evaluation.md told readers "read fp, not fa + fd", which
  teaches a false lesson about the classes. FP = FA + FD by construction,
  and fa + fd on a node works fine; what the old snippet missed was
  reading fa on aggregate AT ALL. The fix is the node, not the field, as
  the two sibling pages already said.

Nine new tests pin the corrected claims, including match_threshold's
inertness for a nested object, so the retired remedy cannot be
re-published silently.

2346 pass, ruff clean, mkdocs at the 9-warning dev baseline with no new
anchor warnings.

* feat(239): infer comparators for fields a config did not specify

Docs first, then implementation, and the docs caught two things before any
code was written.

A large extraction schema has a few fields whose comparison rules matter
and a long tail where anything sensible will do. The config-driven paths
gave three answers to "no comparator named", none of them what
stickler.evaluate() chooses:

  model_from_json()      raises
  from_json_schema()     number -> NumericComparator @ 0.50
  stickler.evaluate()    number -> NumericComparator @ 0.95

`infer_unspecified_fields` on a Stickler config, or
`x-aws-stickler-infer-unspecified` on a JSON Schema object, routes the
unspecified parameters through the same inference auto uses, so the paths
converge. Asserted against auto's own output rather than literals, so the
two cannot drift if inference is retuned.

Inference supplies comparator AND threshold. Half-inferring would leave
from_json_schema at 0.5 against auto's 0.95 and the divergence unresolved.

A field opts in alone with `"comparator": "auto"`, and precedence runs both
ways: "auto" infers one field in an explicit config, and naming a
comparator pins one field in an inferred one.

Partial config is filled per parameter, so {"type": "float",
"threshold": 0.99} gets NumericComparator with the author's 0.99. Treating
any config as fully configured is what left that field on the type-blind
default -- a threshold tuned against edit distance over "1000.00".

Off by default. model_from_json still refuses an unspecified primitive
unless asked, from_json_schema keeps its defaults, and 2322 existing tests
pass unchanged. The refusal now names both ways to opt in.

explain() no longer reports an inferred field as "explicit". It carries the
inference trail with the same source values auto uses (type, name-token),
which is the reporting half of #210.

`stickler.auto` needed no refactor: infer_field_config reads only the
annotation and the field name, so a synthesised FieldInfo around the
resolved type is enough, and the name-token heuristics work too.

Two things found while writing the docs rather than after:

- The published defaults table was wrong. It gave `boolean` as
  ExactComparator @ 1.0; it is 0.5. It also omitted format:date,
  format:date-time, format:uuid and enum, and implied format:email was
  handled when it is not. Corrected, since building a feature on a wrong
  table is how the wrong table survives.

- My own worked example used {"type": "date"}, which model_from_json
  rejects -- its types are str|int|float|bool|list|dict. Worse, a str-typed
  field named like a date does NOT get DateComparator: inference refuses a
  comparator the declared type cannot support and records the refusal in
  `why`. "A date needs date semantics" is one of the cases this feature was
  requested for, so that limit is documented rather than left to be
  discovered.

Two gaps found by the tests, both real: the "auto" sentinel was rejected as
an unknown comparator by a second eager validator, and a model-level flag
stopped at the first nesting level because the nested model is built by
re-entering model_from_json with a synthesised config that dropped it.

2357 pass, ruff clean, mkdocs at the 9-warning dev baseline.

Refs #239, #210

* fix(239): merge comparator_config, scope the nested flag, infer list elements

Self-review of bc8e561 before sending it out. Four defects in my own code,
found by probing the positions a reviewer would probe rather than by
re-reading.

1. Declaring `comparator_config` without `comparator` replaced the inferred
   config wholesale instead of merging over it. Inference gives
   NumericComparator a relative_tolerance of 0.001; setting any other key
   silently took that to 0.0, turning a tolerance-based numeric comparison
   into an exact one. Now merged, author's keys winning, so
   absolute_tolerance=0.5 keeps rel_tol=0.001.

2. `x-aws-stickler-infer-unspecified` on a NESTED object was accepted and
   silently ignored -- the key is a known model-level extension, so #312's
   unknown-key check passes it at any object position, and only the root was
   read. That is the silent drop #210 exists to remove, reintroduced through
   a key those checks consider valid everywhere. A nested object now scopes
   its own subtree in either direction, and the outer value is restored in a
   `finally` so a sibling declared after a nested object does not inherit
   the subtree's setting.

3. The schema path did not infer primitive-list elements while the config
   path did, because the list branch passed no annotation to infer from. One
   flag, two answers, depending on entry point.

4. A code comment promised `source: inferred`, which never occurs -- the
   values are `type` and `name-token`, the same ones auto reports. The docs
   were already corrected; the comment was not.

Also settled a contradiction in my own docs. They said partial config is
filled per parameter, and separately that naming a comparator pins the
field, which disagree about the threshold. The pinning behaviour is right
and now has a reason attached: a threshold only means something beside the
metric that produced the score, so inference's threshold belongs to the
comparator inference would have chosen, not to one the caller named
instead. Documented, and tested both ways.

Filed #326 for a pre-existing bug this surfaced: `create_instance` falls
back to a no-config construction on TypeError, so ONE unknown key in
comparator_config silently discards every valid key beside it, on every
path. The merge here is unaffected, but a typo still costs a user their
whole config.

14 new tests, 49 in the file. 2371 pass, ruff clean, mkdocs at the
9-warning dev baseline.

Refs #239, #326

* fix(246): keep legacy schemas importable and out-of-tree comparators intact

Addresses Vincil's review of #316. All four reproduced on both branches
before changing anything.

HIGH. Every schema a released version exported containing a
List[StructuredModel] field stopped importing. to_json_schema() always
emitted x-aws-stickler-threshold on an array-of-model property, import
forwarded it, and the old `threshold != 0.5` proxy let the placeholder
slide; with the proxy replaced by an explicitness marker, forwarding it
makes __init_subclass__ refuse the class. Verified by exporting on dev and
importing here: ValueError. The new export drops the key, so only new->new
round-trips were exercised and every artifact already on disk broke.

The key is now ignored with a warning rather than forwarded. Warned, not
raised: a legacy placeholder is not distinguishable from a value a human
wrote, and refusing would break persisted artifacts to flag a key whose
only cost is being ignored. This also reconciles the direction #323 took
for the same key, which raises -- the warning carries #323's remediation
text.

MEDIUM. An out-of-tree comparator now adopted its own default, the exact
outcome this PR claims to prevent, on the population that cannot have
migrated. `threshold is not None` is exact only for a subclass defaulting
to None; one written to the documented pattern forwards a number on a bare
construction. Reproduced with the docs' own RegexComparator: 0.5 on dev,
1.0 here, and with clip_under_threshold on that zeroes every imperfect
score. Such a subclass now falls back to comparing against its declared
default -- the old heuristic, old flaw, unchanged behaviour -- and warns
once with the two-line migration. In-tree comparators keep exact
explicitness, including Lev(threshold=0.7) reading as set.

MEDIUM. The docs taught the broken pattern. The BaseComparator interface
example, the RegexComparator example, and Custom_Comparator_Demo.ipynb all
showed `threshold: float = ...`, so a reader following them got the
silently-adopted default. All three migrated to
`Optional[float] = None` + DEFAULT_THRESHOLD, with a paragraph on why.
Also corrected "Every comparator below takes a threshold", which
LLMComparator in that same table does not.

MEDIUM. `List[Model] = ComparableField(threshold=0.5)` raised where dev
accepted it. dev detected a field threshold by comparing against the
literal 0.5, so the declaration was legal at exactly one value and raised
at every other. Refusing all values is the consistent rule, but it is
breaking, and the CHANGELOG's "Unchanged: a field that states its own
threshold" was wrong. Both now in the breaking list.

One existing test asserted `_threshold == 0.8` for a threshold on an
array-of-models -- a value stored and never read, since Hungarian matching
gates on the element class. Updated to assert it is ignored; the weight
assertion beside it was always the load-bearing half.

Non-blocking items noted rather than changed: the single-nested-model
round-trip gap is #317/#323's territory, and to_stickler_config() still
emitting a threshold for a list-of-models is recorded in the CHANGELOG
rather than changed in a PR about thresholds.

15 new tests, 50 in the file. 2372 pass, ruff clean, mkdocs at the
9-warning dev baseline.

Refs #246, #323

* docs(288): read the node whose children you mean

Addresses Vincil's second review of #295. All six reproduced; every number
he published matched.

The findings share one root: every example in the section was a model whose
ONLY field is the list, and `overall` sums a node's DIRECT children -- which
this PR itself now states. Add the header fields a real invoice has and the
object-verdict framing stops holding at the root.

  5 items, everything correct
    root  overall                     tp=8      3 header leaves + 5 pairings
    cm['fields']['lines']['overall']  tp=5      the item count

So "How many list items did the model find? -> overall" overstates by the
number of header fields. Corrected in the lookup row, in the framing on both
pages, in classification-logic.md, and in both docstrings -- which matter
most, since they publish to the API reference where no surrounding
line-item context signals that the claim was list-scoped. Added a worked
example with header fields so the mixing is visible rather than described.

The all-rejected warning was scoped to the document and needed to be scoped
to the list. The fallback fires per node whenever THAT node's leaf sum is
all-zero, so with three correct header fields beside a fully rejected list
the document is plainly not all-rejected and the root still reads

    root  overall    tp=3 fd=2
    root  aggregate  tp=3 fd=2    cm_precision 0.6000

five rows where fifteen leaves exist. A reader checking the document
condition concluded correctly that it did not apply and divided by 15
anyway, and the closing advice to read `overall` did not help either since
it reports the same numbers. The condition that actually holds is
`tp == 0` on the list field's own `overall`, which is what the warning now
says.

That same shape falsifies "the two nodes coincide only where there is no
accepted subtree to expand". They coincide there WITH an accepted subtree
present. The rule was stated in three places -- the page, the CHANGELOG,
and this test file's own module docstring -- and all three …
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