Skip to content

feat(469): evaluate System One decision models - #540

Draft
sromoam wants to merge 1 commit into
devfrom
feat/469-decision-models
Draft

sromoam wants to merge 1 commit into
devfrom
feat/469-decision-models

Conversation

@sromoam

@sromoam sromoam commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Pull Request

Issue Reference

Closes #469

Description of Changes

Adds first-class evaluation for typed decision models that answer System One questions (Strands Decider, OpenJev, Jev). The questions sent to the model are the eval schema; answers are scored as returned.

Triage = model_from_questions(questions, weights={"queue": 2.0})
ev = BulkStructuredModelEvaluator(target_schema=Triage)
ev.update(Triage(**gold), Triage.from_json(from_systemone(response)))
res = ev.compute()
res.decision_metrics["fields"]["queue"]["calibration"]

Changes Made

  • stickler.decisions: Choice, Score, Noul fields; answer normalisation; DecisionAccumulator; numpy-only metrics; accept_or_escalate(); confidence_intervals(). Design notes in src/stickler/decisions/README.md.
  • stickler.integrations.systemone: model_from_questions(), from_systemone(). No dependency on typesafe_sdk or strands-decider.
  • Core changes (highest-risk part of the diff, worth the closest look):
    • StructuredModel.from_json converts System One answers on decision fields to rich values before validation.
    • ComparisonEngine and StructuredModel.compare(): a decision field with gold None (not asked) carries no weight, adds no confusion-matrix counts, and gets no field_comparisons row or field_scores entry. A document with only unasked decisions scores 1.0, as compare() already did.
    • BulkStructuredModelEvaluator installs DecisionAccumulator when target_schema has decision fields; JSONL writes models as dicts only for such schemas.
    • StructuredModel.__pydantic_init_subclass__ rejects a non-Optional decision field.
    • ProcessEvaluation.decision_metrics (new optional field).
  • HTML report: Decision Metrics section, inline SVG, everything escaped. Byte-identical report when there are no decision metrics.
  • Docs and examples: "Evaluating decision models" guide, Evaluate_A_Decider_Model.ipynb, and a 100-ticket fixture in examples/notebooks/fixtures/systemone/ with record_systemone.py.

Why These Changes Are Needed

See #469. Flattening System One answers into rich values loses the distribution, invites wrong calibration (noul is P(yes), and the answer's confidence is not P(correct)), and gives extraction F1 where decision users need per-class, ordinal and accept-or-escalate metrics.

