Skip to content

Changes for #201. - #207

Merged
sromoam merged 7 commits into
devfrom
sr/201
Aug 10, 2026
Merged

sromoam merged 7 commits into
devfrom
sr/201

Conversation

@sromoam

@sromoam sromoam commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Issue #, if available:

Fixes #201. Substantially covers #187 and #184.

Description of changes

Three related changes, all in service of making pip install stickler-eval install a comparison library rather than a scientific-computing stack.

1. Widen the supported Python range. requires-python moves from >=3.12 to >=3.10, with trove classifiers for 3.10-3.14 and a CI matrix covering every version claimed, so the floor is enforced rather than asserted.

2. Slim the core dependencies. pandas, scipy, scikit-learn, and jinja2 leave [project.dependencies] for extras. Core is now six packages: pydantic, rapidfuzz, munkres, numpy, jsonschema, python-dateutil.

3. Defer the corresponding imports. Module-level imports of the heavy packages become function-local (with ImportError messages naming the extra) or TYPE_CHECKING-only. Optional comparators resolve lazily via PEP 562 __getattr__, and BERTComparator no longer loads its model at import time.

Measured effect

before after
modules on import stickler (core install) 1664 463
heavy packages on the import path all 8 none
core dependencies 10 6

None of pandas, scipy, scikit-learn, jinja2, torch, transformers, strands, or boto3 is imported by import stickler.

⚠️ Breaking change

Removing core dependencies breaks code that used the peripheral modules without installing an extra. Each now raises ImportError naming what to install:

what you were using now needs
stickler.doc_split (raises at import) stickler-eval[docsplit]
AUROCMetric.compute() stickler-eval[confidence]
MarkdownUtil.table_df() stickler-eval[reporting]
LLMComparator(...) stickler-eval[llm]
SemanticComparator cosine similarity stickler-eval[semantic]

pip install "stickler-eval[all]" restores everything except bert.

Only stickler.doc_split fails at import time; the rest fail at first use. SemanticComparator still constructs on a core install and raises when the similarity function runs, which matches the pre-existing lazy boto3 gate in comparators/utils.py.

This is in the CHANGELOG under Changed and belongs in the release notes.

Unannounced constraint relaxation

The scikit-learn floor drops from >=1.8.0 to >=1.7.2. 1.8.0 requires Python 3.11+, so the old floor made the 3.10 support above unresolvable. The lock pins 1.7.2 below 3.11 and 1.8.0 above. Flagged because it is a relaxation on a shared dependency rather than a bump.

New extras

semantic (Bedrock embeddings), confidence (calibration metrics), docsplit (document packet splitting), reporting (HTML report tables). all is written as a self-referential extra so it cannot drift out of sync:

all = ["stickler-eval[llm,semantic,confidence,docsplit,reporting]"]

bert is deliberately excluded from all: its ML stack (torch, transformers) is large enough that pulling it in unasked is a surprise.

Testing

tests/test_core_import_weight.py (11 tests) guards the import-weight property in a subprocess, so the already-imported state of the test session cannot mask a regression. It also pins that a lazily-exported comparator still resolves on access, and that an installed-but-broken extra does not take down import stickler.

  • 1570 passed, 2 skipped under the exact CI condition (uv sync --extra llm --extra bert + coverage)
  • 1568 passed on Python 3.10 and 3.14, both ends of the declared range
  • uv lock --check clean, ruff check src/ tests/ clean

Review status

All three items from @vawsgit's review are addressed:

  1. Blocker — the guard test failed 9/9 under the CI extras. Fixed in c94fc54 by making the optional imports genuinely lazy, rather than by weakening the test. The diagnosis was exactly right: __init__.py was importing the optional comparators eagerly and bert.py called evaluate.load() at import time. Now 11/11 pass under --extra llm --extra bert, and the four strands/boto3/torch/transformers entries in FORBIDDEN_ON_CORE_PATH hold rather than being unfixable-by-design.
  2. fail-fast: false added to the 5-version matrix, so a single red version no longer cancels the other four.
  3. [all] omitted boto3 and strands-agents. Fixed using the self-referential form above; confirmed [all] now resolves boto3==1.43.61 and strands-agents==1.50.2.

Also addressed: the < 900 bound in test_core_import_stays_small now records the measured 463-module baseline so it doesn't read as arbitrary, and the two items above (breaking change, scikit-learn floor) are called out here and in the CHANGELOG as requested.

Not addressed: splitting this into three PRs. Agreed in principle that version widening, dependency slimming, and import deferral are independently reviewable, but they're entangled here (the 3.10 floor needs the scikit-learn relaxation, which is only safe because the imports are deferred), and the branch is already reviewed. Worth doing next time rather than redoing now.

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

* Widening python tsting from 3.10-3.14
* Improving import isolation so we don't have heavy load times
* Removing depndencies from the core installation reuqirements where not required.
@sromoam
sromoam requested a review from vawsgit July 31, 2026 21:12

@vawsgit vawsgit left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What the PR does

Three changes bundled together:

  1. Widens the supported Python range from >=3.12 to >=3.10, adds trove classifiers for 3.10–3.14, and expands the CI test matrix from ["3.12"] to ["3.10" … "3.14"].
  2. Slims the core dependency set — removes scipy, psutil, pandas, scikit-learn, and jinja2 from [project.dependencies], moving them into new/existing extras (semantic, llm, confidence, docsplit, reporting, all) plus the dev/test groups.
  3. Defers the corresponding imports — module-level imports of pandas/scipy/sklearn/jinja2 become function-local (with actionable ImportError messages naming the extra) or TYPE_CHECKING-only, so import stickler no longer drags in a scientific-computing stack.

Adds tests/test_core_import_weight.py to guard the import-weight property.

The underlying goal is achieved and I verified it. On a core-only install (uv sync --frozen --no-default-groups, Python 3.12), import stickler loads 465 modules and pulls in none of pandas, scipy, sklearn, jinja2, torch, transformers, strands, or boto3 — down from 1664 modules with pandas/scipy/sklearn/jinja2 all present on dev. That is a real and substantial improvement. The extras gates also work: stickler.doc_split, SemanticComparator's cosine path, and AUROCMetric each raise an ImportError naming the right extra. The 3.10 floor is genuine — the full suite (excluding the new file) passes 1541 passed, 2 skipped on Python 3.10, and I found no 3.11+/3.12+ syntax or stdlib usage in src/.

The blocker below is confined to the new test file, not to the feature.


BLOCKER 1 — The new guard test file fails in this PR's own CI configuration (all 9 tests)

File: tests/test_core_import_weight.py (new, all tests)
Confirmed: reproduced locally on Python 3.10 and 3.14; matches the red test (3.14) check on 4c101a2.

tests/test_core_import_weight.py asserts that a subprocess import stickler does not load pandas, scipy, sklearn, jinja2, torch, transformers, strands, or boto3, and that fewer than 900 modules load. But it measures the ambient environment, not a core-only install — and CI deliberately installs extras:

# .github/workflows/run_pytest.yaml
run: uv sync --extra llm --extra bert --frozen

--extra llm installs strands-agents, whose transitive deps include boto3/botocore; --extra bert installs torch, transformers, and bert-score (which itself depends on pandas). src/stickler/__init__.py then intentionally imports the optional comparators when available:

  • from .comparators.llm import STRANDS_AVAILABLE — the try: from strands import Agent block at llm.py:36-38 succeeds, loading strands + boto3.
  • from .comparators.bert import BERTComparator — bert.py:5 does a module-level import evaluate, and line 12 calls evaluate.load("bertscore", …) at import time, loading torch, transformers, pandas, scipy, sklearn, and jinja2 (a torch dep).

So the test's premise and the CI install command directly contradict each other.

Reproduction — Python 3.14, exactly CI's extras:

$ uv sync --extra llm --extra bert --frozen --python 3.14
$ uv run --python 3.14 python -m pytest tests/test_core_import_weight.py -q
FAILED test_heavy_package_not_on_core_import_path[boto3-semantic]
FAILED test_heavy_package_not_on_core_import_path[jinja2-llm]
FAILED test_heavy_package_not_on_core_import_path[pandas-docsplit / reporting]
FAILED test_heavy_package_not_on_core_import_path[scipy-semantic / docsplit]
FAILED test_heavy_package_not_on_core_import_path[sklearn-confidence / docsplit]
FAILED test_heavy_package_not_on_core_import_path[strands-llm]
FAILED test_heavy_package_not_on_core_import_path[torch-bert]
FAILED test_heavy_package_not_on_core_import_path[transformers-bert]
FAILED test_core_import_stays_small
    AssertionError: `import stickler` now loads 4878 modules  (assert 4878 < 900)
========================= 9 failed in 83.52s =========================

Also fails on 3.10 with only --extra llm (1 of 9 — the boto3 case, via strands' transitive dep), which is what stops the full run:

$ uv sync --extra llm --frozen --python 3.10
$ uv run --python 3.10 python -m pytest -q -x
FAILED tests/test_core_import_weight.py::test_heavy_package_not_on_core_import_path[boto3-semantic]
====== 1 failed, 1517 passed, 2 skipped in 74.19s ======

This is consistent with CI on the head commit: test (3.14) = failure, and test (3.10)/(3.11)/(3.12)/(3.13) = cancelled (the matrix has no fail-fast: false, so the 3.14 failure cancels its siblings — those four are cancelled, not passing).

Note the test's own docstring states the opposite of the actual behaviour: "the suite installs every extra, so the import still succeeds here while a default install breaks for users." The test as written fails whenever an extra is installed, so it cannot run green in any environment that exercises the optional comparators — and green CI on this repo requires the bert extra by design (the workflow comment says so explicitly).

Fix — measure a core-only environment instead of the ambient one. The property under test is "a default install stays light," so the subprocess needs a core-only interpreter. Options, roughly in order of preference:

  1. Make it a static check rather than a runtime one — no environment dependence, fast, and it catches the regression the file is actually aimed at (a module-level import sneaking back in). Walk src/stickler/**/*.py with ast and assert no module-level Import/ImportFrom of a forbidden package outside a TYPE_CHECKING block or a try/except ImportError guard. This is my recommendation: it tests the invariant the PR establishes without needing a second install.

  2. Build a throwaway core-only venv in the test (session-scoped fixture) and run the probe with its interpreter:

    subprocess.run(["uv", "venv", tmp], check=True)
    subprocess.run(["uv", "pip", "install", "--python", py, "--no-deps", "-e", REPO_ROOT], check=True)
    subprocess.run(["uv", "pip", "install", "--python", py, *CORE_DEPS], check=True)

    Accurate, but slow and needs network — mark it @pytest.mark.slow (the marker already exists in pyproject.toml) and/or gate on uv being present.

  3. Add a dedicated CI job that installs core-only (uv sync --frozen --no-default-groups) and runs only this file, and mark the tests to skip elsewhere (e.g. @pytest.mark.skipif on detecting an installed extra). Keeps the runtime measurement but makes the environment explicit.

Whichever route: the strands/boto3/torch/transformers entries in FORBIDDEN_ON_CORE_PATH can only ever hold under option 2 or 3 — src/stickler/__init__.py imports the optional comparators on purpose when they are installed, so under the current ambient-measurement design those four are unfixable-by-design, not regressions.

Secondary, same file: the < 900 bound in test_core_import_stays_small is loose but was presumably calibrated against a core-only install. I measure 465 modules core-only on 3.12, so 900 leaves ~2× headroom — fine as a tripwire, but worth a comment recording the measured baseline so a future reader knows 900 isn't arbitrary.


Also worth fixing before merge (high, not blocking)

fail-fast: false is missing from the new 5-version matrix

.github/workflows/run_pytest.yaml sets no fail-fast, so it defaults to true. With a 1-version matrix that was harmless; with 5 it means the first failure cancels the other four, and you lose the signal on which versions actually broke. This is visible on the head commit right now — 3.14 failed, and 3.10/3.11/3.12/3.13 all report cancelled rather than a real result. Since the whole point of this PR is "the floor is enforced rather than asserted," the matrix should report per-version outcomes:

strategy:
  fail-fast: false
  matrix:
    python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]

[all] doesn't include the extras it claims to

pyproject.toml's all extra lists only jinja2, pandas, scipy, scikit-learn — it omits boto3 (semantic) and strands-agents (llm). So pip install "stickler-eval[all]" gives you neither SemanticComparator's Bedrock client nor LLMComparator at all. I confirmed the resolution:

$ uv pip install --dry-run ".[all]"
 + jinja2==3.1.6   + pandas==2.3.3   + scikit-learn==1.9.0   + scipy==1.18.0

No boto3, no strands. The README describes [all] as "all of the above except the ML stack" — but [llm] and [semantic] are in "the above" and are not the ML stack; only [bert] is. Either make all reference the real extras, or correct the README row. Preferred, and self-maintaining:

all = ["stickler-eval[llm,semantic,confidence,docsplit,reporting]"]

(Self-referential extras are supported by pip ≥ 21.2 and by uv.) If [bert] is deliberately excluded, keep it excluded and say so precisely — "everything except [bert]'s ML stack."


Non-blocking observations

  • The import-deferral changes themselves look correct. The TYPE_CHECKING guards (markdown_util.py, llm.py) correctly quote the annotations ("pd.DataFrame", "Template"), so they don't NameError at runtime. _cosine_distance in semantic.py keeps the SIMILARITY_FUNCTIONS lambda's signature intact. The ImportError messages all name the right extra, and I verified each gate fires on a core-only install.
  • SemanticComparator construction still succeeds on a core-only install and only raises when the cosine function is called. That's a reasonable trade (it matches the pre-existing lazy boto3 gate in comparators/utils.py), but it does mean the failure surfaces at first comparison rather than at construction. Fine as-is; noting it since it's a small behavioural shift.
  • scikit-learn floor moved down >=1.8.0 → >=1.7.2, which is what lets 3.10 resolve (the lock pins 1.7.2 for python_full_version < '3.11' and 1.8.0 above). Deliberate and correct, but it's an unannounced constraint relaxation on a shared dep — worth a line in the PR description.
  • Three concerns in one PR (version widening, dependency slimming, import deferral). Each is independently reviewable and independently revertable; splitting would make bisection easier if one causes fallout downstream. Not worth redoing now, but the PR description should at least call out that removing core dependencies is a breaking change for anyone importing stickler.doc_split, the AUROC metric, or MarkdownUtil.table_df without installing the new extra — that belongs in the 0.6.0 release notes.

Verdict

Request changes — one blocker.

The feature is sound and I verified the headline claims: core-only import stickler drops from 1664 to 465 modules with no heavy packages on the path, all extras gates raise actionable errors, and the 3.10 floor is real (1541 tests pass on 3.10). But tests/test_core_import_weight.py cannot pass in the CI configuration this PR ships — 9/9 fail under --extra llm --extra bert, which is why test (3.14) is red and the other four versions are cancelled. Fix the test to measure a core-only environment (or make it a static AST check), add fail-fast: false, and correct the [all] extra.

sromoam added 3 commits July 31, 2026 17:33
* resolving the failing tests on the CI
* adding in import error messages for uncommon uses.
* adding tests to prevent failures.
- Replace eager imports of LLMComparator and BERTComparator with PEP 562 __getattr__ lazy loading
- Add _dependency_available() helper to check for optional dependencies without importing them
- Move boto3 import into generate_bedrock_embedding() to avoid pulling it onto the import path
- Refactor ComparatorRegistry to use dynamic imports via importlib instead of try/except blocks
- Add __dir__() to support dir() introspection on the comparators module
- Improve error messages to direct users to install specific extras (llm, bert, semantic)
- Defer heavy dependencies (strands-agents, torch, transformers, boto3) until actually needed
- Maintain backward compatibility: hasattr() and imports work identically to before
sromoam added 2 commits August 7, 2026 11:21
Adds the Unreleased entries this PR was missing, including the breaking
one: pandas, scipy, scikit-learn and jinja2 are no longer core
dependencies, so the peripheral modules now require their extra. The
table names each affected entry point and the extra that restores it,
and distinguishes doc_split (fails at import) from the rest (fail at
first use).

Also records the scikit-learn floor relaxation to >=1.7.2, which is what
makes the 3.10 floor resolvable, since 1.8.0 requires 3.11+. Both were
review asks from #207 that had not made it into the PR description.

Notes the measured 463-module baseline next to the < 900 tripwire in
test_core_import_stays_small so the bound does not read as arbitrary.
@sromoam

sromoam commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

