Skip to content

release(v1.0.1): HTML report security fixes and scoring corrections - #473

Closed
sromoam wants to merge 491 commits into
mainfrom
dev
Closed

sromoam wants to merge 491 commits into
mainfrom
dev

Conversation

@sromoam

@sromoam sromoam commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Summary

Security. Untrusted document data could run script in the generated HTML report (GHSA-r553-884h-v3r5, published with this release).

Scoring and results

Models, import and export

Other fixes

Docs

Tests, refactors, CI and dependencies

Version

1.0.0 → 1.0.1 (patch: fixes only; not breaking. Inputs that 1.0.0 accepted and that dev had started refusing keep 1.0.0's result with a warning, #471. Some scores move where 1.0.0 scored a case wrong, as each CHANGELOG entry states.)

Test plan

dependabot Bot and others added 30 commits September 2, 2026 17:49
…updates

Bumps the github-actions group with 6 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [actions/checkout](https://github.com/actions/checkout) | `4.3.1` | `7.0.1` |
| [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) | `5.4.2` | `10.0.1` |
| [actions/download-artifact](https://github.com/actions/download-artifact) | `4.3.0` | `8.0.1` |
| [actions/github-script](https://github.com/actions/github-script) | `7.1.0` | `9.0.0` |
| [actions/upload-artifact](https://github.com/actions/upload-artifact) | `4.6.2` | `7.0.1` |
| [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) | `1.14.0` | `1.14.2` |



Updates `actions/checkout` from 4.3.1 to 7.0.1
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](actions/checkout@34e1148...3d3c42e)

Updates `astral-sh/setup-uv` from 5.4.2 to 10.0.1
- [Release notes](https://github.com/astral-sh/setup-uv/releases)
- [Commits](astral-sh/setup-uv@d4b2f3b...20cfd1b)

Updates `actions/download-artifact` from 4.3.0 to 8.0.1
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](actions/download-artifact@d3f86a1...3e5f45b)

Updates `actions/github-script` from 7.1.0 to 9.0.0
- [Release notes](https://github.com/actions/github-script/releases)
- [Commits](actions/github-script@f28e40c...3a2844b)

Updates `actions/upload-artifact` from 4.6.2 to 7.0.1
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](actions/upload-artifact@ea165f8...043fb46)

Updates `pypa/gh-action-pypi-publish` from 1.14.0 to 1.14.2
- [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases)
- [Commits](pypa/gh-action-pypi-publish@cef2210...dc37677)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: 7.0.1
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
- dependency-name: actions/download-artifact
  dependency-version: 8.0.1
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
- dependency-name: actions/github-script
  dependency-version: 9.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
- dependency-name: actions/upload-artifact
  dependency-version: 7.0.1
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
- dependency-name: astral-sh/setup-uv
  dependency-version: 9.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
- dependency-name: pypa/gh-action-pypi-publish
  dependency-version: 1.14.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
refactor(schema): delegate JSON Schema parsing
…thub-actions-e2a66e10a6

chore(deps): bump the github-actions group across 1 directory with 6 updates
Resolve the CHANGELOG.md conflict under [Unreleased]. Both sides appended
sections, so the resolution keeps both: the two #231 entries move into the
single ### Fixed list that dev introduced, ahead of the #233 entries, and
dev's ### Removed, ### Performance and ### Changed sections are untouched.

No upstream commit touched src/stickler/algorithms/hungarian.py or its
tests. 358c455 (#233) edited two of this branch's docs files and merged
cleanly; it adopts the same FD vocabulary at object level.
…-print

fix(pretty_print): default name_width to 0 when per-field confusion matrix is empty (#307)
Closes #287. Closes #23.

`all_fields_matched` quantified over top-level fields only and did not recurse.
`comparison_engine.py` computed it as
`len(threshold_matched_fields) == len(model_fields)`, where a nested field counts
as matched when its own subtree mean clears its own threshold. So a failing leaf
underneath was invisible:

    one top-level list field, 1 of 3 leaves wrong  -> score 0.667, flag True
    two top-level scalars,    1 of 2 wrong         -> score 0.500, flag False

Two external reports read it as a quantifier over every leaf, which is what the
name and the docs said. They expected opposite behaviours from each other: #23
expected False when a nested item fell below its match_threshold, #275 expected
False when a leaf failed inside an item that paired successfully. No single
implementation satisfies both, so the key is removed rather than redefined.

Everything it was reached for already existed: `overall_score` for the scalar
summary, `confusion_matrix.aggregate.fd` for whether any leaf failed,
`field_comparisons` for which one.

`EvalResult.matched` read the removed key, so it is defined directly as
`overall_score >= match_threshold`. That is what its docstring already claimed,
and it cannot disagree with the score beside it. The two definitions genuinely
diverged: with one of three fields wrong the key read False while
`overall_score >= match_threshold` was True.

Six producer sites removed, six docstrings corrected, and seven documentation
sites that described the universal-quantifier reading the code never had --
including a dedicated section in understanding-results.md and the sample outputs
in Getting-Started/README.md and Guides/Evaluation/README.md.

`TestMatchedHasOneDefinition` pins the removal, the new definition moving with
`match_threshold` rather than with a field count, and the dilution case: a wrong
leaf among five correct siblings keeps `overall_score` strictly below 1.0 where
the old flag flipped to True.

Verified: 1969 passed, 2 skipped. `ruff check` clean. `mkdocs build` clean.
The first commit corrected the documentation that described the key but left
prose narrating its removal. Docs should describe what exists; the migration note
belongs in the CHANGELOG, which has it.

More importantly, this fixes real breakage the first commit missed. Five example
scripts and three notebooks read `result['all_fields_matched']` directly and now
raise KeyError:

    examples/scripts/quick_start.py                (2 sites)
    examples/scripts/bert_comparator_demo.py
    examples/scripts/non_match_analysis_demo.py
    examples/scripts/json_schema_demo.py
    examples/notebooks/Quick_start.ipynb           (2 sites)
    examples/notebooks/Complex_nested_structure.ipynb

`Quick_start` is onboarding material, so this would have been the first thing a
new user hit. Nothing in CI executes the examples, which is #118.

Three doc sites lose their explanatory paragraphs and instead state what to use:
`confusion_matrix.aggregate.fd` for whether any leaf failed, `field_comparisons`
for which ones, `overall_score` for the scalar, and `EvalResult.matched` for the
object-level verdict.

No reference to the key remains anywhere outside the CHANGELOG, the source
comment explaining why `EvalResult.matched` is defined as it is, and the tests
that pin its absence.

Verified: 1969 passed, 2 skipped. `mkdocs build` clean. Both touched scripts run.
Both touched notebooks are valid JSON. The 16 `ruff` findings under examples/ are
pre-existing on dev and unrelated.
Ten findings from @vawsgit's review on #290, each verified before fixing.

Blocking:

- `EvalResult.matched` ignored a `StructuredModel`'s own declared
  `match_threshold`. `eval_for` took the passthrough branch and stored the
  facade default of 0.7, so a model declaring 0.95 reported a 0.80 pair as
  matched. The removed `all_fields_matched` honoured the model's per-field
  thresholds, so this was a regression on top of the documented redefinition
  and it contradicted `eval_for`'s own AS CONFIGURED promise. The public
  entry points now take `match_threshold=None` as a "caller said nothing"
  sentinel: a declaration wins over the default, an explicit argument wins
  over both, and a class that declares nothing is unaffected. Pinned in all
  three directions by a new test.

- The CHANGELOG's divergence example was inverted. One of three fields wrong
  scores 0.6667, which is below the 0.7 default, so the new definition reads
  False there rather than True. Replaced with the case that does diverge: one
  wrong field among six scores 0.8333, old False and new True.

- `confusion_matrix.aggregate.fd` was given as the replacement for asking
  whether anything failed, in the CHANGELOG and two doc pages. It misses
  missing fields, which are `fn` and leave `fd` at 0, so a user following it
  reads fd == 0 on a document the old key called False. Corrected to
  `fd + fn == 0` in all three places, with the two categories spelled out.
  Extras are `overall.fa` rather than an aggregate count, which the guidance
  now says explicitly.

Also:

- `test_a_leaf_failure_under_a_nested_field_is_not_hidden` asserted only
  `overall_score < 1.0` while `matched` is True on its inputs. Both the score
  verdict and the `fd + fn` replacement are now pinned, so neither can drift
  into the other's job.
- Removed `threshold_matched_fields`, dead since the consumer went but still
  costing a `_get_comparison_info` lookup and a `raw_similarity_score`
  subscript per field per comparison. Updated the contributor architecture
  doc, which documented it as one of "three tracking variables", and its two
  stale line-number pointers.
- Dropped the trailing commas left behind in three ```json samples. All three
  now parse.
- Deleted 16 assertions that were exact duplicates of the line above them and
  could never fail. A duplicate of its predecessor is a deletion with extra
  characters, so counting them as "updated" overstated the change.
- Re-serialized both notebooks with `ensure_ascii=False`. The previous pass
  escaped every emoji, which was 116 of the 119 changed lines and buried the
  three real edits.
- Deduplicated a paragraph in understanding-results.md that said the same
  thing twice, and restored the `bool()` cast on `matched`, whose annotation
  says bool and whose tests use `is True`.

1970 passed, ruff clean.
…egate

The guidance added in ef24593 said `aggregate.fd + fn == 0` answers "did every
ground truth leaf land". It does not, because it silently scopes the question to
the objects that were comparable.

An object scoring below `match_threshold` is a spurious non-match: it is recorded
as one `fd` on `overall` and is not descended into, so it contributes no leaf
rows. That is deliberate, since reporting the leaves of an object already
rejected as a whole would score something the comparison declared not comparable.
The consequence for the guidance is that `aggregate` alone cannot see it:

    2 items, 12 leaves, item 1 has N of its 6 leaves wrong

     N  item score  comparable?  overall      aggregate
     1      0.8333          yes  tp=2 fd=0    tp=11 fd=1
     2      0.6667           no  tp=1 fd=1    tp=6  fd=0

At N=2 two leaves are wrong and `aggregate.fd + fn == 0`, because the only leaves
scored are the six belonging to the object that was comparable. The rejection is
recorded on `overall` instead.

Measured over eight shapes (clean, a leaf failure inside a comparable object,
leaf failures in a rejected one, a missing object, a hallucinated field, and the
three flat-model equivalents), `aggregate.fd + fn` alone is wrong on two of
eight. Reading both nodes is right on all eight:

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

`overall` is also the only node carrying `fa`, since an invented field maps to no
ground truth leaf.

Corrected in the CHANGELOG entry and both doc pages, and framed as the two nodes
scoping different questions rather than as a defect: `overall` carries object
verdicts, `aggregate` carries leaf detail for comparable objects, and
`match_threshold` is the knob for how much leaf detail you get. Whether
aggregates should also count below-threshold leaves is a separately deferred
question.

`test_a_rejected_object_contributes_no_leaf_rows` pins the behaviour so the
corrected guidance is anchored rather than asserted.

1971 passed, ruff clean.
Review caught that the `aggregate`-removal entry was deleted from
`[Unreleased]`. That was collateral from resolving the CHANGELOG conflict
during the rebase, not a deliberate scope change, and it is the one loss
that matters: once released, those notes are simply missing.

Restored verbatim from `dev`, and the check I should have run the first
time now confirms nothing else is gone: zero bullets present in `dev`'s
`[Unreleased]` are absent here. Also merged the duplicate `### Fixed`
heading the recovery dragged along.

Second time this exact mistake has bitten on this branch. I caught the
`all_fields_matched` entry going missing and then failed to check for
anything else, when the check is three lines and mechanical.

2044 passed, 12 skipped.
feat!: remove all_fields_matched and define EvalResult.matched directly
…t equality

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Tau remains settable where it is a real choice:

    ComparableField(comparator=ANLSStarComparator(threshold=0.85))

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

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

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

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

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

1995 passed, ruff clean, mkdocs unchanged at the pre-existing 9 warnings.
…e thing

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

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

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

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

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

`config` now emits `leaf_threshold` instead of `threshold`, so a schema
exported before this change and re-imported after it would read a
non-default tau as a verdict threshold. Only affects non-default values,
which nothing in the repo exports.
Every one reproduced before fixing; each has a test that fails without its fix.

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

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

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

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

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

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

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

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

2088 passed, 12 skipped, ruff clean on src and tests.
Reverts the type-aware leaf comparison added in the previous commit, and
addresses the two findings that are independent of it.

## Why the leaf typing is reverted

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

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

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

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

## What canonical means, and its cost

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

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

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

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

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

## The two findings that survive the revert

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

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

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

Net: -39 lines of leaf logic, -121 lines of tests pinning it, +14 tests pinning
the canonical contract instead. 2084 passed, 12 skipped, ruff clean.
Three defects, all introduced earlier on this branch, all found by review
rather than by tests. The suite was 2084 green before and after the fixes,
which is the finding behind the findings.

## Declaring ComparableField changed which comparator a field got

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

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

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

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

## Naming the comparator re-enabled clipping

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

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

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

## ExactComparator canonicalised a lone mapping

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

## Tests

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

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

2089 passed, 12 skipped, ruff clean on src and tests.
## Values with no JSON form are refused rather than scored

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

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

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

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

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

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

## Docs rewritten for someone deciding whether to use this

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

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

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

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

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

11 new tests. 2105 passed, 12 skipped, ruff clean, mkdocs warnings unchanged
from dev.
The parameter was documented by what it does and by a warning not to set it to
0.0, but never by why anyone would change it. The answer is concrete once
measured: character similarity scales with length, so one cutoff is lenient for a
short value and strict for a long one. At the default, a wholly wrong short code
still earns half credit.

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

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

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

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

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

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

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

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

2105 passed, ruff clean, mkdocs warnings unchanged.
Review caught that the entire `### BBoxIoUComparator` section was gone while the
summary table still linked `#bboxioucomparator`, so that link was dead.

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

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

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

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

2110 passed, 12 skipped, mkdocs warnings unchanged from dev.
feat!: score undeclared dict fields with ANLS* instead of whole-object equality
fix(hungarian): count a low score pair as fd and not as fn
…ng them

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

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

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

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

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

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

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

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

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

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

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

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

Refs #210
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.
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.
Resolve two conflicts:

- src/stickler/comparators/base.py: dev still carries the 0.7.0 shim, which
  this branch replaces. Kept our __init_subclass__ (the shadowing warning) and
  dropped dev's reinstated shim, including its now-unused _unmigrated stub and
  the comparator-compare-rename warn_once id.

- CHANGELOG.md: dev reorganised [Unreleased] and added its own ### Removed
  section. Folded our shim entry into that section, after the
  ComparableField(aggregate=) entry, rather than opening a second ### Removed.
  Dropped our copy of the ### Changed / AUROC entry, which dev already carries
  up in the reorganised section.
feat(comparators)!: remove compare() shim, warn on shadowing (#215)
sromoam and others added 27 commits October 29, 2026 14:00
… doc_id as a string

pdf.js 3.11.174 runs script from a crafted PDF font unless eval is off.
Pass isEvalSupported: false to getDocument, the upstream mitigation.

The per-document view compares ids as strings, so an integer doc_id from a
DataFrame matched nothing and the page kept showing aggregate numbers.
_load_individual_results now converts it, matching the tables' str().

Both fixes as specified by vawsgit in the #452 review.
… and its pdf.js

Three tests in a new test_pdf_viewer.py, alongside the existing
test_the_pdf_viewer_disables_eval:

- the page has exactly one pdfjsLib.getDocument(...) call and it carries
  isEvalSupported: false. A check for the safe form alone still passes when a
  second loader is added without the option, e.g. getDocument(u);
- the viewer is not embedded without individual_results_jsonl_path;
- the pdf.js <script> tag still loads 3.11.174 and has no integrity hash, so
  the upgrade is a deliberate change. Its failure messages say to invert the
  integrity assertion then, not delete it.
Nine tests on _load_individual_results: zero, float and NaN ids become
strings; a string id, None and a missing key are left alone; a line that is
not an object does not drop the records after it; ids that differ only by type
now map to the same string; and every id embedded by generate_report is a
string, including one above 2**53. Several guard against a mis-fix rather
than the fix: dropping the dict guard, converting None, testing the id for
truthiness, or converting only int each pass the existing tests.
…he prediction

The fixture gave prediction_value the value 'short', so only the ground-truth
column could tell truncate-then-escape from escape-then-truncate. Both columns
now carry 97 characters and an ampersand, and both are asserted.
Reports generated with individual_results_jsonl_path take longer to write
since the script-block escaping: 467 ms against 42 ms at 1.0.0 for 1,000
documents, per #457. Evaluation results are unaffected.
* fix(306): accept default_factory on ComparableField

ComparableField forwarded its own `default` to Field() unconditionally, so a
caller-supplied `default_factory` collided with it and pydantic rejected the
pair. Every collection field was affected, which is the case pydantic's own
documentation tells users to write `default_factory` for.

Forward `default` only when the caller did not supply a factory. The parameter
now defaults to a sentinel rather than None so that an explicitly written
`default` is still passed through alongside a factory, letting pydantic raise
as it normally would instead of one of the two being dropped here. An omitted
`default` keeps its historical None, which the schema generator already reads
as a construction-tolerance marker rather than a real default.

* docs(306): changelog entry for the default_factory fix

Recorded under [Unreleased] per the PR checklist, since the accepted argument
set is user-visible.

* fix(306): keep default_factory=None from turning a field required

The guard added for #306 tested for the KEY, not its value:

    if "default_factory" in clean_field_kwargs:

`None` is pydantic's own signature default for `default_factory`, so a caller
forwarding kwargs through a wrapper or a config-driven builder can pass it
explicitly without meaning anything by it. Read as "a real factory was
supplied", it dropped our own default, and a field that was optional with
`None` became required:

    ComparableField(default_factory=None, comparator=ExactComparator())

    before  is_required=False  default=None            N().note = None
    after   is_required=True   default=PydanticUndefined
            N()  ->  ValidationError: note  Field required

Checking the value says what the branch actually means: it exists because a
real factory conflicts with our default, and `None` is not a real factory.

* fix(306): export a factory's value, not PydanticUndefined

Both exporters read `FieldInfo.default`, and neither knew about factories.
They could not have: on `dev` a `default_factory` field dies at class
definition, so these paths were unreachable until #306 made them reachable.

`to_stickler_config()` wrote `PydanticUndefined` through verbatim, which is
not serialisable, from a method whose whole purpose is producing a config you
can write to a file:

    json.dumps(cfg)  ->  TypeError: Object of type PydanticUndefinedType
                         is not JSON serializable

and the in-process round trip rebuilt the field as required, so
`M2(name='a')` raised `ValidationError: tags  Field required`.

`to_json_schema()` failed the same way but quietly: the default vanished, and
`from_json_schema()` rebuilt `tags` as `None` rather than `[]`, so the failure
surfaced later at the first `.append()`, away from its cause.

Both now go through one helper. For `list`, `dict` and `set` it calls the
factory and exports the value it produces, which round-trips and is what a
reader expects; any other factory leaves the key out rather than being
invoked, since a caller's callable could read a clock or a database and an
export should not run it.

A set is exported as a list. Exporting the set itself reproduces the first
failure above one value type over, and `List[str] =
ComparableField(default_factory=set)` is legal:

    json.dumps(M.to_stickler_config())
      ->  TypeError: Object of type set is not JSON serializable

JSON has no set, and the factory is the builtin called with no arguments, so
the value is always empty and the conversion is unambiguous.

* docs(306): record the exporter half of the default_factory fix

The entry described the field accepting a factory and stopped there, but the
two exporters changed as well and both are user-visible: a config that would
not serialise now does, and a schema round trip returns `[]` where it used to
return `None`.

* fix(306): export a factory default on List[StructuredModel] fields

Both exporters' list-of-models branches skipped resolve_exportable_default, so subs: List[Sub] = ComparableField(default_factory=list) exported no default and rebuilt as None through model_from_json and from_json_schema.

* fix(306): give the unset default a readable repr in the signature

* fix(306): export mapping fields as objects and share the default export

* test(306): arm the identity factory after the class is built

On Python < 3.13, pydantic's inspect.signature(factory) at class definition
reaches inspect._signature_is_builtin, which tests `obj in (type, object)`
and so calls the factory's __eq__. The trap fired before the export ran,
failing the 3.10, 3.11 and 3.12 CI jobs. Arm it once the class exists so
the test checks only the export's identity match.

* fix(306): export Annotated list factories; state default + default_factory; mark the mapping export Breaking

- _exports_as_container strips Annotated as well as Optional
  (ConfigurationHelper.strip_annotation_wrappers), so
  Optional[Annotated[List[...], ...]] = ComparableField(default_factory=list)
  exports "default": [] and rebuilds as [] through both exporters, not None.
- default=... beside default_factory mirrors pydantic's Field: ignored, the
  field is optional. README, docstring and CHANGELOG now say so instead of
  claiming every pairing raises; a test pins it against pydantic.
- The mapping-export CHANGELOG entry moves to Changed and is marked
  Breaking, as the matching #349 export-type change is.
- model-export.md states how a Dict field and a default_factory export
  and round-trip.

* fix(306): keep Optional list and mapping fields nullable through to_stickler_config

A Stickler config has no nullable flag; model_from_json() widens a field to
Optional only when its default is None. Exporting a factory's [] or {} (or a
literal empty one) on an Optional field therefore rebuilt it non-nullable,
rejecting the None the original accepts. dev exported no default, so this
regressed with the factory export.

- to_stickler_config() writes no empty [] / {} default on a nullable field
  (Annotated stripped); it rebuilds with None, which scores the same.
  to_json_schema() keeps the default: its "null" type already round-trips.
- model_from_json() widens a list_structured_model field with a None default
  to Optional, as the primitive path does (#149); it rebuilt as List[Model]
  and rejected None, on dev too.
- Round-trip test over Optional[Annotated[List[str]]],
  Optional[Annotated[List[Model]]], Optional[List[int]], Optional[Dict[str,
  int]]: both rebuilt models accept None and score all 16 unset/None/empty/
  value pairs as the original.
- Docs: model-export.md states the Optional rule; CHANGELOG scopes the
  List[Dict] "string" note to to_json_schema(); README names both
  default=... and default=PydanticUndefined as accepted beside a factory.

* fix(306): keep a non-Optional List[Model] non-nullable over repeated config round trips

The list-of-models branch of to_stickler_config() did not write a literal
default, so the first rebuild's `[]` went missing in the second export and
model_from_json()'s new None-default widening made the field Optional.

- Write an empty literal `[]` there, as field_to_stickler_config() does. A
  non-empty literal holds model instances, which are not JSON, so it is
  still not exported (include_literal=True would break json.dumps()).
- The nullable check reuses is_optional_union(unwrap_annotated(...)).
- Correct the docstring: the JSON Schema rebuild accepts None because
  JsonSchemaImporter widens every non-required field, not because "null"
  is in the exported type.
- Tests: double config round trip of List[Model] with a factory and with a
  literal [] stays non-nullable; a hand-written non-required
  list_structured_model accepts None and a required one stays List[Model].
- Docs: model-export.md and CHANGELOG say the Optional rule covers empty
  defaults only, and that the rebuilt default is None (model_dump() shows
  null); dynamic-models.md states model_from_json()'s None-default widening.

* docs(306): scope the config nullability rules to what they cover

- dynamic-models.md: the None-default widening applies to primitive and
  list_structured_model fields; a structured_model field is never widened.
- model-export.md and CHANGELOG: the Optional rule covers an empty list or
  mapping default only (`""` is written). A List[Model] default that is not
  written (a non-empty literal, a tuple, a factory other than list, dict or
  set) rebuilds as Optional with a None default, Optional original or not;
  None scores the same as [].
- json_schema_field_converter.py docstring: "as before #306", not "as on dev".

---------

Co-authored-by: Spencer Romo <sromo@amazon.com>
…row (#249, #338) (#403)

* docs(249): stop promising mean_score for leaves under list parents

The _accumulate_field_metrics docstring said mean_score is recorded at
every node, "including leaves under list parents". It is not: those
leaves carry CM counts only, which the user docs and tests already
state. Reword the docstring to match. No behaviour change.

Refs #249 (per-leaf scores for list children remain open, post-1.0).

* docs(338): split the [Plain, NoteSM] row by annotation

The element-gate table is headed with a bare Optional[List[Any]], but its
[Plain, NoteSM] vs [Plain, Note2SM] row was measured with a declared
comparator. Bare, the pair scores 0.0 under the list-wide gate and 0.5
now, because the bare annotation refuses the Plain pair on its own
([Plain] vs [Plain] scores 0.0), not because of the cross-class rule.

Split the row into bare and declared cases in comparison_helper.py and
the test docstring. The released 1.0.0 CHANGELOG section is left as is;
an Unreleased entry corrects it. No behaviour change.

Closes #338.

* docs(249,338): fix claims the first two commits left wrong

- `_accumulate_field_metrics`: list-of-StructuredModel element fields
  arrive under `fields`, not `nested_fields`; compare_with no longer
  emits `nested_fields` (its emitter went in ad19ac8). Note that only a
  finite score is summed.
- bulk-evaluation.md and understanding-results.md said compare_with
  "only emits the score at the list parent". An object node inside a
  list element is scored too (`items.addr` gets a mean_score); only the
  leaves are not.
- CHANGELOG: move the #338 correction from `### Fixed` with a
  `**Documentation:**` prefix to a `### Documentation` section, the
  heading earlier releases use.

Refs #249, #338

* docs(249,338): address review on #403

- Guides: leaves and primitive lists anywhere inside a List[StructuredModel]
  element have no mean_score, and every path inside an element counts only
  pairs that met the match threshold (a pair below it emits no element fields).
- _accumulate_field_metrics docstring: same scope, replacing "leaves under a
  list parent".
- _ClassGatedComparator and test-class docstrings: both [Plain, NoteSM] rows
  enforced the cross-class rule under the list-wide gate (bare fd=2).
- Pin the bare row: [Plain] vs [Plain] = 0.0, bare [Plain, NoteA] vs
  [Plain, NoteB] = 0.5 (tp=1, fd=1).
- Fix the two surviving "emits only at the list parent" comments in
  test_bulk_structured_model_evaluator.py.
- CHANGELOG: Unreleased Documentation entry for the mean_score guide fix.

* docs: list the paths inside a list element that get mean_score

Inside a List[StructuredModel] element, only the element's own object and
List[StructuredModel] fields (items.addr, items.parts) carry a mean_score,
and each document's value is the first matched element pair's score.
Every other path inside an element, including objects two or more levels
down (items.addr.geo), has confusion-matrix counts only. Fix the CHANGELOG,
both guides and the _accumulate_field_metrics docstring, and extend the pinning test to
the depth-2 object node, a primitive list and a depth-2 leaf (#249).

* docs: link the element-order dependence to #428

* docs: name StructuredModel fields as the scored ones in a list element, and pin items.parts and a plain field
The Documents card interpolated document_count into the page unescaped.
ProcessEvaluation validates the field as an int at construction, but not on
assignment or through model_construct, so a caller that assigns it, or builds
the model with model_construct, could put markup into the report. Document
data does not reach it: the bulk evaluator sets an int, and a results dict
falls back to 1.

The value now goes through html.escape like the other cells, and a test
assigns markup after construction and asserts it is escaped. It has the same
in-process-caller reachability as #453; #456 escapes the visualization_engine.py
cells, not this one.
test(report): harden #464's report tests, and record the #457 slowdown
fix(453): escape :.3f/:1f cells after formatting
…rom-452

# Conflicts:
#	src/stickler/reporting/html/visualization_engine.py
#	tests/reporting/html/test_visualization_engine.py
# Conflicts:
#	docs/docs/Guides/.nav.yml
fix(report): escape the executive summary's document count
StructuredOutputSimilarity ships in strands-agents-evals 1.6.0 with the
stickler extra, so drop the sromoam/evals branch pin and the unreleased
wording from the guide, both evaluator notebooks and examples/README.md.
Point the design-notes sentence at the Strands Evals README section.
A plain model's element pairs are gated by the evaluator's
match_threshold; only a StructuredModel element uses its own. The
date-typed document also passes (0.80); what differs is the field: 0.9
as str against 0.0 as date. Measured against strands-agents-evals 1.6.0
with stickler 1.0.0 and dev.
docs(examples): Strands Evals integration notebooks and guide
fix(report): carry the #452 report hardening onto dev, and mitigate CVE-2024-4367
fix(333): export a List[Dict] element as an object so the schema loads its own data
…thub-actions-e7bdc2f13e

chore(deps): bump the github-actions group with 2 updates
@sromoam

sromoam commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

Closing so @digalaviz can open and own the dev → main release PR. The summary and test plan above are a starting point if useful: every PR merged into dev since v1.0.0, plus #471 (warnings instead of raises) and #472 (version bump and CHANGELOG cut), which need to land on dev first. One thing to watch: this is the first release on gh-action-pypi-publish 1.14.3 (#459).

@sromoam sromoam closed this Oct 30, 2026
@github-actions

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-10-30T19:54:01+00:00
  • Time since scan: 3 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-10-30T19:50:17+00:00
  • ASH version: 3.1.2

Summary

Scanner Results

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

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

Top 4 Hotspots

Files with the highest number of security findings:

Finding Count File Location
2 tests/comparators/test_anls_leaf_semantics.py
2 .ash/ash_output/converted/jupyter/examples__notebooks__Strands_Evals_FCC_Live_Agent__ipynb-converted.py
2 tests/structured_object_evaluator/test_rollup_node_semantics.py
1 tests/test_readme_examples.py

Detailed Findings

Show 7 actionable findings

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

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

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

Code Snippet:

Secret of type Hex High Entropy String detected

Finding 2: B310

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B310
  • Location: .ash/ash_output/converted/jupyter/examples__notebooks__Strands_Evals_FCC_Live_Agent__ipynb-converted.py:83-85

Description:
Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.

Code Snippet:

)
with urllib.request.urlopen(url, timeout=60) as resp:
    rows = [item["row"] for item in json.load(resp)["rows"]]

Finding 3: B108

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

Description:
Probable insecure usage of temp file/directory.

Code Snippet:

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

Finding 4: B307

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

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

Code Snippet:

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

Finding 5: B307

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

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

Code Snippet:

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

Finding 6: B102

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B102
  • Location: tests/test_readme_examples.py:55-57

Description:
Use of exec detected.

Code Snippet:

with contextlib.redirect_stdout(out):
        exec(code, namespace)
    prints = [line for line in code.splitlines() if line.startswith("print(")]

Finding 7: B310

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B310
  • Location: .ash/ash_output/converted/jupyter/examples__notebooks__Strands_Evals_FCC_Live_Agent__ipynb-converted.py:83-85

Description:
Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.

Code Snippet:

)
with urllib.request.urlopen(url, timeout=60) as resp:
    rows = [item["row"] for item in json.load(resp)["rows"]]

Report generated by Automated Security Helper (ASH) at 2026-10-30T19:54:03+00:00

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.