Where this differs from the issue text

  • Confidence intervals are confidence_intervals(res) after compute(), not a ci=True flag (compute() takes no arguments).
  • Decision fields must be Optional (None means not asked or not answered) and do not support alias.
  • Comparing two runs stays out of scope ([FEATURE]: Compare paired evaluation runs by document ID #303).

Testing

  • Unit tests added/updated: tests/decisions/ (metrics against sklearn, end to end, nested and list fields, fixture, review regressions), tests/integrations/test_systemone.py (contract tests pinned to Decider's published shapes), tests/reporting/html/test_decision_metrics_section.py (including injection attempts).
  • Integration tests added/updated
  • Manual testing completed: notebook executed top to bottom; models without decision fields compared byte for byte against dev (scores, confusion matrix, field_comparisons, non_matches, bulk output, warnings, HTML report).
  • All existing tests pass: 4254 passed, 3 skipped, 1 xfailed. tests/test_docs_build.py: 77 passed.

An independent review of the diff found 10 issues (a stale path cache on forward references, a cache leak, missing-decision gaps in two list shapes and the JSONL round trip, unasked fields still counted in the confusion matrix, and others). All are fixed with regression tests in tests/decisions/test_review_regressions.py.

Reviewers

@digalaviz

Checklist

  • Code follows the project's coding standards
  • Self-review of code completed
  • Documentation updated (if applicable)
  • CHANGELOG.md entry added under [Unreleased]
  • Tests added/updated for new functionality
  • All CI checks are passing
  • Ready for review

Additional Notes

  • The fixture's responses are synthetic placeholders. provenance.json says so and every score cell in the notebook repeats it. They will be replaced with real Strands Decider outputs recorded with record_systemone.py. Do not cite the notebook's scores.
  • from_json overhead for models without decision fields: about 1.6 µs per call on a small model.
  • Release target is still open: this is additive, so semver would call it a minor release.

Add stickler.decisions: Choice, Score and Noul fields that score typed
decision models (Strands Decider, OpenJev, Jev) against gold labels.

- The questions sent to the model are the eval schema:
  stickler.integrations.systemone.model_from_questions builds the model,
  and from_systemone passes a response's answers through.
- from_json reads each System One answer into its predicted value and
  confidence, the probability of the predicted answer. Only
  probabilities/noul are read; choice, confidence and legend are not.
- BulkStructuredModelEvaluator adds a DecisionAccumulator on its own when
  the schema has decision fields, at any depth. Results land in
  ProcessEvaluation.decision_metrics: correctness and calibration per
  field, by question type.
- A decision field whose gold is None was not asked: it carries no
  weight and adds no counts, comparisons or confidence pairs.
- accept_or_escalate() and confidence_intervals() (bootstrap by
  document) run on the stored records after compute().
- The HTML report gains a Decision Metrics section (inline SVG
  reliability diagram and risk-coverage plot).
- A 100-ticket System One fixture with a recorder script, a guide, and
  an example notebook. The committed responses are synthetic placeholders
  until recorded.

Models without decision fields produce byte-identical results.
@sromoam
sromoam requested a review from digalaviz November 4, 2026 18:38
@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-11-04T18:42:06+00:00
  • Time since scan: 3 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-11-04T18:39:01+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 9 0 0 6885 0 9 FAILED MEDIUM (global)
cdk-nag 0 0 0 0 0 0 0 PASSED MEDIUM (global)
cfn-nag 0 0 0 0 0 0 0 MISSING MEDIUM (global)
checkov 0 0 0 0 0 0 0 PASSED MEDIUM (global)
detect-secrets 0 1 0 0 0 0 1 SKIPPED MEDIUM (global)
grype 0 0 0 0 0 0 0 MISSING MEDIUM (global)
npm-audit 0 0 0 0 0 0 0 PASSED MEDIUM (global)
opengrep 0 0 0 0 0 0 0 MISSING MEDIUM (global)
semgrep 3 1 0 0 0 0 1 FAILED MEDIUM (global)
syft 0 0 0 0 0 0 0 MISSING MEDIUM (global)

Top 6 Hotspots

Files with the highest number of security findings:

Finding Count File Location
2 tests/comparators/test_anls_leaf_semantics.py
2 .ash/ash_output/converted/jupyter/examples__notebooks__Evaluate_A_Decider_Model__ipynb-converted.py
2 .ash/ash_output/converted/jupyter/examples__notebooks__Strands_Evals_FCC_Live_Agent__ipynb-converted.py
2 examples/notebooks/fixtures/systemone/record_systemone.py
2 tests/structured_object_evaluator/test_rollup_node_semantics.py
1 tests/test_readme_examples.py

Detailed Findings

Show 11 actionable findings

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

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

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

Code Snippet:

Secret of type Hex High Entropy String detected

Finding 2: B310

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B310
  • Location: .ash/ash_output/converted/jupyter/examples__notebooks__Evaluate_A_Decider_Model__ipynb-converted.py:351-353

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

Code Snippet:

)
    with urllib.request.urlopen(req, timeout=120) as resp:
        return json.loads(resp.read().decode())

Finding 3: B310

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

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

Code Snippet:

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

Finding 4: B310

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B310
  • Location: examples/notebooks/fixtures/systemone/record_systemone.py:45-47

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

Code Snippet:

)
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return json.loads(resp.read().decode())

Finding 5: B108

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

Description:
Probable insecure usage of temp file/directory.

Code Snippet:

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

Finding 6: B307

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

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

Code Snippet:

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

Finding 7: B307

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

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

Code Snippet:

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

Finding 8: B102

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

Description:
Use of exec detected.

Code Snippet:

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

Finding 9: B310

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B310
  • Location: .ash/ash_output/converted/jupyter/examples__notebooks__Evaluate_A_Decider_Model__ipynb-converted.py:351-353

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

Code Snippet:

)
    with urllib.request.urlopen(req, timeout=120) as resp:
        return json.loads(resp.read().decode())

Finding 10: B310

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

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

Code Snippet:

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