@vawsgit rebased onto current dev (now includes #183 and #159) and pushed b3531e4. Your review predates the fix for the blocker, so re-review rather than assuming the test was weakened — it wasn't.

All three items are addressed:

1. The blocker. Fixed in c94fc54, which landed after your review, by making the optional imports genuinely lazy rather than by touching the test. Your diagnosis was exactly right about the cause: __init__.py imported the optional comparators eagerly and bert.py called evaluate.load() at import time. Verified under your exact condition:

you measured now
test_core_import_weight.py with --extra llm --extra bert 9/9 failed 11/11 pass
modules on import stickler 1664 463
heavy packages on the path all 8 none

Your point that strands/boto3/torch/transformers were "unfixable-by-design" under ambient measurement was the useful part — it was true, and it meant the design was wrong, not the test. Those four now hold.

Also: your 465 and my 463 agree within noise, which is reassuring about our environments matching.

2. fail-fast: false added to the matrix.

3. [all] now uses the self-referential form you suggested. Confirmed it resolves boto3==1.43.61 and strands-agents==1.50.2, which were both absent before.

Your secondary and non-blocking asks are in too:

  • The < 900 bound now records the measured 463-module baseline in the docstring, so it doesn't read as arbitrary.
  • The breaking change is now in the PR description and the CHANGELOG under Changed, with a table naming each affected entry point and its extra. I also pinned down the exact surface, since "breaks doc_split / AUROC / table_df" was less precise than it should be: only stickler.doc_split fails at import; AUROCMetric.compute(), MarkdownUtil.table_df() and LLMComparator(...) fail at first use. MarkdownUtil.table_df is arguably unreachable on a core install anyway, since you can't construct a pd.DataFrame to pass it.
  • The scikit-learn floor relaxation (>=1.8.0 → >=1.7.2) is called out in both, with the reason: 1.8.0 requires Python 3.11+, so the old floor made the 3.10 support unresolvable.

On splitting into three PRs: you're right in principle, and I'm not going to pretend the bundle is ideal. They're entangled here — the 3.10 floor needs the scikit-learn relaxation, which is only safe because the imports are deferred — and the branch has already been through a review round. Noted for next time rather than redone now.

Verification on the rebased branch:

  • 1570 passed, 2 skipped under the exact CI condition (--extra llm --extra bert + coverage)
  • 1568 passed on 3.10 and 3.14
  • uv lock --check clean, ruff check src/ tests/ clean

One thing outside the PR: GitHub Actions has been in a major_outage since yesterday afternoon, so the checks here may sit queued for a while. That's why CI looks stalled rather than failing. Everything above is local verification against the pushed head.

Thanks for the thorough review — the blocker was a real design problem and I'd have shipped it without you catching it.

@github-actions

github-actions Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-08-07T17:38:58+00:00
  • Time since scan: 2 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-08-07T17:36:38+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 0 0 0 4334 0 0 PASSED 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 0 0 0 0 0 0 PASSED 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 0 3 0 0 0 0 3 FAILED MEDIUM (global)
syft 0 0 0 0 0 0 0 MISSING MEDIUM (global)

Top 3 Hotspots

Files with the highest number of security findings:

Finding Count File Location
1 src/stickler/init.py
1 src/stickler/comparators/init.py
1 src/stickler/structured_object_evaluator/models/comparator_registry.py

Detailed Findings

Show 3 actionable findings

Finding 1: python.lang.security.audit.non-literal-import.non-literal-import

  • Severity: HIGH
  • Scanner: semgrep
  • Rule ID: python.lang.security.audit.non-literal-import.non-literal-import
  • Location: src/stickler/init.py:112

Description:
Untrusted user input in importlib.import_module() function allows an attacker to load arbitrary code. Avoid dynamic values in importlib.import_module() or use a whitelist to prevent running untrusted code.

Code Snippet:

module = _il.import_module(module_path, __name__)

Finding 2: python.lang.security.audit.non-literal-import.non-literal-import

  • Severity: HIGH
  • Scanner: semgrep
  • Rule ID: python.lang.security.audit.non-literal-import.non-literal-import
  • Location: src/stickler/comparators/init.py:79

Description:
Untrusted user input in importlib.import_module() function allows an attacker to load arbitrary code. Avoid dynamic values in importlib.import_module() or use a whitelist to prevent running untrusted code.

Code Snippet:

module = _il.import_module(module_path)

Finding 3: python.lang.security.audit.non-literal-import.non-literal-import

  • Severity: HIGH
  • Scanner: semgrep
  • Rule ID: python.lang.security.audit.non-literal-import.non-literal-import
  • Location: src/stickler/structured_object_evaluator/models/comparator_registry.py:73

Description:
Untrusted user input in importlib.import_module() function allows an attacker to load arbitrary code. Avoid dynamic values in importlib.import_module() or use a whitelist to prevent running untrusted code.

Code Snippet:

module = importlib.import_module(module_path)

Report generated by Automated Security Helper (ASH) at 2026-08-07T17:38:59+00:00

Confidence calibration answers "does the model's self-reported
confidence track correctness," which is part of evaluating a model
rather than an optional add-on. Splitting it behind an extra made a
core capability opt-in.

Moves scikit-learn back into [project.dependencies] and empties the
confidence extra, keeping the extra name so existing pins keep
resolving. Three of the four calibration metrics (Brier, ECE, error
capture at budget) were already pure Python and worked on a core
install; only AUROC was gated, so this closes a gap that made the
feature look partly broken by default.

The sklearn import stays inside AUROCMetric.compute() rather than
moving to module scope: confidence/metrics.py IS on the `import
stickler` path, so an eager import would put ~33MB there for every
user whether or not they compute AUROC. Verified 421 modules on a core
install with sklearn still absent from the import path, so the import
weight work from #201 is preserved.

Issue #216 tracks replacing AUROC with a numpy implementation of the
Mann-Whitney form, after which scikit-learn leaves the dependency set
entirely and document-packet evaluation can move to the core with only
pandas behind an extra. Verified numerically before filing: numpy AUROC
matches sklearn to 1.1e-16 across 4420 cases including heavy ties.

@vawsgit vawsgit left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-reviewed at bc2302b. Thanks for the detailed reply — I re-verified all three items rather than taking them on trust, and they hold. Confirmations first, then what's still open.

Your three items: confirmed

Item Verified at bc2302b
Blocker — guard test fails under CI's extras Fixed. 421 modules on a core install, none of pandas / scipy / sklearn / jinja2 / torch / transformers / strands / boto3 on the path. Fixed by making the imports genuinely lazy, not by weakening the test — I checked the test still asserts what it did.
fail-fast: false Added, with a comment explaining why.
[all] Fixed via the self-referential form.

The < 900 bound now records the measured baseline in the docstring, and the breaking-change surface is in both the PR description and the CHANGELOG. Your correction to my own wording was right and worth stating: only stickler.doc_split fails at import; AUROCMetric.compute(), MarkdownUtil.table_df() and LLMComparator(...) fail at first use. My original phrasing was imprecise; yours is the accurate one.

Our 465 vs 463 vs my 421 now: the drop to 421 is real, not noise — bc2302b moved the sklearn import out of module scope.

bc2302b also makes calibration core rather than an extra, which I agree with as a product call — calibration is core functionality, not an add-on. The commit message is unusually good: it explains why the sklearn import stays function-local, cites the measured module count, and files #216 to remove the dependency via a numpy Mann-Whitney implementation. My one concern is that it takes the heavier of the two routes to get there.


1. MEDIUM — making sklearn core pulls scipy into every default install

pyproject.toml:44

scikit-learn declares scipy>=1.10.0 as a hard runtime requirement, so adding sklearn to [project.dependencies] transitively adds scipy to the core set. Measured on a fresh core-only editable install (Python 3.12):

sklearn   47M
scipy     98M
numpy     34M
site-packages total: 217M

The import path claim is true and well-guarded — 421 modules, sklearn and scipy both absent, and I confirmed AUROCMetric().compute(pairs) → {'value': 1.0} works on a core install with the import staying inside compute(). That part is solid.

The install weight claim is now overstated. The README says a default install "does not pull an ML stack" and the CHANGELOG says import stickler "no longer pulls a scientific-computing stack." The second is precisely true (it's about import); the first reads as being about install, and pip install stickler-eval now pulls the two heaviest packages the PR set out to remove. Since dependency hygiene is the PR's headline, this is the one place the new commit works against it.

Three verified consequences:

1a. SemanticComparator's scipy gate is masked, not satisfied. from scipy import spatial; spatial.distance.cosine(...) works on a bare core install today — purely because sklearn dragged scipy in. So the cosine path silently appears fixed. When #216 lands and sklearn leaves, it regresses silently, and no test covers it. This is the consequence I'd most want addressed, because it fails quietly and later.

1b. The docsplit error message is now wrong. packet_evaluation_metrics.py:41 says "requires pandas, scipy, and scikit-learn," but on a core install only pandas is actually missing:

pandas False   scipy True   sklearn True
ImportError: stickler.doc_split requires pandas, scipy, and scikit-learn.

Users are told to chase three packages when they need one.

1c. A latent floor conflict. sklearn accepts scipy>=1.10.0; [semantic] and [test] want >=1.12.0 (pyproject.toml:62,97,106,164). A core install resolves to whatever sklearn accepts, so core+manual-scipy can legally sit at 1.10/1.11 while the code assumes 1.12.

Worth reconsidering whether #216 should land before this rather than after. It's the cheaper ordering: a numpy AUROC keeps calibration core — the outcome you're arguing for, which I agree with — without putting ~145 MB of scipy+sklearn into the default install. If you'd rather keep this order, the fix is smaller: correct the README/CHANGELOG install-weight wording and add a test pinning scipy's availability for the semantic path so 1a can't regress unnoticed.

2. LOW — confidence = [] deprecation is invisible outside the CHANGELOG

pyproject.toml:102,117

Keeping the name so old pins resolve is the right instinct and it works. Two loose ends: the README row was deleted rather than marked deprecated, so nothing tells someone pinning [confidence] that it's now a no-op (an empty extra is indistinguishable from a typo at install time); and all = [...confidence...] still names it, which becomes pure cruft once #216 removes sklearn.

3. LOW — the guard test's sklearn entry contradicts itself in its own failure message

tests/test_core_import_weight.py:33

FORBIDDEN_ON_CORE_PATH maps a package to "the extra that owns it," and every other value is an extra name. The new value is "core (function-local in AUROCMetric)", which is a different kind of fact, and it interpolates into the message:

`import stickler` loaded 'sklearn', which belongs to the
core (function-local in AUROCMetric) extra. Move the import inside...

"belongs to the core ... extra" reads as a contradiction to whoever trips it. Minor, but this is the guard protecting the PR's central invariant. scipy is also still labeled "semantic / docsplit" when it's now a core transitive dep (finding 1) — correctly kept off the import path, but the label misleads.


Still open from the last round

HIGH — unguarded find_spec() raises ValueError on a mock-injected module. comparators/utils.py:7, comparator_registry.py:59. Re-verified on this head:

sys.modules['boto3'] = MagicMock(); import stickler
  -> ValueError: boto3.__spec__ is not set

stickler/__init__.py:63 already has the correct _dependency_available() helper catching (ImportError, ValueError) — these two call sites just don't use it. utils.py:7 is the worse one because it runs at module scope on the unavoidable import stickler path. Two-line fix.

HIGH — a broken extra breaks __all__-driven consumers. __init__.py:113. With an evaluate shim that raises ImportError: import stickler OK, 'BERTComparator' in __all__ True, but hasattr(...) and from stickler import * both raise ImportError. The docstring at :95 claims AttributeError keeps hasattr() False — true for the missing branch, not the broken one. The CHANGELOG makes the same claim.

HIGH — [llm] is missing boto3. pyproject.toml:88. llm.py:36 imports botocore.exceptions at module scope inside the block setting STRANDS_AVAILABLE. Works today only because strands-agents pulls boto3 transitively — a transitive dep you don't control.

MEDIUM — doc_split unavailability is package-wide. doc_split/__init__.py:17 eagerly imports both submodules, so the pandas-free DocSplitClassificationMetrics is collateral damage: importing it on a core install raises the [docsplit] ImportError from the sibling module. (See 1b — that message is also now inaccurate.)

MEDIUM — registry availability is inconsistent and self-mutating. comparator_registry.py:68. _resolve pops from _pending before it can fail:

is_registered('BERTComparator')                -> True
get('BERTComparator')                          -> KeyError
is_registered('BERTComparator')  (same object) -> False   # mutated by the failed get

tests/auto/test_risk_surface.py:374 relies on the invariant this breaks.

LOW, but highest leverage — no core-only CI leg. .github/workflows/run_pytest.yaml:26 still runs uv sync --extra llm --extra bert --frozen, so every raise ImportError("...install stickler-eval[X]") branch is dead in CI. The source concedes it with five # pragma: no cover - exercised by the extras gate comments naming a gate that doesn't exist. Findings 1a, 1b, the broken-extra case, and the doc_split case were all found by hand-building a core-only venv — one extra matrix leg catches all four automatically. This is the single change I'd prioritize.

Smaller items: psutil is in neither [all] nor any feature extra, yet the stress tests import it (pyproject.toml:57,157); [project.optional-dependencies].dev and [dependency-groups].test still hand-restate jinja2/pandas/scipy/scikit-learn in four places a bound can drift, now five with the core sklearn pin — the "keep in sync" comment at :143 is doing load-bearing work a tool should do. tests/common/comparators/ still aborts at collection on a core install (ModuleNotFoundError: jinja2), taking 275 tests with it. ruff format --check src/stickler/__init__.py src/stickler/comparators/__init__.py → 2 files would be reformatted (ruff check passes; the lint workflow is continue-on-error: true).

The scikit-learn floor relaxation is now explained by a comment at pyproject.toml:43 — that one's resolved.

One note on the CHANGELOG: it says "BERTComparator no longer loads its model at import time," but bert.py:12 still calls evaluate.load("bertscore", ...) at module scope. The claim holds in practice because __init__.py no longer imports the module eagerly — the model loads on first access of the comparator, not on import stickler. Accurate outcome, slightly misleading wording.


Verification

  • Full suite at bc2302b: 1570 passed, 2 skipped (Python 3.12, all extras).
  • Core-only editable install: 421 modules, no heavy packages on the path, AUROCMetric works.
  • uv.lock correctly moves sklearn from the confidence optional block into base dependencies with the python_full_version fork (1.7.2 for <3.11, 1.8.0 for >=3.11).
  • Only two modules remain unimportable on a core install: stickler.comparators.bert (expected) and stickler.doc_split (finding above).

Verdict

The blocker is genuinely fixed and the three follow-ups are done. The remaining items are all small and local — reuse the existing _dependency_available() helper at two call sites, raise AttributeError in the broken-extra branch, add boto3 to [llm], don't pop before you can fail. None of them is a reason to hold the PR if you'd rather land it and follow up, with one exception I'd flag: 1a will regress silently when #216 removes sklearn, so it wants either a test or the #216-first ordering. The core-only CI leg is what stops this class of issue recurring.

LGTM!

@sromoam
sromoam merged commit a29354e into dev Aug 10, 2026
18 checks passed
@sromoam
sromoam deleted the sr/201 branch August 10, 2026 16:20
sromoam added a commit that referenced this pull request Aug 10, 2026
Resolves the CHANGELOG collision with #207, which added Added/Changed
entries under Unreleased where this branch added Fixed. Kept both, in
Keep a Changelog section order.
sromoam added a commit that referenced this pull request Aug 25, 2026
* Update: add 4 file(s), modify 4 file(s)

* Update: modify 1 file(s)

* reverted .gitignore changes

* Update: modify 4 file(s)

* Update: modify 1 file(s)

* Update: modify 3 file(s)

* Update: modify 6 file(s)

* Update: modify 3 file(s)

* Fixing the issues refernced in Issue #33
https://github.com/awslabs/stickler/issues/33

* Resolving Additya's feedback.

* docs: restructure documentation with new sections and navigation (#86)

* docs: restructure documentation with new sections and navigation

* docs: add dark/light mode theme toggle and site URL config

* docs: update code examples and installation requirements

* docs: update deployment section to reflect implemented workflow

* docs: add comparison engine architecture guide for contributors

* docs: restructure documentation with consolidated navigation

* docs: address PR review feedback — add KIE framing, architecture diagrams, sample outputs, SME calibration guide, and namespaced extras

* Adding in the docsplit metrics. (#82)

* Adding in the docsplit metrics.
* Impementing 1:1 metrics porting
* Added a namespace for Stickler docsplit metrics
* Added tests.

* ruff linting

* Updating the packet split metrics to include the new metrics in addition to classical
* Updating the mkdocs UI
* Adding tests
* Adding docs.
* Updating with the new evaluation tooling

Changes were made to the tooling to support JSON based invocation.

* Adding an example for docsplit.

* resolving the remaining comments
* Fixing the docs for the page number clarity.
* Removing the extra init file.
* Adding a case to cover empty data frame.

* Removing an empty readme.
Adding init py file to a test directory.

* chore: bump version to 0.2.0 for release

* Sr/fix 17 (#84)

* Fixing the issues refernced in Issue #33
https://github.com/awslabs/stickler/issues/33

* This PR includes tests that cover the complaint in #17

* This PR adds testing to prove that we aren't suffering the error pointed out in Issue #17.
https://github.com/awslabs/stickler/issues/17

* reverting the unneeded file change from dev.

* Fixing the ruff linting issues in this PR.

* fix: update packet evaluation metric (#95)

* fix: update packet evaluation metric

* test: update single-page group ordering test to match new behavior

* test: add test_single_page_groups_score_perfect per reviewer feedback

---------

Co-authored-by: Sirajus Salekin <salekin@amazon.com>

* chore: migrate conda to uv (#97)

* chore: migrate from conda to uv for environment and dependency management

* docs: update commands to uv run with pip+venv fallback notes and sync pyproject.toml dev extras

* docs: add uv pip install alternative to installation guide

* fix: address PR review feedback for lint parity, docs accuracy, and notebook format

* fix: include static assets (CSS, JS) in package distribution (#91)

The HTML report styling and interactive JS files were not included
in the built wheel because setuptools only packages .py files by
default. This resulted in unstyled HTML reports when installed from
PyPI.

* fix: remove unused inspect import in structured_model.py (#100)

* fix: resolve PyPI release issues (missing __init__.py, dependency bounds, metadata) (#101)

* fix: resolve PyPI release issues (missing __init__.py, dependency bounds, metadata)

* fix: correct dependency lower bounds for Python 3.12 compatibility

* fix: add dependency upper bounds and ignore dist/ for PyPI release readiness

* chore: bump version to 0.2.1 for release

* fix: bump pillow, cryptography, and pytest to resolve dependabot alerts

* Bump python-multipart in the uv group across 1 directory

Bumps the uv group with 1 update in the / directory: [python-multipart](https://github.com/Kludex/python-multipart).


Updates `python-multipart` from 0.0.22 to 0.0.26
- [Release notes](https://github.com/Kludex/python-multipart/releases)
- [Changelog](https://github.com/Kludex/python-multipart/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Kludex/python-multipart/compare/0.0.22...0.0.26)

---
updated-dependencies:
- dependency-name: python-multipart
  dependency-version: 0.0.26
  dependency-type: indirect
  dependency-group: uv
...

Signed-off-by: dependabot[bot] <support@github.com>

* fix: restore dropped notebook cell from merge conflict resolution

* fix: remove duplicate docs targets from merge conflict resolution

* fix: resolve PR #102 review feedback — round-trip fidelity, doc corrections, version bump to 0.3.0

* fix: repair broken notebooks — kernel specs and evaluator_format crash

* fix: keep semantic model_id as string (#116)

* chore(deps): bump python-multipart in the uv group across 1 directory (#126)

Bumps the uv group with 1 update in the / directory: [python-multipart](https://github.com/Kludex/python-multipart).


Updates `python-multipart` from 0.0.26 to 0.0.27
- [Release notes](https://github.com/Kludex/python-multipart/releases)
- [Changelog](https://github.com/Kludex/python-multipart/blob/main/CHANGELOG.md)
- [Commits](https://github.com/Kludex/python-multipart/compare/0.0.26...0.0.27)

---
updated-dependencies:
- dependency-name: python-multipart
  dependency-version: 0.0.27
  dependency-type: indirect
  dependency-group: uv
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump urllib3 in the uv group across 1 directory (#128)

Bumps the uv group with 1 update in the / directory: [urllib3](https://github.com/urllib3/urllib3).


Updates `urllib3` from 2.6.3 to 2.7.0
- [Release notes](https://github.com/urllib3/urllib3/releases)
- [Changelog](https://github.com/urllib3/urllib3/blob/main/CHANGES.rst)
- [Commits](https://github.com/urllib3/urllib3/compare/2.6.3...2.7.0)

---
updated-dependencies:
- dependency-name: urllib3
  dependency-version: 2.7.0
  dependency-type: indirect
  dependency-group: uv
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* fix: expose weight-aware aggregate in BulkStructuredModelEvaluator (#122)

* fix: prevent defaultdict mutation and cover list-of-models in weighted score aggregation

* refactor: simplify weighted score accumulators and drop dead defensive branch

* chore: address copilot review comments on PR #124

* fix: distinguish unscored paths from zero-scored paths in bulk field_metrics

* test: cover reset, mid-stream polling, batch, aggregate helper, and disjoint-merge for weighted score

* refactor: drop redundant verbose guards and tighten comments

* docs: propagate weighted_overall_score and mean_score across docsite

* fix: support JSON Schema list-form nullable types

* Confidence Evaluation tooling  (#98)

* This branch has capabilities to enable bulk estimation of confidence quality.
* Breakout of metrics, ECE, AUROC, Brier Score.
* Enhancement of the 'rich field' to be tested, and support extension.
* Documentation of the confidence estimation capabilities.
* Notebooks demonstrating single and multi-doc confidence estimation.

* Adding in notebooks, and changes to the bulk structured model eval.

* updating to add ECARB. Error capture at review budget.
Metric to compute gain from reviewing documents.
testing and notebooks to show using these metrics.

* Updating the docs to add the confidence estimation tools to the main guides page.

* Fixing copilot flagged issues.
* Adding todo about the rich value 'value' key bing potentially an issue.
* Fixing edge cases on several modules.
* resolving incorrect coverage accounting.

* whoops, missed files in the commit.

* Fixing many of the nits on the PR.

* Big refactor.
* Creating mechanism for bulk evlaaution against JSON's from individual comparison 'map-reduce pattern'
* creating helpers for these additional evlauations to fit into the bulk evaluator.
* Adding testing.

* feat: add pluggable confidence metrics framework and rich value pattern

- Add pluggable confidence metrics framework (AUROC, Brier Score, ECE, Error Capture at Review Budget) under `stickler.structured_object_evaluator.models.confidence`
- Rename Rich Value Pattern convention keys from `{"value", "confidence"}` to `{"_value", "_confidence"}` to prevent collision with user data fields
- Update `StructuredModel.from_json(process_confidence=...)` to `from_json(process_rich_values=...)` to reflect broader scope
- Rename single-doc confidence result key from `auroc_confidence_metric` to nested `confidence_metrics` dict with `overall`, `fields`, and `coverage` keys
- Add `BulkStructuredModelEvaluator` confidence metrics accumulation across documents in aggregated results
- Add `StructuredModel.compare_with(..., add_confidence_metrics=True)` to include structured confidence block in single-doc results
- Introduce `PostComparisonAccumulator` interface for pluggable accumulators (e.g. bbox mAP) in bulk pipeline
- Add `prediction_raw` round-tripping through comparison results for lossless map/reduce aggregation from JSONL corpora
- Fix `ConfidencePair` validation to ensure `confidence` and `similarity` are finite floats in `[0.0, 1.0]`
- Fix `ErrorCaptureAtBudgetMetric` to report gain against actual reviewed fraction rather than requested budget
- Fix `ConfidenceCalculator.extract` to skip field comparison rows with `actual_key=None` to prevent coverage bias
- Fix `StructuredModel` to always capture `_raw_json` when `process_rich_values=True` for map/reduce aggregation
- Include deprecation shims for one release to support old `{"value", "confidence"}` format and legacy API calls
- Add CHANGELOG.md documenting all changes, deprecations, and migration guide
- Update documentation and notebooks to reflect Rich Value Pattern rename and new confidence metrics API

* fix: address PR #98 review comments for confidence evaluation

* docs: clarify update_from_comparison_result error and jsonl ordering

* chore: refresh uv.lock after dev merge

* fix: address PR #98 review (drop changelog, document accumulators, add bbox jsonl tests, guard duplicate accumulator names)

* fix: tighten legacy rich-value detector and address PR #98 review followups

* refactor: simplify confidence pipeline and close out PR #98 pre-merge gaps

* chore: pin deprecation removal to 0.5.0 (0.4.0 introduces shims)

* fix: log handle close failures in BulkStructuredModelEvaluator.close()/__del__

---------

Co-authored-by: Aditya Addepalli <adiadd@amazon.com>

* chore(deps-dev): bump pymdown-extensions (#129)

Bumps the uv group with 1 update in the / directory: [pymdown-extensions](https://github.com/facelessuser/pymdown-extensions).


Updates `pymdown-extensions` from 10.21.2 to 10.21.3
- [Release notes](https://github.com/facelessuser/pymdown-extensions/releases)
- [Commits](https://github.com/facelessuser/pymdown-extensions/compare/10.21.2...10.21.3)

---
updated-dependencies:
- dependency-name: pymdown-extensions
  dependency-version: 10.21.3
  dependency-type: direct:development
  dependency-group: uv
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore: bump version to 0.4.0 for release

* chore(deps): bump idna in the uv group across 1 directory (#130)

Bumps the uv group with 1 update in the / directory: [idna](https://github.com/kjd/idna).


Updates `idna` from 3.11 to 3.15
- [Release notes](https://github.com/kjd/idna/releases)
- [Changelog](https://github.com/kjd/idna/blob/master/HISTORY.md)
- [Commits](https://github.com/kjd/idna/compare/v3.11...v3.15)

---
updated-dependencies:
- dependency-name: idna
  dependency-version: '3.15'
  dependency-type: indirect
  dependency-group: uv
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* docs: fix v0.4.0 release doc bugs flagged on PR #131 (#132)

- rich-value-pattern.md: legacy shape removal is 0.5.0, not 0.4.0
  (matches rich_value_helper.py docstring and the 0.4.0 deprecation
  shim — 0.4.0 introduces the shim, 0.5.0 removes it)
- confidence-evaluation.md, confidence-metrics.md: cast budget to float
  before formatting with :.0%. ECARB budget keys are strings ("0.10")
  for JSON round-trip, so the previous snippet would TypeError when
  copied verbatim.

* feat: add BERTComparator example script (#111) (#120)

Co-authored-by: Heinrich Kreuser <heikreus@amazon.com>

* ci: split security scan PR comment into workflow_run trigger for fork PR support (#125)

PR comments from fork-triggered pull_request runs were failing with 403
because GITHUB_TOKEN is read-only for fork PRs. Move the comment step to
a separate workflow_run workflow that executes in the base repo context
with write permissions, and upsert the comment to avoid duplicates.

* fix: use innerHTML instead of textContent in createElement helper (#92)

* fix: use innerHTML instead of textContent in createElement helper

The createElement helper named its third parameter 'innerHTML' but
assigned it via textContent, causing HTML strings (filter controls,
table rows, PDF navigation) to render as escaped text instead of
being interpreted as HTML.

* refactor: hoist escapeHtml helper to module scope

Move escapeHtml from inside updateDocumentFiles to module scope
next to createElement, making it accessible to all functions.

* fix: escape interpolated data in innerHTML to prevent XSS

Wrap user-controlled values with escapeHtml in updateNonMatchesTable
and loadPDF to prevent cross-site scripting via doc_id, field_path,
and other interpolated fields.

* fix: build PDF nav via DOM + addEventListener and unescape .id assignments

Co-authored-by: Simone Gaiarin <simgunz@gmail.com>

---------

Co-authored-by: Aditya Addepalli <adiadd@amazon.com>

* test: implement 8 LLMComparator placeholder unit tests (#114)

* test: implement 8 LLMComparator unit tests

Remove @pytest.mark.skip decorators and rewrite the 8 placeholder test
bodies to target the current strands-agents-based LLMComparator API.

The stubs were written against an older BedrockRuntime/invoke_model
pattern. The comparator now uses an eagerly-initialized strands Agent,
accepts `model` + `eval_guidelines` (not `model_name`/`temperature`/
`client`/`prompt_template`), and HTML-escapes values before rendering
the Jinja2 prompt template.

Each of the 8 tests covers a distinct scenario not already exercised
by the existing implemented tests:
- test_init: attribute shape at construction time
- test_init_with_client: init with a Model object (not a string ID)
- test_client_initialization: Agent eagerly initialized with correct kwargs
- test_compare_values_equal: "true" response yields 1.0; values in prompt
- test_compare_values_not_equal: "false" response yields 0.0; values in prompt
- test_compare_with_special_values: HTML-special chars in values are escaped
- test_compare_with_custom_prompt: eval_guidelines escaped + in <guidelines>
- test_compare_exception_handling: exceptions propagate; comparator recovers

Also removes the now-unused `import json` to keep the module clean.

Closes #109

* test: address PR #114 review — dedupe and tighten LLMComparator tests

Apply option 1 from the review thread: keep the rewritten stub tests,
drop pre-existing duplicates, and tighten assertions per the inline
comments.

- pin test_init to _default_system_prompt() and the parsing invariant
- rename test_init_with_client → test_init_with_model_instance
- scope test_compare_with_special_values negative to Value 1/2 lines
- rename test_compare_with_custom_prompt → test_compare_escapes_eval_guidelines
  with a regex pinning the escaped value inside <guidelines>...</guidelines>
- swap RuntimeError for the module's NoCredentialsError so we hit the
  dedicated except branch; recovery now uses 'true' → 1.0
- delete duplicates: test_no_match, test_case_variations,
  test_default_initialization, test_agent_initialization,
  test_prompt_template_with_guidelines, test_agent_exception_handling,
  test_error_recovery_after_exception, test_no_credentials_error_handling
- add fixture comment about the shared mock_agent reference
- fix typo in module docstring

Co-authored-by: Yarizakura <126939795+CrepuscularIRIS@users.noreply.github.com>

* test: parametrize true/false response tests across case and whitespace

---------

Co-authored-by: Aditya Addepalli <adiadd@amazon.com>

* docs: update structuredmodel refactoring documentation

* docs: update structuredmodel architecture documentation

* fix: preserve nullability for array elements typed as object

* test: add outer-level nullable object and array coverage

Signed-off-by: Sai Asish Y <say.apm35@gmail.com>

* test: add reversed-order and stricter match for nullable rejection

Signed-off-by: Sai Asish Y <say.apm35@gmail.com>

* 🙈 chore: ignore .claude and working directories (#147)

* chore(deps): bump aiohttp in the uv group across 1 directory (#145)

---
updated-dependencies:
- dependency-name: aiohttp
  dependency-version: 3.14.0
  dependency-type: indirect
  dependency-group: uv
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump starlette in the uv group across 1 directory (#148)

Bumps the uv group with 1 update in the / directory: [starlette](https://github.com/Kludex/starlette).


Updates `starlette` from 1.0.0 to 1.0.1
- [Release notes](https://github.com/Kludex/starlette/releases)
- [Changelog](https://github.com/Kludex/starlette/blob/main/docs/release-notes.md)
- [Commits](https://github.com/Kludex/starlette/compare/1.0.0...1.0.1)

---
updated-dependencies:
- dependency-name: starlette
  dependency-version: 1.0.1
  dependency-type: indirect
  dependency-group: uv
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* fix: guard None elements in nullable object list comparison

Signed-off-by: Sai Asish Y <say.apm35@gmail.com>

* fix: log semantic embedding fallback failures (#119)

* fix: log semantic embedding fallback failures

* fix: include semantic fallback log context

* feat: export comparators from top-level stickler package (#110) (#121)

* feat: export comparators from top-level stickler package (#110)

* fix: broaden BERT gate to ImportError, finish import sweep, harden export tests

---------

Co-authored-by: Heinrich Kreuser <heikreus@amazon.com>
Co-authored-by: Aditya Addepalli <adiadd@amazon.com>

* chore(deps): bump the uv group across 1 directory with 2 updates (#153)

Bumps the uv group with 2 updates in the / directory: [torch](https://github.com/pytorch/pytorch) and [pyjwt](https://github.com/jpadilla/pyjwt).


Updates `torch` from 2.11.0 to 2.12.0
- [Release notes](https://github.com/pytorch/pytorch/releases)
- [Changelog](https://github.com/pytorch/pytorch/blob/main/RELEASE.md)
- [Commits](https://github.com/pytorch/pytorch/compare/v2.11.0...v2.12.0)

Updates `pyjwt` from 2.12.1 to 2.13.0
- [Release notes](https://github.com/jpadilla/pyjwt/releases)
- [Changelog](https://github.com/jpadilla/pyjwt/blob/master/CHANGELOG.rst)
- [Commits](https://github.com/jpadilla/pyjwt/compare/2.12.1...2.13.0)

---
updated-dependencies:
- dependency-name: torch
  dependency-version: 2.12.0
  dependency-type: direct:production
  dependency-group: uv
- dependency-name: pyjwt
  dependency-version: 2.13.0
  dependency-type: indirect
  dependency-group: uv
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Date Comparator (#141)

* feat(comparators): add DateComparator with comprehensive date matching

- Add DateComparator implementation with semantic date parsing and
  comparison
- Support configurable matching tiers: surface-form normalization,
  partial dates, date ranges
- Add date_requirements.md specification document detailing all matching
  behaviors and edge cases
- Implement configurable options: allow_partial_year,
  partial_match_score, range_match_score, range_endpoints_score,
  two_digit_year_pivot, dayfirst, case_insensitive_textual,
  strip_weekday_prefix, warn_on_corrupted_input
- Wire DateComparator into ComparatorRegistry and comparators package
  exports
- Declare python-dateutil as a direct dependency
- Add comprehensive test coverage (143 tests) for date parsing,
  normalization, range matching, and edge cases
- Add example script demonstrating DateComparator usage patterns
- Update comparators documentation and navigation to include
  date-comparator guide
- Handle year hallucination, zero-padding, separator normalization,
  locale-aware parsing, and data quality warnings
- Grounded in empirical analysis of 6,630 real date-field failures from
  document extraction evaluation

* docs(comparators): add Date_Comparator_Demo notebook

Walks through DateComparator section-by-section: surface-form
normalization, partial-year handling, range scoring under all four
range_mode policies, two-digit-year resolution, dayfirst locale, edge
cases, and a StructuredModel example with three date fields each tuned
for its own situation. Includes a configuration cheat-sheet and a brief
note on the empirical grounding (6,630 real failures).

Notebook executes end-to-end against the implementation. Each numeric
claim in the prose was verified against the actual cell output (Jaccard
math uses textual months for unambiguous parsing, two-digit-year row
choices avoid the 50-year sliding-window boundary).

* test(date): lock in JSON-schema config flow for IDP integration

DateComparator was already JSON-configurable through both
StructuredModel.model_from_json (the dict flow) and
StructuredModel.from_json_schema (the x-aws-stickler-* extension flow
used by the IDP accelerator), but neither path had test coverage.

Adds 35 tests covering:
- ComparatorRegistry registration and create_comparator() factory
- DateComparator's `config` property round-trip (timedelta -> int days,
  whole vs sub-day, JSON-serializable, omits zero-tolerance)
- model_from_json() propagating every comparator_config option
- from_json_schema() propagating x-aws-stickler-comparator-config across
  every option (tolerance, dayfirst, allow_partial_year, range_mode)
- Realistic IDP invoice scenario end-to-end via both entry points
- Error pathway: invalid range_mode / dayfirst surface with field
  attribution at schema-load time

Also adds Section 8b to the Date_Comparator_Demo notebook showing the
schema-driven flow alongside the Python-class flow, and drops the
extraneous date_requirements.md design doc.

* feat(comparators): add precision_mode parameter to DateComparator

- Add `precision_mode` parameter to control how month/day resolution mismatches are scored (`Jan 2024` vs `Jan 1, 2024`)
- Implement three precision modes: `"exact"` (default, strict), `"gt_loose"` (partial credit), and `"overlap"` (range-based scoring)
- Update DateComparator documentation with new parameter, behavior matrix, and configuration examples
- Add comprehensive test coverage for precision_mode across all three modes and edge cases
- Update API reference and configuration guide to reflect new parameter
- Document two-digit year handling using python-dateutil's sliding 50-year window
- Clarify relationship between comparator threshold and ComparableField threshold in documentation
- Update dependencies in pyproject.toml and uv.lock
- Add precision_mode support to JSON schema configuration round-trip serialization

* fix(date): gate range-vs-single by precision_mode; fix doc row and lint

---------

Co-authored-by: Aditya Addepalli <adiadd@amazon.com>

* fix: prevent script injection in security workflow PR number step (#154)

* feat: mAP scoring for bounding box evaluation (#89) (#151)

* feat: add BBoxIoUComparator for bounding box similarity via IoU

Computes Intersection over Union between two bounding boxes as a
similarity score. Supports two-point ([[x1,y1],[x2,y2]]) and flat
([x1,y1,x2,y2]) formats with coordinate normalization. Registered in
the comparator registry and exported from stickler.comparators.

* feat: add MAPCalculator and BBoxMAPAccumulator for mAP scoring

Adds mean Average Precision scoring for bounding box localization,
built on the rich-value (_bbox) pattern and the PostComparisonAccumulator
interface.

- MAPCalculator: extract_from_dicts() joins field_comparisons with gt/pred
  bounding boxes into keyed pairs; compute_metrics() produces per-field
  IoU/precision/recall/F1/AP plus overall mean AP and coverage. Mirrors
  ConfidenceCalculator's calculator/accumulator split.
- BBoxMAPAccumulator: PostComparisonAccumulator implementation
  (name 'bbox_map_metrics') for bulk evaluation, with get/load/merge_state
  for checkpointing and distributed runs.
- comparison_engine: pre-extracts ground_truth_bboxes and prediction_bboxes
  into the result (mirrors prediction_confidences) so the accumulator can
  join both sides without the model instances; adds a single-document
  add_bbox_metrics sanity-check path.
- structured_model: forwards add_bbox_metrics and bbox_iou_threshold.

* test: add comprehensive tests for bbox mAP scoring

43 tests covering BBoxIoUComparator IoU math and edge cases,
MAPCalculator extraction/metrics/coverage, BBoxMAPAccumulator
accumulation and state round-trip/merge, bulk evaluator integration
(including coexistence with ConfidenceAccumulator), and the
single-document add_bbox_metrics path.

* docs: add bounding box mAP metrics documentation

Adds the Advanced/bbox-map-metrics.md page (accumulator-first usage with
the _bbox rich-value key, plus single-document sanity-check path), wires
it into the Advanced nav, and documents BBoxIoUComparator in the
Comparators guide.

* fix: guard non-finite bbox coords and drop dead margin_percent param

- Reject NaN/inf coordinates in _normalize_bbox (return None -> scores as a
  miss) so they no longer return nan from compare() and leak into JSON output.
- Remove the margin_percent parameter, its config serialization, and the
  docstring describing a snap correction that was never implemented; update the
  comparators guide that told users to configure a no-op.
- Document the zero-area-box (point annotation) IoU=0.0 behavior.

Addresses review: bbox.py:49, bbox.py:109.

* fix: correct GT/pred bbox join and compute real Average Precision

Blocking review fixes (map_calculator.py:166, :221).

GT/pred join (B1):
- Look up ground-truth boxes by the GT-side expected_key and prediction boxes
  by the prediction-side actual_key, which diverge once Hungarian matching
  reorders list items. The previous code joined both by actual_key, so
  reordered-but-correct list items scored mean_ap=0.0.
- FN rows (actual_key None, often reported at the object level) now record a
  localization miss for every GT bbox at or under the expected_key prefix, so
  missed ground-truth boxes deflate recall instead of being dropped.
- Group observations by a list-index-normalized class key
  (LineItems[2].StartDate -> LineItems[].StartDate) so AP is per field-type.

Real AP (B2):
- Replace ap = precision * recall with true Average Precision: rank a field's
  predicted boxes by _confidence, label TP/FP at the IoU threshold, and
  integrate the precision-recall curve (Pascal VOC 2010+ all-points). mean_ap
  macro-averages per-field AP over fields with at least one GT box.
- BBoxObservation now carries has_gt/has_pred/iou/confidence; accumulator state
  and the prediction-confidence join updated accordingly.
- Drop the useless prediction_raw fallback (GT boxes are unrecoverable from it)
  and the dead KeyedBBoxPairsState alias.

Addresses review: bbox_map_accumulator.py:78, :137.

* fix: harden add_bbox_metrics edge cases in compare_with

- Warn when add_bbox_metrics is combined with evaluator_format=True, which
  rebuilds the result from a fixed key set and silently drops bbox_metrics.
- Guard an empty field_comparisons list (e.g. a model whose only list field is
  empty on both sides) and return a coverage-only result instead of letting
  MAPCalculator.extract raise ValueError.
- Collapse the two in-function MAPCalculator imports into one module-level
  import (no circular-import risk).

Addresses review: comparison_engine.py:394, :419, :431.

* test: cover real AP, list-field join, FN misses, and edge cases

- Confidence-ranking AP tests (asymmetric fixtures distinguishing orderings).
- Reordered list-item test proving mean_ap=1.0 (the join-correctness regression)
  and a missing-item test proving the recall miss is recorded.
- NaN/inf coordinate, evaluator_format warning, empty-list coverage-only, and
  JSONL update_from_comparison_result round-trip parity.
- Strengthen state round-trip to assert known values; class_key normalization.
- Drop the margin_percent config assertions.

* docs: document real AP, dual FP+FN counting, and macro-averaging

- Describe Average Precision as the confidence-ranked PR-curve area (VOC
  2010+), the _confidence requirement, and the no-confidence fallback.
- State that a below-threshold detection counts as both a false positive and a
  false negative (the example numbers depend on it).
- Document the macro-average-over-classes denominator, list-index normalization,
  and how mean_ap differs from coverage.
- Update the result-structure example to the new per-field keys; drop the
  margin_percent row from the comparators guide.

Addresses review: bbox-map-metrics.md:188, map_calculator.py:261.

* docs: note bool coordinate acceptance in BBoxIoUComparator

bool is an int subclass, so True/False pass coordinate validation as 1/0.
Document it for users working with point annotations.

Addresses review nit: bbox.py.

* refactor: move bbox mAP modules into models/bbox subpackage

Mirror the sibling models/confidence package layout:
- map_calculator.py -> bbox/calculator.py
- bbox_map_accumulator.py -> bbox/accumulator.py
- add bbox/__init__.py re-exporting the public API (MAPCalculator,
  BBoxMAPAccumulator, BBoxObservation, etc.)
- add bbox/README.md and the previously-missing models/README.md per AGENTS.md.

Imports updated in comparison_engine.py and the tests. No behavior change.

Addresses review nit (models/bbox subpackage + README).

* test: add multi-detection AP curve tests with hand-derived VOC values

Strengthen Average Precision coverage beyond the 2-detection cases:
- FP,TP,TP (num_gt=2): asserts AP=2/3 and that it exceeds the
  non-interpolated value (~0.583), proving the VOC precision envelope is
  applied rather than a plain step sum.
- TP,FP,TP,FP,TP (num_gt=3): a richer alternating curve hand-derived to
  34/45, exercising the curve integration across multiple recall steps.

Note: not cross-checked against sklearn.average_precision_score on purpose
- that computes a non-interpolated AP and differs from VOC 2010+ all-points
(0.583 vs 0.667 on the first case).

* feat: COCO-style multi-threshold mAP with 101-point interpolation

Align AP computation with the pycocotools / torchmetrics standard:

- 101-point interpolation: apply the precision envelope ('remove zig-zags')
  then average precision sampled at 101 fixed recall points, instead of the
  previous exact-area integration. Matches torchmetrics on the envelope (and
  so deliberately differs from sklearn's non-interpolated AP).
- IoU-threshold range: AP is computed per (field-type class, IoU threshold)
  and mean_ap now averages over a configurable range, defaulting to the COCO
  set [0.50, 0.55, ..., 0.95]. Adds map_50 / map_75 and iou_thresholds to the
  result; per-field entries gain ap_50 / ap_75 (ap is the over-range mean).
- MAPCalculator/BBoxMAPAccumulator take iou_thresholds (float or iterable);
  compare_with takes bbox_iou_thresholds. Raw iou+confidence are already stored
  per observation, so re-thresholding needs no data-model change.

Note: the 'mean' in mAP is the average over classes (field-types), which we
already did; this adds the separate COCO averaging over the IoU range.

* test: cover COCO 101-point AP and multi-threshold mAP

- AP unit tests updated to the (confidence, iou) + threshold signature and
  COCO 101-point values (Case A 2/3 unchanged; Case B 0.7564; ranking
  51/101 vs 25.5/101); envelope assertion (> sklearn-style 0.583) retained.
- New multi-threshold test: a detection with IoU 0.7 is TP at 5/10 COCO
  thresholds -> mean_ap 0.5, map_50 1.0, map_75 0.0.
- New single-threshold test: map_75 is None when 0.75 isn't configured.
- Missing-item list test updated to the 101-point value (51/101).

* docs: describe COCO 101-point AP and IoU-threshold-range mAP

Update the mAP docs and bbox package README: AP now matches pycocotools /
torchmetrics (precision envelope + 101-point sampling), mean_ap averages over
the COCO IoU range with map_50 / map_75, and the result-structure example and
iou_thresholds usage reflect the new API.

* docs: note metric scope (COCO AP definition, not many-to-many detection)

Clarify that the metric matches COCO's AP definition (envelope + 101-point +
IoU range) but is not a full object-detection evaluator: each document field
carries one GT and one predicted box, paired by field path, with no
many-to-many box assignment per image.

* docs: showcase bbox mAP across the docsite (v2 review)

Address the v2 review's docs requests so the new functionality is visible:

- API-Reference/comparators.md: add the missing BBoxIoUComparator block.
- Guides/Evaluation/README.md: document add_bbox_metrics / bbox_iou_thresholds
  in the compare_with parameter table, and add an 'Evaluating bounding boxes?'
  tip callout mirroring the confidence one.
- Advanced/rich-value-pattern.md: flip bbox from 'future' to supported, drop the
  get_field_bbox() promise (the calculator reads boxes from get_all_extras()),
  and add a See Also link.
- Advanced/README.md: add the bbox-map-metrics.md entry to Contents.
- index.md: mention bounding-box (IoU) in the comparators card.

Also annotate bbox_iou_thresholds / iou_thresholds params (Union[float,
Iterable[float]]) so they render in the API docs, and add a comment noting the
unconditional bbox pre-extraction is deliberate (the bulk accumulator path
reads the stashed maps without setting add_bbox_metrics).

* style: ruff format two dict comprehensions in bbox calculator

* docs: list BBoxIoUComparator in remaining comparator catalogs

Second pass for bbox coverage beyond the docs site:

- Top-level README.md: add BBoxIoUComparator to the 'Available Comparators'
  table (it's registered and usable by string name) and mention IoU matching in
  the comparator overview sentence.
- src/stickler/comparators/Comparators.md: add a Spatial Comparators section for
  BBoxIoUComparator and list it under Best Practices.
- Getting-Started overview: include bounding-box IoU in the comparator list.

* fix: keep bbox coverage ratio consistent for object-level FN rows

---------

Co-authored-by: Divya Bhargavi <dbharga@amazon.com>
Co-authored-by: Aditya Addepalli <adiadd@amazon.com>

* chore: bump version to 0.5.0 for release

* fix: resolve ASH security findings (top-level workflow permissions, bandit exec suppression) (#156)

* fix: register BERTComparator under correct name in comparator registry (#157)

* chore(deps): bump the uv group across 1 directory with 7 updates (#167)

---
updated-dependencies:
- dependency-name: torch
  dependency-version: 2.12.1
  dependency-type: direct:production
  dependency-group: uv
- dependency-name: aiohttp
  dependency-version: 3.14.1
  dependency-type: indirect
  dependency-group: uv
- dependency-name: cryptography
  dependency-version: 48.0.1
  dependency-type: indirect
  dependency-group: uv
- dependency-name: pydantic-settings
  dependency-version: 2.14.2
  dependency-type: indirect
  dependency-group: uv
- dependency-name: python-multipart
  dependency-version: 0.0.31
  dependency-type: indirect
  dependency-group: uv
- dependency-name: soupsieve
  dependency-version: 2.8.4
  dependency-type: indirect
  dependency-group: uv
- dependency-name: starlette
  dependency-version: 1.3.1
  dependency-type: indirect
  dependency-group: uv
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump transformers in the uv group across 1 directory (#168)

Bumps the uv group with 1 update in the / directory: [transformers](https://github.com/huggingface/transformers).


Updates `transformers` from 5.4.0 to 5.5.0
- [Release notes](https://github.com/huggingface/transformers/releases)
- [Commits](https://github.com/huggingface/transformers/compare/v5.4.0...v5.5.0)

---
updated-dependencies:
- dependency-name: transformers
  dependency-version: 5.5.0
  dependency-type: indirect
  dependency-group: uv
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore: add CLAUDE.md importing AGENTS.md for Claude Code

* fix: pin GitHub Actions to commit SHAs and add uv dependency cooldown

* fix: satisfy semgrep cooldown rules and pin ASH install to release commit

* docs: add maintainer handoff artifacts (MAINTAINERS, CODEOWNERS, RELEASING, CHANGELOG, maintainer's guide)

* docs: address copilot review (remove nonexistent v1.5.0 tag claim, fix file path, clarify link text)

* feat(auto): zero-config evaluation of vanilla pydantic models

Add stickler.evaluate(gt, pred) / stickler.eval_for(cls): turn any plain
pydantic BaseModel (e.g. a Strands agent response_model) into a scored
stickler evaluation with no StructuredModel subclass, JSON schema, or
x-aws-stickler-* annotation.

New src/stickler/auto/ package:
- inference.py: per-field comparator/threshold/weight inference from the
  live python type + field-name tokens (Optional-unwrap, enum/Literal/date
  handling, availability gate). Weights default to 1.0; name-token weight
  bumps are opt-in via weight_hints. Semantic/BERT/LLM never auto-selected.
- builder.py: walks cls.model_fields (never the lossy/crashing
  model_json_schema path), recurses nested BaseModel / List[BaseModel] with
  cycle detection, delegates to ModelFactory.create_model_from_fields, caches
  shadow classes in a WeakKeyDictionary.
- facade.py: evaluate / eval_for / EvalSpec / EvalResult. Normalizes instances
  via model_dump(mode="json") and reads metrics from a single compare_with
  call (field_scores + derived precision/recall/f1/accuracy). .explain()
  surfaces per-field provenance.

Overrides ({field: ComparableField}) are honored verbatim at highest
precedence. Exported from top-level stickler. 23 new tests; full suite green.

* refactor(auto): drop per-field overrides (top-level-only was half-working)

The overrides={} param only matched top-level field names and silently
dropped nested / list-element keys (e.g. "lines.price"), which is a footgun.
Rather than ship a partial API, remove it entirely: evaluate/eval_for now
infer every field, with weight_hints as the only tuning knob.

A proper nested override API (dotted paths, model-list weight-only guard,
loud errors on unknown keys) can be added later; the InferredSpec config
dict remains the single contract a future producer would target.

Removes overrides from evaluate/eval_for/EvalSpec/structured_model_for,
the override provenance branch, and the override test. 22 auto tests pass;
full suite green.

* docs(auto): ultra quick start page, notebook, and Strands example

For the "I don't want to configure anything or read docs" user: show that
stickler.evaluate(gt, pred) scores a vanilla Pydantic model with zero setup,
and that .explain() makes every inferred decision defensible.

- docs: Getting-Started/ultra-quick-start.md (+ nav) — the one-line pitch,
  a full worked Invoice example (enum/date/optional/nested list), the
  inference cheat-sheet, and how to defend/override.
- docs: Guides/Use-Cases/evaluate-strands-agent.md (+ nav) — the whole
  integration for a Strands agent's structured_output, single-pair and
  dataset loops, and the [llm] extra note.
- examples/notebooks/Ultra_Quick_Start.ipynb — clean (output-free, per repo
  convention); every code cell verified to run end-to-end.
- examples/scripts/strands_agent_eval_demo.py — runs the real agent when
  [llm] + creds are present, else falls back to a fabricated prediction so
  it's always runnable.
- examples/README.md — surface both new artifacts.

* docs(auto): soften ultra-quick-start tone, remove em dashes

Drop the "I'm too lazy..." quote framing (reads as passive-aggressive to a
reader who didn't say it) in favor of a plain "evaluate as-is, no config
required" opener, in both the doc page and the notebook.

Remove all em dashes from the auto docs, notebook, examples, and package
docstrings/README per user preference; replace with commas, colons,
parentheses, or separate sentences.

* docs(auto): remove em dashes hidden as unicode escapes in notebook

The prior "remove em dashes" pass missed the notebook: JSON serializes
non-ascii as backslash-u escapes, so a literal-character grep reported it
clean when 13 em dashes were still present. Rewrote the affected markdown
cells with plain punctuation (also dropping the leftover "defend"/"stay
lazy" tone that was already softened in the doc page), and fixed the
cell-4 import ordering ruff flagged. Notebook re-verified: valid,
lint-clean, executes end-to-end.

* docs: surface zero-config stickler.evaluate in root README

Add a short section after Installation so the vanilla-Pydantic evaluation
path is discoverable from the front door, linking to the Ultra Quick Start.

* fix: guard None elements in remaining nullable object list comparison paths

#127 made List[Optional[Model]] constructible from from_json_schema and
added None guards to three comparison branches, but missed two:

- structured_list_comparator.py is_simple_list branch: a both-None matched
  pair scored 1.0, survived the match-threshold filter, and reached
  getattr(None, sub_field_name) -> AttributeError when the element model
  carried a list-valued sub-field.
- evaluator_format_helper.py Hungarian loop: called compare_with directly
  on matched pairs with no None guard -> AttributeError on any None element.

Both fixes mirror the existing sibling-branch guards: a None element carries
no sub-fields, so the pair is skipped in the per-field breakdown (its score
is computed at the list level). Adds a regression test per crash path.

Addresses the two blocking crash items in #179.

* fix(auto): harden zero-config evaluation against the full vanilla-model surface

Adversarial review (43 verification agents, every finding reproduced by
execution) found the zero-config path failed on a wide band of ordinary
pydantic models. Root-cause fixes:

Type handling:
- unwrap_optional/_field_kind now accept PEP 604 unions (X | None): nested
  models no longer crash evaluate(); primitives keep their type comparator
  instead of falling back to Levenshtein.
- The 'compared as JSON string form' wire contract is now real: dict, tuple,
  set, Any, multi-arm unions, IntEnum, int Literals and unparameterized
  containers canonicalize to a deterministic JSON string (sorted keys; sets
  also sort elements) via a shadow-field BeforeValidator, instead of crashing
  with a ValidationError naming an internal shadow class.
- Nullability now comes from the source annotation, not required-ness:
  required Optional[X] accepts None; Optional[List[X]] = None works.

Inference integrity:
- Name-token rules are gated on type compatibility. A rule whose comparator
  cannot parse the field's type keeps the type default (recorded in
  provenance) instead of silently scoring identical values 0.0
  (bool has_due_date -> Date, str amount -> Numeric, etc.).
- bool/Enum/Literal are never token-refined; email/phone rule now precedes
  the numeric rules so phone_num resolves to Exact; over-broad 'num' token
  dropped; tokenizer sheds digit suffixes (isbn13) and plurals (ids).
- datetime fields get a 1-minute Date tolerance so timestamps hours apart no
  longer score 1.0 (date fields keep calendar-day semantics).

Scoring consistency:
- Single nested models use match_threshold with clip_under_threshold=False,
  so a mostly-right child gets the same partial credit as the identical
  object inside a one-element list (was: hardcoded 0.9 clip -> 0.0 vs 0.8).
- StructuredModel classes pass through as configured: eval_for never
  re-infers over explicit comparators, nested StructuredModel fields are
  used directly, and explain() reports source=explicit.

API/auditability:
- explain() now covers every depth via dotted paths (lines.sku) and reports
  the comparator actually installed for primitive lists (was: divergent
  second inference walk).
- EvalResult.explain() joins per-pair actuals: score, raw_similarity, and a
  clip verdict ('raw 0.56 < threshold 0.85 -> clipped to 0.0').
- EvalSpec.evaluate accepts dicts (validated through the source class);
  EvalResult.matched exposes the match_threshold verdict; match_threshold
  semantics documented precisely.
- Recursive models, empty models, and the reserved extra_fields name raise
  actionable TypeErrors at build time instead of RecursionError/leaked
  internals.

Tests: new tests/auto/test_risk_surface.py (39 tests) pins the contracts:
identity invariant across every supported shape (incl. a token/type-conflict
grid), wire canonicalization, annotation-derived nullability, structural
errors, StructuredModel passthrough, explain coverage/accuracy, single-vs-
list nested consistency, dict acceptance, determinism, datetime sensitivity.
Docs updated (dotted-path explain output, per-pair verdict, type-gates-token
rule, README precedence table and unsupported-shapes section).

Full suite: 1507 passed, 2 skipped. ruff clean.

* feat(auto): bridge EvalSpec into the standard bulk-evaluation pattern

The Strands guide pointed dataset users at BulkStructuredModelEvaluator but
gave no working path: feeding vanilla pydantic instances silently returned
document_count=0, and the correct incantation (shadow-model from_json) was
undocumented. Rather than invent a parallel batch API, wire the zero-config
path into the existing update/compute pattern:

- EvalSpec.to_model(instance_or_dict): converts a source instance (or plain
  dict) into the compiled shadow StructuredModel, the currency every
  existing stickler tool accepts (compare_with, bulk evaluator, reports).
  evaluate() now routes through it.
- EvalSpec.bulk_evaluator(**kwargs): returns a standard
  BulkStructuredModelEvaluator with target_schema wired to the compiled
  model; all kwargs (doc_id tracking, JSONL output, checkpointing) pass
  through unchanged.

Docs: the Strands guide's dataset section now shows the real update/compute
loop with corpus-level F1 and links to the Bulk Evaluation guide as the
single source of truth; ultra-quick-start gains the same three-liner.

Tests: bulk update/compute over mixed instances+dicts asserts
document_count and aggregate F1; to_model output verified comparable.
Full suite: 1509 passed, 2 skipped. ruff clean.

* docs(auto): make the bulk update/compute pattern the only dataset path

Remove the hand-rolled mean-of-scores loop from the Strands guide and
quick-start: two documented ways to aggregate a dataset invites drift, and
mean-of-overall_score is a weaker statistic than the accumulated
confusion-matrix metrics the standard BulkStructuredModelEvaluator already
computes. The dataset section now leads with spec.bulk_evaluator() +
spec.to_model() and points at the Bulk Evaluation guide as the single source
of truth; per-pair spec.evaluate() remains for single-document inspection.

* refactor(auto): expose inference as StructuredModel.from_pydantic, drop bespoke bulk bridge

Review feedback: EvalSpec.bulk_evaluator()/to_model() invented a parallel
mechanism where the library already has its seam. Replace with a first-class
constructor, sibling to from_json_schema()/model_from_json():

    InvoiceEval = StructuredModel.from_pydantic(Invoice)

The returned class is an ordinary StructuredModel, so everything downstream
is just the existing machinery, unchanged: BulkStructuredModelEvaluator
takes it as target_schema, instances come from
InvoiceEval.from_json(instance.model_dump()), and the export -> edit ->
rebuild story (to_stickler_config / model_from_json) covers 'tweak an
inferred decision' with no zero-config-specific API.

To make from_json accept plain model_dump() output as well as
model_dump(mode='json'), shadow date/datetime fields coerce native date
objects to ISO strings and the JSON canonicalizer unwraps enum members, so
both dump modes validate and compare identically (test locks this in).

A StructuredModel subclass passes through from_pydantic unchanged (explicit
configuration always wins). EvalSpec.bulk_evaluator()/to_model() removed;
evaluate()/eval_for() are unchanged as the single-pair conveniences.

Docs: quick-start and Strands guide dataset sections now show the standard
bulk update/compute pattern with from_pydantic; auto/README documents the
constructor as the integration point and the deliberate absence of any
bulk-specific API in the package.

Tests: from_pydantic + BulkStructuredModelEvaluator as-is (document_count,
corpus F1), native-vs-json dump equivalence, passthrough identity,
export-edit-rebuild round-trip, facade/constructor score agreement.
Full suite: 1513 passed, 2 skipped. ruff clean (structured_model.py format
failure is pre-existing on dev).

* refactor: remove duplicate structured field helper

* fix(json-schema): annotate optional fields as Optional[T] so from_json accepts None

from_json_schema() built optional fields (those absent from `required`) with
`default=None` but a NON-nullable annotation (bare `str`, not `Optional[str]`).
Plain `ModelClass(**data)` tolerated the omitted field, but
`from_json(process_rich_values=True)` did not: the rich-value path round-trips
nested objects through `from_json(...).model_dump()`
(ConfigurationHelper._process_nested_structured_data), which materializes the
`None` default and re-validates it against the bare annotation, raising a
pydantic ValidationError ("Input should be a valid string ... input_value=None").

Fix widens `field_type` to `Optional[field_type]` whenever the field is not
required, mirroring the existing `default = ... if is_required else None`
decision, at all three conversion sites:
- primitive types (convert_property_to_field)
- nested objects (_handle_nested_object)
- arrays (_handle_array_type)

Required fields keep their bare annotation. Downstream configuration_helper
already handles `Optional[...]` correctly; it simply never received them.

Existing converter assertions that checked bare `is str`/`is int`/List[...] for
NOT-REQUIRED fields are updated to unwrap the Optional wrapper (required fields
stay bare). Adds regression coverage for the #149 repro and for the
optional->Optional annotation at all three sites.

Fixes #149

* fix(json-schema): make optional-field Optional[T] widening consistent across paths

Addresses @adiadd's review on #150. The Optional[T] widening for non-required
fields was correct but incomplete -- several consumers and a parallel producer
didn't understand the widened annotation:

- comparison: is_structured_field_type now recognizes Optional[StructuredModel],
  so compare_recursive keeps the nested metric breakdown for optional nested
  objects inside list items (was silently collapsing to flat counts)
- widening condition is now `not is_required or default is None`, so a required
  field with an explicit "default": null is also widened
- collapse the three widening sites into the sole dispatcher
  convert_property_to_field (also the convergence point with #127)
- stickler-config path (field_converter.py) widens too, closing the
  to_stickler_config -> model_from_json round-trip hole
- HTML report threshold extraction unwraps Optional[...] so nested thresholds
  no longer vanish for schema-built optional models
- document the explicit-null contract (anyOf:[T,null]); nest the two regression
  tests that previously passed without the fix; tidy review nits

* docs+test: pin the optional-field export contract after the #127 rebase

Rebasing onto dev folded this PR's single-site widening together with #127's
list-form nullable support: widen_to_optional now also honours is_nullable, so
type: ["X","null"] and "absent from required" reach the same one decision.

That convergence makes an optional-but-not-nullable field round-trip out as
["X","null"], which the input schema never declared. Make it an intentional,
tested decision rather than an emergent one: pin it with a round-trip test
asserting idempotence and an unchanged accepted-value set, and state the
contract in dynamic-models.md.

Also unwrap the outer Optional in #127's test_nullable_array_items, which
predates the interaction -- item-level List[Optional[T]] is unchanged.

* fix(auto): address final adversarial verification findings

A four-lens adversarial pass over the assembled branch (regression sweep,
edge-case matrix, mutation testing, docs execution) confirmed nine findings.
Fixes:

Correctness:
- NumericComparator: guard non-finite Decimals before tolerance arithmetic.
  With relative_tolerance>0 (which inference now sets for every float),
  abs(num1-num2)/abs(num1) on NaN/Infinity raised decimal.InvalidOperation,
  so a NaN float field crashed stickler.evaluate() outright. NaN matches
  nothing (including NaN); infinities match only exactly, matching the
  tolerance=0 path's semantics.
- Decimal is now a first-class numeric type in inference: it was falling to
  the Levenshtein string fallback, so Decimal('100') vs Decimal('100.00')
  (numerically equal money) scored 0.0, and amount/price token rules were
  type-gated away from it. Now NumericComparator(exact), and the numeric
  token family includes it.
- Dump-mode equivalence: canonicalization runs values through
  pydantic_core.to_jsonable_python first, so plain model_dump() and
  model_dump(mode='json') normalize identically. Fixes a hard TypeError on
  Dict[date, X] keys and silent 0.0 scores on Set fields (native set repr vs
  JSON list) via the from_pydantic + from_json(model_dump()) path the
  docstring recommends.

Test quality (mutation survivors from the verification pass):
- Nested-model clip_under_threshold=False had no killing test: the existing
  case scored 0.8 > threshold so clipping never engaged. Added a 2/5-correct
  child (0.4 < 0.7) that fails if the flag flips.
- Token rule ORDER (phone before numeric) had no killing test; added a direct
  inference assertion for phone_num -> Exact.
- The entire _gate degrade machinery was uncovered; added four tests
  (unregistered, construction failure, never-auto LLM, Date -> Exact).
- Added NaN/Infinity/Decimal and dump-mode-equivalence regression tests.
- De-pinned two brittle tests: the from_json_schema 'still crashes' assertion
  (an implementation detail that may improve independently) and the exact
  weight-bump magic constants (now asserts the contract: hinted > uniform).
- Strengthened test_date_matches_exactly_not_levenshtein, which compared two
  IDENTICAL dates and so could not detect the comparator it names; it now
  also asserts an off-by-one-day date scores 0.

Docs:
- The Strands guide crashed when run top to bottom: the bulk block rebound
  'result' to a ProcessEvaluation, then 'Defending the numbers' called
  result.explain() on it. Renamed to 'corpus' and pointed the prose at the
  single-pair result; also fixed a reference to an undefined 'spec'. All five
  blocks now execute in one namespace.
- Updated the deprecated Strands API throughout the guide and demo script:
  agent.structured_output(Model, prompt) -> agent(prompt,
  structured_output_model=Model).structured_output.
- auto/README: the 'mode=json is mandatory' claim is no longer true; document
  that both dump modes work, and add Decimal to the type table.

Full suite: 1526 passed, 2 skipped. ruff clean.

* fix(auto): address review findings on zero-config evaluation

Docs/code mismatches and test gaps found reviewing #176. No behavior change
to the existing library; one intentional behavior change inside auto/.

Exotic-type comparator (behavior change, auto/ only):
- dict/tuple/set/Any/multi-arm unions now infer ExactComparator over the
  canonical JSON string, which is what auto/README.md already documented.
  They were using Levenshtein@0.7, so two substantively different dicts
  scored 0.955 instead of 0.0. Edit distance over a JSON blob is not
  defensible in a metrics API.

Docs corrected to match actual behavior:
- Scope the "export -> edit -> rebuild" round-trip. to_stickler_config()
  carries comparators/thresholds/weights but not the BeforeValidator wire
  normalizers, so a rebuilt class needs model_dump(mode="json") and cannot
  round-trip dict/set fields at all. Previously promised unconditionally in
  ultra-quick-start.md, evaluate-strands-agent.md, and auto/README.md.
- Fix the auto/README.md type-table threshold column for those types.

Strands version floor:
- Raise [llm] to strands-agents>=1.14.0. The documented
  structured_output_model= kwarg landed in 1.14.0; on 1.0-1.13 Agent.__call__
  swallows it via **kwargs, so no structured output is requested and the call
  dies later on .structured_output.
- Narrow the demo's fallback: only a missing install falls back quietly. A
  real agent failure (expired creds, no model access) is now reported
  distinctly instead of being reported as "Strands unavailable" while the
  demo scores the fabricated invoice.

Tests (+15), each verified to fail against the mutation it guards:
- Pin the type-dispatch table with token-free field names and a provenance
  assertion. The existing rows used names carrying tokens (count, price,
  total_amount), so a name rule could satisfy them even with the type branch
  returning something else. Swapping date/int/Decimal to Levenshtein left the
  whole suite green.
- test_date_matches_exactly_not_levenshtein now asserts the comparator and
  raw_similarity. Its post-clip assertion held under both comparators
  (Levenshtein's raw 0.9 clips to 0.0 at the 0.95 threshold), so the test
  could not fail for the reason its comment described.
- Pin the shadow-class cache key on match_threshold and weight_hints.
  Dropping match_threshold from the key made results depend on call order
  within a process, with the suite still green, and no test passed
  match_threshold to the new API at all.
- Pin the sorted set wire form via from_json on differently-ordered JSON
  lists. Both existing Set tests build from set literals in one process, so
  the unsorted JSON strings coincidentally matched.
- Add token-free Decimal coverage and a money-tolerance band pair.
- Tighten test_different_exotic_values_do_not_score_one from < 1.0 to an
  exact score plus comparator assertion.

Also removes two em dashes in builder.py comments.

Full suite 1541 passed, 2 skipped. ruff clean.

* chore: bump version to 0.6.0 for release

* Un-pinning Strands to allow higher versions. Testing.

* Adding the UV.lock file.

* Changes for #201.
* Widening python tsting from 3.10-3.14
* Improving import isolation so we don't have heavy load times
* Removing depndencies from the core installation reuqirements where not required.

* Resolving some of the issues flagged in #187
* resolving the failing tests on the CI
* adding in import error messages for uncommon uses.
* adding tests to prevent failures.

* refactor(comparators): implement lazy loading for optional dependencies

- Replace eager imports of LLMComparator and BERTComparator with PEP 562 __getattr__ lazy loading
- Add _dependency_available() helper to check for optional dependencies without importing them
- Move boto3 import into generate_bedrock_embedding() to avoid pulling it onto the import path
- Refactor ComparatorRegistry to use dynamic imports via importlib instead of try/except blocks
- Add __dir__() to support dir() introspection on the comparators module
- Improve error messages to direct users to install specific extras (llm, bert, semantic)
- Defer heavy dependencies (strands-agents, torch, transformers, boto3) until actually needed
- Maintain backward compatibility: hasattr() and imports work identically to before

* docs(changelog): record the #201 dependency and Python-range changes

Adds the Unreleased entries this PR was missing, including the breaking
one: pandas, scipy, scikit-learn and jinja2 are no longer core
dependencies, so the peripheral modules now require their extra. The
table names each affected entry point and the extra that restores it,
and distinguishes doc_split (fails at import) from the rest (fail at
first use).

Also records the scikit-learn floor relaxation to >=1.7.2, which is what
makes the 3.10 floor resolvable, since 1.8.0 requires 3.11+. Both were
review asks from #207 that had not made it into the PR description.

Notes the measured 463-module baseline next to the < 900 tripwire in
test_core_import_stays_small so the bound does not read as arbitrary.

* feat: make confidence calibration core, not an extra

Confidence calibration answers "does the model's self-reported
confidence track correctness," which is part of evaluating a model
rather than an optional add-on. Splitting it behind an extra made a
core capability opt-in.

Moves scikit-learn back into [project.dependencies] and empties the
confidence extra, keeping the extra name so existing pins keep
resolving. Three of the four calibration metrics (Brier, ECE, error
capture at budget) were already pure Python and worked on a core
install; only AUROC was gated, so this closes a gap that made the
feature look partly broken by default.

The sklearn import stays inside AUROCMetric.compute() rather than
moving to module scope: confidence/metrics.py IS on the `import
stickler` path, so an eager import would put ~33MB there for every
user whether or not they compute AUROC. Verified 421 modules on a core
install with sklearn still absent from the import path, so the import
weight work from #201 is preserved.

Issue #216 tracks replacing AUROC with a numpy implementation of the
Mann-Whitney form, after which scikit-learn leaves the dependency set
entirely and document-packet evaluation can move to the core with only
pandas behind an extra. Verified numerically before filing: numpy AUROC
matches sklearn to 1.1e-16 across 4420 cases including heavy ties.

* fix(json-schema): support nullable anyOf and implicit objects

Normalize two-branch nullable anyOf schemas before conversion and infer object shapes from properties. Reuse the same path for array items and preserve existing local reference handling.

Fixes #105

* fix: handle None consistently across all comparators

Comparators disagreed on how None compares to an empty string.
LevenshteinComparator coerced None to "" before comparing, so
(None, "") scored 1.0 while every other comparator scored 0.0.
SemanticComparator and BERTComparator had the inverse gap: an
or-check without the and-case, so (None, None) scored 0.0 instead
of 1.0.

Since str fields infer to LevenshteinComparator by default, this is
the path most string fields take, and the divergence propagated
through the confusion matrix into corpus-level precision and recall.

Move the policy into BaseComparator as a template method: compare()
applies it once and delegates to a new abstract _compare() for
values that are actually present. Comparators implement _compare()
and never see None, so the policy is defined in one place and cannot
drift between comparators or be forgotten by a new one. Implementing
only compare() leaves the class abstract, so the mistake fails at
construction rather than silently bypassing the policy.

None is a missing value and no longer compares equal to an empty
string: (None, "") is 0.0 and (None, None) is 1.0, everywhere.

BREAKING (custom comparators): the extension point is now _compare()
instead of compare(). Subclasses must rename their compare() and can
delete any None handling it contains. Callers are unaffected --
compare(), __call__ and binary_compare() are unchanged.

Fixes #200

* docs,test: document the migration surface of the compare() rename

Review follow-ups on #200.

The CHANGELOG claimed an un-migrated comparator "stays abstract and raises
TypeError on instantiation, so the change surfaces immediately". That holds
only when subclassing BaseComparator directly. A subclass of a concrete
comparator inherits _compare(), so it constructs, and its legacy compare()
shadows the template method and bypasses the None policy without any error.

Replace the claim with the per-shape behavior, and note that the pre-fix
(None, "") -> 1.0 result cannot be inherited: the coercion was removed from
Levenshtein's algorithm rather than guarded, so an un-migrated subclass that
delegates upward gets the corrected score. Only a subclass that
reimplemented the coercion in its own compare() still returns the old value.

Add TestPreRenameSubclassMigration covering both shapes, and rename the
existing abstract-class test to say which shape it actually covers.

Comparators.md said "All comparators handle None values gracefully", which
predates the policy and says nothing about what it does. State the policy,
and note the template method / _compare split in the ove…
sromoam added a commit that referenced this pull request Sep 14, 2026
…ics (#345)

* docs: surface zero-config stickler.evaluate in root README

Add a short section after Installation so the vanilla-Pydantic evaluation
path is discoverable from the front door, linking to the Ultra Quick Start.

* fix: guard None elements in remaining nullable object list comparison paths

#127 made List[Optional[Model]] constructible from from_json_schema and
added None guards to three comparison branches, but missed two:

- structured_list_comparator.py is_simple_list branch: a both-None matched
  pair scored 1.0, survived the match-threshold filter, and reached
  getattr(None, sub_field_name) -> AttributeError when the element model
  carried a list-valued sub-field.
- evaluator_format_helper.py Hungarian loop: called compare_with directly
  on matched pairs with no None guard -> AttributeError on any None element.

Both fixes mirror the existing sibling-branch guards: a None element carries
no sub-fields, so the pair is skipped in the per-field breakdown (its score
is computed at the list level). Adds a regression test per crash path.

Addresses the two blocking crash items in #179.

* fix(auto): harden zero-config evaluation against the full vanilla-model surface

Adversarial review (43 verification agents, every finding reproduced by
execution) found the zero-config path failed on a wide band of ordinary
pydantic models. Root-cause fixes:

Type handling:
- unwrap_optional/_field_kind now accept PEP 604 unions (X | None): nested
  models no longer crash evaluate(); primitives keep their type comparator
  instead of falling back to Levenshtein.
- The 'compared as JSON string form' wire contract is now real: dict, tuple,
  set, Any, multi-arm unions, IntEnum, int Literals and unparameterized
  containers canonicalize to a deterministic JSON string (sorted keys; sets
  also sort elements) via a shadow-field BeforeValidator, instead of crashing
  with a ValidationError naming an internal shadow class.
- Nullability now comes from the source annotation, not required-ness:
  required Optional[X] accepts None; Optional[List[X]] = None works.

Inference integrity:
- Name-token rules are gated on type compatibility. A rule whose comparator
  cannot parse the field's type keeps the type default (recorded in
  provenance) instead of silently scoring identical values 0.0
  (bool has_due_date -> Date, str amount -> Numeric, etc.).
- bool/Enum/Literal are never token-refined; email/phone rule now precedes
  the numeric rules so phone_num resolves to Exact; over-broad 'num' token
  dropped; tokenizer sheds digit suffixes (isbn13) and plurals (ids).
- datetime fields get a 1-minute Date tolerance so timestamps hours apart no
  longer score 1.0 (date fields keep calendar-day semantics).

Scoring consistency:
- Single nested models use match_threshold with clip_under_threshold=False,
  so a mostly-right child gets the same partial credit as the identical
  object inside a one-element list (was: hardcoded 0.9 clip -> 0.0 vs 0.8).
- StructuredModel classes pass through as configured: eval_for never
  re-infers over explicit comparators, nested StructuredModel fields are
  used directly, and explain() reports source=explicit.

API/auditability:
- explain() now covers every depth via dotted paths (lines.sku) and reports
  the comparator actually installed for primitive lists (was: divergent
  second inference walk).
- EvalResult.explain() joins per-pair actuals: score, raw_similarity, and a
  clip verdict ('raw 0.56 < threshold 0.85 -> clipped to 0.0').
- EvalSpec.evaluate accepts dicts (validated through the source class);
  EvalResult.matched exposes the match_threshold verdict; match_threshold
  semantics documented precisely.
- Recursive models, empty models, and the reserved extra_fields name raise
  actionable TypeErrors at build time instead of RecursionError/leaked
  internals.

Tests: new tests/auto/test_risk_surface.py (39 tests) pins the contracts:
identity invariant across every supported shape (incl. a token/type-conflict
grid), wire canonicalization, annotation-derived nullability, structural
errors, StructuredModel passthrough, explain coverage/accuracy, single-vs-
list nested consistency, dict acceptance, determinism, datetime sensitivity.
Docs updated (dotted-path explain output, per-pair verdict, type-gates-token
rule, README precedence table and unsupported-shapes section).

Full suite: 1507 passed, 2 skipped. ruff clean.

* feat(auto): bridge EvalSpec into the standard bulk-evaluation pattern

The Strands guide pointed dataset users at BulkStructuredModelEvaluator but
gave no working path: feeding vanilla pydantic instances silently returned
document_count=0, and the correct incantation (shadow-model from_json) was
undocumented. Rather than invent a parallel batch API, wire the zero-config
path into the existing update/compute pattern:

- EvalSpec.to_model(instance_or_dict): converts a source instance (or plain
  dict) into the compiled shadow StructuredModel, the currency every
  existing stickler tool accepts (compare_with, bulk evaluator, reports).
  evaluate() now routes through it.
- EvalSpec.bulk_evaluator(**kwargs): returns a standard
  BulkStructuredModelEvaluator with target_schema wired to the compiled
  model; all kwargs (doc_id tracking, JSONL output, checkpointing) pass
  through unchanged.

Docs: the Strands guide's dataset section now shows the real update/compute
loop with corpus-level F1 and links to the Bulk Evaluation guide as the
single source of truth; ultra-quick-start gains the same three-liner.

Tests: bulk update/compute over mixed instances+dicts asserts
document_count and aggregate F1; to_model output verified comparable.
Full suite: 1509 passed, 2 skipped. ruff clean.

* docs(auto): make the bulk update/compute pattern the only dataset path

Remove the hand-rolled mean-of-scores loop from the Strands guide and
quick-start: two documented ways to aggregate a dataset invites drift, and
mean-of-overall_score is a weaker statistic than the accumulated
confusion-matrix metrics the standard BulkStructuredModelEvaluator already
computes. The dataset section now leads with spec.bulk_evaluator() +
spec.to_model() and points at the Bulk Evaluation guide as the single source
of truth; per-pair spec.evaluate() remains for single-document inspection.

* refactor(auto): expose inference as StructuredModel.from_pydantic, drop bespoke bulk bridge

Review feedback: EvalSpec.bulk_evaluator()/to_model() invented a parallel
mechanism where the library already has its seam. Replace with a first-class
constructor, sibling to from_json_schema()/model_from_json():

    InvoiceEval = StructuredModel.from_pydantic(Invoice)

The returned class is an ordinary StructuredModel, so everything downstream
is just the existing machinery, unchanged: BulkStructuredModelEvaluator
takes it as target_schema, instances come from
InvoiceEval.from_json(instance.model_dump()), and the export -> edit ->
rebuild story (to_stickler_config / model_from_json) covers 'tweak an
inferred decision' with no zero-config-specific API.

To make from_json accept plain model_dump() output as well as
model_dump(mode='json'), shadow date/datetime fields coerce native date
objects to ISO strings and the JSON canonicalizer unwraps enum members, so
both dump modes validate and compare identically (test locks this in).

A StructuredModel subclass passes through from_pydantic unchanged (explicit
configuration always wins). EvalSpec.bulk_evaluator()/to_model() removed;
evaluate()/eval_for() are unchanged as the single-pair conveniences.

Docs: quick-start and Strands guide dataset sections now show the standard
bulk update/compute pattern with from_pydantic; auto/README documents the
constructor as the integration point and the deliberate absence of any
bulk-specific API in the package.

Tests: from_pydantic + BulkStructuredModelEvaluator as-is (document_count,
corpus F1), native-vs-json dump equivalence, passthrough identity,
export-edit-rebuild round-trip, facade/constructor score agreement.
Full suite: 1513 passed, 2 skipped. ruff clean (structured_model.py format
failure is pre-existing on dev).

* refactor: remove duplicate structured field helper

* fix(json-schema): annotate optional fields as Optional[T] so from_json accepts None

from_json_schema() built optional fields (those absent from `required`) with
`default=None` but a NON-nullable annotation (bare `str`, not `Optional[str]`).
Plain `ModelClass(**data)` tolerated the omitted field, but
`from_json(process_rich_values=True)` did not: the rich-value path round-trips
nested objects through `from_json(...).model_dump()`
(ConfigurationHelper._process_nested_structured_data), which materializes the
`None` default and re-validates it against the bare annotation, raising a
pydantic ValidationError ("Input should be a valid string ... input_value=None").

Fix widens `field_type` to `Optional[field_type]` whenever the field is not
required, mirroring the existing `default = ... if is_required else None`
decision, at all three conversion sites:
- primitive types (convert_property_to_field)
- nested objects (_handle_nested_object)
- arrays (_handle_array_type)

Required fields keep their bare annotation. Downstream configuration_helper
already handles `Optional[...]` correctly; it simply never received them.

Existing converter assertions that checked bare `is str`/`is int`/List[...] for
NOT-REQUIRED fields are updated to unwrap the Optional wrapper (required fields
stay bare). Adds regression coverage for the #149 repro and for the
optional->Optional annotation at all three sites.

Fixes #149

* fix(json-schema): make optional-field Optional[T] widening consistent across paths

Addresses @adiadd's review on #150. The Optional[T] widening for non-required
fields was correct but incomplete -- several consumers and a parallel producer
didn't understand the widened annotation:

- comparison: is_structured_field_type now recognizes Optional[StructuredModel],
  so compare_recursive keeps the nested metric breakdown for optional nested
  objects inside list items (was silently collapsing to flat counts)
- widening condition is now `not is_required or default is None`, so a required
  field with an explicit "default": null is also widened
- collapse the three widening sites into the sole dispatcher
  convert_property_to_field (also the convergence point with #127)
- stickler-config path (field_converter.py) widens too, closing the
  to_stickler_config -> model_from_json round-trip hole
- HTML report threshold extraction unwraps Optional[...] so nested thresholds
  no longer vanish for schema-built optional models
- document the explicit-null contract (anyOf:[T,null]); nest the two regression
  tests that previously passed without the fix; tidy review nits

* docs+test: pin the optional-field export contract after the #127 rebase

Rebasing onto dev folded this PR's single-site widening together with #127's
list-form nullable support: widen_to_optional now also honours is_nullable, so
type: ["X","null"] and "absent from required" reach the same one decision.

That convergence makes an optional-but-not-nullable field round-trip out as
["X","null"], which the input schema never declared. Make it an intentional,
tested decision rather than an emergent one: pin it with a round-trip test
asserting idempotence and an unchanged accepted-value set, and state the
contract in dynamic-models.md.

Also unwrap the outer Optional in #127's test_nullable_array_items, which
predates the interaction -- item-level List[Optional[T]] is unchanged.

* fix(auto): address final adversarial verification findings

A four-lens adversarial pass over the assembled branch (regression sweep,
edge-case matrix, mutation testing, docs execution) confirmed nine findings.
Fixes:

Correctness:
- NumericComparator: guard non-finite Decimals before tolerance arithmetic.
  With relative_tolerance>0 (which inference now sets for every float),
  abs(num1-num2)/abs(num1) on NaN/Infinity raised decimal.InvalidOperation,
  so a NaN float field crashed stickler.evaluate() outright. NaN matches
  nothing (including NaN); infinities match only exactly, matching the
  tolerance=0 path's semantics.
- Decimal is now a first-class numeric type in inference: it was falling to
  the Levenshtein string fallback, so Decimal('100') vs Decimal('100.00')
  (numerically equal money) scored 0.0, and amount/price token rules were
  type-gated away from it. Now NumericComparator(exact), and the numeric
  token family includes it.
- Dump-mode equivalence: canonicalization runs values through
  pydantic_core.to_jsonable_python first, so plain model_dump() and
  model_dump(mode='json') normalize identically. Fixes a hard TypeError on
  Dict[date, X] keys and silent 0.0 scores on Set fields (native set repr vs
  JSON list) via the from_pydantic + from_json(model_dump()) path the
  docstring recommends.

Test quality (mutation survivors from the verification pass):
- Nested-model clip_under_threshold=False had no killing test: the existing
  case scored 0.8 > threshold so clipping never engaged. Added a 2/5-correct
  child (0.4 < 0.7) that fails if the flag flips.
- Token rule ORDER (phone before numeric) had no killing test; added a direct
  inference assertion for phone_num -> Exact.
- The entire _gate degrade machinery was uncovered; added four tests
  (unregistered, construction failure, never-auto LLM, Date -> Exact).
- Added NaN/Infinity/Decimal and dump-mode-equivalence regression tests.
- De-pinned two brittle tests: the from_json_schema 'still crashes' assertion
  (an implementation detail that may improve independently) and the exact
  weight-bump magic constants (now asserts the contract: hinted > uniform).
- Strengthened test_date_matches_exactly_not_levenshtein, which compared two
  IDENTICAL dates and so could not detect the comparator it names; it now
  also asserts an off-by-one-day date scores 0.

Docs:
- The Strands guide crashed when run top to bottom: the bulk block rebound
  'result' to a ProcessEvaluation, then 'Defending the numbers' called
  result.explain() on it. Renamed to 'corpus' and pointed the prose at the
  single-pair result; also fixed a reference to an undefined 'spec'. All five
  blocks now execute in one namespace.
- Updated the deprecated Strands API throughout the guide and demo script:
  agent.structured_output(Model, prompt) -> agent(prompt,
  structured_output_model=Model).structured_output.
- auto/README: the 'mode=json is mandatory' claim is no longer true; document
  that both dump modes work, and add Decimal to the type table.

Full suite: 1526 passed, 2 skipped. ruff clean.

* fix(auto): address review findings on zero-config evaluation

Docs/code mismatches and test gaps found reviewing #176. No behavior change
to the existing library; one intentional behavior change inside auto/.

Exotic-type comparator (behavior change, auto/ only):
- dict/tuple/set/Any/multi-arm unions now infer ExactComparator over the
  canonical JSON string, which is what auto/README.md already documented.
  They were using Levenshtein@0.7, so two substantively different dicts
  scored 0.955 instead of 0.0. Edit distance over a JSON blob is not
  defensible in a metrics API.

Docs corrected to match actual behavior:
- Scope the "export -> edit -> rebuild" round-trip. to_stickler_config()
  carries comparators/thresholds/weights but not the BeforeValidator wire
  normalizers, so a rebuilt class needs model_dump(mode="json") and cannot
  round-trip dict/set fields at all. Previously promised unconditionally in
  ultra-quick-start.md, evaluate-strands-agent.md, and auto/README.md.
- Fix the auto/README.md type-table threshold column for those types.

Strands version floor:
- Raise [llm] to strands-agents>=1.14.0. The documented
  structured_output_model= kwarg landed in 1.14.0; on 1.0-1.13 Agent.__call__
  swallows it via **kwargs, so no structured output is requested and the call
  dies later on .structured_output.
- Narrow the demo's fallback: only a missing install falls back quietly. A
  real agent failure (expired creds, no model access) is now reported
  distinctly instead of being reported as "Strands unavailable" while the
  demo scores the fabricated invoice.

Tests (+15), each verified to fail against the mutation it guards:
- Pin the type-dispatch table with token-free field names and a provenance
  assertion. The existing rows used names carrying tokens (count, price,
  total_amount), so a name rule could satisfy them even with the type branch
  returning something else. Swapping date/int/Decimal to Levenshtein left the
  whole suite green.
- test_date_matches_exactly_not_levenshtein now asserts the comparator and
  raw_similarity. Its post-clip assertion held under both comparators
  (Levenshtein's raw 0.9 clips to 0.0 at the 0.95 threshold), so the test
  could not fail for the reason its comment described.
- Pin the shadow-class cache key on match_threshold and weight_hints.
  Dropping match_threshold from the key made results depend on call order
  within a process, with the suite still green, and no test passed
  match_threshold to the new API at all.
- Pin the sorted set wire form via from_json on differently-ordered JSON
  lists. Both existing Set tests build from set literals in one process, so
  the unsorted JSON strings coincidentally matched.
- Add token-free Decimal coverage and a money-tolerance band pair.
- Tighten test_different_exotic_values_do_not_score_one from < 1.0 to an
  exact score plus comparator assertion.

Also removes two em dashes in builder.py comments.

Full suite 1541 passed, 2 skipped. ruff clean.

* chore: bump version to 0.6.0 for release

* Un-pinning Strands to allow higher versions. Testing.

* Adding the UV.lock file.

* Changes for #201.
* Widening python tsting from 3.10-3.14
* Improving import isolation so we don't have heavy load times
* Removing depndencies from the core installation reuqirements where not required.

* Resolving some of the issues flagged in #187
* resolving the failing tests on the CI
* adding in import error messages for uncommon uses.
* adding tests to prevent failures.

* refactor(comparators): implement lazy loading for optional dependencies

- Replace eager imports of LLMComparator and BERTComparator with PEP 562 __getattr__ lazy loading
- Add _dependency_available() helper to check for optional dependencies without importing them
- Move boto3 import into generate_bedrock_embedding() to avoid pulling it onto the import path
- Refactor ComparatorRegistry to use dynamic imports via importlib instead of try/except blocks
- Add __dir__() to support dir() introspection on the comparators module
- Improve error messages to direct users to install specific extras (llm, bert, semantic)
- Defer heavy dependencies (strands-agents, torch, transformers, boto3) until actually needed
- Maintain backward compatibility: hasattr() and imports work identically to before

* docs(changelog): record the #201 dependency and Python-range changes

Adds the Unreleased entries this PR was missing, including the breaking
one: pandas, scipy, scikit-learn and jinja2 are no longer core
dependencies, so the peripheral modules now require their extra. The
table names each affected entry point and the extra that restores it,
and distinguishes doc_split (fails at import) from the rest (fail at
first use).

Also records the scikit-learn floor relaxation to >=1.7.2, which is what
makes the 3.10 floor resolvable, since 1.8.0 requires 3.11+. Both were
review asks from #207 that had not made it into the PR description.

Notes the measured 463-module baseline next to the < 900 tripwire in
test_core_import_stays_small so the bound does not read as arbitrary.

* feat: make confidence calibration core, not an extra

Confidence calibration answers "does the model's self-reported
confidence track correctness," which is part of evaluating a model
rather than an optional add-on. Splitting it behind an extra made a
core capability opt-in.

Moves scikit-learn back into [project.dependencies] and empties the
confidence extra, keeping the extra name so existing pins keep
resolving. Three of the four calibration metrics (Brier, ECE, error
capture at budget) were already pure Python and worked on a core
install; only AUROC was gated, so this closes a gap that made the
feature look partly broken by default.

The sklearn import stays inside AUROCMetric.compute() rather than
moving to module scope: confidence/metrics.py IS on the `import
stickler` path, so an eager import would put ~33MB there for every
user whether or not they compute AUROC. Verified 421 modules on a core
install with sklearn still absent from the import path, so the import
weight work from #201 is preserved.

Issue #216 tracks replacing AUROC with a numpy implementation of the
Mann-Whitney form, after which scikit-learn leaves the dependency set
entirely and document-packet evaluation can move to the core with only
pandas behind an extra. Verified numerically before filing: numpy AUROC
matches sklearn to 1.1e-16 across 4420 cases including heavy ties.

* fix(json-schema): support nullable anyOf and implicit objects

Normalize two-branch nullable anyOf schemas before conversion and infer object shapes from properties. Reuse the same path for array items and preserve existing local reference handling.

Fixes #105

* fix: handle None consistently across all comparators

Comparators disagreed on how None compares to an empty string.
LevenshteinComparator coerced None to "" before comparing, so
(None, "") scored 1.0 while every other comparator scored 0.0.
SemanticComparator and BERTComparator had the inverse gap: an
or-check without the and-case, so (None, None) scored 0.0 instead
of 1.0.

Since str fields infer to LevenshteinComparator by default, this is
the path most string fields take, and the divergence propagated
through the confusion matrix into corpus-level precision and recall.

Move the policy into BaseComparator as a template method: compare()
applies it once and delegates to a new abstract _compare() for
values that are actually present. Comparators implement _compare()
and never see None, so the policy is defined in one place and cannot
drift between comparators or be forgotten by a new one. Implementing
only compare() leaves the class abstract, so the mistake fails at
construction rather than silently bypassing the policy.

None is a missing value and no longer compares equal to an empty
string: (None, "") is 0.0 and (None, None) is 1.0, everywhere.

BREAKING (custom comparators): the extension point is now _compare()
instead of compare(). Subclasses must rename their compare() and can
delete any None handling it contains. Callers are unaffected --
compare(), __call__ and binary_compare() are unchanged.

Fixes #200

* docs,test: document the migration surface of the compare() rename

Review follow-ups on #200.

The CHANGELOG claimed an un-migrated comparator "stays abstract and raises
TypeError on instantiation, so the change surfaces immediately". That holds
only when subclassing BaseComparator directly. A subclass of a concrete
comparator inherits _compare(), so it constructs, and its legacy compare()
shadows the template method and bypasses the None policy without any error.

Replace the claim with the per-shape behavior, and note that the pre-fix
(None, "") -> 1.0 result cannot be inherited: the coercion was removed from
Levenshtein's algorithm rather than guarded, so an un-migrated subclass that
delegates upward gets the corrected score. Only a subclass that
reimplemented the coercion in its own compare() still returns the old value.

Add TestPreRenameSubclassMigration covering both shapes, and rename the
existing abstract-class test to say which shape it actually covers.

Comparators.md said "All comparators handle None values gracefully", which
predates the policy and says nothing about what it does. State the policy,
and note the template method / _compare split in the overview.

* feat(comparators): deprecate compare() instead of breaking it

The _compare() rename made pre-rename comparators fail: extending
BaseComparator directly and implementing only compare() left _compare
unimplemented, so the class was abstract and raised TypeError at
construction. At 0.6.0 with a Beta classifier that is too early for a hard
break, even though the migration is two lines.

Add a deprecation shim in __init_subclass__. A pre-rename subclass is left
exactly as written: its compare() still overrides the template method, so
its behavior is unchanged. The hook only fills the _compare slot when
nothing in the MRO provides one, so the class is not abstract, and warns
that the rename is needed. Reuses warn_once, so a bulk evaluation warns
once per class rather than once per document.

It deliberately does not rewire compare() to _compare(). Moving the method
breaks any subclass whose body calls super().compare(...): the parent would
no longer have a real compare, so the call lands on the template method,
which dispatches straight back to the function that made it. Both
pre-rename subclasses that existed in this suite were that shape.

An un-migrated comparator does not receive the None policy, since its
compare() shadows the template. The shim buys an upgrade path, not
correctness, so it is removed in 0.8.0 (#215).

Invert the abstract-class test to assert the shape still works and warns,
and cover the delegating, mixin, policy-bypass and migrated shapes. Reset
warn_once sentinels per test, mirroring the existing conftest fixture in
tests/structured_object_evaluator.

Contributes to #200

* docs: publish _compare docstrings and repair the docs build

Two documentation defects, both surfaced while reviewing #209.

The compare() -> _compare() rename moved every comparator's behavior
docstring onto a single-underscore method. mkdocstrings excludes those by
default (_DEFAULT_FILTERS = ["!^_[^_]"]), so the per-comparator Args,
Returns and Raises stopped being published: the comparator API reference
went from 8 compare entries to 1. Re-admit that one name rather than
dropping the default exclusion, so nothing else private leaks in.

Keeping the docstrings on _compare, rather than promoting them into the
class docstrings, is deliberate. The class docstrings already carry the
configuration matrix and are substantial (DateComparator is 34 lines);
what _compare holds is per-call signature reference, including
Levenshtein's TypeError on dict input, which belongs on the method.

Separately, `mkdocs build` was already failing on dev before this change:

    Could not collect 'stickler.comparators.BERTComparator'

BERTComparator and LLMComparator are exposed lazily through the package
__getattr__ so that importing stickler does not pull torch/transformers
or strands/boto3. griffe resolves identifiers statically, so it cannot
see a name that only exists at attribute-access time. Address both by
their defining module instead. Reproduced in the CI environment exactly
(`uv sync --group docs --frozen`), and confirmed present on origin/dev
and absent on origin/main, so this has been broken since the lazy-import
work landed and would have failed the next docs deploy from main.

The anchors for these two become stickler.comparators.bert.BERTComparator
rather than stickler.comparators.BERTComparator. preload_modules does not
avoid that, since the name still is not statically resolvable on the
package.

Also drop the stale None note and compare(None, None) example from
LLMComparator._compare's docstring. Both are true of the public compare()
but misfiled on the method whose contract is that it never receives None.

Docs and docstrings only; no behavior change.

Verified with `uv sync --group docs --frozen`: build clean, 12 _compare
entries, and the tier-system, IoU, tolerance and dict-TypeError text all
reachable in the rendered HTML. Suite 1632 passed, 10 skipped; ruff clean.

Closes #228

* fix(security): resolve ASH non-literal-import findings

ASH/semgrep reports three HIGH `non-literal-import` findings:

  src/stickler/__init__.py:112
  src/stickler/comparators/__init__.py:79
  src/stickler/structured_object_evaluator/models/comparator_registry.py:73

All three are false positives. Each site looks the caller's string up in a
module-level allowlist and imports the *value*, so the caller's string is
only ever a dict key and never an import path. An unrecognized name is
rejected before any import is attempted: AttributeError from the two
__getattr__ hooks, KeyError from the registry. Semgrep's taint rule cannot
see through the dict lookup, so it treats the local variable as attacker
controlled.

Verified by attempting injection through every public entry point. `os`,
`subprocess`, `os.path`, `builtins`, `../../etc/passwd` and a dotted
`stickler.comparators.llm` are all rejected at all three sites; only
allowlisted comparator names resolve.

Suppress with `# nosemgrep` naming the rule, plus a comment recording why
the finding does not hold. Confirmed the suppression is precise rather than
blanket: on a two-call fixture it silenced the annotated line and left the
unannotated one reported. Rule findings go 3 -> 0, and the ASH semgrep
scanner goes FAILED -> PASSED.

Add tests/test_lazy_import_allowlists.py so the property the suppressions
claim is enforced rather than asserted in a comment. The rejection tests
alone were not load-bearing: a deliberately vulnerable variant still passed
them, because they only checked which exception surfaced, not whether an
import happened first. Importing a module executes its top-level code, so
the spy tests monkeypatch `import_module` and assert it is never called for
a hostile name. Reverified against a truly vulnerable variant: 9 failures
with it applied, all passing after revert.

detect-secrets separately reports SECRET-HEX-HIGH-ENTROPY-STRING in
.ruff_cache/CACHEDIR.TAG. That is a local untracked artifact, gitignored and
absent from a CI checkout, so it is out of scope here.

No behavior change. Suite 1699 passed, 2 skipped; ruff clean.

* fix(hungarian): align the single-item fast path with the general path (#224)

calculate_metrics has a shortcut for len==1 on both sides that bypassed
the assignment algorithm, and it disagreed with the general multi-item
path in two ways:

1. A zero-similarity pair was dropped from matched_pairs, so downstream
   counted one FN + one FA. The general path keeps the pair, which
   StructuredListComparator classifies as FD. Same situation, different
   answer, purely because of list length.

2. The shortcut gated on `score > 0` rather than
   `score >= match_threshold`, so any non-zero similarity counted as a
   true positive however far below threshold it was. A single-item list
   could report a TP for a pair the general path calls an FD.

Both violated the contract already documented in
docs/docs/Advanced/hungarian-matching.md: the threshold splits matched
pairs into TP and FD without un-matching them, and only items with no
partner become FN or FA. The docs were right; the code was not.

The shortcut now always returns the assigned pair and counts tp only at
or above match_threshold. Whether an FD counts against recall stays the
recall_with_fd knob's job.

Adds tests/common/algorithms/test_hungarian_path_parity.py (19 tests)
pinning classification against list length -- the property that would
have caught this. Verified load-bearing: 6 fail with the fix reverted.

Two existing tests in test_simple_list_in_structured_list.py asserted the
old FN+FA behavior and now assert FD. One of them documents a separate
pre-existing bug it brushes against: an object whose only field is an
empty list gets list-path similarity 0.0 even though comparing the two
objects directly scores 1.0. That is untouched here and noted in the test
docstring.

Also documents the zero-similarity case explicitly in
hungarian-matching.md, since the table stated the rule but never said
that similarity magnitude cannot un-match a pair.

* fix(hungarian): address review findings on the fast-path alignment

Review of #225 raised eight findings. Four needed code or doc changes; two
were the fix working as documented and are recorded rather than changed.

No behavior change from this commit -- #224's classification fix is
unchanged. What changes is what the code claims and what the tests pin.

Findings addressed:

4. `match_threshold=0.0` makes a zero-similarity pair a TP, because the gate
   is `>=`. Not special-cased: the general path has identical semantics, so
   diverging would reintroduce exactly the path disagreement #224 fixed.
   Documented instead at both ends -- on `calculate_metrics`, and at the one
   construction site (`ComparisonHelper.compare_unordered_lists`) where `0.0`
   is used as a capture-all sentinel and only `matched_pairs` is read. Added
   a parametrised test pinning the boundary at n=1,2,3; the existing sweep
   started at 0.1, leaving it uncovered.

5. `test_empty_simple_list_within_structured_list` pinned `fd == 1` for two
   *identical* objects, which the same comparison scores `overall_score 1.0`.
   The 0.0-similarity-for-identical-objects bug behind that is out of scope,
   so the test now asserts only the #224 property (an assigned pair is not
   FN + FA) plus that the pair is counted exactly once, whichever way it is
   classified. Pinning `fd` would have cemented the contradiction and had to
   be undone when the similarity bug is fixed.

3. Documented the metric direction, which the CHANGELOG omitted. Because
   `recall_with_fd` defaults to False, FD is absent from the recall
   denominator, so reclassifying FN as FD *raises* default recall for an
   unchanged prediction: a document with three single-item list fields, one
   wholly wrong, goes from recall 0.667 to 1.000. Both numbers verified.
   Expanded the docs cross-reference from a pointer into a section with the
   two formulas, since this is the most consequential effect of the change.

8. Marked the `fp == n` / `fn == n` parity assertions as descriptive of
   today rather than the intended contract, so a later fix to `fn`
   semantics is not read as breaking a guarantee.

Recorded, not changed:

1. `fn`/`fp` from `calculate_metrics` are threshold-based (`len(list) - tp`),
   so a below-threshold pair is reported as matched *and* as fn/fp. Real, but
   pre-existing in the general path at every list length -- not introduced
   here. Documented in the Returns note, pointing at the downstream FD split.

2. A below-threshold 1-vs-1 list no longer emits sub-field entries. This is
   the documented threshold-gating rule, not a regression: on dev, a 2-vs-2
   all-poor list already returns `fields: {}`. The 1-vs-1 case produced a
   breakdown only because the dropped pair fired the unmatched branch, which
   is the same root cause #224 fixed. Attempting to emit zero-valued keys
   instead broke three tests that assert the opposite and contradicted
   docs/docs/Advanced/threshold-gated-evaluation.md, whose rationale is that
   below the threshold the pairing is spurious, so field-level numbers would
   be noise. Called out in the CHANGELOG as a result-shape change.

Also resolves the CHANGELOG conflict with dev and folds the #224 entry into
the existing Fixed section rather than adding a second one.

Suite 1663 passed, 2 skipped; ruff clean; mkdocs build clean.

* docs: correct the recall direction and document both changed result shapes

Re-review of #225 found three remaining issues, two of them introduced by
the revision that answered the first review. No behavior change.

C (medium) -- the paragraph I added to hungarian-matching.md stated the
recall relationship backwards:

    "Raising `match_threshold` moves pairs from TP to FD, which *raises*
     default recall while lowering precision."

Default recall is TP/(TP+FN). A TP->FD move decrements numerator and
denominator together and leaves FN alone, so recall can only fall or stay
equal. Verified exhaustively over tp0 in 1..4, fn in 0..3, moving k in
1..tp0 pairs: 0 cases where recall rose, 6 equal, 34 fell. Confirmed
end-to-end too -- thresholds 0.1/0.6/0.9 give recall 0.750/0.750/0.500,
monotonically decreasing.

The FN->FD move is the one that raises recall, which is what 1-vs-1 lists
actually saw. The two moves are now contrasted in a table so they cannot be
conflated again, and the recall_with_fd recommendation no longer rests on
the inverted premise.

A (high) -- the CHANGELOG documented only half the result-shape change. It
covered confusion_matrix.fields losing sub-field entries but not
`non_matches` moving the opposite way: from 2 object-level records
(false_negative + false_alarm, whole-object values, similarity_score None)
to one field-level false_discovery per sub-field, with scalar values and a
real score. A consumer grouping by non_match_type to count misses
silently reclassifies every single-line-item document.

Both shapes are now documented with before/after tables, and the KeyError
is named as a KeyError with the two ways to avoid it rather than the vaguer
"treat it as absent". Verified n=2 is byte-identical on head and base, so
this is the 1-vs-1 case becoming consistent, as with everything else in
#224.

Added tests/structured_object_evaluator/test_non_match_documentation.py
coverage: per-sub-field FD records parametrised at n=1,2,3, plus a direct
n=1-vs-n=2 record-shape comparison. This was untested. Verified
load-bearing -- restoring the pre-#224 fast path fails 2 of them.

B (medium) -- threshold=0.0 on a list field is user-reachable, and the two
sites documenting the 0.0 sentinel both framed it as internal, so a user
who sets it would not find the explanation. Because the gate is `>=`, every
pair clears a zero threshold, and a wholly wrong prediction reports
recall/precision/F1/accuracy all 1.000. That is the hardest direction to
notice. Added a warning to the threshold-gated-evaluation page, where
someone choosing a threshold will be reading, pointing at a small positive
value instead and distinguishing the internal sentinel use.

Filed the three deferred follow-ups as a merge condition: #231 (fd key on
calculate_metrics), #232 (delete the fast path), #233 (overall_score vs
confusion matrix reading different score sources).

Suite 1667 passed, 2 skipped; ruff clean. mkdocs emits 9 warnings, all
pre-existing and identical on dev.

* feat(thresholds): warn when a threshold is exactly 0.0

The threshold test is `>=`, so a threshold of 0.0 is satisfied by every
score including 0.0 itself. Every compared pair becomes a true positive and
a wholly incorrect prediction reports perfect precision, recall, F1 and
accuracy. Nothing raises and the numbers look ideal, which makes it the
hardest misconfiguration to notice.

Warn on exactly 0.0 rather than on "low" thresholds. Measured on a list
field, `["X"]` vs `["A"]`:

    threshold=0.0   tp=1  recall=1.000
    threshold=0.01  tp=0 fd=1  recall=0.000
    threshold=0.1   tp=0 fd=1  recall=0.000

It is a cliff, not a slope: 0.01 already classifies correctly. A check on
low-but-positive values would fire on legitimate configuration, since 0.1 is
a reasonable "accept weak matches" setting. `match_threshold` has the
identical cliff.

Both existing validation sites (field_converter.py:274,
structured_model.py:669) check `0.0 <= value <= 1.0`, so they explicitly
permit the one value that misbehaves, and the direct
ComparableField(threshold=0.0) path has no validation at all.

UserWarning rather than DeprecationWarning: this is a misconfiguration, not
a scheduled removal, and 0.0 stays legal for anyone relying on it. Routed
through the existing warn_once so a bulk run warns once per configured site
instead of once per document.

Three call sites are needed to cover the ways a threshold arrives:

- StructuredModel.__init_subclass__ for a field `threshold`
- the same hook for a `match_threshold` set in a class body, which is a
  plain class attribute and not covered by the field loop
- ModelFactory, twice, because `match_threshold` from a JSON config is
  assigned after create_model() and so is invisible to __init_subclass__.
  Without this a config-driven 0.0 would warn nowhere -- found by testing
  the path rather than assuming the class hook covered it.

Only the class that sets `match_threshold` warns; subclasses inherit the
attribute and would otherwise re-warn for a value they never chose.

Verified the internal capture-all sentinel stays silent: a normal
compare_with() builds HungarianMatcher(match_threshold=0.0) inside
ComparisonHelper.compare_unordered_lists deliberately, reads only
matched_pairs, and emits no warning.

test_the_behavior_the_warning_describes pins the misbehavior itself so the
warning cannot outlive its cause. It uses a two-item list on purpose: the
one-item case only exhibits the trap once #224 lands, since the single-item
fast path currently drops the pair, so asserting on n=1 would pass or fail
depending on merge order. Confirmed the file passes both on dev and against
a simulated merge with #225.

Closes #234

Suite 1660 passed, 2 skipped; ruff clean.

* fix(security): address review findings on the import allowlist tests

Review of #230 found five issues. The false-positive verdict on the three
semgrep findings holds; these are about the test file's guarantees being
weaker than claimed, plus one real robustness bug in source.

1 and 2 (medium) -- the test file's central claim was wrong. It asserted
that spying on `_il.import_module` was scoped per hook and would catch any
future regression. Neither held:

  - stickler._il, stickler.comparators._il and the registry's importlib are
    all the same module object, so patching one is process-global. Verified
    all three `is importlib`. The isolation comment was simply false, and
    `calls == []` would have recorded unrelated imports from anywhere in the
    process -- a latent flake keyed on import timing.
  - A vulnerable variant using `from importlib import import_module as f`
    and calling `f(name)` passed all 59 tests. The alias binds at module
    import time, before any patch. Reproduced exactly as reported.

Patching builtins.__import__ instead does not fix this either, which the
review did not note and I found by trying it: __import__ does not fire for a
module already in sys.modules, and every plausible hostile name (os, sys,
builtins, os.path, importlib) is already cached. That approach silently
passes for the same reason.

Replaced the spy with a canary module: a real file on sys.path whose body
appends to a witness list. Importing a module executes its top-level code,
and that side effect is the actual hazard, so observing the effect covers
every spelling -- import_module, a rebound alias, __import__, exec -- and
cannot be evaded by rebinding. Added test_the_canary_is_wired_up so the
guard cannot silently stop guarding.

Verified against both vulnerable variants: the standard import_module form
and the rebound-alias form each fail 2 tests now. The old suite caught only
the first.

3 (medium) -- real bug, not just a test issue.
ComparatorRegistry._builtin_is_available called find_spec bare, which raises
ValueError for a sys.modules entry with no __spec__ rather than returning
None. A MagicMock injection produces exactly that, so constructing a
registry while a mock was installed raised. Both package-level
_dependency_available helpers already carry this guard; the registry now
does too, with a regression test.

4 (low) -- confirmed the nosemgrep rule ID is correct rather than asserting
it. Removing a single suppression yields exactly one finding reporting
`python.lang.security.audit.non-literal-import.non-literal-import`, the ID
the annotations name. With all three in place: 0 findings.

Also corrected the mechanism named in the comments: the upstream rule is a
`patterns` match on a non-literal first argument, not `mode: taint`. The
conclusion was right, the reason given was not.

5 (low) -- added the explicit `import importlib.util`. The file relied on
stickler/__init__.py importing it as a side effect.

Suite 1678 passed, 2 skipped; also green at -n 4 and with the
mock-injecting tests/common/comparators conftest interleaved. ruff clean.
Semgrep still 0 findings.

* chore(deprecation): warn on any explicit ComparableField(aggregate=) use

The parameter has no effect -- aggregation moved to the comparison layer
in #94, and every node in compare_with() output already carries an
`aggregate` block. But only `aggregate=True` warned; `aggregate=False`
was silent, so those callers had no signal the parameter is going away
and would have met a bare TypeError when #226 removes it in 0.8.0.

Uses a sentinel default to tell "argument omitted" from "argument passed
as False", since False is both the historical default and a value a user
may pass deliberately. Only the explicit case warns. The message now
names the removal version and links the tracking issue.

field_converter.py forwards the sentinel when a config has no "aggregate"
key, so reconstructing a model from config does not emit a warning the
user cannot act on.

Also drops the no-op argument from 14 call sites in our own tests, which
were passing aggregate=False and would otherwise have filled the suite
with warnings about our own code. test_model_export keeps using the
parameter on purpose -- it pins that `aggregate` survives the export
round trip, which has to keep working until the field is removed -- with
the expected warning suppressed locally.

Known and deliberately deferred: to_stickler_config() and
to_json_schema() still write the `aggregate` key, so re-importing an
exported model emits one warning the user cannot avoid. Left alone here
rather than changing the serialized format one release before the
removal; it goes away with #226 in 0.8.0.

* chore(deprecation): stop warning on exported-config round trips

Review of #227 found one medium blocker and several cleanups. The blocker was
mine to own: I reported "2 remaining warnings, deferred to 0.8.0" and both
halves of that were wrong.

1 (medium) -- the sentinel forwarding did not fix the case it was written
for. The comment claimed forwarding _UNSET spared configs without an
"aggregate" key, but to_stickler_config() writes that key for every field, so
.get("aggregate", _UNSET) always found it and the default never applied. A
plain public round trip

    cfg = MyModel.to_stickler_config()
    StructuredModel.model_from_json(cfg)

emitted one DeprecationWarning per field, attributed to
field_converter.py:102 -- stickler's own frame, for a key the caller never
wrote and cannot remove. Under -W error::DeprecationWarning, which many
downstream projects set, that is a hard failure, not a warning. Verified: 3
warnings for a 3-field model, and DeprecationWarning raised under -W error.

The "2 warnings" figure was also a pytest dedup artifact -- pytest collapses
by (location, message) and there were 2 distinct locations. Real emission
count across the suite was 30.

Fixed by never reading a config's aggregate value at either call site.
Reading a config is not an explicit use of the parameter. The export format is
unchanged (the deliberate deferral), round trips are silent again, and the
suite goes from 30 emissions to 0.

2 (medium) -- docs still taught the parameter. dynamic-models.md presented
"aggregate": false in the canonical config block, so a user copying the docs
got warned for following them; that key and the x-aws-stickler-aggregate row
are gone. The Guides/Evaluation reference row now names the 0.8.0 removal and
links #226, which is the first place the aggregate=False cohort will look.

4 (low) -- test_mixed_aggregate_settings no longer tested anything mixed:
both fields became byte-identical once the argument was dropped, agg_cm was
computed and never asserted, and the comments still described a distinction
that no longer existed. Rewritten as
test_two_identically_configured_nested_fields_agree, which asserts the two
fields produce identical metrics and that each nested object is counted once.

5 (low) -- deleted test_aggregate_true_would_rollup: identical to the
module-level model once the flag was stripped, and it had no assertions, only
prints. Its docstrings were also mangled by an earlier automated edit
("Test that  would roll up nested metrics"). Fixed the stale file-level and
test-level docstrings the same way the sibling file was.

6 (low) -- restored the type signal on the parameter: Any ->
Union[bool, _Unset], so a checker still flags ComparableField(aggregate="yes").
Documented that identity detection is namespace-fragile (two import spellings
give two sentinels) and why the consequence is benign.

3 -- not changed. The is_aggregate branch in
confusion_matrix_calculator.py:157 is unreachable from compare_with() but does
alter results when called directly. Noted on #226 to be deleted with the
parameter, so the removal does not leave a branch keyed on a flag nothing can
set.

Also rebased onto dev and resolved the CHANGELOG conflict, folding the entry
under the existing Deprecated heading rather than adding a second one.

Suite 1641 passed, 2 skipped; 0 aggregate warnings; ruff clean.

* feat(schema): render StructuredModel's true shape for tool specs (#188)

A StructuredModel handed to a Strands agent as its structured_output_model
sent a materially degraded schema versus the plain BaseModel twin a
developer would otherwise write: `required` was empty (ComparableField's
default=None made every field optional in Pydantic's eyes), required types
widened to ["type", "null"], and comparison config (x-comparison) rode
into the tool spec -- 141% payload bloat that also showed the model the
rubric it was about to be graded against. "One class, two jobs" silently
sabotaged the extraction half.

The insight that makes this fixable without a breaking change: the
annotation already says what the user meant. `shipment_id: str` is
required; `notes: Optional[str]` is not. default=None is construction
tolerance (the engine builds instances from partial prediction JSON), not
a statement about the schema. So this changes only what
model_json_schema() emits:

- A custom GenerateJsonSchema derives `required` from the annotation: a
  field is required when its annotation is non-Optional and it carries no
  real default. Runs at generation time so nested models in $defs get the
  same treatment. Runtime construction is untouched.
- default: null is dropped from required properties (it contradicted the
  requiredness and schema flatteners read it as permission to null-widen).
- x-comparison is stripped recursively. Evaluation config is not part of
  the shape; to_json_schema() still carries it as x-aws-stickler-*.

description, examples, and alias still pass through -- those genuinely
help the model.

Verified through Strands' convert_pydantic_to_tool_spec: a configured
StructuredModel and its plain-BaseModel twin now produce identical
required lists, unwidened types, and near-identical payloads (243 vs 238
chars on the issue's example, down from 700). New
test_strands_tool_spec_parity.py pins both integration flows end to end,
including that ExactComparator config is still honored in compare_with()
and that partial predictions still construct. Schema-shape equivalents
that need no strands live in test_model_schema.py.

Existing tests that asserted x-comparison in model_json_schema() output
now assert the opposite and read the metadata from json_schema_extra the
way the engine does. HTML report threshold extraction verified unaffected.

Docs: the Strands guide now presents both flows explicitly -- plain
Pydantic + inference (flow 1) and one configured class driving agent and
evaluation (flow 2).

* docs: scope the model_json_schema round-trip claim

Rebasing off #217 (closed) left model-export.md describing `x-comparison`
metadata that model_json_schema() no longer emits, and left a side effect
undocumented.

Dropping the internal `extra_fields` property means
`from_json_schema(M.model_json_schema())` now parses where it previously
raised ValueError. That is not a round trip: the rebuilt model carries
default thresholds, weights and comparators, because a shape-only schema does
not describe them. Verified on this branch -- the call succeeds and the
configuration is gone.

That silent-loss behavior is exactly why #217 was closed, so it is named
rather than left for someone to discover from drifting metrics. The docs keep
"Round-trip: No" and now say what actually happens and which two methods to
use instead. Tracked in #214 for 0.8.0.

Also updated the method table and example, which pointed readers at
`schema["properties"]["name"]["x-comparison"]` -- a key that is no longer
there.

Suite 1650 passed, 2 skipped; mkdocs build clean.

* feat(thresholds): correct the warning's claims and locate it honestly

Review of #236 found seven issues. All reproduced before changing anything.
Five were the warning saying something untrue or unfindable; two were real
behavior bugs in the warning itself.

1 (medium) -- the match_threshold message asserted an outcome that does not
occur. match_threshold is only read for List[StructuredModel] element
matching, so on a standalone model the value is inert. Verified: same model at
None, 0.0 and 0.7 gives identical output (tp 0, fd 1, recall 0.0, score 0.0),
yet the warning claimed "every compared pair is counted as a true positive".
The hook cannot know at class-definition time whether the class will be a
list element, so the message now states the condition ("if this model is
compared as a list element") rather than asserting the result. A warning that
is wrong where it fires trains people to ignore the one that matters.

Also removed the inert `match_threshold = 0.0` from
test_structured_model_comparators.py's FuzzyVariantsModel, which is compared
directly and never as a list element -- the suite was itself an example of the
false positive.

2 (medium) -- the factory keyed warn_once on model_name, which defaults to
"DynamicModel", so two different anonymous configs collided and only the first
warned. Verified 1 warning for 2 misconfigured configs. Now keyed on class
identity. Added a `dedup_key` parameter rather than folding the id into
`context`, so an internal identity does not leak into user-visible text --
the first attempt printed "DynamicModel#4355291632 sets ...".

3 (medium) -- stacklevel=4 pointed at <frozen abc>:106 for the class path and
at stickler's own structured_model.py:485 for the config path. The frames are
warn_once -> warn_if_threshold_is_zero -> __init_subclass__ ->
ABCMeta.__new__ -> ModelMetaclass.__new__ -> user code, with a C frame not
counted, and the two call sites sit at different depths, so no constant
reaches user code. Dropped to stacklevel=1, which is honest about pointing at
stickler, and the message names the exact configuration site. A misleading
location is worse than an obviously internal one, and it silently breaks
module-scoped warning filters.

4 (low) -- bool passed the numeric guard: `match_threshold = False` reported
"sets match_threshold=0.0", naming a value the user never wrote. bool is an
int and False == 0.0. Now returns early for bool; a wrong type is a different
problem.

5 (low) -- the link pointed at threshold-gated-evaluation.md, whose only
mention of zero is "raw similarity score (0.0 -- 1.0)". A reader who followed
it learned nothing. Points at issue #234 until #235 adds a section, and the
test now asserts the specific URL rather than just "https://" in the message.

6 (low) -- the List[StructuredModel] guard interpolated the rejected value
into its remedy, so `threshold=0.0` produced "Set 'match_threshold = 0.0'" --
instructing the user into the exact state this PR warns about. Zero now gets
a distinct remedy pointing at the explanation; non-zero is unchanged.

7 (low) -- the message claimed perfect "precision and recall". Recall holds
only for equal-length lists. Verified 2 GT vs 1 pred at match_threshold=0.0:
precision 1.0, recall 0.5, because the unpaired item is still an FN. Claims
precision only now, with tests pinning both the equal-length and
unequal-length cases so the wording cannot drift back.

Suite 1668 passed, 2 skipped; ruff clean. The 3 remaining zero-threshold
warnings all come from tests that set 0.0 deliberately.

* fix(thresholds): name the invariant, and stop the dedup key flooding stderr

Adversarial verification of bc3a017 found that two of its own "fixes" were
wrong. Both were mine, and both were worse than what they replaced.

1. The precision-only claim was over-claiming in the mirror direction.

bc3a017 dropped "perfect recall" because an unmatched ground-truth item is
still an FN (2 GT vs 1 pred -> recall 0.5). That reasoning was right and was
applied to exactly one of the two directions. Flip the lists: an unmatched
prediction is still an FA, so 2 GT vs 3 pred gives precision 0.667. Swept
36 list-length combinations: precision was 1.0 in only 20 of them. The scalar
field case fails the same way -- a hallucination (gt None, pred set) is an FA
and a miss (gt set, pred None) is an FN, neither a TP.

So the surviving claim was as false as the one it deleted, and false in the
direction that matters: a user with more predictions than ground truth sees
imperfect precision, concludes the warning does not describe their situation,
and keeps the broken threshold.

Both messages now name the invariant instead of a metric. FD means "compared
and scored below threshold" and nothing scores below 0.0, so no false
discovery is possible. Measured exhaustively at 0.0: FD was 0 in all 36
list-length and all 256 scalar-value combinations. Tests pin the invariant
across lengths and deliberately assert that precision is NOT always perfect,
so the message cannot drift back to claiming it.

2. Keying dedup on id(DynamicClass) defeated warn_once entirely.

A new class object is created per factory call, so loading the same config in
a loop warned every time: 200 loads -> 192 warnings, with the process-global
_warned set growing to 192 entries and never shrinking. That is precisely the
stderr flood warn_once exists to prevent, in the path most likely to loop (a
service building models per request). The existing warn-once test only
re-instantiated one statically declared class, so it covered __init_subclass__
and never touched the factory path where the regression lived.

Root cause of the original collision was that model_name defaults to
"DynamicModel", so keying on the name alone silenced later anonymous configs.
Fixed by naming the config rather than the object: _config_identity() appends
the sorted field names for anonymous models. That is stable across repeated
loads of one config and distinct between configs, so it serves as both the
message text and the key -- the separate dedup_key parameter is gone.

3. Identical message text was being swallowed by Python's own registry.

Distinct anonymous configs previously produced byte-identical text
("DynamicModel sets match_threshold=0.0..."). __warningregistry__ is keyed on
the message, so under the default once-per-location action the interpreter
printed only the first -- losing the second misconfiguration even though
warn_once had approved it. Verified: 2 anonymous configs -> 1 printed before,
2 after. Naming the fields fixes the reader's problem and this one together.

Verified independently of the above: no well-configured public path warns
under -W error::UserWarning (compare_with, to_stickler_config ->
model_from_json, to_json_schema -> from_json_schema, import stickler,
stickler.evaluate), and the new dedup test fails if the id() key is restored.

Suite 1671 passed, 2 skipped; ruff clean.

* test(thresholds): close a tautological assertion and cover every entry point

Mutation-tested each guard in the warning to confirm the tests are
load-bearing. Four of five mutations failed a test as they should; one did
not, which is a test defect worth fixing rather than a source problem.

Breaking THRESHOLD_DOCS_URL to a useless value passed all 36 tests. The
assertion was `THRESHOLD_DOCS_URL in message`, which compares the constant to
itself and holds for any value. Now asserts the literal target as well, so a
URL that explains nothing fails. Re-verified: the same mutation now fails.

The four that were already sound, for the record: removing the bool guard,
widening the check from `== 0.0` to `<= 0.05`, restoring the "perfect
precision and recall" claim, and making the match_threshold message
unconditional each fail a test.

Also enumerated every public way to configure a threshold and asserted the
result, rather than assuming the three call sites covered them:

  class body field threshold        warns
  class body match_threshold        warns
  model_from_json field             warns
  model_from_json match_threshold   warns
  from_json_schema field            warns
  from_json_schema match_threshold  warns
  create_model_from_fields          warns
  subclass setting its own 0.0      warns
  inherited match_threshold         silent (correct - not the subclass's choice)
  post-hoc setattr                  silent (known gap)

from_json_schema and create_model_from_fields had no coverage; they work, but
nothing pinned them. Added tests for both.

The post-hoc `Model.match_threshold = 0.0` gap is inherent: the checks run at
class creation and config conversion, so a later assignment is invisible.
Catching it needs a metaclass __setattr__, which is disproportionate for a
path nobody writes deliberately. Documented in the docstring and pinned by a
test framed as a known limitation, so if it ever starts warning the test says
to update the docs rather than treating it as a break.

Suite 1676 passed, 2 skipped; green at -n 4; ruff clean. Re-confirmed no
well-configured public path warns under -W error::UserWarning.

* fix(thresholds): share one dedup identity across both warning paths

Addresses findings 8 and 9 from the re-review of bc3a017.

Finding 8 (id() key is recycled after collection) was already fixed in
1b797fd, which landed after that review was written. Worth recording that
the reviewer found a case my own fix reasoning had missed: I knew id() was
unstable across calls, but not that CPython *reuses* the address once a class
is freed, so a batch loop that builds, uses and drops each model collides on
the same key. Their measurement was 19 warnings from 50 configs. Verified on
the config-content key with an explicit del + gc.collect() each iteration:
50 of 50 warn. Added a test in that shape -- the previous one held every
class alive simultaneously, which is exactly what hid the bug.

Finding 9 is new and real. The field-level threshold check still keyed on
f"{cls.__name__}.{field_name}", which is "DynamicModel.amount" for every
anonymous config, so a second config with a zero-threshold field of the same
name was silent. Field names like amount, date, id and name recur constantly
across document schemas, so this is a common shape rather than an exotic one.
Reproduced: 2 configs sharing a zero-threshold `amount` gave 1 warning.

Fixed by threading the same identity scheme through both paths. Moved the
helper out of ModelFactory into threshold_helper as `model_identity()` so the
two modules share one implementation rather than each having its own notion of
what names a model. Both paths now give 2 of 2, with distinct keys.

Verified load-bearing: restoring the bare cls.__name__ keying fails the new
field-name test.

Suite 1678 passed, 2 skipped; ruff clean. Repeated loads of one config still
warn once with a bounded _warned set, so closing these gaps did not reopen the
flood.

* fix(registry): mirror the package helpers when probing a dependency

Addresses findings 6, 7 and 8 from the re-review of 1969dc7.

6 (medium) -- the guard I added contradicted its own docstring. It claimed to
be "the same guard the two package-level _dependency_available helpers already
carry", but those check sys.modules first and return True for a
present-but-specless module, while mine returned False for exactly that case.
Same exception caught, opposite verdict.

The consequence is two public entry points disagreeing in one process. With
strands mocked:

    stickler._dependency_available('strands')   True
    registry._builtin_is_available(llm spec)    False
    hasattr(stickler, 'LLMComparator')          True
    registry.get('LLMComparator')               KeyError: Unknown comparator

So stickler.LLMComparator resolves while the config-driven path used by
field_converter reports the comparator does not exist. Limited blast radius --
_global_registry is built during import stickler, before any test mock lands --
but worth fixing rather than documenting, since the divergence was accidental.

Now consults sys.modules before probing, so both agree. My test had pinned the
divergence as intended ("the strands-gated comparator is simply absent rather
than taking construction down with it"); it now asserts the agreement instead.

7 (low) -- one bare find_spec remained, in test_allowlisted_name_still_resolves:
the same failure the commit had just fixed in src/, sitting in the test that
guards it. Uses stickler._dependency_available now. Reproduced the reviewer's
mock-leak scenario (module-scoped MagicMock injection alongside a copy of the
file): 1 failure before, 38 passed after.

8 (low) -- recorded in the module docstr…
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.

[CHORE]: slim the core dependencies, drop dead psutil, and lower the Python floor to 3.10

2 participants