Skip to content

feat!: score undeclared dict fields with ANLS* instead of whole-object equality - #300

Merged
sromoam merged 10 commits into
devfrom
feat/277-anls-star-dict-comparison
Sep 3, 2026
Merged

sromoam merged 10 commits into
devfrom
feat/277-anls-star-dict-comparison

Conversation

@sromoam

@sromoam sromoam commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Closes #277 and #297. Makes #276 documentation-only.

The problem

A dict field was compared by whole-object equality. Ground truth {"vendor": "Acme Corporation", "terms": "Net 30", "po": "PO-88231"}:

prediction before after (tau 0.5)
identical 1.0 1.0
keys reordered 1.0 1.0
vendor abbreviated to "Acme Corp" 0.0 0.8542
po key missing 0.0 0.6667
extra currency key 0.0 0.7500
all three values wrong 0.0 0.0

The middle three were indistinguishable, so a dict field could not rank two extractors, detect a regression, or say which document got worse. docs/docs/Guides/Integrations/strands-evals.md cites exactly that failure as the reason this library exists; dict fields were the one place it survived.

Worse, on the explicit path a dict scored 0.0 against an identical copy of itself, and the configured comparator was never consulted. ComparisonDispatcher handled str/int/float, list and StructuredModel only, so a mapping fell through to the mismatched-types branch. A comparator hardcoded to return 1.0 still produced 0.0 (#297).

No new dependency

stickler.structured_object_evaluator.trees is already a complete ANLS* implementation, previously reachable only through anls_score and otherwise vestigial (one caller in src/). ANLSStarComparator wraps it. This also gives that module a defined role rather than being a second engine to deprecate (#135).

Tau is a parameter, not a constant

trees/base.py hardcoded the per-leaf cutoff as a class attribute:

THRESHOLD = 0.5  # ANLS threshold. 0.5 is a standard value.

That non-overrideable cutoff is what motivated this work. It now threads through make_tree into every nested node, settable three ways:

ANLSStarComparator(threshold=0.85)               # per field
anls_score(gt, pred, threshold=0.85)             # direct
evaluate(gt, pred, dict_leaf_threshold=0.85)     # zero-config

It cannot simply be removed: at tau 0.0 an unrelated string earns credit for incidental character overlap, so a wholly wrong value scores above zero. anls_score keeps its 0.5 default, so existing callers are unaffected.

Also fixed

  • A mapping-annotated field with no explicit comparator got the type-blind LevenshteinComparator, which rejects mappings. Substitution now happens in __init_subclass__, the earliest point where the annotation and the field metadata are both available, so to_json_schema(), explain(), the HTML reports and the engine all report one comparator. Substituting at read time exported LevenshteinComparator for a field the engine scored with ANLS*, and reimporting that schema made the model raise on a field the original scored fine.
  • A mapping meeting a scalar comparator (reachable via Any or Union[str, Dict[...]], where no annotation declares the shape) is counted as a false discovery with a warning naming the remedies, rather than raising. Shape is data-dependent, so raising ends a corpus run on document N after succeeding on N-1, and no test would catch it. One gate, shared by compare() and compare_with().
  • A dict field is no longer exempt from a declared match_threshold; it used a hardcoded 0.7 while sibling fields honoured the declared value.

Self-review found three of my own defects

Recording these because two are mistakes I sent other PRs back for:

  1. _compare caught ValueError broadly, converting a genuine tree-building bug into a silent 0.0. The same failure mode I rejected in fix: score an uncomparable list item 0.0 instead of raising (List[Dict] regression) #281 for the equivalent TypeError catch. Removed the catch entirely by normalizing to JSON form up front, so the tree only ever sees types it handles and real errors still surface.
  2. That normalization then flattened a ground-truth tuple to a list, destroying ANLS*'s 1-of-n alternatives contract. anls_score returned 1.0 where ANLSStarComparator returned 0.0 on identical input, so two public entry points disagreed. Ground truth now normalizes tuple-preserving.
  3. Dict[Any, Any] as the wire type turned a non-mapping value into a ValidationError, so an extractor returning an array where the schema said object aborted the run. Annotated Any instead; the dispatcher classifies the mismatch as FD.

Cost, measured

Structural scoring is far more expensive than the equality it replaces:

200-key flat dict:  3.25 ms   vs 0.0001 ms for Exact over a canonical string

Quadratic inside List[Model], where the Hungarian matrix pays it per cell:

20 line items x 30-key dict  ->  220 ms for ONE document

roughly 37 minutes over a 10,000-document corpus for that one field. Documented in the class docstring with #204 named as the fix, since that issue already proposes the batch hook and prefilter for exactly this n x m blow-up. Worth deciding whether #204 should be milestoned for 1.0 as a result.

Two things a reviewer should know

This is arguably two PRs, and I'd take that feedback. About 12 files serve the actual ask (the comparator, tau, the dispatcher branch, auto routing). The other ~14 exist because the explicit path's default comparator is type-blind: once the dispatcher consults a field's comparator, every StructuredModel with a dict field started hitting Levenshtein's guard. Everything downstream of that — the two explicit-markers, the __init_subclass__ substitution, broadened mapping detection, the handles_mappings gate — is a scoped slice of #239, which was never in scope. If you want it split, the clean line is: PR A = comparator + tau + auto routing + the handles_mappings gate (explicit-path outcome unchanged, just warned); PR B = the type-aware mapping default. Nothing breaks at that boundary.

One public signature changed. ComparableField(clip_under_threshold=...) now defaults to None meaning "not specified" rather than True. The effective default is unchanged. The sentinel is what lets a mapping field default it to False (so partial credit is not zeroed by the field threshold) while an explicit True/False is always honoured. Flagging it because a signature change should not ride along quietly inside "add a comparator", and it belongs to the PR B half above.

Not fixed, and pre-existing

A Dict field still exports as "type": "string" and reimports as Optional[str]. I verified this on dev before touching anything, so it is #214 territory, not new. The comparator now round-trips correctly; the type does not, so a round-tripped model degrades to string comparison rather than raising. Better than before, still wrong.

Docs

  • docs/docs/Guides/Comparators/README.md: new section plus a row in the selection table
  • src/stickler/auto/README.md: the inference-precedence table said dict → Exact over canonical JSON; corrected, and the wire-form section now says why dict is the one type that keeps its shape
  • CHANGELOG.md, NOTICE, tests/comparators/README.md
  • dict_leaf_threshold documented on eval_for and evaluate (it was only on infer_field_config, which users do not call)

Attribution

ANLS* and the walk-it-as-a-tree approach come from anls_star (Apache-2.0). NOTICE previously carried only the Amazon copyright line and named no third-party work; it now credits the project, and both module docstrings point at it. I could not determine from git history whether trees/ was ported or written independently, so the wording credits the design without asserting either.

Verification

  • 1996 passed, 2 skipped
  • ruff check clean
  • mkdocs build --strict adds no new warnings (9 pre-existing, count identical to dev)
  • 22 new tests in tests/comparators/test_anls_star.py covering every way a mapping field can be declared, tau propagation to depth 25, the tau-0.0 trap, non-mapping degradation, schema round-trip, the shadow-cache key, dump-mode equivalence for Dict[date, X], and the five-extractor ranking property

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

github-actions Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-09-03T18:53:26+00:00
  • Time since scan: 5 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-09-03T18:47:49+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 1 0 0 5039 0 1 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 1 Hotspots

Files with the highest number of security findings:

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

Detailed Findings

Show 2 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",

Report generated by Automated Security Helper (ASH) at 2026-09-03T18:53:27+00:00

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

Review of the ANLS* dict-comparison change: one high-severity scoring regression, four medium correctness/consistency issues, two low. All findings were reproduced against this branch (1979 passed locally, so none of these are caught by the suite). Details in the inline threads.

Comment thread src/stickler/comparators/anls.py Resolved
Comment thread src/stickler/auto/inference.py Resolved
return instance

@staticmethod
def can_score_mapping(model_cls, field_name: str, comparator) -> bool:

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.

Medium — the gate reintroduces a list/scalar divergence for identical values, on the same axis #278/#281 closed.

The list path retries a refused item against canonicalize_json, so it answers correctly; the scalar path now returns 0.0 instead. Same annotation, same comparator, same data:

class X(StructuredModel):
    a: Any = ComparableField()
class Y(StructuredModel):
    a: List[Any] = ComparableField()

d1 = {"vendor": "Acme Corporation", "po": "PO-1"}
d2 = {"po": "PO-1", "vendor": "Acme Corporation"}   # identical content

X(a=d1).compare(X(a=d2))      # 0.0   + UserWarning
Y(a=[d1]).compare(Y(a=[d2]))  # 1.0

Reporting a false discovery for two identical mappings is a metric lie, and Any / Dict[str, Any] are the annotations users actually reach for. test_an_explicitly_declared_levenshtein_cannot_score_a_dict records this as "the only divergence left", but the remedy is already in the codebase: fall back to canonicalize_json on both sides here, exactly as HungarianMatcher._score does, which yields 1.0 for identical content and restores parity. The warning can stay — it is the 0.0 that is wrong.

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.

Still reproduces at da1414c, unchanged, and I am leaving it open — but as a non-blocking note now, because the denylist means it only fires for a comparator the user explicitly declared and was warned about.

class Scalar(StructuredModel):
    d: Dict[str, str]       = ComparableField(comparator=LevenshteinComparator(), threshold=0.7)
class Listy(StructuredModel):
    d: List[Dict[str, str]] = ComparableField(comparator=LevenshteinComparator(), threshold=0.7)

v = {"a": "x", "b": "y"}
Scalar(d=v).compare_with(Scalar(d=dict(v)))    # {"d": 0.0}
Listy(d=[v]).compare_with(Listy(d=[dict(v)]))  # {"d": 1.0}

Same annotation family, same explicit comparator, identical data, two answers — and the list side is the one that gets it right, via the #281 canonicalize-on-refusal fallback.

The fix looks small and reuses machinery you already have: in the refusal path, instead of returning 0.0, run both sides through canonicalize_json_sorted and hand the strings to the declared comparator, exactly as HungarianMatcher does for a refused list item. That makes the scalar path answer 1.0 here and deletes the divergence rather than documenting it. Your call whether that belongs in this PR or a follow-up.

Comment thread src/stickler/auto/builder.py Resolved
@sromoam

sromoam commented Aug 28, 2026

Copy link
Copy Markdown
Contributor Author

Subtraction pass: 40796d9

Two deletions, which between them fix three findings without adding any code. Net -84 lines.

1. jsonable_preserving_tuples removed

I added it in ce112d4 to protect ANLS*'s 1-of-n-alternatives contract, where a tuple in the ground truth means "any one of these is correct". Applying that to a value pulled off a pydantic field was simply wrong: a tuple there is a tuple. Preserving it on the ground-truth side only made the normalization asymmetric, so the same tuple became ANLSTuple on one side and ANLSList on the other.

Dict[str, Tuple[int, int]] before after
identical 0.0 1.0
vs a truncated prediction 1.0 0.0
tuple used as a dict key TypeError 1.0

Row 1 is the exact symptom #297 describes, reintroduced by my fix for it. Row 2 is worse: a wrong prediction scoring above a right one. Row 3 is the run-aborting failure the up-front normalization was supposed to eliminate.

Both sides now normalize identically. The 1-of-n contract stays on anls_score, which normalizes nothing and is unaffected.

2. dict_leaf_threshold removed

45 references across three files: two facade parameters, threading through five builder call sites, an inference parameter, an entry in the shadow-cache key, and a warning for the case where it could not apply. All plumbing for one knob, on a path where #263 already proposes general per-field overrides.

Tau remains settable where it is a real choice:

ComparableField(comparator=ANLSStarComparator(threshold=0.85))

This also deletes the finding that _primitive_spec dropped the parameter for List[Dict[...]] -- there is no parameter left to drop. It now forwards match_threshold instead, which is the one that still matters.

3. Removing the knob exposed a wrong default

This is the part worth reading. With no per-call override the default carries the whole feature, and 0.85 did not:

tau=0.85   perfect 1.0   near-miss 0.6667   dropped-key 0.6667   ...  4/5 distinct
tau=0.5    perfect 1.0   near-miss 0.8542   dropped-key 0.6667   ...  5/5 distinct

An abbreviated value and a missing key scored identically at the shipped default, which is precisely the ranking failure this PR opens by criticising whole-object equality for. I chose 0.85 for consistency with the name-token Levenshtein default; that is a weak reason and it broke the feature. 0.5 is the standard ANLS value.

The knob was hiding it: every example and test passed dict_leaf_threshold=0.5, so nothing exercised the default. The CHANGELOG and comparator docs also printed the table at tau 0.5 while shipping 0.85, so they documented behaviour the code did not produce. Both now state the default and say what raising tau costs.

Still open

Four findings remain, and all four live in the explicit-path half of this PR -- the part the description already argues could be split out:

  • zero-config does not route Mapping[...] / OrderedDict[...] to ANLS*, so the two paths disagree and three docs overstate the coverage
  • _install_mapping_comparators reads raw cls.__annotations__, so from __future__ import annotations defeats it and reinstates the export/engine divergence it exists to prevent
  • handles_mappings is set only by ANLSStarComparator, so a declared ExactComparator now yields 0.0 for two identical dicts even though == handles them
  • CHANGELOG.md has two ### Changed sections under [Unreleased]

Dropping that half deletes three of the four outright. I would rather settle the split question before fixing findings in code we may remove, since spending effort on code that then gets deleted is the trap that produced the tuple regression above. Happy to go either way -- say which and I will do it.

@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 — two high-severity leaf-typing gaps, plus a silent override of user-declared comparators

I reproduced everything below against c5c8e4f in a clean worktree (2088 passed, 12 skipped there, so none of these are covered by the new tests). The direction is right and the docs are unusually thorough; the blockers are all in the new leaf type classification and in the handles_mappings gate.

Two of the three high/medium findings are the same failure mode this PR's fourth commit says it fixed, just for value types the fix does not reach: a numerically equal pair scoring 0.0, and a 9x-wrong Decimal clearing the field threshold as a TRUE POSITIVE.

Detail is in the inline threads. Findings 1, 2 and 3 are what I'd call blocking; 4, 5 and 6 are worth resolving or explicitly deferring with an issue; 7 and 8 are cheap cleanups.

On the "this is arguably two PRs" question: I agree, and the split you propose is the right line — but I would not re-cut it now. Findings 1, 2 and 4 all live in PR A's half, so splitting does not reduce what has to be fixed.

that with a JSON blob. Keys and values are still normalized (so a
`Dict[date, X]` compares equal between `model_dump()` and
`model_dump(mode="json")`), but the mapping arrives at the comparator as a
mapping. A dict field whose value is not a mapping in some document is not a

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.

MEDIUM — this paragraph, and the _WireDict = Annotated[Any, ...] decision it justifies, do not hold: the run still aborts.

EvalSpec.evaluate coerces a dict prediction through the user's own model before the shadow model ever sees it (facade.py:127 -> _coerce -> self.source_cls.model_validate(value)), so a non-mapping in a dict field raises before the lenient Any wire type applies:

class Q(BaseModel):
    m: Dict[str, str] = {}

eval_for(Q).evaluate(Q(m={"a": "1"}), {"m": ["a", "1"]})
# pydantic_core.ValidationError: m -> Input should be a valid dictionary

The explicit path is the same — StructuredModel.from_json({"d": ["a", "1"]}) raises ValidationError for d: Dict[str, str].

So the third self-review item in the PR body ("Dict[Any, Any] as the wire type turned a non-mapping value into a ValidationError, so an extractor returning an array where the schema said object aborted the run. Annotated Any instead") does not change the observable outcome — the abort just moves one frame earlier, into _coerce. I could not construct an input where Annotated[Any, ...] behaves differently from Dict[Any, Any].

Either make _coerce tolerate a shape mismatch in a mapping field (which would make the claim true and is a genuinely useful property for a corpus run), or drop this paragraph and the Any-vs-Dict[Any, Any] rationale so the docs don't promise robustness the code doesn't have. Worth resolving rather than leaving, since "one odd document does not abort a corpus run" is the kind of guarantee someone will build a batch job on.

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.

Still accurate at da1414c. Confirmed with the declared-Dict case:

class Inv(BaseModel):
    d: Dict[str, str]

spec = stickler.eval_for(Inv)
spec.evaluate({"d": {"vendor": "Acme"}}, {"d": ["not", "a", "dict"]})
# pydantic_core ValidationError: 1 validation error for Inv -> d

_coerce runs source_cls.model_validate before the shadow model is reached, so the corpus run does abort. The paragraph only holds when the source field is Any — that case does score ({"d": 0.0}), which I verified separately.

Annotated[Any, ...] is still a fine choice for _WireDict; it is the justification that overstates itself. Suggest narrowing the claim in src/stickler/auto/README.md and in the _WireDict comment to "a field declared Any that happens to hold a mapping", and pointing at the user's own model as the thing that decides shape errors. Docs-only, non-blocking.

@sromoam

sromoam commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

@vawsgit ready for re-review at da1414c. 2105 passed, 12 skipped, ruff clean, mergeable.

Everything you raised reproduced exactly as written. V3 and V5 are fixed. V1, V2 and V4 are being answered by design rather than patched, which needs justifying since you filed two of them as HIGH.

Why the leaf typing was reverted rather than fixed

Your diagnosis pointed further than the three bugs: "both_strings is inferred after the type signal was destroyed." Following it, the real problem is that type-aware leaves are a second inference table, and it contradicts the first:

value auto (declared field) typed leaf (as I had written it)
amount: float NumericComparator @ 0.95, tol 0.001 exact equality
issued: date DateComparator @ 0.95 string equality
total: Decimal NumericComparator @ 0.95, tol 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 it. That is the divergence #239 exists to remove, and I would have been adding a fifth answer while writing the contract that says there should be one.

Also worth recording: my typed version regressed the public anls_score. anls_score({"a": 1000}, {"a": 1000.0}) went 0.6667 to 0.0. The revert undoes that too.

So leaves are canonical ANLS*: compared as text, whatever their type. What ANLS* generalises is the structure, not the leaf metric.

The cost is now documented in both directions

You were right that Dict[str, Decimal] money is the real workload, so this is stated in the comparator docstring, the comparators guide, the CHANGELOG, and tests that assert the numbers.

Your direction, wrong values scoring high:

account  DE89370400440532013000  vs  DE89370400440532013001   0.9545
amount   1000000                 vs  2000000                  0.8571
vendor   "Acme Corporation"      vs  "Acme Corp"              0.5625

And the direction neither of us wrote down, which I think is the likelier one to bite:

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

Numerically equal values scoring 0.0. That is your CSV-int against JSON-float scenario, and it was the last thing I was unwilling to defend as "intended" while undocumented. It now has its own table, names NumericComparator as the remedy, and has a test asserting that remedy actually works so the docs cannot recommend something untrue.

infer_types=True is written up where someone will look for it, including that it must delegate to stickler.auto.inference rather than invent rules, and that #49 blocks it because the two sides can disagree about their type.

V3, and I took your second suggestion over your first

"Treat _comparator_explicit as consent" does not work unconditionally: honouring consent for an explicitly declared LevenshteinComparator on a dict means raising TypeError mid-corpus, the failure mode we have now rejected three times (#241, #285, this PR).

So it is a denylist of the two comparators known wrong on measured evidence, which was your alternative. Levenshtein raises; Fuzzy scores a changed value at 0.944, above a mere key reordering at 0.667. Your MyDictComparator now returns 1.0.

And rather than document handles_mappings as an authoring contract, I deleted it. Nothing reads it now.

V5 fixed, plus your low items

Both paths compute 0.5625 for your example; the auto path's 0.0 is list thresholding applied after, which is correct. The builder.py indent and both "raises" comments are fixed.

On match_threshold not reaching _primitive_spec: you are right, and I left it with a comment rather than threading it, since element thresholds are type-derived for every other primitive too. Push back if you would rather it were threaded.

Four defects in my own fixes, found after your review

Worth listing because two are the same mistake I made responding to you, and none were caught by the suite, which stayed green at 2084 across all of them:

  • List[Dict[...]] got a different comparator depending on whether the field carried ComparableField(...) (Levenshtein at 0.7667, clearing a 0.7 threshold, versus ANLS* at 0.5625). I fixed the routing in one branch and not its sibling.
  • Naming the comparator silently re-enabled clipping. ComparableField(comparator=ANLSStarComparator(), threshold=0.9) scored 0.0 where the unnamed form scored 0.8542, because the clip default rode along with the substitution. The form my own new docs recommend for setting leaf_threshold deleted the partial credit the feature exists for.
  • ExactComparator canonicalised when either side was a mapping, making a dict equal to its own JSON-string spelling, so compare() said 1.0 while compare_with() called the same pair a false discovery.
  • Values with no JSON form had text invented for them. to_jsonable_python(fallback=str) gives <module.Class object at 0xADDRESS>, so two unrelated objects scored 0.8684 and two equal ones 0.8857 — it was comparing memory addresses, and scored higher for longer class names. Such a value is now refused: 0.0, with a warn_once per type so a refusal is distinguishable from a wrong extraction.

Known limits, recorded not fixed

A dict field exports as type: "string" and re-imports as Optional[str], so a round-tripped model cannot hold a mapping. Pre-existing and identical on dev; the comparator does survive. Pinned in a test.

comparison_dispatcher.py CASE 4 re-resolves the field config that is already in scope, roughly tripling config resolution per Hungarian cell. Real, and I am not attempting it at the end of this branch — my first try deleted a needed assignment and took the suite to 620 failures. Happy to file it.

Where you may still disagree

V1 and V2 were HIGH for you and I am overriding them with a design decision. The table at the top is the argument, and it is yours to reject. If you do, the fallback I would reach for is not typed leaves but raising the dict field's default threshold so these scores stop clearing it.

Thanks for both passes. The second one changed the design rather than the code, which is the more useful kind.

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

Approve — the design questions are settled, and I am satisfied with how

Reviewed at da1414c in a clean worktree: 2110 passed, 12 skipped, ruff check clean of anything new (the 16 findings and the 145 unformatted files are byte-identical on the base commit 6d6c24b).

I reproduced the PR's own headline table exactly, which is the thing I most wanted to confirm is real rather than asserted:

identical  1.0000   reordered  1.0000   abbreviated  0.8542
missing key 0.6667   extra key  0.7500   all wrong    0.0000

Five distinct outcomes where dev produced 0.0 four times. That is the ranking capability the library exists to provide, and dict fields were the last place it was missing. Merging this.

Everything I filed last round, verified

finding outcome
V1 typed leaves / numerically-equal 0.0 answered by design, and I accept it. Your table settles it — a second leaf inference table contradicting stickler.auto.inference would be worse than the documented cost, and the anls_score regression your version caused proves the point. The cost is now in the docstring, the guide, the CHANGELOG and in tests asserting the numbers
V2 Decimal takes the string branch moot after the reversion
V3 handles_mappings overrides an explicit comparator fixed. Explicit ExactComparator on a Dict[str, str] → 1.0 for identical mappings, through both compare() and compare_with(). Deleting the attribute rather than documenting it was the better half of that call
V4 Mapping[...] not routed by zero-config fixed and verified. Dict, Mapping, OrderedDict, bare dict and Optional[Dict[...]] all get ANLSStarComparator@0.7 / clip False, and all five score 0.5625 end to end
V5 PEP 563 defeats the substitution fixed. cls.model_fields from __pydantic_init_subclass__; confirmed under from __future__ import annotations
— shared json_schema_extra closure leak fixed. Confirmed in both definition orders; the str sibling keeps Levenshtein and clipping
— builder.py indent + match_threshold both fixed; it is threaded through _primitive_spec now
— two stale "still raises" comments fixed
— duplicate ### Changed fixed
— CASE 4 redundant lookup deferral accepted — please file it

Prior threads resolved accordingly. Two I left open as non-blocking because they still reproduce verbatim (the scalar/list divergence for an explicitly-declared Levenshtein, and the _WireDict justification paragraph).

Things I checked and could not break

  • Import cycles. comparison_dispatcher moving StructuredModel out of TYPE_CHECKING, plus configuration_helper and structured_model importing comparators.anls at module scope, is safe from every entry point I tried in isolation.
  • Schema round-trip of the comparator config. ANLSStarComparator(leaf_threshold=0.85) at threshold=0.9 exports and re-imports with both values and clip False intact.
  • Export honesty for scalar dict fields. to_json_schema(), the HTML report extractor (_comparison_metadata) and the engine all read ANLSStarComparator. The __pydantic_init_subclass__ timing works — pydantic reads json_schema_extra lazily at generation time.
  • _amend_clip_default / substituted interaction. Idempotent across subclass re-runs, and an explicit clip_under_threshold=True on a dict field is genuinely honoured (ANLS* with clipping).
  • Edge values. {} vs {} → 1.0; empty/None/[]/nested-{}, list reordering, date vs its ISO string, bytes, UUID, Path, set, tuple, tuple and date dict keys — all sane, nothing raises.

Performance

Measured against 6d6c24b, worst realistic case (a Dict field inside List[Model], Hungarian n×m):

base this PR
20 lines × 30 keys 3.7 ms 123 ms

~33x, matching the ~220 ms figure the docstring discloses, and the docstring names the remedies. Disclosed, bounded, and buying a metric that previously answered 0.0 for everything — that is a trade I am happy to take. Worth noting the other direction too: the same 20×30 payload held as a JSON string and scored by Levenshtein takes 9.3 s on both branches, so a dict-as-string was never the fast path people might imagine.

One cheap follow-up in the inline notes: within Hungarian matching each cell re-normalizes and rebuilds both trees, so a 20×20 matrix does ~800 tree builds where 40 would do.

NOTICE

Thank you for the Apache-2.0 attribution to anls_star, including the specific divergence. That is the right thing to have done and it is easy to forget.

One thing please fix before merge

docs/docs/Guides/Comparators/README.md lost the entire ### BBoxIoUComparator section — the new ANLS* section was written over it. The summary table still links #bboxioucomparator. Details inline; it is a 26-line restore and I did not want to hold the PR for it.

LGTM!

---

### BBoxIoUComparator
### ANLSStarComparator

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.

Please fix before merge — the ### BBoxIoUComparator section was deleted, not moved.

The new ANLS* section replaced it in place. On 6d6c24b lines 174-199 held the BBox description, the when-to-use paragraph, a ComparableField(comparator=BBoxIoUComparator(threshold=0.5)) example, the threshold parameter table, and the !!! tip "Rich Value Pattern" note pointing at ../../Advanced/bbox-map-metrics.md. All of it is gone:

$ grep -n '^### ' docs/docs/Guides/Comparators/README.md
26 ExactComparator / 53 Levenshtein / 79 Numeric / 107 Date / 138 Fuzzy
175 ANLSStarComparator          <- was 174 BBoxIoUComparator
349 Semantic / 377 BERT / 404 LLM

$ grep -n BBoxIoU docs/docs/Guides/Comparators/README.md
16: | [**BBoxIoUComparator**](#bboxioucomparator) | Bounding boxes, ...

So the summary table at line 16 is now a dead anchor: a reader who clicks "BBoxIoUComparator" scrolls nowhere, and the only pointer from this page to the mAP feature is gone. mkdocs is not run in strict mode (.github/workflows/docs.yml just does gh-deploy --force), so CI will not catch it.

Restoring the 26 lines above the new section is the whole fix.

While you are in this file: the Default Comparators by Type table at line 436 is now incomplete for the same reason this PR exists. It has object → "Recursive comparison" / 0.7 and no row for a bare dict / Dict[...] / Mapping[...], which is exactly the case that changed. A row reading ANLSStarComparator / 0.7 / "structural partial credit; keys not declared" would close it.

succeeding on N-1, and no test would catch it. The warning carries the
same information without stopping.
"""
if comparator.__class__.__name__ not in _COMPARATORS_THAT_CANNOT_SCORE_MAPPINGS:

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.

Medium, non-blocking — the denylist matches on the exact class name, so a LevenshteinComparator subclass slips through and raises mid-corpus.

comparator.__class__.__name__ not in {...} is True for anything that is not literally named LevenshteinComparator, including a subclass of it:

class MyLev(LevenshteinComparator):
    pass

class M(StructuredModel):
    d: Dict[str, str] = ComparableField(comparator=MyLev(), threshold=0.7)

M.from_json(gt).compare_with(M.from_json(pred))
# TypeError: Dictionary objects cannot be compared using LevenshteinComparator...

Verified: raises on both entry points, compare_with() and compare(). That is precisely the outcome this method's docstring says it exists to prevent — "raising ends a corpus run on document N after succeeding on N-1, and no test would catch it" — reached by the one route the name check does not cover. A thin subclass that only overrides name or tweaks a default is a normal thing for a user to write, and inheriting the dict rejection is the last thing they would expect to have inherited.

I do understand why you chose names over isinstance — "so an out-of-tree comparator is never caught by it". But isinstance against the two concrete classes has the same property: it cannot catch a comparator that does not inherit from them. The only behaviour it changes is subclasses, which inherit the broken _compare and therefore should be caught. Suggest:

from stickler.comparators.fuzzy import FuzzyComparator
_COMPARATORS_THAT_CANNOT_SCORE_MAPPINGS = (LevenshteinComparator, FuzzyComparator)
...
if not isinstance(comparator, _COMPARATORS_THAT_CANNOT_SCORE_MAPPINGS):
    return True

(If the FuzzyComparator import is awkward at module scope, keeping that one by name and switching only Levenshtein to isinstance closes the raising half, which is the half that aborts runs.)

# already resolved, so a module using `from __future__ import annotations`
# (PEP 563) is handled without special-casing the string form, and its
# `FieldInfo` is the object every reader consults.
for field_name, field_info in cls.model_fields.items():

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.

Medium, non-blocking — this loop skips List[Dict[...]], so the exported schema and the engine disagree for exactly that annotation.

is_mapping_annotation is correctly False for List[Dict[str, str]], and there is no _is_list_of_mappings check here — but ConfigurationHelper.get_comparison_info does substitute for it. So the two readers of the same field return different answers:

class M(StructuredModel):
    rows: List[Dict[str, str]] = ComparableField(threshold=0.7)

M._get_comparison_info("rows")
# ANLSStarComparator, clip False, threshold 0.7   <- engine

M.to_json_schema()["properties"]["rows"]
# "x-aws-stickler-comparator": "LevenshteinComparator",
# "x-aws-stickler-comparator-config": {"normalize": true},
# "x-aws-stickler-clip-under-threshold": true       <- exported

That is the schema/engine divergence this method's docstring names as its own reason to exist, and it has the follow-on the docstring predicts: re-importing that schema declares LevenshteinComparator explicitly, which sets _comparator_explicit and permanently suppresses the substitution on the round-tripped model. The x-comparison metadata the HTML report reads is wrong for the same reason.

_is_list_of_mappings already exists and is already a @staticmethod on ConfigurationHelper, so this looks like adding it to the continue guard:

if not (
    ConfigurationHelper.is_mapping_annotation(field_info.annotation)
    or ConfigurationHelper._is_list_of_mappings(field_info)
):
    continue

I am not asking you to fix the type: "string" half of the round-trip — that is the pre-existing lossy export you have already pinned in a test. This is only about the exported metadata contradicting the engine on the same branch.

Args:
threshold: The verdict threshold, meaning what it means on every other
comparator: the score at or above which a field using this comparator
counts as a match, unless the field states its own via

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.

Low — this promise is not kept, and it silently loosens the field the docs tell people to declare.

"unless the field states its own via ComparableField(threshold=...)" reads as though omitting threshold= leaves the comparator's 0.7 in force. It does not: ComparableField's own threshold parameter defaults to 0.5 and is always written into the field config, so the comparator's DEFAULT_VERDICT_THRESHOLD is unreachable through this form.

class M(StructuredModel):
    d: Dict[str, str] = ComparableField(comparator=ANLSStarComparator())

M._get_comparison_info("d").threshold             # 0.5
M._get_comparison_info("d").comparator.threshold  # 0.7  (never consulted)

class N(StructuredModel):
    d: Dict[str, str]                             # bare annotation

N._get_comparison_info("d").threshold             # 0.7

The bite is that the affected form is the one the new docs recommend. ComparableField(comparator=ANLSStarComparator(leaf_threshold=0.85)) — the "Declaring it explicitly" snippet in the comparators guide, whose whole point is to be stricter — quietly drops the verdict threshold from 0.7 to 0.5, so it is more permissive at the field level than writing no ComparableField at all. Someone raising leaf_threshold to reject abbreviations gets a field that now counts weaker mappings as matches.

I would not change the framework precedence here (it is pre-existing for NumericComparator(threshold=0.95) and friends, and #263 is the right place for it). Just make the docstring say what happens, and add threshold=0.7 to the guide's snippet so the recommended form does not surprise anyone.

# markers would score 1.0, so every out-of-domain value would match every
# other. Refusing is also why equality is not consulted -- an out-of-domain
# value is not scored, whether or not the two happen to be equal.
if _UNSCOREABLE in (this_str, other_str):

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.

Low — the short-circuit guards leaf values but not dict keys, and the comment above explains exactly why that matters.

"two identical markers would score 1.0, making every out-of-domain object match every other" is the reason for this line, and it applies verbatim to keys — where nothing short-circuits, because a key never becomes an ANLSLeaf. to_jsonable_python stringifies keys through the same fallback, so every unscoreable key collapses to the same marker string:

class O:
    def __init__(self, n): self.n = n
a, b = O(1), O(2)
c = ANLSStarComparator()

c.compare({a: "v"}, {b: "v"})            # 1.0  -- two DIFFERENT keys, perfect match
c.compare({a: "p", b: "q"}, {a: "p", b: "q"})  # 1.0, but both sides collapsed
                                               # to ONE key; half the data vanished

Row 1 is a wrong-scores-1.0, which is the direction that misleads. Row 2 is right by luck: both sides lost a key to the same collision, so the score agrees with a two-key comparison it never performed.

Narrow — it needs a non-JSON-able dict key, so Dict[Any, Any] or a dict reached through Any. Worth noting that a plain object key does not raise; it just silently becomes the marker, so there is no signal at all beyond the one warn_once. If you want a cheap guard, refusing the whole mapping when any normalized key equals _UNSCOREABLE would be consistent with how the value case is handled.

# the normalization asymmetric, so `Dict[str, Tuple[int, int]]` scored
# 0.0 against an identical copy and 1.0 against a truncated prediction.
# The 1-of-n contract lives on `anls_score`, which normalizes nothing.
gt_value = to_jsonable_python(str1, fallback=_jsonable_or_unscoreable)

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.

Low, and not a regression — but the argument above is stronger than what the code delivers.

"Normalizing up front means the tree only ever sees types it handles, so no catch is needed and a real error still surfaces" is true of make_tree, but to_jsonable_python can itself raise, and its fallback= hook is not consulted for either case:

c = ANLSStarComparator()

c.compare({frozenset({1}): "v"}, {frozenset({1}): "v"})
# TypeError: `frozenset` not valid as object key

d = {}; d["self"] = d
c.compare(d, d)
# ValueError: Circular reference detected (id repeated)

fallback covers unrepresentable values (which is what _UNSCOREABLE is for) but not unrepresentable object keys, and not cycles.

I checked before filing: both raise identically from canonicalize_json on 6d6c24b, so this PR neither introduces nor widens them, and I would not block on a pre-existing behaviour. Recording it because the surrounding comment argues the class of failure has been eliminated, and it has not — a Dict[Any, Any] holding a frozenset key still ends a corpus run on document N. If you want the comment to be literally true, wrapping these two calls and returning 0.0 with a warn_once (the treatment _UNSCOREABLE already gets) would do it; otherwise please soften the claim so the next reader does not rely on it.

The case to watch is a dict field inside a ``List[Model]``, where
Hungarian matching builds an n x m matrix and every cell pays the cost:

20 line items, 30-key dict -> 220 ms for ONE document

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.

Perf note, non-blocking — the Cost section is honest, and there is a cheap win it does not mention.

I measured against 6d6c24b and your figures hold up:

base this PR
5 lines × 10 keys ~ 13 ms
10 lines × 20 keys 1.3 ms 24 ms
20 lines × 30 keys 3.7 ms 123 ms

~33x on the worst case, same order as the 220 ms you quote. I am fine with this: it buys a metric that previously returned 0.0 for every non-identical mapping, the remedies are named, and #204 is the right long-term answer.

The unmentioned win is that the n×m blow-up is worse than it has to be. _compare normalizes and rebuilds both trees on every call, so inside Hungarian matching the same ground-truth mapping is re-normalized and re-walked once per prediction candidate. A 20×20 matrix does ~800 tree builds where 40 would suffice; the per-side work is O(n+m) and it is being paid O(n·m) times.

An id()-keyed memo on the built tree, scoped to the comparison, would recover most of that without waiting for the batch-comparator hook — mappings are unhashable so lru_cache is out, but the values are alive for the duration of the matrix. Purely a suggestion for a follow-up; please do not add it to this branch.

@@ -22,6 +22,7 @@ def __init__(self, threshold: float = 0.7):
"""
self.threshold = threshold

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 — stray blank line, almost certainly edit debris rather than intent.

This file, comparators/exact.py:77 and comparators/structured.py:15 each gained a second consecutive blank line inside a class body, in hunks that otherwise change nothing there. ruff format would remove all three, but .github/workflows/lint.yaml only runs ruff check, and E303 is not in the ["E4", "E7", "E9", "F"] selection — so nothing will flag them.

Same category, same hunk-noise origin: src/stickler/auto/builder.py:29 is now 131 characters after the docstring reflow (...so repeated ``evaluate`` calls in a loop are cheap without pinning user classes in memory.), against the line-length = 88 in ruff.toml. It was wrapped correctly before this PR. E501 is also unselected, so again nothing catches it.

Four one-line reverts, no behaviour.

sromoam added a commit that referenced this pull request Sep 3, 2026
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.
@sromoam

sromoam commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in ee4c34b. Good catch, and it was worse than a missing section: the summary table still linked #bboxioucomparator, so that anchor was dead.

Cause. I rewrote the ANLS* section by replacing everything between ### ANLSStarComparator and ### SemanticComparator. BBoxIoU sat between them, so a slice meant to touch one section silently consumed two. Restored verbatim from dev, in its original position.

I also ran the check that would have caught it, and it is mechanical:

  • every heading and bolded label present in dev's version of the file is present here: 0 missing
  • every same-page anchor the document links resolves to a heading that exists: 0 broken
  • same comparison across the other docs this PR touches: sections added, none removed

That is the third loss of this shape between this PR and #290, all from index-based slicing or conflict resolution, and none of them catchable by the suite because nothing tests prose. Two of the three were found by you rather than by me, which is the part worth fixing about how I work rather than about the code.

2110 passed, 12 skipped, ruff clean, mkdocs warnings unchanged from dev. Mergeable and approved.

…t equality

A dict field was compared by whole-object equality, which is the antipattern
this library exists to replace. Ground truth
{"vendor": "Acme Corporation", "terms": "Net 30", "po": "PO-88231"}:

    prediction                              before   after (tau 0.5)
    vendor abbreviated to "Acme Corp"          0.0            0.8542
    po key missing                             0.0            0.6667
    extra currency key                         0.0            0.7500
    all three values wrong                     0.0            0.0

The first three were indistinguishable, so a dict field could not rank two
extractors, detect a regression, or say which document got worse. Our own
Strands Evals docs cite exactly this failure as the reason the library exists,
and dict fields were the one place it survived (#277).

The implementation was already here. `stickler.structured_object_evaluator.trees`
is a complete ANLS* tree, previously reachable only through `anls_score` and
otherwise vestigial. No new dependency: `ANLSStarComparator` wraps it.

Tau is a parameter, not a constant
----------------------------------
`trees/base.py` hardcoded the per-leaf cutoff at 0.5 as a class attribute, which
is the non-overrideable behaviour that motivated this work. It now threads
through `make_tree` into every nested node, and is settable three ways:

    ANLSStarComparator(threshold=0.85)              per field
    anls_score(gt, pred, threshold=0.85)            direct
    evaluate(gt, pred, dict_leaf_threshold=0.85)    zero-config

It cannot be removed: at tau 0.0 an unrelated string earns credit for incidental
character overlap, so a wholly wrong value scores above zero. `anls_score` keeps
its 0.5 default so existing callers are unaffected.

Fixes that fell out
-------------------
- A dict scored 0.0 against an identical copy on the explicit path, and the
  configured comparator was never called: the dispatcher handled str/int/float,
  list and StructuredModel only. A comparator hardcoded to return 1.0 still gave
  0.0 (#297).
- A mapping-annotated field with no explicit comparator got the type-blind
  LevenshteinComparator, which rejects mappings. The substitution now happens in
  `__init_subclass__`, the earliest point where the annotation and the field
  metadata are both available, so `to_json_schema()`, `explain()`, the HTML
  reports and the engine all report the same comparator. Substituting at read
  time had exported LevenshteinComparator for a field the engine scored with
  ANLS*, and reimporting that schema made the model raise.
- A mapping meeting a scalar comparator (reachable via `Any` or
  `Union[str, Dict[...]]`, where no annotation declares the shape) is counted as
  a false discovery with a warning naming the remedies, rather than raising.
  Shape is data-dependent, so raising ended a corpus run on document N after
  succeeding on N-1. One gate, shared by `compare()` and `compare_with()`.
- A dict field is no longer exempt from a declared `match_threshold`.

Reviewed adversarially before commit; three of my own defects found and fixed:
- `_compare` caught ValueError broadly, converting a genuine tree-building bug
  into a silent 0.0. The same failure mode rejected in #281. Removed by
  normalizing to JSON form up front so the tree only sees types it handles.
- That normalization then flattened a ground-truth tuple to a list, destroying
  ANLS*'s 1-of-n alternatives contract: `anls_score` returned 1.0 where
  `ANLSStarComparator` returned 0.0 on the same input. Ground truth now
  normalizes tuple-preserving.
- `Dict[Any, Any]` as the wire type made a non-mapping value a ValidationError,
  so messy output aborted the run. Annotated `Any` instead.

Cost, measured and documented
-----------------------------
Structural scoring is far more expensive than the equality it replaces: 3.25 ms
for a 200-key dict against 0.0001 ms. Quadratic inside `List[Model]`, where the
Hungarian matrix pays it per cell: 20 line items with a 30-key dict is 220 ms
for one document. In the class docstring, with #204 named as the fix.

Attribution
-----------
ANLS* and the walk-it-as-a-tree approach come from the `anls_star` project
(Apache-2.0). NOTICE previously carried only the Amazon copyright line and named
no third-party work; it now credits the project, and both module docstrings
point at it.

1996 passed, ruff clean, mkdocs adds no new warnings.
Two subtractions. Both remove code, and between them they fix three review
findings without adding any.

1. `jsonable_preserving_tuples` is gone (-48 lines)
-------------------------------------------------
Added in the previous commit to protect ANLS*'s 1-of-n-alternatives contract,
where a tuple in the ground truth means "any one of these is correct". Applying
that to a value pulled off a pydantic field was wrong: a tuple there is a tuple.
Preserving it on one side only made the normalization asymmetric, so the same
tuple became ANLSTuple on the ground-truth side and ANLSList on the prediction
side:

    Dict[str, Tuple[int, int]]        before   after
    identical                            0.0     1.0
    vs a truncated prediction            1.0     0.0
    tuple used as a dict key       TypeError     1.0

The first row is the exact symptom #297 describes, reintroduced by the fix for
it. The second is worse: a wrong prediction scoring higher than a right one. The
third is the run-aborting failure the up-front normalization was supposed to
remove.

Both sides now normalize identically. The 1-of-n contract stays where it belongs,
on `anls_score`, which normalizes nothing and is unaffected.

2. `dict_leaf_threshold` is gone (-45 references across 3 files)
---------------------------------------------------------------
Two facade parameters, threading through five builder call sites, an inference
parameter, an entry in the shadow-cache key, and a warning for the case where it
could not apply. All of it plumbing for one knob, on a path where #263 is already
specced to provide general per-field overrides.

Tau remains settable where it is a real choice:

    ComparableField(comparator=ANLSStarComparator(threshold=0.85))

That also deletes the finding that `_primitive_spec` dropped the parameter for
`List[Dict[...]]`, since there is no parameter to drop. `_primitive_spec` now
forwards `match_threshold` instead, which is the one that still matters.

3. The default tau was wrong, and removing the knob exposed it
-------------------------------------------------------------
With no per-call override the default carries the whole feature, and 0.85 did not:

    tau=0.85  perfect 1.0  near-miss 0.6667  dropped-key 0.6667  ...  4/5 distinct
    tau=0.5   perfect 1.0  near-miss 0.8542  dropped-key 0.6667  ...  5/5 distinct

An abbreviated value and a missing key scored identically, which is precisely the
ranking failure this comparator exists to remove: the PR opens by criticising
whole-object equality for exactly that. 0.85 was chosen for consistency with the
name-token Levenshtein default, which is a weak reason that broke the feature.
0.5 is the standard ANLS value and makes the documented table true.

The CHANGELOG and comparator docs previously showed the table at tau 0.5 while
shipping 0.85, so they described behaviour the default did not produce. Both now
state the default, and say what raising tau costs.

1995 passed, ruff clean, mkdocs unchanged at the pre-existing 9 warnings.
…e 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.
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.
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.
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.
## 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.
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.
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.
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.
@sromoam
sromoam force-pushed the feat/277-anls-star-dict-comparison branch from ee4c34b to 4d40087 Compare September 3, 2026 18:30
@sromoam
sromoam merged commit 31d7ed4 into dev Sep 3, 2026
18 checks passed
@sromoam
sromoam deleted the feat/277-anls-star-dict-comparison branch September 3, 2026 19:02
sromoam added a commit that referenced this pull request Sep 3, 2026
…ng 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
sromoam added a commit that referenced this pull request Sep 3, 2026
…ng 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
sromoam added a commit to RachelHanspal/stickler that referenced this pull request Sep 11, 2026
`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 (awslabs#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 awslabs#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
awslabs#300, so only the threshold half was missing.

Also records `_threshold_explicit`, which is what awslabs#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.
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.

[BUG]: dict fields are scored by whole-object equality, with no partial credit and no per-key detail

2 participants