Finding 11: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected

  • Severity: HIGH
  • Scanner: semgrep
  • Rule ID: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected
  • Location: examples/notebooks/fixtures/systemone/record_systemone.py:46

Description:
Detected a dynamic value being used with urllib. urllib supports 'file://' schemes, so a dynamic value controlled by a malicious actor may allow them to read arbitrary files. Audit uses of urllib calls to ensure user data cannot control the URLs, or consider using the 'requests' library instead.

Code Snippet:

with urllib.request.urlopen(req, timeout=timeout) as resp:

Report generated by Automated Security Helper (ASH) at 2026-11-04T18:42:07+00:00

@digalaviz digalaviz self-assigned this Nov 8, 2026

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

First pass on 6320fbc: the feature matches #469 in substance and leaves existing results unchanged, but I'd split it before approval, and a few answer-parsing paths should fail instead of defaulting.

What I checked. Each rule in #469 against the code; the full suite on this head; dev's own tests against this src; a compare_with result for a model without decision fields hashes identically on both trees; timings for compare_with, from_json and bulk update are within noise; no new dependencies; the HTML section escapes option keys, field names and doc ids (a </script> payload renders as text).

Blocking

  1. Scope. This ships all three phases of #469 in one +5981 PR. Phase 1 (systemone, Choice/Noul, their metrics, contract tests, notebook) reviews on its own. The HTML section (~657 lines with its test), accept_or_escalate (174), confidence_intervals (44+) and the recorder/generator scripts (400) could follow. Can we split it that way?
  2. Silent defaults in answer parsing. A bare label answer ({"queue": "billing"}) is accepted as one-hot, so it enters calibration with confidence 1.0. On the dict path, from_systemone({"answers": [1, 2]}) returns [1, 2] instead of raising, while the object path checks the type. Both should raise AnswerError.

Non-blocking

  1. _score_key_index uses str.isdigit() (normalize.py:69): "٢" is read as level 2 and "²" raises ValueError rather than AnswerError. With criteria ["2", "1", "0"], the key "2" is read as a level number without the ambiguity error the issue describes.
  2. Every ProcessEvaluation and save_metrics() file now carries decision_metrics: null, and ReportConfig gains include_decision_metrics. The CHANGELOG says other fields are unchanged; worth one line for consumers that check key sets.
  3. A user accumulator named "decision_metrics" is picked up as decision metrics and handed to the reporter (bulk_structured_model_evaluator.py:674). Reserve the name or key off the accumulator type.
  4. The fixtures are synthetic, and provenance.json says so clearly; #469 asks for recorded outputs with model and version. Fine for offline tests, but the notebook should not present those numbers as a model's results until a recording replaces them.
  5. Notebook cell 2's committed output prints a local temp path; clear or regenerate it.
  6. renormalise only for float drift vs the max(0.01, k * 5e-4) tolerance: the comment explains the rounding case, so I read this as intended. Worth aligning the issue text or the guide.

Notebook and recorder

