Repository navigation
fix(246)!: honour a threshold set on a comparator - #316
Conversation
`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.
Security Scan ResultsASH Security Scan Report
Scan Metadata
SummaryScanner ResultsThe table below shows findings by scanner, with status based on severity thresholds and dependencies:
Top 2 HotspotsFiles with the highest number of security findings:
Detailed FindingsShow 4 actionable findingsFinding 1: SECRET-HEX-HIGH-ENTROPY-STRING
Description: Code Snippet: Finding 2: B108
Description: Code Snippet: Finding 3: B307
Description: Code Snippet: Finding 4: B307
Description: Code Snippet: Report generated by Automated Security Helper (ASH) at 2026-09-09T21:24:10+00:00 |
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
vawsgit
left a comment
There was a problem hiding this comment.
Requesting changes — 1 high, 3 medium blockers
The core change is sound: moving explicitness into BaseComparator.__init__ rather than inferring it from signature defaults is the right fix for #246. All 12 DEFAULT_THRESHOLD values match the old signature defaults, every subclass chains to super().__init__, Optional is imported everywhere it is now used, 0.0 is correctly treated as a set value, and LLMComparator (no threshold parameter) is unaffected. Suite is clean on the branch (2358 passed, 12 skipped) and so is ruff.
Four issues need addressing before merge. Each was reproduced by running code on both dev and this branch.
HIGH — Every previously exported JSON schema containing a List[StructuredModel] field now fails to import
src/stickler/structured_object_evaluator/models/json_schema_importer.py:386
to_json_schema() on dev always emits x-aws-stickler-threshold: 0.5 on an array-of-model property. Import used to pass that value through to ComparableField, and the old threshold != 0.5 proxy let it slide. Now _comparison_from_extensions forwards extensions.get("threshold", None) → 0.5, _threshold_explicit becomes True, and __init_subclass__ raises.
Reproduced — Cart.to_json_schema() on dev, then StructuredModel.from_json_schema(...) on this branch:
ValueError: Field 'products' is a List[StructuredModel] and cannot have a 'threshold' parameter…
The new export drops the key, so only new→new round-trips are exercised by the tests; every schema artifact already persisted by a released version breaks. Suggest ignoring the key on array-of-model properties on import — it is inert there — rather than raising.
MEDIUM — For out-of-tree comparators, a comparator's default threshold now IS adopted
src/stickler/comparators/base.py:120
threshold_was_set = threshold is not None is only meaningful if every subclass defaults its own parameter to None. Any third-party comparator written to the pattern this repo documented until now —
def __init__(self, threshold: float = 1.0):
super().__init__(threshold=threshold)— forwards a number on a bare construction, so threshold_was_set is True. Reproduced with the docs' own RegexComparator: ComparableField(comparator=RegexComparator()) moves from 0.5 on dev to 1.0 here, and with clip_under_threshold=True every imperfect score is silently zeroed. That is the exact outcome the PR says it prevents. TestASubclassThatForwardsKwargs covers the **kwargs shape but not this (much more common) one.
MEDIUM — The documented BaseComparator interface is now wrong, and the example teaches the pattern above
docs/docs/Guides/Comparators/README.md:546 still shows def __init__(self, threshold: float = 0.7): self.threshold = threshold — no Optional, no DEFAULT_THRESHOLD, no threshold_was_set. The RegexComparator example at line 597 uses threshold: float = 1.0, and examples/notebooks/Custom_Comparator_Demo.ipynb cell 4 uses threshold: float = 0.7. A user following these docs gets the silently-adopted default from the previous finding.
Separately, line 9's "Every comparator below takes a threshold" is false: LLMComparator, in that same table, is __init__(self, model, eval_guidelines), so LLMComparator(threshold=0.8) is a TypeError.
MEDIUM — List[Model] = ComparableField(threshold=0.5) now raises where dev accepted it
src/stickler/structured_object_evaluator/models/structured_model.py:587
Reproduced on both branches: dev prints ACCEPTED, this branch raises ValueError: … cannot have a 'threshold' parameter …. Replacing the threshold != 0.5 proxy with _threshold_explicit is right in principle, but it converts a previously legal (if pointless) declaration into a hard failure. The CHANGELOG's "Unchanged: … a field that states its own threshold" is inaccurate — this belongs in the breaking-change list.
Non-blocking
json_schema_importer.py:366— An adopted threshold on a single nestedStructuredModelfield does not survive a JSON-schema round-trip. The nested-model branch hardcodesthreshold=0.7and never consultsextensions.get("threshold"). Reproduced:ComparableField(comparator=StructuredModelComparator(threshold=0.9))→0.9in process,0.9exported,0.7reimported. Pre-existing importer gap, but the PR description's "adopted threshold round-trips throughto_json_schema()" holds only for primitive fields, and the newly honoured values make the drift reachable.structured_model.py:1997—to_stickler_config()still emitsthresholdfor aList[StructuredModel]field whileto_json_schema()now drops it. Harmless today only becausefield_converter._convert_nested_model_fieldforcesthreshold=Nonefor that type — the same "export what import must reject" hazard as the HIGH finding, left standing in the other exporter behind a different guard.comparable_field.py:144— On aList[StructuredModel]field, a comparator-named threshold is silently swallowed while the same number written asthreshold=raises with remediation advice.ComparableField(comparator=LevenshteinComparator(threshold=0.9))resolves to0.9, is never read (Hungarian matching uses the element class'smatch_threshold), and warns about nothing — precisely the situation the guard exists to surface. Consider a warning there.
…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
Aligns this PR with the fix Vincil asked for on #316, so the two cannot disagree and their merge order does not matter. This PR translated the `List[StructuredModel]` threshold refusal into schema language. #316's review found the refusal itself is wrong: every `to_json_schema()` on a released version emitted `x-aws-stickler-threshold` on an array-of-model property, so refusing it stops every previously exported schema containing a list of models from importing. Verified by exporting on dev and importing on that branch. So the key is dropped with a warning at the import site rather than forwarded and then translated on the way out. The warning carries the same remediation text the translation had. That removes the translation and the `structured_model.py` wrapper it needed, taking that file out of this diff entirely. The object-typed-property fix this PR exists for is unchanged: a declared `x-aws-stickler-threshold` on a nested-model property is read where it used to be silently dropped, and it still changes the score, not just the reported number. The Python path still raises with its advice naming `ComparableField` and `match_threshold`, which is correct for someone holding a class. Only the schema key is ignored. One pre-existing test asserted `_threshold == 0.8` for a threshold on an array-of-models -- stored and never read -- and now asserts it is ignored. Same update #316 makes to the same test. 2336 pass, ruff clean. Refs #317, #316
Self-review before sending for review. Five findings, the first mine from aligning this branch with #316 earlier today. 1 The warning fired on stickler's OWN export. `to_json_schema()` writes `x-aws-stickler-threshold: 0.5` on every `List[StructuredModel]` property and cannot write anything else, since `__init_subclass__` refuses a named threshold on that shape, so warning on the key's PRESENCE meant every model with a list of models drew a warning on round-trip -- about a key the library wrote, advising a change the author never made. `dev` is silent there, so the warning was itself the regression. Gated on the value now, same sentinel as `structured_model.py`. Worse, the advice said to put `'x-aws-stickler-match-threshold': 0.88` inside `items`. That is the element class's real gate and a different number, so following it would overwrite a working configuration with the value being discarded. The message names the key without echoing the value. 2 The CHANGELOG quoted a message the code never emits ("...and is refused", "Could not import JSON Schema:") and described translation code this branch no longer has. Rewritten, and the quote is now verified byte-for-byte against the emitted string rather than written by hand. 3 `assert _threshold != 0.8` passes for every other value, so it pinned nothing -- the same empty-assertion defect flagged on #319. Pinned to `== 0.5`. 4 The test module docstring still described the refuse-and-translate design. 5 `warn_once` memoises on `(id, field_path)` for the process lifetime, so a SECOND schema declaring the same property name imported silently and its author never heard about their dead key -- the silent drop this module exists to prevent. `warn_once` is right for a per-document deprecation; a schema import happens once per call, so plain `warnings.warn` is both sufficient and correct. Three tests pin it, including that gating on the value survives the change. Also unbundled a repo-wide formatter run: the diff was 85 files and 3901/3327 lines, of which 79 files were pure reformatting and two more differed only in docstring whitespace. Verified by AST comparison against `origin/dev`, so the claim is checked rather than eyeballed. Now 6 files. Docs: both extension tables documented `x-aws-stickler-threshold` unqualified; they now name the one position where it is ignored. NOT fixed here, deliberately: `x-aws-stickler-comparator` on an object property is also validated then dropped. #314 already reports that through `explain()`, so fixing it here would collide. 2344 passed, 12 skipped ruff check clean mkdocs --strict: 9 warnings, the dev baseline
Self-review before asking for re-review. The HIGH fix warned on presence of
`x-aws-stickler-threshold` on an array-of-model property, so it fired on EVERY
legacy artifact -- exactly the schemas the ignore-instead-of-raise behaviour was
added to keep importable -- telling the author to change a key the library itself
wrote. Measured in isolated processes (a single process hid it behind
`warn_once`'s memo):
before threshold=0.5 warnings=1 <- our own released output
threshold=0.88 warnings=1
after threshold=0.5 warnings=0
threshold=0.88 warnings=1
`0.5` is the only value a released export could write there, since a named
threshold on that shape is refused at class definition, so it carries no
authorial intent. Any other value is the author's and still warns.
Two things fixed with it:
- The advice said to put `'x-aws-stickler-match-threshold': <discarded>` inside
`items`. That is the element class's real gate and a different number, so
following it would overwrite a working configuration with the value being
thrown away. The message names the key without echoing the value.
- `warn_once` memoises on `(id, field_path)` for the process, so a second schema
declaring the same property name imported silently. A schema import happens once
per call, so plain `warnings.warn` is correct here.
This also removes a divergence I had created between this PR and #323, which fixed
the same defect from the other side. Both branches now answer identically at both
values, so their merge order does not change behaviour.
`test_the_ignored_key_is_reported` asserted the wrong invariant -- "silently
ignoring it would be the drop this work exists to remove" confused a value a human
chose with one we emitted. Replaced by three tests: the placeholder is silent, an
authored value still warns, and the warning does not name the discarded value as
the fix.
2374 passed, 12 skipped ruff check clean
Closes the last non-blocking finding, which is the same asymmetry the PR exists to
remove, one spelling over. On a `List[StructuredModel]` field:
ComparableField(threshold=0.9) -> raises, with remedy
ComparableField(comparator=Lev(threshold=0.9)) -> silently swallowed
The second only became reachable because this PR adopts comparator thresholds. It
resolves, is never read (Hungarian matching pairs items with the element class's
`match_threshold`), and reported nothing.
Warned rather than raised: a comparator instance can be bound to several fields, so
refusing the class would reject a construction that is legitimate wherever else it
appears. A field-level `threshold=` cannot be shared that way, which is why that
one stays an error -- a test pins that the two spellings do not swap places.
My first attempt was a no-op and the standalone probe said so: 0 warnings. It asked
`x-comparison` for a `comparator` key, which that dict never carries -- it holds
`comparator_type` / `comparator_name` strings, and the instance lives on the
`json_schema_extra` callable as `_comparator_instance`. So the branch was dead on
arrival. Reverse-verified the fix: reintroducing the wrong lookup fails three of
the new tests, which is what the first version should have had.
Quiet in the three neighbouring cases, each pinned: a bare comparator (its own
default is never adopted, so nothing is swallowed), no comparator at all, and a
scalar field, where the threshold IS consulted and reporting it would be wrong.
2380 passed, 12 skipped ruff check clean
|
All four blockers fixed, and all three non-blocking items too -- HIGH, legacy schemas. Fixed, and then fixed again after I found my own fix was worse than the bug in one respect. Warning on the key's mere presence fired on every legacy artifact -- exactly the schemas ignore-instead-of-raise exists to rescue -- telling the author to change a key the library itself wrote. Measured in isolated processes (a single process hides it behind
Two things fixed alongside it: the advice said to put This also removes a divergence I had created with #323, which fixed the same defect from the other side. Both branches now answer identically at both values, so their merge order does not change behaviour. MEDIUM, out-of-tree comparators. Fixed. A comparator written to the pattern the docs taught ( MEDIUM, the docs. MEDIUM, Non-blocking 3, the swallowed comparator threshold. Fixed rather than deferred, since it is the same asymmetry this PR exists to remove one spelling over. Worth recording how that one went, because the first version was a no-op: it asked Non-blocking 1 and 2 are left as you scoped them: the nested-model |
vawsgit
left a comment
There was a problem hiding this comment.
Re-review at 3bf1418 — previous blockers resolved, 2 new medium items
All four blockers from my earlier pass are fixed: the array-of-model import no longer raises (warn-and-ignore), threshold_was_set no longer adopts an out-of-tree comparator's signature default, the comparator docs and notebook class definition are migrated, and the CHANGELOG now lists the behaviour change. Suite is green in a clean worktree (2397 passed, 2 skipped), ruff check clean. I verified empirically that the precedence table matches the docs, that a field-level threshold really is unread for List[StructuredModel] (identical scores with a bare comparator vs. one at threshold=1.0, so warn-instead-of-raise is safe), and that an adopted threshold does reach verdicts and clipping.
Two medium findings remain.
MEDIUM — warn_once key collides across dynamically built models
src/stickler/structured_object_evaluator/models/structured_model.py:646
The new warning for a swallowed comparator threshold keys on cls.__qualname__. Every dynamically built model is named DynamicModel, so two unrelated models that share a field name collide and only the first ever warns.
Verified: two distinct type("DynamicModel", …) classes, each with lines: List[Model] = ComparableField(comparator=LevenshteinComparator(threshold=0.9)), emit 1 warning, not 2.
The sibling _warn_if_threshold_is_zero call 30 lines below (line 677) uses _model_identity(cls.__name__, cls.__annotations__) for exactly this reason, and its comment spells out the hazard. Use _model_identity(...) here too.
MEDIUM — Nested single-StructuredModel threshold still lost on JSON-schema round-trip
src/stickler/structured_object_evaluator/models/json_schema_importer.py:375
The nested-model branch hardcodes threshold=0.7 and never consults extensions.get("threshold") — which it extracts on the line immediately above.
Verified: head: Item = ComparableField(comparator=StructuredModelComparator(threshold=0.9)) exports x-aws-stickler-threshold: 0.9 and re-imports at 0.7; same for an explicit ComparableField(threshold=0.9). The original and round-tripped models then disagree on TP/FD for any score in [0.7, 0.9).
Pre-existing, but this PR makes it load-bearing and contradicts its own "adopted threshold round-trips through to_json_schema()" claim for that shape. One line: threshold=extensions.get("threshold", 0.7).
Non-blocking
field_converter.py:179— The stickler-config path forcesthreshold=Noneforlist_structured_modeland drops a declared"threshold"silently, while the JSON-Schema path now warns for the identical mistake. A hand-written{"type": "list_structured_model", "threshold": 0.9}gets no feedback.comparable_field.py:144— A0.0adopted from a comparator flows into the zero-threshold warning as if the field wrote it:ComparableField(comparator=LevenshteinComparator(threshold=0.0))reports "M.fsets threshold=0.0", naming a parameter absent from the call site, and the remedy doesn't mention that the value lives on the comparator. Same misattribution class the PR fixed for theList[StructuredModel]error.comparators/base.py:34—_caller_named_itreturnsTrueunconditionally when the subclass signature default isNone, so a half-migrated out-of-tree comparator —def __init__(self, threshold: Optional[float] = None): super().__init__(threshold if threshold is not None else 0.9)— reports a bare construction as caller-named and silently becomes 0.9 with clipping on. Reached by following half the migration message. Worth adding "do not resolve your default beforesuper().__init__" to the warning text and the custom-comparator docs.comparable_field.py:22—_comparator_threshold_was_sethas a boolean name but returnsOptional[float]. Both callers correctly testis not None; a futureif _comparator_threshold_was_set(c):would silently drop a deliberate0.0, which this codebase treats as meaningful (it has a dedicated warning for it). Consider_named_comparator_threshold.
Two prose fixes before this becomes a release note
- The PR description still says "
DateComparator(threshold=1.0)reads as not set, because it equals the class default." That describes the rejected design. Verified the opposite: it is adopted, andallow_partial_yearcredit drops 0.7 → 0.0. The in-diff docs (thresholds-and-metrics.md,Guides/Comparators/README.md) and the CHANGELOG are correct — only the PR body is stale. examples/notebooks/Custom_Comparator_Demo.ipynbhad its class definition migrated but not its demo cells, which passLevenshteinComparator(threshold=0.8)/NumericProximityComparator(threshold=0.7). The printed table changes (last row'snamescore 0.6 → 0.0) while the surrounding markdown still says those comparators "give partial credit". Re-run and adjust the narrative.
Both mediums from the re-review, plus the cheap non-blocking items and the two
prose fixes.
MEDIUM 1 -- the warning I added two hours ago keyed on `cls.__qualname__`. Every
dynamically built model is named `DynamicModel`, so two unrelated ones sharing a
field name collided in `warn_once`'s memo and only the first warned. Verified: two
`type("DynamicModel", ...)` classes with the same `rows` field emitted 1 warning,
now 2. The sibling `_warn_if_threshold_is_zero` call thirty lines below already
used `_model_identity` for this exact reason, with a comment spelling out the
hazard. I keyed on the name anyway.
MEDIUM 2 -- the nested-model branch hardcoding `threshold=0.7` is #317's fix and is
already implemented in #323, on this same line with its reasoning. Duplicating it
here would put two of my own branches in conflict on one line, so instead the
contradicting claim is gone: the PR body now scopes "adopted threshold round-trips"
to primitive fields and names #323 for the nested-model shape. Say the word if you
would rather have the line here and #323 rebased on it.
Non-blocking, all fixed:
- `_caller_named_it` half-migration. Reproduced: changing the signature but keeping
`super().__init__(threshold if threshold is not None else 0.9)` makes a bare
construction read as caller-named, so the field silently adopts 0.9 with clipping
on and nothing warns -- worse than not migrating. Undetectable at runtime, since
the value arrives indistinguishable from a real caller's, so the migration
warning and the custom-comparator docs now both say to forward the parameter
unchanged, with the wrong form shown beside the right one.
- The zero-threshold warning said "M.f sets threshold=0.0" for a `0.0` that came
from the comparator, naming a `ComparableField` argument absent from the call
site. Now "sets comparator threshold=0.0" when the field did not write it.
- `_comparator_threshold_was_set` -> `_named_comparator_threshold`, since it
returns `Optional[float]` and a boolean-sounding name invites `if f(c):`, which
would drop a deliberate `0.0`.
- PR body's `DateComparator(threshold=1.0)` paragraph described the rejected
design. Rewritten to what ships, including why: it is adopted, and that drops
year-less partial credit 0.7 -> 0.0.
Notebook: the class definition was migrated last round but the demo models still
passed `LevenshteinComparator(threshold=0.8)`, which now clips the partial credit
the surrounding markdown promises. Measured, then removed from the three model
fields, restoring `'Wireless Mice'` to 0.7857 from 0.0. A comment says why so it is
not re-added, and points at the field-level spelling for a real verdict threshold.
Surgical text edit: 10 insertions, 3 deletions, JSON still valid.
Both mediums reverse-verified: putting the old key and the old attribution back
fails the two new test classes.
2384 passed, 12 skipped ruff check clean
|
Both mediums addressed, all four non-blocking items fixed, and both prose fixes done -- MEDIUM 1, the colliding warning key. Yours entirely; this was mine from the previous commit. Reproduced exactly as you described -- two MEDIUM 2, the nested-model threshold. I did not put the line here, and want to be explicit about why rather than have it look overlooked. So I removed the contradiction instead: the PR body now scopes "adopted threshold round-trips" to primitive fields and names #323 for the single-nested- Non-blocking, all four fixed
def __init__(self, threshold: Optional[float] = None):
super().__init__(threshold if threshold is not None else 0.9)Measured: a bare construction reads as caller-named, the field adopts The zero-threshold misattribution. Now reads
ProsePR body rewritten. You were right that it described the rejected design; it now says The notebook. Good catch, and it was worse than the narrative drifting: the three model fields still passed Both mediums are reverse-verified: restoring the old key and the old attribution fails the two new test classes. |
vawsgit
left a comment
There was a problem hiding this comment.
Re-review at ad16f2f — prior blockers fixed, 3 new medium items
Both mediums from my last pass are resolved: the swallowed-threshold warning now keys on _model_identity(...), and the nested-model importer no longer hardcodes its threshold. Suite green in a scratch worktree (2384 passed, 12 skipped). One correction to the PR body: ruff check is not clean — it reports 16 errors, but they are byte-identical to dev, so this change adds none.
Three medium findings, each verified empirically against both branches.
MEDIUM — A **kwargs passthrough subclass defeats the migration guard entirely
src/stickler/comparators/base.py:34
_caller_named_it inspects only type(comparator).__init__, so it stops at the wrong frame for a wrapper:
class Legacy(BaseComparator):
def __init__(self, threshold: float = 1.0):
super().__init__(threshold=threshold)
class Wrapper(Legacy):
def __init__(self, **kwargs):
super().__init__(**kwargs)A bare Wrapper() forwards nothing, Legacy resolves 1.0, and because Wrapper.__init__ declares no threshold parameter the function returns True at the first branch. Measured: threshold_was_set=True, the field adopts 1.0, and ComparableField(comparator=Wrapper()) scores "abcdefghij" vs "abcdefghiX" as 0.0 instead of 0.9 — with no migration warning emitted. That is precisely the silent strictness regression the docstring says this guard prevents, hitting exactly the un-migrated population it exists for. Walking the MRO for the first __init__ that declares threshold closes it.
MEDIUM — Adopting a comparator threshold diverges Dict[...] from List[Dict[...]]
src/stickler/structured_object_evaluator/models/structured_model.py:447
_install_mapping_comparators gates _amend_clip_default on is_mapping_annotation(field_info.annotation) alone, so the clip-off exemption never reaches a list-of-mappings field whose comparator was named explicitly. (ConfigurationHelper.get_comparison_info does cover _is_list_of_mappings — but only when the comparator is not explicit.)
Measured with both fields declared ComparableField(comparator=ANLSStarComparator(threshold=0.9)) over identical content ({"a": "Acme Corporation"} vs {"a": "Acme Corp"}):
| dict field | list-of-dict field | |
|---|---|---|
dev |
0.78125 | 0.78125 |
| this PR | 0.78125 | 0.0 |
One annotation, two answers — the divergence the surrounding comments say this work removes. Applying _amend_clip_default for _is_list_of_mappings too fixes it.
MEDIUM — The fix doesn't reach the schema/config surfaces, and the new marker is wrong there
src/stickler/structured_object_evaluator/models/json_schema_importer.py:561, field_converter.py:69
Both paths still pass a concrete threshold for primitive fields — extensions.get("threshold", threshold) with a type-derived default, and field_config.get("threshold", 0.5) — so a threshold named only inside x-aws-stickler-comparator-config / comparator_config is still discarded. Measured: a schema declaring ANLSStarComparator with {"threshold": 0.9} and no x-aws-stickler-threshold resolves to 0.5, while the equivalent Python declaration now correctly resolves to 0.9.
Worse for provenance: because a value is always passed, _threshold_explicit is True for every imported field, even when no threshold was named anywhere — and #210 provenance is the stated reason the marker exists. The list_structured_model cases were switched to None; the primitive cases need the same treatment.
Non-blocking
field_converter.py:187— No warning parity between authoring surfaces. A JSON Schema namingx-aws-stickler-thresholdon an array-of-models now warns; a hand-written Stickler config namingthresholdon alist_structured_modelis dropped in total silence (measured:0.9→ resolved0.5, zero warnings). Same dead key, same mistake, one signal.comparators/base.py:40— The migration warning lands inside the library.warn_once's defaultstacklevel=3resolves towarn_once → _caller_named_it → BaseComparator.__init__; measured attribution isbase.py:174. Every other warning site in this change set picks a stacklevel deliberately and says why (stacklevel=4in__init_subclass__,stacklevel=1with a rationale inthreshold_helper). The message does name the class, so it's recoverable, but neither the definition nor the construction site is identified.structured_model.py:636— The newelifwarns before the class is refused for an unrelated reason, and burns the warn-once key doing it.List[Item] = ComparableField(comparator=ExactComparator(threshold=0.9))advises "setmatch_thresholdon the element class", then raisesValueError: … cannot have a 'comparator' parameter— wrong knob, for a class that never gets built. And sincewarn_oncealready recorded(…, Model.field), a corrected redefinition in the same process never warns. Moving the comparator-type check ahead of the threshold checks resolves both.json_schema_importer.py:524—ignore_thresholddrops the value but not the key._make_comparison_fieldcopiessource.json_schema_extraverbatim, sox-aws-stickler-threshold: 0.8survives onto the rebuilt field;model_json_schema()re-emits it on the array property (verified) and re-importing that output warns again. A user who follows the advice can't clear the warning by round-tripping — onlyto_json_schema()omits it.structured_model.py:652— Leftover first-person review note contradicting the code it annotates: "…uses this helper for exactly that reason, and I keyed on the name anyway." The code keys on_model_identity(...). In a file where comments are the design record, that will mislead.
Checked and correct
No missing Optional import in any touched comparator; every one forwards threshold unchanged to super().__init__ and none reassigns self.threshold after. The List[StructuredModel] warning's "is not consulted" claim is accurate (no clipping on that path — overall_score is 0.9 on both branches with a comparator threshold of 0.99). _named_comparator_threshold(None) is safe via getattr; Optional[List[Model]] degrades gracefully; the _EXPORTED_ARRAY_THRESHOLD_SENTINEL = 0.5 premise holds (every pre-PR path wrote exactly 0.5). ComparableField(threshold=0.5) on a List[StructuredModel] raising where dev accepted it is confirmed but disclosed in the CHANGELOG's breaking list, so not filed. The demo notebook's committed outputs still reproduce.
vawsgit
left a comment
There was a problem hiding this comment.
One blocker left — a silent scoring regression on List[Dict[...]]. Everything else is waived for merge.
This has been through several rounds and the core change is sound and well tested. I re-ran at ad16f2f with a deliberately narrow bar: only defects that silently corrupt measured scores block. Everything else below is filed as a note or a follow-up, not a merge condition.
Exactly one finding clears that bar, and I verified it against dev rather than relying on reading.
BLOCKER — List[Dict[...]] with a named comparator threshold silently drops to 0.0
src/stickler/structured_object_evaluator/models/structured_model.py:447
Two fields, same annotation shape, same comparator, same content:
class M(StructuredModel):
d: Dict[str, str] = ComparableField(comparator=ANLSStarComparator(threshold=0.9))
ld: List[Dict[str, str]] = ComparableField(comparator=ANLSStarComparator(threshold=0.9))
M(d={"a": "Acme Corporation"}, ld=[{"a": "Acme Corporation"}]).compare_recursive(
M(d={"a": "Acme Corp"}, ld=[{"a": "Acme Corp"}]))Dict[str, str] |
List[Dict[str, str]] |
|
|---|---|---|
dev |
0.5625 | 0.5625 |
ad16f2f |
0.5625 | 0.0 |
The dict field is right on both branches. The list-of-dicts field loses its partial credit only on this branch, with no warning and no CHANGELOG entry — a real number moving to zero in anyone's metrics.
This is not a policy disagreement; it's the gate on line 447 being narrower than the comment 10 lines below it. That comment says the clip default "follows the ANNOTATION, so it applies even when the caller named the comparator", and gives this exact scenario as the thing it exists to prevent:
ComparableField(comparator=ANLSStarComparator(leaf_threshold=...))— the form the docs recommend for setting the leaf cutoff — kept clipping on and zeroed exactly the partial credit ANLS* produces.
But _install_mapping_comparators gates on ConfigurationHelper.is_mapping_annotation(field_info.annotation) alone, which excludes List[Dict[...]] — even though CHANGELOG:340 says that shape "is routed on the explicit path too, keyed on the element type". ConfigurationHelper.get_comparison_info covers _is_list_of_mappings, but only when the comparator is not explicit, which is why naming it is what breaks.
Fix is one condition — admit _is_list_of_mappings to the same clip-default amendment at line 447 — plus a regression test asserting the two fields above score identically. With that, I'll approve immediately.
Waived — real, but not merge conditions
Filing these as follow-ups; none of them silently moves a score today.
comparators/base.py:34—_caller_named_itis defeated by a**kwargspassthrough subclass. Verified:class Wrapper(Legacy): def __init__(self, **kwargs)over a legacythreshold: float = 1.0yieldsthreshold_was_set=True,threshold=1.0, and zero migration warnings. I checked whether this corrupts scores and it does not — the field still scores0.9, same asdev, because clipping doesn't engage on that path. Latent correctness bug, worth an issue, not a blocker. (An earlier round of mine implied a score change here; measured, there isn't one.)json_schema_importer.py:561/field_converter.py:69— a comparator-named threshold is still discarded on the schema and stickler-config paths (0.95→0.5), so the two front doors disagree with the Python API. This is status quo —devdid the same thing — so it's an unfinished extension of #246, not a regression. Please open an issue and add a line to the CHANGELOG so the "both spellings gate the same thing" claim isn't read as covering schemas.comparable_field.py:148— namingDateComparator(threshold=1.0)zeroes that comparator's own partial credit (0.70→0.00). This is the PR's announced semantics working as designed — a named threshold is honoured — and1.0happens to be the value the class documents, so it's the one users are most likely to spell. Not a defect, butdocs/docs/Guides/Comparators/date-comparator.mdwasn't touched and should call it out.comparators/anls.py:130and:217— docstrings still promise default adoption ("DefaultDEFAULT_VERDICT_THRESHOLD, 0.7, rather thanBaseComparator's 0.5, because a mapping is judged as an object"). Under the new rule a default is never adopted, so such a field gets0.5. Docs-only.structured_model.py:636— the new warning fires immediately ahead of an unrelated hard failure, advisingmatch_thresholdon a class that is then refused for carrying a comparator at all. Cosmetic;__init_subclass__'s own comment argues against exactly this ("warning as well would just add noise ahead of a hard failure").structured_model.py:652— leftover first-person review note that contradicts the adjacent code ("…and I keyed on the name anyway" — it keys on_model_identity(...)). Worth deleting on the way past.
Confirmed sound
Suite green (2384 passed, 12 skipped). Optional imported in all twelve touched comparator modules; no positional-parameter order changed; LLMComparator unaffected. to_json_schema()'s metadata.pop("threshold") is scoped to the list-of-models branch only. Legacy array-of-model schemas import silently at 0.5 and warn at any other value, as designed. bbox mAP is untouched — MAPCalculator builds its own BBoxIoUComparator() and reads raw compare(), never the clipped field score. Custom_Comparator_Demo.ipynb outputs still reproduce byte-identically.
…List[Dict] split
The review's sole remaining blocker: two fields of the same shape, same
comparator, same content, scoring differently.
d: Dict[str, str] = ComparableField(comparator=ANLSStarComparator(threshold=0.9))
ld: List[Dict[str, str]] = ComparableField(comparator=ANLSStarComparator(threshold=0.9))
d ld
dev 0.5625 0.5625
before 0.5625 0.0
now 0.5625 0.5625
The diagnosis in the review was one layer off, and its proposed one-condition fix
is inert. I applied it exactly -- admitting `_is_list_of_mappings` to the clip
amendment -- and the field resolved `clip_under_threshold=False` and still scored
0.0. Four independent measurements confirm it changes no score under any spelling.
The real cause: `clip_under_threshold` was a no-op on EVERY list path.
`PrimitiveListComparator` sets `threshold_applied_score = raw_similarity` under a
comment saying lists never clip, but `raw_similarity` arrives from
`ComparisonHelper.unordered_list_metrics`, which had already zeroed each
sub-threshold pair before averaging, regardless of the field's setting. The line
preserving partial credit was preserving a score already thrown away, so a list
field could not opt out while a scalar field could.
The flag is now applied per ELEMENT and means one thing on a scalar and on a list.
Default stays True, so an ordinary list is byte-identical. Classification is
deliberately untouched -- a sub-threshold pair is still one `fd` -- so no
confusion-matrix count moves anywhere.
Both amendments are needed and neither suffices alone: the clip default has to
reach the list shape, and the list path has to read it.
WHY THIS WAS A DECISION AND NOT A BUG FIX
The docs contradict each other. `architecture.md` said "Lists are exempt ... always
preserve partial match scores", while `threshold-gated-evaluation.md`,
`Guides/Evaluation/README.md` and `understanding-results.md` all state the clipping
rule generically with no list carve-out -- and no page defines how a list field's
score is computed, which is the mechanism that decides. The exemption read as true
because it quoted real code; that code sits downstream of the clipping. So
"make the code match the docs" was not available, and the choice was to give the
flag one meaning everywhere. `architecture.md` is corrected accordingly.
TWO SCORES MOVE, both in the container direction, both declared in the CHANGELOG
- `List[Dict[...]]` keeps partial credit, as the singular `Dict[...]` always has.
- any list field that explicitly declared `clip_under_threshold=False` now gets it;
a `List[str]` with a sub-threshold element scores its partial similarity. This is
unrelated to comparator thresholds and is disclosed because nothing else would.
One existing test flipped, `test_a_dict_aware_comparator_still_receives_the_dict`,
from 0.0 to 1/3. That number is exactly `KeyOverlap`'s answer for one shared key of
three, which is what proves the comparator still receives raw dicts, so the test's
actual point is intact and only its clip expectation changed.
DISCLOSED RATHER THAN DISCOVERED, tracked in #330
`List[StructuredModel]` still ignores the flag: its pairs are scored through each
item's own `compare_with`, so clipping already happened per item and the
field-level flag has nothing left to apply. And `raw_similarity_score` on a list
node is the clipped mean, contradicting its name and `compare_field_raw()`.
Restoring the raw/clipped split is the better engineering and was deliberately
deferred: it changes reported output for every list field and deserves its own
review, not a fourth round bolted onto #246.
For the record, the asymmetry predates this branch. On dev, naming the threshold on
the FIELD already gave `d=0.5625, ld=0.0`; this change made it reachable through a
comparator, which is how it surfaced.
Six new tests pin the invariant, the classification, the bounded blast radius, and
both directions of an explicit clip choice on a list.
2390 passed, 12 skipped; ruff clean; mkdocs --strict at the same 9 pre-existing
warnings as dev.
…nothing
The adversarial pass on the previous commit found a movement I had not declared,
and it is the broadest of the three. A BARE `List[Dict[str, str]]` annotation --
no `ComparableField`, no comparator, no threshold -- goes from `0.0` to `0.5625`
on a partly-correct element.
dev, bare annotation d=0.5625 ld=0.0
dev, ComparableField(threshold=0.9) d=0.5625 ld=0.0
now, both spellings d=0.5625 ld=0.5625
Both trees already resolve `clip_under_threshold=False` for that field, because a
mapping is a container, so it was asking to keep partial credit all along and the
list path was discarding it regardless of the setting. The movement therefore comes
entirely from making the flag work, not from the clip amendment, and it reaches any
model with such a field whether or not it configures anything.
The CHANGELOG previously listed two movements, both configured, which understated
the reach. It now leads with this one and says plainly that list-of-mapping field
scores will RISE where an element is partly correct.
It also records that both `dev` rows above are pre-existing: the Dict / List[Dict]
split exists on dev for a bare annotation and for an explicit field threshold
alike, so this change did not introduce the asymmetry -- honouring comparator
thresholds made it reachable from a third spelling, which is how it surfaced.
A test pins it separately from the configured cases, since a regression here would
silently change someone's published numbers rather than someone's configuration.
2391 passed, 12 skipped; ruff clean.
vawsgit
left a comment
There was a problem hiding this comment.
LGTM! — approving
The blocker from my last pass is fixed and verified. With an explicitly named comparator threshold, all three shapes now agree with dev:
Dict[str, str] 0.5625
List[Dict[str, str]] 0.5625 (was 0.0)
Optional[List[Dict[str, str]]] 0.5625
Suite green (2391 passed, 12 skipped). The core change is sound: Optional[float] = None + DEFAULT_THRESHOLD, threshold_was_set recorded at construction and adopted only when explicitly named. All 13 in-repo comparators keep their old effective defaults, Optional imports are present throughout, LLMComparator is unaffected, and unordered_list_metrics' new parameter is appended so both positional callers still work.
I re-reviewed at 35e6de1 against a deliberately narrow bar: only defects that corrupt a currently-working measurement path block. Nothing clears it. The remaining items are real but either pre-existing on dev or confined to an already-broken path, so they're follow-up material rather than merge conditions.
Worth filing, highest first
structured_model.py:455— the clip amendment now writesx-aws-stickler-clip-under-threshold: falseinto the exported schema forList[Dict[...]](trueondev), a setting the user never wrote. I checked whether this corrupts scoring and it doesn't reach a working path: both branches already exportitems: {"type": "string"}for that field and re-import it asOptional[List[str]](#319), so the round trip is type-broken before this change. Once #319 is fixed, this needs fixing with it or the shape comes back as a primitive list with clipping off. This is the only item new in this PR.field_converter.py:69andjson_schema_importer.py:561— a threshold named only on the comparator is still discarded on the config and JSON-Schema paths (0.9→0.5), so the documented precedence "field → comparator → 0.5" holds only for the Python API. Pre-existing ondev, so no regression, but it means #246 is fixed on one of three front doors. Fix is to passNonewhen the key is absent.docs/docs/Guides/Comparators/llm-as-a-judge.md:48and:121— these examples passSemanticComparator(..., threshold=0.8)/BERTComparator(threshold=0.85)as the only threshold and then printfield_scoreswith "High similarity score" comments. Under the new rule that threshold becomes the verdict threshold with clipping on, so sub-threshold pairs now print0.0. The same hazard was fixed inCustom_Comparator_Demo.ipynbandbert_comparator_demo.py; these two were missed.field_converter.py:187— athresholdwritten on alist_structured_modelconfig is dropped in total silence while the sibling JSON-Schema path warns for the identical mistake. The key is inert either way, so no score moves.comparators/base.py:40— the migration warning uses the defaultstacklevel=3where the chain needs 5, so it is attributed tobase.py:174instead of the construction site, andfilterwarnings(module=...)can't target it. The sibling at line 124 setsstacklevel=4for this reason.- Cosmetic — leftover first-person editing note at
structured_model.py:666("…and I keyed on the name anyway") contradicting the_model_identitycall it documents;docs/structured_model_REFACTORING.md:275andsrc/stickler/comparators/Comparators.mdstill teach the pre-PR__init__shape.
Not re-litigating, confirmed correct: the List[StructuredModel] guard refusing a field threshold at every value is a genuine break but disclosed in the CHANGELOG and covered by tests; legacy array-of-model schemas import silently at 0.5 and warn otherwise; _EXPORTED_ARRAY_THRESHOLD_SENTINEL = 0.5 is justified; the clip_under_threshold threading leaves every confusion-matrix count untouched; range validation still runs before the ignore-pop.
#316 landed in dev and touched the same clip-default and list-scoring code this branch changes. Merged rather than rebased: nine commits against a CHANGELOG that both branches append to would conflict at nearly every step, and this history has been through four review rounds. Eight conflict hunks across five files, all semantic rather than textual. **The two designed to compose, and did.** #316 gated the object-grade comparator substitution to a singular mapping and admitted `List[Dict[...]]` for the clip amendment only, with a comment saying the widening "belongs with the reader alignment in #319 rather than here". This is that branch, so the resolution takes #319's `is_object_grade_annotation` and lets all four object-grade shapes run the full loop body. `is_mapping` / `is_mapping_list` disappear with it. **Both parameter sets kept** on `compare_unordered_lists` and `StructuredModel._compare_unordered_lists`: #316's `clip_under_threshold`, which makes the flag work per element, alongside #319's `model_cls` / `field_name`, which carry the object-pair gate to a list element. Neither is optional -- `primitive_list_comparator` now passes both. **Both CHANGELOG entries kept**, #316's first since it is already in dev. Verified by measurement rather than by a green suite, since every conflict here could move a score silently: #316 Dict / List[Dict] with a named comparator threshold 0.5625 / 0.5625 #319 all four object-grade shapes, engine vs to_json_schema agree #319 Cat vs Dog on a declared ANLS* field 0.0, fd=1 2555 passed, 12 skipped -- both branches' suites together; ruff clean.
#316 landed in dev and rewrote the same `_comparison_from_extensions` signature and body this branch extends. Two conflicts, both semantic. **`_comparison_from_extensions` took changes from both sides.** #316 widened `threshold` to `Optional[float]` and added `ignore_threshold` with the array-threshold warning; this branch added `annotation` and `element_of_list` for inference plus the `normalize_comparator_config` validation. The resolution carries all four parameters and both bodies, with #316's `extensions.pop("threshold")` block first. Two mistakes in my first scripted resolution, both caught by the suite rather than by reading, and worth recording because a green suite was the only thing that separated them from shipping: - a DUPLICATE `extensions = self._extract_extensions(...)` survived from the second side, re-reading extensions after #316's block had popped `threshold` from them. That silently undid the ignore-threshold behaviour and failed 12 tests across four files. - a missing newline joined `)` to the next statement, which ruff caught as a syntax error. **Both CHANGELOG entries kept**, #316's first since it is already in dev. Verified after the merge rather than trusting the suite alone, since both sides touch threshold resolution: #316 array threshold 0.5 (export sentinel) 0 warnings #316 array threshold 0.88 (author's) 1 warning #324 comparator-config on a type default applied #324 list-element provenance, both paths identical 2549 passed, 12 skipped; ruff clean; bandit 0 issues at every severity.
#316 landed in dev, and it had solved the same array-threshold defect this branch addressed -- more thoroughly. Six conflict hunks, all on that shared ground. **dev's version wins in the importer.** This branch gated the warning on the export sentinel; #316 goes further and stops emitting `x-aws-stickler-threshold` on a `List[StructuredModel]` property at all, passing `threshold=None` with an explicitness marker instead of the legacy `0.5`. Both formulations were mine, written a day apart on two branches, and this one is superseded. Its four hunks resolve to dev rather than being reconciled. That is also the claim from this PR's own review comment coming due: it said "#316 had the same defect from the other side and is now fixed to match, so the two branches answer identically and their merge order does not change behaviour." Merge order turned out not to matter, but they did not answer identically -- #316's answer is better, and this merge adopts it. **One test of this branch's asserted the old premise and had to invert.** `test_export_emits_the_sentinel_there` pinned that our export writes `0.5` there, and said in its own docstring that the class could go if export ever stopped. It has, so the assertion now requires the key to be ABSENT: an emitted threshold on that shape would be a regression, since a named one is refused at class definition. The round-trip silence it guards now has a stronger cause than a value comparison -- there is nothing on the property to ignore. **#317's own contribution is untouched and verified**: a schema declaring `x-aws-stickler-threshold: 0.95` on an object-typed property resolves to 0.95, where dev silently dropped it to 0.7. 2473 passed, 12 skipped; ruff clean.
Adversarial pass over the merge resolution and over every falsifiable number in the branch's own prose. Behaviour is unchanged; three claims that a reviewer would have checked and found wrong are corrected. `compare_unordered_lists` carried a stray blank line inside its signature, left by resolving the #316 conflict, and its Args block still named `list1`/`list2` while documenting none of the three parameters the last two changes added. The two gate parameters are now described for what they actually do: they name the field in the warning, and the verdict does not depend on either, so a caller with no field in hand still gets the gate. The CHANGELOG cited #135 for `stickler.evaluate()` wrapping a plain model in a generated `StructuredModel`. #135 is the RFC on the two parallel evaluation paths and says nothing about it. The statement is true -- verified: `confusion_matrix["fields"]["address"]["fields"]["city"]` is populated with nothing declared -- so it keeps the statement and drops the citation. `0.8182` for a wholly wrong dict element in a `List[Any]` is not reproducible: no test pins it and no plausible dict content produces it. The sentence's actual point is that the number is IDENTICAL on this branch and on `dev`, which is verified for every spelling measured, so it now says that instead of a number a reviewer cannot reproduce. The asymmetry it confesses -- a dict element is scored where a plain-model element is refused -- is now pinned by a test, asserted as a bound rather than a magic number, since a refusal reads 0.0 with fd=1 and a score does not. Also updates a #316 test docstring that still named `_install_mapping_comparators`, which this branch renamed, so the narrative pointed at a symbol no longer in the tree. Verified against the merge: 2556 tests pass; 17/17 numbers asserted by the new docs and 20/21 by the CHANGELOG reproduce exactly, the last being the 0.8182 corrected here; #316's three declared score movements and its blast-radius bound are intact; every other issue number cited resolves and is on topic.
|
Follow-ups filed, and one correction to my approval above.
Correction: my approval cited "#319" for the mistyped- The three remaining minor items (silent threshold drop on a |
Adversarial pass over every falsifiable statement this branch adds. The
one-line code fix is unchanged and correct; five prose claims were wrong
and two real gaps were undeclared.
"Ignored on an array of objects" was false, in all three places the
branch says it. `items: {"type": "object"}` becomes `List[dict]`, which
READS the declared threshold and warns about nothing; only `items` with
declared `properties` ignores it. Worse, the remedy the new sentence
prescribes is itself swallowed on the free-form shape. Now says "an array
of models -- an array whose `items` declare `properties`", matching how
the entry three bullets up already words it, and
TestAnArrayOfFreeFormObjectsReadsIt pins both halves.
The score move is now marked **Breaking:**. Measured on a four-leaf child
with one leaf wrong and the schema declaring only a 0.88 threshold: dev
resolves 0.70 and scores 0.75, this branch resolves 0.88 and scores 0.00.
The repo's marker is `**Breaking:**` and the comparator-threshold entry
in the same section uses it for the same knob. No clip declaration is
needed for the drop: the importer defaults that key to true everywhere.
"Export writes 0.5 there and can write nothing else" was present-tense
false. #316 stopped emitting the key on an array-of-models, which this
branch's own test asserts; measured export now carries only weight and
clip-under-threshold. Restated in the past tense, as dev's own entry
already has it.
Two docs table columns were wrong independently of this change. The
Default cell for the threshold said "0.5 or 1.0", excluding the 0.7 the
edited sentence newly documents, so it now points at a per-position table
measured for all five positions. The clip row claimed a `false` default;
it is `true` in every position, and clipping is the only mechanism by
which this fix moves a nested score.
"One node honoured two field-level keys and discarded the third" invited
a reviewer to find a fourth. `x-aws-stickler-comparator` on that same
node is parsed, validated -- a bogus name still raises -- and then dropped
without being stored or exported, because the object branch passes a
fixed comparator_name rather than the node's extensions. Score-inert for
a nested model, which is compared by recursion, so it is recorded rather
than carried, and TestTheComparatorOnTheSameNodeIsStillDropped keeps the
sentence honest.
Declared gap: `$ref` into `$defs` does not see the extension. The same
child node resolves 0.88 inline and 0.70 through `$defs`, silently, and a
typo that raises inline is accepted there. Both halves are pre-existing --
the walk does not descend into `$defs` for any key -- but `$ref` is how a
generated schema spells a reusable nested object, so this release makes
the loss score-relevant for the key it ships. Fixing it means deciding
whether an extension on a `$defs` node belongs to the definition or to
each referencing site, which is a schema-semantics question, so it is
pinned by TestTheKeyIsStillDroppedInsideDefs rather than guessed at.
Test rework, because 17 of the 22 original tests passed unchanged against
dev source:
- test_below_the_threshold_the_subtree_is_clipped cannot see the fix. A
two-leaf subtree scores 0.5, under the old hardcoded 0.7 as well as
under the declared 0.6. Kept, relabelled, and joined by a four-leaf
case scoring 0.75 against a declared 0.8, which fails on dev.
- test_an_unstated_threshold_keeps_the_object_grade_default named the
wrong mechanism: 0.7 is the class's match_threshold, while the
object-grade/ComparableField default is 0.5. Renamed, and a scalar
property asserting 0.5 supplies the contrast.
- TestAnUndeclaredSchemaIsUnaffectedEndToEnd bounds the blast radius:
a schema declaring nothing exports 0.7, re-imports at 0.7, and scores
identically, so the export/import cycle moves no one who never touched
the key. That refutes a reviewer concern I could not otherwise answer.
2603 tests pass; 34 in this file, up from 22, of which 7 now fail against
dev source, up from 5. ruff clean. mkdocs --strict fails identically on
dev and CI does not run it.
…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 …
Issue Reference
Fixes #246. Unblocks the remaining acceptance criterion of #210.
The bug
Comparator(threshold=...)is accepted everywhere and read almost nowhere. The only functional reader outside ANLS* isbinary_compare(), which has no callers insrc/. So this:produced a field whose verdict threshold was
0.5. Measured ondev:The value was stored, visible in the comparator's
repr, and never consulted. There are 49 sites in this repo alone passing a threshold that went nowhere.A threshold is only meaningful beside the metric that produced the score:
0.85means one thing on edit distance and another on a semantic embedding. So a threshold the caller put on the comparator is a statement of intent about that field, and discarding it silently is the wrong default.Precedence
Why a comparator's default threshold is not adopted
This is the part that keeps the change safe, and it is not caution for its own sake. Those defaults were only ever read by
binary_compare(), never as verdict thresholds, so they have not been audited as such, and at least one is actively wrong for the job:DateComparatordefaults tothreshold=1.0while awarding0.7partial credit for a match with no year. Adopting the default would put the verdict threshold above the comparator's own partial credit, clipping that feature to zero. There is a test for exactly this.Explicitness is recorded in
BaseComparator.__init__asthreshold_was_set, because it cannot be recovered downstream: each subclass used to resolve its own default before callingsuper().__init__, soDateComparator()andDateComparator(threshold=1.0)both arrived holding1.0.thresholdnow defaults toNoneon every comparator, meaning "use myDEFAULT_THRESHOLD".An earlier revision did recover it by comparing against the declared class default, and that design was rejected: it made the effective threshold non-monotonic (
0.69gave0.69while a stricter0.70fell back to0.50) and collapsed the strictest spelling of every 1.0-default comparator.DateComparator(threshold=1.0)is adopted now, and that is load-bearing: it drops the comparator's own year-less partial credit from0.7to0.0, which is why the docs tell callers to think before naming it. Out-of-tree comparators that still declare a concrete default keep the old fallback, with a migration warning.Breaking change, and how far it reaches
thresholdmoves for any field that named a comparator with an explicit threshold and no field threshold. A score between the old0.5and the adopted value flips from true positive to false discovery.A test asserts the flip rather than just the stored number, since asserting the number alone would pass even if nothing downstream read it, which is the bug:
Nothing else moves.
threshold=0.0stays a value rather than an omission and still triggers the zero-threshold warning, and a field stating its own threshold is unaffected. Full suite is2342 passed, 12 skippedwith no existing test modified.Reimplemented, not rebased
The original branch predated #212's delegation to
json-schema-to-pydantic, which cutjson_schema_field_converter.pyfrom about 570 lines to 239, so its conflicts were against a structure that no longer exists. Reimplementing was smaller and safer than resolving them, anddevalready carried_comparator_explicitand_clip_explicitfrom #300, so only the threshold half was missing.Relation to #210
This records
_threshold_explicitalongside the two existing markers. That is what #210's acceptance criterion 4 needs:auto/builder.pycurrently hardcodesprovenance=["explicit: configured on the StructuredModel class"]for every field of everyStructuredModel, so a bareComparableField()claims to be explicitly configured. With all three markers present,explain()can report provenance accurately. That follow-on is not in this PR.It also makes #314's ignored-comparator note exact rather than approximate, since that check currently cannot distinguish an explicitly named
LevenshteinComparatorfrom the installed default.Verification
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.