I ran all 15 code cells offline in order on this head: no errors, and 14 of 15 outputs match the committed ones (the 15th is the path in item 7). Re-running make_synthetic_responses.py reproduces responses.jsonl and provenance.json byte for byte, and the notebook follows the #469 method (legend and confidence ignored, gold None, missing answers, tau as an input).

  1. Blocking: one more item I'll send you directly rather than here.
  2. Blocking: a recording where every answer comes back empty exits 0 and writes "synthetic": false, so it would pass as a real measurement. Fail the run when a ticket, or the run, has no answers.
  3. provenance.json records the endpoint URL, so a private host or a token in the URL would be committed with the fixture. Record the model and version only.
  4. A refusal (the HTTP 422 case #469 cites) aborts the recorder and raises in the live cell, so the missing-answer rule never applies to a real model. Record it as missing.
  5. Cell 21: "Lower is better for all of them" follows auroc_label, where higher is better.
  6. Cell 20 reads q from cell 18, which cells 12 and 30 overwrite as a loop variable; re-running cell 12 then 20 raises TypeError.
  7. Cell 26 formats tau with :.3f, while the guide says tau_at_target can be None.

Versioning. This adds public API (stickler.decisions, stickler.integrations.systemone), so the release that carries it is 1.1.0.

Not verified: rendering in a Jupyter kernel (I executed the cells as a script), and the contract tests against the real decider schema.

@sromoam
sromoam requested a review from harrycav November 16, 2026 21:42
@digalaviz

Copy link
Copy Markdown
Contributor

@sromoam in my opinion this fits 1.1.0 better than 1.0.2. It conflicts with dev and touches 45 files, and it adds new public packages (stickler.decisions, stickler.integrations.systemone), which fits a minor release. #469 would move to 1.1.0 with it. The points from the first pass on 6320fbc still apply: split the change before approval, and make the answer-parsing paths that default fail instead.

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

Thanks Spencer, this is a really useful direction. Decision models have a growing audience: Decider passed 1.2k stars in about 7 weeks. Their users need something stickler is well placed to give: field-by-field evaluation of multi-question pipelines, and in particular "how far can I trust this model on its own?"

I reviewed this as a design first and code second. Short version: yes to supporting decision models, and I'm happy for most of this to ship, with a few changes first. Details below.

Bigger points

1. Keep it out of stickler's core.
Right now the new field types need edits to JSON loading, ComparisonEngine, StructuredModel.compare and the bulk evaluator. That means every user runs the new code paths, even if they never use decision models. I'd suggest:

  • keep the fields as normal ComparableFields
  • have from_systemone() produce rich values carrying the probabilities
  • put the metrics in an opt-in DecisionAccumulator, the way BBoxMAPAccumulator works

Same features, with zero change for everyone else.

2. Mark it experimental.
Once it's in 1.x, every public name (Choice(), accept_or_escalate(), the result-file fields) becomes a compatibility promise. We don't know yet what users will need, so labelling it experimental (in the docs or a namespace) keeps us free to change it without a breaking release.

3. Target 1.1.0, not 1.0.2.
It's a new feature, so a minor release fits semver better than a patch. That also gives time for the fixes below. #469 is still on the 1.0.2 milestone: shall we move it?

4. Make accept-or-escalate the headline.
It's the question these teams actually ask: "if I auto-accept above X, how much is handled automatically, and how much of that is wrong?" The System One docs (docs.typesafe.ai) are built around exactly this (act / confirm / escalate). I'd lead the docs and notebook with it, with calibration metrics underneath as the explanation. Could it be built on the existing ErrorCaptureAtBudgetMetric rather than as a second implementation?

5. Show it on real recorded outputs.
The fixture says it's synthetic and "NOT a recording". Generated test cases are fine, but we should run a real model on them and save what it actually outputs. We should also avoid datasets the model was trained or calibrated on (banking77, clinc150, PubMedQA, SNLI, FEVER, CUAD, massive_intent and so on), or the results will look better than they really are.

6. Measure what users actually threshold on.

  • The confidence field. The docs tell users to set cut-offs on confidence, which is the rescaled top probability, not the top probability itself. The accept-or-escalate table should be able to use it.
  • The companion yes/no check. The docs teach a "should I trust this answer?" Noul alongside the main question. It would be great to score that check against whether the main answer was right.
  • The model version. Record it per result, so you can compare across vendor updates.

7. Avoid duplicates.
ECE and Brier already exist in stickler, so I'd reuse them rather than add second versions. I'd also leave overall_score and weights untouched by decision fields.

Must fix before merge

  1. AURC improves when the model refuses to answer (escalate.py:166). The curve only uses answered rows. In my test, 4 answers gave AURC 0.1146, and the same 4 plus 4 refusals gave 0.0573. Refusals should count as errors, or be reported separately.
  2. An answer with no probabilities counts as 100% confident (accumulator.py, _probs). This skews calibration toward "overconfident". I'd exclude those rows from the confidence metrics, or flag them.
  3. The exported schema can't be loaded back. x-stickler-decision doesn't round-trip, and it breaks the x-aws-stickler- naming convention. A round-trip test would catch this.

Smaller fixes

  • Noul precision/recall/F1 shows 0.0 when there are no positive cases. That should be "undefined" (0.0 reads as "terrible").
  • Level names like "1", "2", "3" can be mistaken for list positions. Reject them or document how they're read.
  • Small samples mislead: a perfectly calibrated model shows ECE of about 0.23 at n=20. A warning below a minimum n would help.
  • Confidence intervals are computed on counts rather than rates.
  • Saved files contain decision_metrics: null, and records are written twice.
  • One very wrong row can dominate log loss. Clip it, or report the median too.
  • Name which AURC convention is used in the docstring.
  • The risk-coverage curve is implemented twice (data_extractors.py:330-345 and escalate._curve). One would be better.

After it ships

Ideas to get it adopted:

  • the real-output notebook
  • a one-line CLI command
  • a listing on awesome-jev
  • a short docs PR to Decider (its issues #43–45 ask for evaluation help)
  • reading JevBench's format

On Strands Evals, decision fields already work there as normal fields, so I think a docs recipe is enough for now.

Happy to pair on any of this, especially the accumulator refactor or the recorded-output notebook.

@sromoam sromoam added this to the 1.1.0 milestone Nov 18, 2026
@parmidaatg

Copy link
Copy Markdown

Amazing Job, Thank you so much. Here are a few fixes that would be great to have.

Summary

The metric definitions are sound, and they match an independent implementation closely. I scored 2 × 2,270 real
yes/no decisions (BoolQ test questions from two systems: an LLM giving verbalized probabilities and a model
read out from log-probs) with this PR and with a separate implementation. These agree to 1e-6:

  • accuracy and coverage;
  • auroc_label;
  • ece_mass with 5 bins, before and after Platt scaling fitted outside the library;
  • brier, which is half the two-class Brier, as expected;
  • log_loss;
  • coverage_at_target;
  • the bootstrap bounds of accuracy.

Tie handling in ece_mass and in the accept_or_escalate cuts is the right call. The other implementation had to
be changed to match it.

Four issues change reported numbers and should be fixed before merge. One is a floating-point bug in how yes/no
confidences are derived. The other three are definitions (AURC with missing answers, CI bins, document identity).
The rest are suggestions, nits, and two follow-ups for after this PR. Comparing runs is out of scope as the PR
says (#303), so it isn't raised here.

# Comment Severity
1 Yes/no confidences derived as 1 − P(yes) break ties should fix
2 AURC improves as answers go missing should fix
3 confidence_intervals ignores the evaluator's n_bins should fix
4 A reused doc_id silently becomes a new document should fix
5 One malformed answer rejects the whole document suggestion
6 Balanced accuracy, and recall for "no" suggestion
7 Policy for answers that omit options suggestion
8 Percentile intervals for ece_mass can exclude the estimate suggestion
9 confidence_intervals bounds every numeric leaf nit
10 Per-field taus in accept_or_escalate nit
11 Ship py.typed nit
12 Answers with a stated confidence, or a label only follow-up
13 Options that change per request follow-up

Should fix

1. Yes/no confidences derived as 1 − P(yes) break ties

src/stickler/decisions/normalize.py:109 stores a yes/no answer as [1.0 - p_yes, p_yes], and
arrays.py:74 takes the confidence as the row maximum. For a "no" answer, the confidence is therefore
1 - p_yes. In binary floating point that often isn't the number the model meant. For example
1 - 0.43 == 0.5700000000000001. A "yes" at 0.57 and a "no" sent as P(yes) = 0.43 express the same confidence,
but they no longer tie.

This happens for clean inputs: for 8 of the 49 two-decimal confidences from 0.51 to 0.99, 1 - (1 - c) != c.

Repro:

Doc = model_from_questions({"q": {"type": "noul", "instructions": "?"}}, model_name="Doc")
ev = BulkStructuredModelEvaluator(target_schema=Doc)
ev.update(Doc(q=True), Doc.from_json({"q": {"type": "noul", "noul": 0.57}}), doc_id="a")  # yes at 0.57, right
ev.update(Doc(q=True), Doc.from_json({"q": {"type": "noul", "noul": 0.43}}), doc_id="b")  # no at 0.57, wrong
ev.compute().decision_metrics["fields"]["q"]["calibration"]["auroc"]  # 0.0; a tie should give 0.5

Why it matters:

  • auroc (average ranks), ece_mass (never splits a tie) and the accept_or_escalate cuts (only between distinct
    confidences) all rely on exact equality.
  • Models that state round confidences produce large tie blocks. On the 2,270-item run, all correctness flags were
    identical and confidences differed by at most 1.1e-16 from the reference, yet auroc moved by about 2.5e-4 and
    its interval bounds by about 3e-4.
  • The direction depends on whether the "yes" or the "no" answers in each tie block are more often right, which is
    arbitrary.

Suggest: snap confidences to a fixed precision before any tie-sensitive step, for example
np.round(conf, 12) in DecisionArrays.conf. Add a test where a "yes" at c and a "no" at 1 − c must tie,
for every two-decimal c.

2. AURC improves as answers go missing

In _curve, src/stickler/decisions/escalate.py:55–70, coverage is divided by every asked decision
(n_total), but the curve is drawn over answered decisions only (line 166 passes conf[answered]). So the curve
ends at coverage = answered share, and the area is scaled down by that share.

Repro: 400 yes/no documents, then the same answers with every second answer removed.

accuracy AURC (lower is better) coverage_at_target (0.9)
no missing answers 0.912 0.0189 1.000
half missing 0.458 0.0111 0.500

Why it matters: AURC is used to rank systems, and a system that times out or refuses more often gets a better
AURC. coverage_at_target handles this correctly, because a missing answer is never accepted. AURC disagrees with
it, and with the PR's own rule that a missing answer counts as wrong.

Suggest: pick one definition and document it. Two candidates:

  • aurc over answered decisions, with coverage relative to answered: the standard selective-prediction
    definition.
  • An aurc where missing answers are accepted last as errors, so the curve always runs to coverage 1.

Reporting both, under clearly named keys, also works. Either way, the current mix of the two shouldn't ship.

3. confidence_intervals ignores the evaluator's n_bins

DecisionAccumulator(n_bins=…) sets the bins for the point estimate (accumulator.py:188). But
confidence_intervals calls calibration(a) with its default of 10 bins (intervals.py:43–44). With
n_bins=5, the reported ece_mass is a 5-bin ECE, while its interval is the interval of a 10-bin ECE: a
different statistic.

Suggest: carry n_bins in the stored decision metrics and use it in confidence_intervals, or take it as an
argument there and default it to the evaluator's value.

4. A reused doc_id silently becomes a new document

DecisionAccumulator numbers documents by call order (accumulator.py:149–150) and ignores doc_id. Calling
update(..., doc_id="same") twice gives document_count 2 and two bootstrap groups, and nothing warns.

Why it matters: the bootstrap is documented as resampling documents (metrics.py:331–347). A common mistake
is feeding repeated runs or perturbed copies of the same items into one evaluator. That multiplies n, treats
correlated copies as independent, and narrows every interval: by about √5 for 5 identical repeats.

Suggest: raise on a reused doc_id by default. Add an opt-in that keeps rows with the same doc_id in one
bootstrap group, which is then the correct way to pool repeats.

Suggestions

5. One malformed answer rejects the whole document

StructuredModel.from_json (structured_model.py:841) raises AnswerError if any one decision field is
malformed, for example a probability of 1.7 or an unknown option key. For documents with several decision
fields, one bad field drops the good answers in the others.

Suggest: from_json(..., on_answer_error="raise" | "missing"). With "missing", the field counts as
missing, and coverage reports a rejected count next to ok and missing.

6. Balanced accuracy, and recall for "no"

Yes/no correctness reports precision, recall and F1 for "yes" only. Choice and Score report per_class and
macro_f1. There's no balanced accuracy (mean recall over gold classes) for any kind. Decision data is often
imbalanced: in BoolQ, 62% of answers are "yes".

Suggest: add balanced_accuracy for every kind, with missing answers counted as wrong as in accuracy, and
include it in confidence_intervals. Also add recall for "no" to yes/no fields.

7. Policy for answers that omit options

normalize.py:127–129 rejects an answer whose probabilities omit any option. Top-k log-prob readouts routinely
omit tail options, and those answers are then counted as missing.

Suggest: missing_options="reject" | "zero", defaulting to "reject", with the number of zero-filled
answers reported in coverage.

8. Percentile intervals for ece_mass can exclude the estimate

ECE is biased upward under resampling: duplicated documents form tighter bins. A percentile bootstrap inherits
that bias. On small synthetic runs (20 and 30 documents, 160 seeds), 2 intervals excluded their own estimate, for
example ece_mass 0.109 with 95% interval [0.110, 0.333].

Suggest: a bias-corrected interval for ece_mass (BCa, or the basic bootstrap 2θ̂ − q), or at least a flag
when the estimate falls outside its interval.

Nits

  1. confidence_intervals returns bounds for every numeric leaf, including per-class support counts,
    confusion cells and bin edges. Intervals on counts aren't meaningful, and the output is large. Consider a
    metrics= argument, defaulting to the headline metrics.
  2. accept_or_escalate(res, taus=[...]) applies one list to every field. Thresholds are often chosen per
    field. Accepting taus={field: [...]} as well would save one call per field.
  3. The package ships no py.typed, so type checkers skip Stickler even though the code is annotated.

Follow-ups (not for this PR)

  1. Answers with a stated confidence, or a label only. Decision fields accept only a full distribution
    (probabilities or noul). The most common baseline for a decision model is an LLM that states a label and a
    0–1 confidence, or just a label. Those can't be scored in the same evaluator today, not even for accuracy.
    One option: accept {"_value", "_confidence"} or _value alone as an answer.
    • Compute correctness, plus the confidence-only metrics (auroc, ece_mass, accept_or_escalate) when a
      confidence is given.
    • Report Brier, log-loss and RPS as unavailable rather than inventing a distribution.
    • Record the source of each confidence.
  2. Options that change per request. Tool selection or picking among retrieved passages changes the option
    list from document to document, which a fixed schema can't express. A choice kind whose answer carries its
    own option list could support the option-agnostic metrics: accuracy, auroc, ece_mass and
    accept_or_escalate.

On release: the PR is additive, so a minor version (1.1.0) on PyPI would let users depend on stickler.decisions
without pinning a git commit.

Checked and fine

  • Unasked fields (gold None) carry no weight and add no confusion-matrix counts.
  • ece_mass never splits a run of tied confidences, and accept_or_escalate cuts only between distinct
    confidences, so the curve matches what a confidence >= τ rule can do at runtime.
  • coverage_at_target divides by every asked decision and never accepts a missing answer.
  • Missing answers count as wrong for accuracy and are excluded from calibration.
  • Yes/no fields report both AUROCs: auroc (confidence against correctness) and auroc_label (P(yes) against
    gold).
  • get_state and merge_state keep document indexes distinct after a merge.
  • Score answers accept level numbers or names.

@sromoam

sromoam commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @parmidaatg, this review was a big help, and the four "should fix" items are fixed. Two of your suggestions we'd like your view on before we settle them.

5. One malformed answer rejects the whole document. We're making this a per-field setting rather than a from_json argument: Choice(criteria, on_invalid="missing"), defaulting to "raise". model_from_questions(..., on_invalid="missing") applies it to every question. A rejected answer counts as missing, and coverage reports it as rejected, separately from refusals.

7. Answers that omit options. We'd rather not fill these in Stickler. Zero-filling a top-k readout leaves the listed probabilities summing to about 0.97, which fails the sum check, so any fill has to put the leftover mass somewhere. Renormalising raises the top probability, making answers look more confident than the model said. Spreading it evenly over the omitted options is a guess about the tail. The converter that builds the answer knows the real tail mass, so our plan is:

  • keep "an answer is a full distribution" as the contract;
  • show a short fill step in the guide;
  • rely on on_invalid="missing" so that an unfilled answer shows up as rejected instead of failing the run.

Does that work for your log-prob system, or is there a fill rule you'd consider standard enough to build in?

@sromoam

sromoam commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

One more, on 8 (percentile intervals for ece_mass). We tried the basic bootstrap on your example: an estimate of 0.109 with percentile interval [0.110, 0.333] gives [−0.115, 0.108]. That still excludes the estimate, so it shifts the interval but doesn't fix the exclusion.

BCa does fix it, and we're open to implementing it for ece_mass only. Percentile intervals would stay for every other metric, since your implementation matches those, and settings would record the method used. Our hesitation is timing: we're close to a release, and the evaluator now warns when a field has fewer than 30 answered decisions, which is where you saw this.

Would you rather see BCa for ece_mass in this PR or in a follow-up? Or would you prefer another approach, such as a debiased ECE estimator?

This branch has not been deployed

No deployments
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.

[FEATURE]: First-class evaluation for decision models (Strands Decider, OpenJev, Jev)

4 participants