Skip to content

fix(auto): dump by field name; leave excluded fields out of evaluation - #380

Closed
sromoam wants to merge 10 commits into
devfrom
fix/378-379-auto-dump
Closed

sromoam wants to merge 10 commits into
devfrom
fix/378-379-auto-dump

Conversation

@sromoam

@sromoam sromoam commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Closes #378. Closes #379.

stickler.evaluate() and eval_for() scored a wrong value as 1.0 when a field never reached the inferred shadow model:

Either way the field was blank on both sides, and blank against blank counts as a match. A required field raised ValidationError instead.

Change

#378, alias keys. _dump in auto/facade.py keeps pydantic's own model_dump(mode="json"), so serializers and ser_json_* config apply as usual, then walks the dump beside the instance. On a plain model, alias keys are renamed to field names, building a fresh dict so an alias that is another field's name can't collide. A StructuredModel, and everything under it, keeps its own key spelling, because it validates through its own config. The walk doesn't enter a RootModel, a model_serializer, anything a serializer produced, or a container whose length changed.

#379, excluded fields are not evaluated on the zero-config path. #379 offered two directions; this takes "leave them out of the eval model and explain()". exclude marks a field as outside the model's output, typically a reasoning trace or internal notes on a response_model. Scoring it grades text nobody asked to be graded, and reporting a mismatch would publish a value the author chose not to serialize.

  • builder.py leaves the field out of the shadow model and explain(), at any depth, so it never reaches field_scores, non_matches or a report, and a required one is no longer required.
  • exclude_if is decided per value, as pydantic decides it: a value it keeps is scored, and a value it leaves out is absent, like None.
  • A StructuredModel is used as configured: its ComparableFields declare what is compared, and exclude only affects serialization. Inside one, _dump adds the excluded field back from its annotation, so evaluate() scores it as compare_with() does instead of 1.0.
  • StructuredModel.from_json() passed a nested StructuredModel on as its model_dump(), which dropped its excluded fields and extra_fields. It still passes the dump, so a mode="before" validator sees a dict, and now puts the excluded fields and extra_fields back at any depth, so a nested excluded field is scored by compare_with() too.

Docs

Tests

In tests/auto/test_risk_surface.py:

  • TestDumpKeepsEveryField: Plain models with serialize_by_alias=True raise or score a wrong prediction 1.0 #378 and the dump walk.
  • TestExcludedFieldsAreNotEvaluated: absent from field_scores, explain() and non_matches; no weight; not required; nested, list, dict, set and nested-list cases; exclude_if firing and not; a model with only excluded fields raises clearly.
  • TestExcludedFieldsOnAStructuredModel: evaluate() matches compare_with(), nested under a plain model, the from_json fix, serializers, and values that fail to dump.

Full suite at cbd8c4b, merged with current dev: 3011 passed, 2 skipped, 1 xfailed on Python 3.12 with the bert and strands-agents extras installed (12 skips under uv sync --frozen), with inspect.getfile(stickler) pointing at this checkout. The Strands Evals 1.6.0 contract suite from #410 passes on this head (776 passed, 1 xfailed).

A plain model with serialize_by_alias=True dumped alias keys the shadow
model never read, and a Field(exclude=True) or exclude_if field was left
out of the dump. Either way the field was blank on both sides and a wrong
value scored 1.0; a required one raised ValidationError.

_dump now dumps plain models with by_alias=False and rebuilds any declared
field the dump dropped, at every nesting level. A StructuredModel keeps its
own dump, since it validates through its own config.

Closes #378
Closes #379
- An excluded value pydantic cannot serialize stays out instead of
  aborting evaluate().
- Excluded fields are compared inside dicts and nested lists, and on a
  StructuredModel (keeping its own key spelling).
- A field serializer, model_serializer or RootModel keeps pydantic's
  output.
- A model-holding field is left out of the parent dump rather than
  serialized twice.
- The exclude_if test skips on a pydantic without it.
@sromoam
sromoam requested a review from vawsgit October 6, 2026 20:20

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

needs changes

  1. src/stickler/auto/facade.py:372: an excluded field that holds a model is rebuilt without the PydanticSerializationError guard, so evaluate() now raises where dev returned a score.
  2. src/stickler/auto/facade.py:374: the excluded-field rebuild also applies to StructuredModel.extra_fields, which writes an extra_fields key into the dump and nests it inside the instance's own extra_fields.

Measured with PYTHONPATH pinned to a worktree at cbd3aa0 and compared against dev at 43a573d.

Comment thread src/stickler/auto/facade.py Outdated
key = (
(field.serialization_alias or field.alias or name) if by_alias else name
)
if name in rebuild:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: excluded model-holding fields abort instead of staying out. A field that is both exclude=True (or exclude_if) and holds a model is in rebuild. This branch calls _wire with no try/except PydanticSerializationError, unlike the elif branch below. The PR description says "An excluded value that pydantic cannot serialize stays out, as before, instead of aborting". That holds only for non-model values.

Reproduction (dev returns 1.0, this branch raises PydanticSerializationError: Unable to serialize unknown type: <class 'Handle'>):

class Handle: pass
class Inner(BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True)
    h: Handle
class Doc(BaseModel):
    name: str
    meta: Optional[Inner] = Field(default=None, exclude=True)
d = Doc(name="a", meta=Inner(h=Handle()))
stickler.evaluate(d, d)

Fix: apply the same guard when name in rebuild and the field was excluded from the original dump, for example by checking field.exclude/exclude_if, or by wrapping both branches in the same try. Add a test next to the existing unserializable-excluded-field test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. 8b6bcdd dropped the rebuild branch: an excluded field is now dumped through a TypeAdapter for its annotation, and in 10c60a0 any error from that dump leaves the field out, as on dev. Your Handle repro scores 1.0, and it's pinned in test_an_excluded_unserializable_model_stays_out.

Comment thread src/stickler/auto/facade.py Outdated
)
if name in rebuild:
out[key] = _wire(getattr(value, name), own_keys)
elif key not in out:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: StructuredModel.extra_fields is now dumped and re-ingested as an extra field. StructuredModel declares extra_fields: Dict[str, Any] = Field(default_factory=dict, exclude=True) (structured_model.py:549). That field is in model_fields and absent from the dump, so this branch adds it under the key extra_fields. ConfigurationHelper.from_json then treats that key as an undeclared field and stores it inside the new instance's extra_fields.

Measured on this branch with a passthrough StructuredModel:

a = SM.from_json({"name": "x", "zzz": 1})
_dump(a)                      # {'name': 'x', 'zzz': 1, 'extra_fields': {'zzz': 1}}
SM.from_json(_dump(a)).extra_fields  # {'extra_fields': {'zzz': 1}, 'zzz': 1}

The same happens for a StructuredModel nested in a plain model. Scores do not change, because comparison skips extra_fields. The ground_truth/prediction instances on EvalResult and their __stickler_raw_json__ now carry the extra extra_fields key, and each re-dump nests it one more level. Fix: skip extra_fields when the model is a StructuredModel, matching how structured_model.py, confusion_matrix_calculator.py and structured_list_comparator.py already skip it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch, thanks. Fixed in 10c60a0: the walk skips extra_fields on a StructuredModel, the same way the comparison engine does. test_structured_model_extra_fields_are_not_dumped covers the passthrough case, the nested case, and a from_json(_dump(a)) round trip that keeps extra_fields == {"zzz": 1}.

… fields

Rebuilding every model-holding field dropped serializers nested in the
annotation and ser_json_* config on siblings, and by_alias=False leaked
into opaque subtrees, so a model_serializer parent broke a nested aliased
StructuredModel.

_wire now keeps pydantic's own dump and walks it beside the instance:
alias keys on plain models become field names, and fields marked
exclude/exclude_if are dumped from their annotation and added back. The
walk stops at RootModel, model_serializer, field serializers and any
container whose shape changed. Unset fields (model_construct) are left
for validation to report. Per-class plans and adapters are cached.
@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-10-28T23:03:15+00:00
  • Time since scan: 3 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-10-28T22:59:40+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 4 0 0 6466 0 4 FAILED MEDIUM (global)
cdk-nag 0 0 0 0 0 0 0 PASSED MEDIUM (global)
cfn-nag 0 0 0 0 0 0 0 MISSING MEDIUM (global)
checkov 0 0 0 0 0 0 0 PASSED MEDIUM (global)
detect-secrets 0 1 0 0 0 0 1 SKIPPED MEDIUM (global)
grype 0 0 0 0 0 0 0 MISSING MEDIUM (global)
npm-audit 0 0 0 0 0 0 0 PASSED MEDIUM (global)
opengrep 0 0 0 0 0 0 0 MISSING MEDIUM (global)
semgrep 3 0 0 0 0 0 0 PASSED MEDIUM (global)
syft 0 0 0 0 0 0 0 MISSING MEDIUM (global)

Top 3 Hotspots

Files with the highest number of security findings:

Finding Count File Location
2 tests/comparators/test_anls_leaf_semantics.py
2 tests/structured_object_evaluator/test_rollup_node_semantics.py
1 tests/test_readme_examples.py

Detailed Findings

Show 5 actionable findings

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

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

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

Code Snippet:

Secret of type Hex High Entropy String detected

Finding 2: B108

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

Description:
Probable insecure usage of temp file/directory.

Code Snippet:

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

Finding 3: 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 4: 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 5: 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(")]

Report generated by Automated Security Helper (ASH) at 2026-10-28T23:03:17+00:00

@sromoam
sromoam requested a review from vawsgit October 9, 2026 16:57
- Re-key into a fresh dict, so one field's alias that is another field's
  name no longer overwrites it.
- Skip StructuredModel.extra_fields, which was dumped and re-ingested as
  an extra field (vawsgit).
- An excluded value that fails to dump for any reason stays out, as it
  did before #379, instead of aborting evaluate().
- Excluded fields carry the parent's ser_json_* settings.
- Do not walk anything a serializer produced, including one nested in
  Optional/Union, or refill an excluded field's own serializer output.
- Walk sets, frozensets and deques.
- Skip fields whose annotation cannot hold a model.
- Cache per-class plans and adapters in WeakKeyDictionaries so runtime
  classes can be collected; fold _wire into _dump.

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

The two reported bugs are genuinely fixed and the test coverage is broad. Not blocking this, but one point needs a decision before it merges: the change turns exclude=True from a serialization decision into evaluated, reportable data, and as written it would land silently in a patch release.

One note on method: I diffed against the merge base 1479c3d, not dev. The branch is 7 commits behind, so a diff against dev shows tests/structured_object_evaluator/test_nan_as_absent.py as deleted and null_helper.py as reverted, when in fact #381 added both afterwards. Against the merge base this is 4 files, +660/-8, matching what GitHub reports.

What works, measured, merge base on the left

case 1479c3d 10c60a0
#378 alias, wrong value ValidationError 0.0
#379 exclude=True optional, differing value 1.0, matched=True 0.5, matched=False
#379 exclude=True required, differing value ValidationError 0.5
excluded field holding an aliased model, wrong value 1.0 0.5
aliased and excluded on the same field, identical ValidationError 1.0
list of aliased models, wrong value ValidationError 0.0

Both of @vawsgit's findings hold as fixed: the Handle repro scores 1.0, and _dump on a passthrough StructuredModel no longer carries an extra_fields key, with from_json(_dump(a)).extra_fields == {'zzz': 1} stable across round trips.

Three places where _restore assumes the dump lines up with the instance, all three clean in my testing:

  • Mapping pairing is positional (zip(dumped.items(), value.values())). With Dict[int, Leaf] the instance order [10, 2, 33] survives as '10', '2', '33', key 10 still holds 'ten', and the nested alias is re-keyed.
  • The sequence branch pairs positionally too (zip(value, dumped)). For set and frozenset the only thing keeping them aligned is that pydantic-core and the zip iterate the same unmodified object. It holds, and it is the least self-evident of the three, so it may be worth a line in the README beside the existing guarantees.
  • exclude_if is conditional, so the field is present in one dump and absent in the other. Present against None scores 0.5 rather than a false 1.0.

Full suite: 2797 passed, 12 skipped, 1 xfailed at the head, against 2769 at the merge base, so +28 tests, matching the count in the description. pydantic 2.12.5, Python 3.12.

The point that needs a decision: excluded values now reach reports

An excluded field's value is now scored and, when it differs, written verbatim into non_matches:

class Doc(BaseModel):
    name: str
    api_key: Optional[str] = Field(default=None, exclude=True)

stickler.evaluate(Doc(name="same", api_key="SECRET-GT-abc123"),
                  Doc(name="same", api_key="SECRET-PRED-xyz789"))
merge base this PR
field_scores["api_key"] 1.0 0.0
non_matches [] ground_truth_value='SECRET-GT-abc123', prediction_value='SECRET-PRED-xyz789'

reporting/html/section_generator.py:93 renders non_matches with both values, so this reaches HTML output too. The same applies to a value that exclude_if omitted.

The scoring change is right, and #379 is clear that a field must not be reported as matched when it was never compared. The part worth a decision is that #379 offered two directions, "either compare excluded fields… or leave them out of the eval model and explain()", and this takes the first without saying so. Comparing a value does require reading it, but it does not require publishing it raw: the non_matches payload could carry a redacted placeholder. #379 also names the typical case, fields "kept out of an API payload, such as reasoning or internal notes", which is the content least expected to turn up in a shared report.

Either resolution would close this for me:

  1. Keep the design and make it loud. Move the entry to ### Changed with the - **Breaking:** prefix, and state in the entry itself that excluded fields are now compared and their values appear in non_matches and HTML reports. The entry is the right place rather than auto/README.md alone, since someone taking a patch upgrade reads the changelog.
  2. Keep confidentiality by default. Leave excluded fields out of the eval model and explain(), as #379's second direction suggests, or make comparing and reporting them opt-in, or redact the reported values.

For context on how this file already handles that kind of change, the closest precedent is the x-aws-stickler-threshold entry: "no longer dropped on an object-typed property, so a schema that declared one now scores differently."

Notes, none of them blocking

Pydantic secret types are not affected. SecretStr with exclude=True still scores 1.0 with an empty non_matches and no plaintext anywhere, so _refuse_secrets in comparators/anls.py keeps doing its job. Worth saying explicitly so the point above is not read as wider than it is.

Annotated serializers on excluded fields now run. A PlainSerializer on an excluded field goes from 0 executions per evaluate() at the merge base to 2. Harmless for a pure function, visible for one with side effects, so it belongs in the new contract.

Two shapes where an excluded field can still score a false 1.0. A class with a @model_serializer, and a Union where some other branch carries a PlainSerializer, since _build_field_plan marks the whole field serialized and the walk does not descend. Neither is a regression, both behave identically at the merge base, and the README does disclose that the walk does not enter a serializer. Raising them only so "compared at any depth" is not read too broadly, and so they are not later reported as a reopened #379. The explain() side is the part most likely to mislead, since it still lists the field among those compared.

Key order changed for models with extras or computed fields: declared fields now come after them, so a passthrough StructuredModel dumps ['zzz', 'name'] where the merge base gave ['name', 'zzz']. field_scores, explain() and non_matches ordering are unchanged, so this looks harmless, but it matters if anything downstream compares dumps as ordered JSON.

Before merge

The branch is CONFLICTING against current dev. The only real conflict is CHANGELOG.md, where this entry and #367's both landed at the top of Unreleased; tests/auto/test_risk_surface.py auto-merges cleanly. Worth re-running the suite after the rebase: #381 touches null_helper.py, which is adjacent to the blank-against-blank semantics this change relies on, and no CI run exists for the combined tree yet.

Comment thread src/stickler/auto/facade.py Outdated
Comment on lines +394 to +397
elif entry.excluded:
item = _dump_excluded(cls, entry, raw, own_keys)
if item is not _MISSING:
out[key] = item

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.

This is where an excluded field is put back, and it is the line that changes exclude=True from a serialization decision into evaluated data.

class Doc(BaseModel):
    name: str
    api_key: Optional[str] = Field(default=None, exclude=True)

stickler.evaluate(Doc(name="same", api_key="SECRET-GT-abc123"),
                  Doc(name="same", api_key="SECRET-PRED-xyz789"))
merge base 1479c3d this PR 10c60a0
field_scores["api_key"] 1.0 0.0
non_matches [] both values verbatim

reporting/html/section_generator.py:93 renders non_matches with ground_truth_value and prediction_value, so the value reaches HTML reports as well. A value omitted by exclude_if behaves the same way.

The new score is the right answer. The open question is the reporting: #379 offered "either compare excluded fields… or leave them out of the eval model and explain()", and it names the typical case as fields "kept out of an API payload, such as reasoning or internal notes". Comparing a value needs to read it, but the non_matches payload could carry a placeholder instead of the value.

Pydantic secret types are unaffected: SecretStr with exclude=True still scores 1.0 with an empty non_matches, so _refuse_secrets keeps working. The exposure is specific to an ordinary value the author chose not to serialize.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Resolved in ec3cf4b by leaving the field out. On a plain model this branch no longer runs: the shadow model has no excluded fields, so nothing is added back, and your repro gives field_scores == {"name": 1.0} with an empty non_matches. It now runs only inside a StructuredModel, where compare_with() already scored the field. The rule is in the new Excluded fields section of docs/API-Reference/auto.md.

Comment on lines +514 to +520
try:
dumped = adapter.dump_python(raw, mode="json")
except Exception:
# Before #379 this field never reached the dump at all, so a value that
# cannot be dumped (an arbitrary type, undecodable bytes, a raising
# serializer) is left out as it always was, rather than aborting.
return _MISSING

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.

Two notes on this branch, neither blocking.

A bare except Exception around the dump keeps a field out when its own serializer raises, which matches the pre-#379 behaviour and is the right default. It also swallows a programming error in that serializer, and the field then silently returns to scoring a false 1.0 with nothing to diagnose from. A narrower catch, or re-raising anything that is not a serialization failure, would keep the fallback without hiding bugs.

Annotated serializers on an excluded field now execute. Measured on a PlainSerializer over an excluded field: 0 calls per evaluate() at the merge base, 2 at this head. Harmless for a pure function, visible for one with side effects, so it is worth stating as part of the new contract.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Narrowed in ec3cf4b to (PydanticSerializationError, ValueError). It can't separate a serializer bug from an unserializable value, because pydantic wraps whatever a serializer raises in PydanticSerializationError (Error calling function ...). Leaving the field out is what happened before #379, when the serializer never ran. The comment says so, and test_a_raising_serializer_on_an_excluded_field_leaves_it_out pins it. Serializers on excluded fields now run only inside a StructuredModel; that's in the README.

Comment thread CHANGELOG.md Outdated
Comment on lines +34 to +44
- **`stickler.evaluate()` and `eval_for()` no longer score unread fields as
matches.** A plain model with `serialize_by_alias=True` dumped alias keys
that the inferred model never read, and a `Field(exclude=True)` (or
`exclude_if`) field was left out of the dump. Either way the field was blank
on both sides, so a wrong value scored `1.0`, and a required field raised
`ValidationError`. Plain models now reach it keyed by field name (a
`StructuredModel` keeps its own key spelling), and excluded fields are
compared at any depth. Serializers and `ser_json_*` config still apply
([#378](https://github.com/awslabs/stickler/issues/378),
[#379](https://github.com/awslabs/stickler/issues/379))

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.

This entry sits under ### Fixed with no marker, but it moves existing scores and now writes previously unserialized values into non_matches and HTML reports.

Either move it to ### Changed with the - **Breaking:** prefix and say that here, or keep excluded fields out of the eval model as #379's second direction suggests. The entry is the right place rather than auto/README.md alone, since someone taking a patch upgrade reads the changelog.

Details and the measured before/after are in my comment on facade.py and in the review body.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Split in two in ec3cf4b. #379 is under Changed with - **Breaking:**, and says excluded fields are no longer evaluated on the zero-config path and links the new docs section. #378 stays under Fixed.

A plain-model field marked exclude=True or exclude_if is outside the
model's output, so the shadow model now leaves it out: it never reaches
field_scores, explain(), non_matches or a report, and a required one is
no longer required. exclude_if counts whether or not it fires.

A StructuredModel is used as configured and keeps scoring its excluded
fields; evaluate() now agrees with compare_with() on them.
StructuredModel.from_json() passed a nested StructuredModel on as its
model_dump(), dropping its excluded fields and extra_fields; it now
passes the instance.

The rule is defined in docs/API-Reference/auto.md, Excluded fields.
The CHANGELOG entry for #379 moves to Changed as Breaking.
@sromoam

sromoam commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @digalaviz, this was the right call to raise. In ec3cf4b we went with your second resolution: on the zero-config path, a field marked exclude=True or exclude_if is no longer evaluated. It's left out of the shadow model, so it doesn't appear in field_scores, explain(), non_matches or HTML reports, at any depth. Your api_key repro now gives field_scores == {"name": 1.0} and an empty non_matches.

The rule and its reasoning are defined in a new Excluded fields section in docs/API-Reference/auto.md, and the CHANGELOG entry moved to Changed with - **Breaking:**.

A StructuredModel keeps its excluded fields, since its ComparableFields declare what is compared, and compare_with() already scored them. evaluate() used to give those a false 1.0; it now agrees with compare_with(). Testing that turned up an engine bug: StructuredModel.from_json() passed a nested StructuredModel on as its model_dump(), dropping its excluded fields and extra_fields. That's fixed here too, with its own Fixed entry.

On your notes:

  • Serializers on excluded fields now run only inside a StructuredModel, and the docs say so.
  • The bare except is narrowed to (PydanticSerializationError, ValueError). It can't go further: pydantic wraps whatever a serializer raises in PydanticSerializationError, so a bug and an unserializable value look the same. Leaving the field out matches what happened before Fields declared Field(exclude=True) are never compared, so a wrong value scores 1.0 #379, when the serializer never ran at all. test_a_raising_serializer_on_an_excluded_field_leaves_it_out pins it.
  • model_serializer and Union shapes no longer matter on a plain model, because the field isn't in the shadow model whatever its serializer does.
  • Key order is unchanged from your measurement. It still only affects the dump, not scores or reports.

dev is merged in (the only conflict was CHANGELOG.md), and the full suite passes on 3.10, 3.12 and 3.14 on the merged tree.

@sromoam
sromoam requested a review from digalaviz October 15, 2026 16:06
@sromoam sromoam changed the title fix(auto): dump by field name and compare excluded fields fix(auto): dump by field name; leave excluded fields out of evaluation Oct 15, 2026
@sromoam sromoam added this to the 1.0.1 (Minor) milestone Oct 15, 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.

The three findings from my last review are addressed, and the new direction is the better one: a field pydantic keeps out of serialization is not something to grade. Measured on ec3cf4b against this PR's base 6abbf26.

case base 6abbf26 head ec3cf4b
plain model, exclude=True, differing secrets api_key scored 1.0, listed in explain() absent from field_scores and explain()
serialize_by_alias=True ValidationError, field never read scored, 1.0 identical and 0.0 differing
a model whose only field is excluded 1.0, nothing compared TypeError naming the cause
StructuredModel with exclude=True evaluate() 1.0 against compare_with() 0.5 both 0.5, the two readers agree

No cost for the dump walk: evaluate() over 12 documents of a nested model with a 12-element list, n=9 interleaved, medians 0.0334s on this head against 0.0343s on the base, head nominally faster and inside the spread.

The narrowed except (PydanticSerializationError, ValueError) reads right, and the comment is the part that makes it reviewable: pydantic wrapping a serializer's own error means a bug there cannot be told from an undumpable value, so leaving the field out is the pre-#379 behaviour rather than a new silence.

Blocking: an exclude_if that does not fire is dropped, and the field scores 1.0

is_excluded (builder.py:152, the or at :162) returns True whenever exclude_if is set, so the field leaves the shadow model for every instance. But exclude_if decides per value, and the common spelling omits only empty optionals, so the field is in pydantic's output for most documents. Measured with note: Optional[str] = Field(default=None, exclude_if=lambda v: v is None):

ground truth vs prediction pydantic's own dump base head
"alpha" vs "beta" carries note 0.6111, note 0.2222 1.0, note not scored
"alpha" vs omitted carries note 0.5, note 0.0 1.0
omitted vs omitted no note 1.0 1.0

The second row is the one that matters: the prediction dropped a field the ground truth carried, and the result is a perfect score. That is the shape #378 and #379 exist to close, reached through a different door, and nothing warns.

The CHANGELOG entry does not cover it either. It says "a value kept out of serialization is never scored or published", and a non-firing exclude_if value is not kept out of serialization.

test_exclude_if_counts_whether_or_not_it_fires (test_risk_surface.py:657) pins this as the contract: it asserts set(r.field_scores) == {"name"} for both values of its parameter, so the field is never scored either way. Its predicate is lambda v: v is not None, which fires on a populated value and not on None, the mirror of the common spelling. Whichever way the fix goes, that test states the behaviour under review and would need to change with it.

Two ways out, either is fine:

  • Split the two flags. exclude=True is static, "never in the output", which is exactly the case for leaving the field out. exclude_if is conditional, so keep the field in the shadow model and let _dump fill it from the annotation. That machinery already exists here: _dump_excluded does it for a StructuredModel.
  • Keep them together and warn, naming the field and saying it will not be scored, the way #350 made a dropped config key visible. A warning at build time costs nothing per document, since the shadow is built once per class.

Not blocking: on a StructuredModel, an excluded value now reaches the report

Scoring an excluded field on the configured path is right, and evaluate() agreeing with compare_with() is the fix. The value travelling with it is the part worth a second look. Measured with api_key: Optional[str] = ComparableField(default=None, exclude=True) on a StructuredModel, ground truth SECRET-GT-abc123 against prediction SECRET-PRED-xyz789:

base head
api_key field score 1.0 0.0
either secret present in non_matches no yes

On the base the field scored 1.0, so there was no mismatch to report; now there is, and non_matches carries both values verbatim. reporting/html/section_generator.py:129-138 renders ground_truth_value and prediction_value into the HTML report, escaped and truncated to 100 characters, so an exclude=True value ends up in a generated artifact.

The caller did declare a ComparableField, so comparing it is their choice and the score is theirs to keep. Publishing the value is the part they did not choose, and exclude=True is the closest thing pydantic has to saying so. A placeholder in the non_matches payload for a field marked excluded would keep the score and drop the disclosure. This repo already refuses to score a SecretStr for a related reason, in ANLSStarComparator.

Mergeability and the suite count

dev moved to f81a33e while this was under review, since #388 merged, and the two overlap in four files. Merging ec3cf4b into f81a33e conflicts in CHANGELOG.md alone: auto/builder.py, auto/facade.py, auto/README.md and configuration_helper.py all auto-merge, including the is_excluded addition beside #366's RootModel refusal.

The stated suite count is not reproducible as written. The body reports 2830 passed, 2 skipped, 1 xfailed on 3.10, 3.12 and 3.14. This head under uv sync --frozen gives 2813 passed, 12 skipped, 1 xfailed on 3.12: the extra 10 skips are extras-gated, bert and strands-agents, so the stated 2 skips imply an environment with those installed. Naming it, or quoting the frozen-env number CI uses, would let the next reader reproduce the figure. It moves again after the merge with dev, since this branch predates #384 and #388.

item = dumped[entry.dumped_key]
if entry.descend and not entry.serialized:
item = _restore(raw, item, own_keys)
out[key] = item

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.

Blocker: a non-firing exclude_if field becomes a false alarm. _restore copies any key present in the dump, including a plain-model field that is_excluded() removed from the shadow model. When exclude_if does not fire, the value is in the dump, the shadow StructuredModel (extra="allow") stores it in __pydantic_extra__, and _count_extra_fields_as_false_alarms counts it as a hallucinated field.

Measured on this branch (/tmp/stickler-pr380/src): class P(BaseModel): a: str; meta: Dict[str,str] = Field(default_factory=dict, exclude_if=lambda v: not v), then evaluate(P(a="x", meta={"k":"v"}), P(a="x", meta={"k":"v"})) gives precision=0.5, f1=0.667 for two identical instances. On dev the same field was scored. Fix: when not own_keys and entry.excluded, skip the entry and do not copy dumped[entry.dumped_key] into out.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, good catch. Fixed in cbd8c4b: exclude_if is now decided per value, so the field stays declared in the inferred model and a kept value is never an extra. Your repro now gives precision 1.0, pinned in test_a_kept_value_is_not_a_false_alarm.

@@ -338,7 +358,12 @@ def _build(
if not field_definitions:

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.

Blocker: a nested model whose fields are all excluded now makes the whole evaluate() raise. _build recurses into nested plain models, so a nested model such as a reasoning trace (class Trace(BaseModel): steps: str = Field("", exclude=True)) inside class Out(BaseModel): answer: str; trace: Trace = Trace() raises TypeError: evaluate() needs at least one field to score; Trace defines none outside exclude=True / exclude_if. On dev, evaluate(Out(answer="a"), Out(answer="a")) returned {'answer': 1.0, 'trace': 1.0}. The raise is right for the top-level class only. For a nested class with no scorable fields, drop the parent field from the shadow model (and from explain()) instead of raising.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed. A nested plain model with nothing left to score is now left out along with its parent field, in the inferred model, in explain() and in the dump. Your Out/Trace case gives {'answer': 1.0} with no false alarm. Only the top-level class still raises. See test_a_nested_model_with_only_excluded_fields_is_left_out.

# The instance itself is returned, not its model_dump(): a dump drops
# every exclude=True field, so a nested excluded field read blank on
# both sides and scored a wrong value 1.0 (#379).
return structured_class.from_json(nested_data, process_rich_values=False)

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.

Blocker: from_json() now passes a model instance where a user's mode="before" validator received a dict. Any parent @model_validator(mode="before") or @field_validator(..., mode="before") that reads nested data as a dict breaks. Measured: class Doc(StructuredModel): addr: Addr with a before-validator doing data["addr"]["city"].upper() gives TypeError: 'Addr' object is not subscriptable on this branch, and works on dev. evaluate() on a passthrough StructuredModel goes through from_json(), so it raises too. This is a change to the public StructuredModel.from_json() contract. Either list it as a breaking change in CHANGELOG.md, or keep the dict and re-attach the excluded fields and extra_fields another way.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Went with keeping the dict. from_json() passes the nested model on as its model_dump() again, and puts back its excluded fields and extra_fields at any depth, so your before-validator works as it does on dev. Covered by test_from_json_still_hands_a_before_validator_a_dict and a depth-2 test.

cls = type(value)
if not isinstance(dumped, dict) or _is_opaque(cls):
return dumped
own_keys = own_keys or isinstance(value, StructuredModel)

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.

#378 is still open for any StructuredModel that uses serialization_alias. Keys under a StructuredModel are kept as dumped because it "validates through its own config". Pydantic validation reads alias/validation_alias, not serialization_alias, so those keys are never read back. Measured on this branch: class SM3(StructuredModel): model_config = ConfigDict(serialize_by_alias=True); code: str = Field("", serialization_alias="Code"); other: str = "", then evaluate(SM3(code="A", other="q"), SM3(code="BBBB", other="q")) gives field_scores={'code': 1.0, ...}. compare_with() scores code 0.0. A plain model nested under a StructuredModel has the same problem (wrong Inner.code scores sm: 1.0). Fix: rename a key to the field's validation key (alias or name) whenever dumped_key differs from it, not only when own_keys is false.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You're right, thanks. Under a StructuredModel the key is now the one validation reads: an alias stays, and a serialization_alias becomes the field name. SM3 scores code 0.0 in both readers, and the nested plain case drops below 1.0. See test_a_serialization_alias_is_read_back.

f"expected a pydantic BaseModel instance, got {type(instance)!r}"
)
return instance.model_dump(mode="json")
return _restore(instance, instance.model_dump(mode="json"), own_keys=False)

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.

Optional (efficiency): _restore rebuilds every dict and list in each dump in Python, on every EvalSpec.evaluate() call. The EvalSpec docstring calls that the efficient path for a dataset. Because _may_hold_model returns True for Any and for Dict[str, Any], a large JSON payload field is copied in full twice per pair even when nothing needs renaming. When a class's plan has no alias rename and no excluded entry (precompute that once per class), return the pydantic dump unchanged.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. Whether a class's dump needs any changes is now decided once per class, and if it doesn't, pydantic's dump is returned as is. The walk also no longer copies anything it leaves alone. A typed nested model goes from about 73µs to 12µs per _dump, roughly the cost of model_dump alone. Any fields are still walked, since they can hold a model.

Comment thread CHANGELOG.md
later on subscripting
([#350](https://github.com/awslabs/stickler/issues/350))

- **Breaking:** on the zero-config path (`stickler.evaluate()`, `eval_for()`,

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.

Optional (conventions): this entry is labelled Breaking, but every commit subject on the branch is fix(auto): ... with no ! and no BREAKING CHANGE: footer. CONTRIBUTING.md requires Conventional Commits and links the spec, which marks a breaking change with ! or a BREAKING CHANGE: footer. Release notes and the version bump are derived from commit subjects, so the squash commit should read fix(auto)!: ..., or include the footer.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fair point. The new commit is fix(auto)!: with a BREAKING CHANGE: footer, and the squash title will be fix(auto)!: ....

@vawsgit

vawsgit commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

needs changes

Blockers, each posted as an inline comment:

  1. src/stickler/auto/facade.py:399: when a plain-model exclude_if does not fire, the field counts as a false alarm. Two identical instances get precision=0.5.
  2. src/stickler/auto/builder.py:358: a nested model whose fields are all excluded makes the whole evaluate() raise TypeError. On dev the same call scored normally.
  3. src/stickler/structured_object_evaluator/models/configuration_helper.py:1099: from_json() now passes a nested instance, not a dict. A user's mode="before" validator that reads the nested dict now raises TypeError.
  4. src/stickler/auto/facade.py:384: Plain models with serialize_by_alias=True raise or score a wrong prediction 1.0 #378 is still open for a StructuredModel that uses serialization_alias. A wrong value scores 1.0.

Two optional items (efficiency, commit subject) are also inline. Numbers were measured against /tmp/stickler-pr380/src at ec3cf4b (Python 3.10, pydantic 2.12.5). Each dev comparison was measured against the dev checkout.

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

needs changes

I measured on head ec3cf4b. Four blockers, each reproduced against dev. Details are in the inline comments.

  1. src/stickler/auto/facade.py:399. When a plain-model exclude_if field does not fire, _restore re-adds its value. The value lands in __pydantic_extra__ and is scored as a false alarm, so two identical instances give precision 0.5. Fix: skip entries where not own_keys and entry.excluded.
  2. src/stickler/auto/builder.py:358. A nested plain model whose fields are all excluded now raises TypeError: needs at least one field, so the parent can no longer be evaluated. On dev, the same input returned {'answer': 1.0, 'trace': 1.0}.
  3. configuration_helper.py:1099. StructuredModel.from_json() now passes a nested model instance instead of a dict. A user's model_validator(mode='before') that reads the nested dict raises TypeError. This public behaviour change is not listed as breaking in the CHANGELOG.
  4. src/stickler/auto/facade.py:384. Under a StructuredModel, own_keys keeps serialization_alias keys, but pydantic validation never reads serialization_alias. #378 is therefore still open: evaluate() scores a wrong value 1.0, while compare_with() gives 0.0.

Optional: the _restore copy cost, and the missing ! on the commit subjects for the #379 breaking change.

…iases

- exclude_if is decided per value: the field stays in the shadow model, a
  value it keeps is scored, and a value it omits is absent, like None. A
  dropped prediction no longer scores 1.0, and a kept value is no longer
  counted as a false alarm. exclude=True is still left out.
- A nested plain model left with no field to score is left out with its
  parent field, instead of raising TypeError.
- StructuredModel.from_json() passes a nested StructuredModel on as a dict
  again, with its excluded fields and extra_fields put back, so a
  mode="before" validator still receives a dict.
- Under a StructuredModel, a serialization_alias key is renamed to the key
  validation reads, so evaluate() agrees with compare_with() (#378).
- _restore returns pydantic's dump as is for a class that never needs a
  change, decided once per class, and copies nothing it leaves alone.

BREAKING CHANGE: on the zero-config path an exclude=True field is not
evaluated, and an exclude_if value it omits is treated as absent (#379).
@sromoam

sromoam commented Oct 19, 2026

Copy link
Copy Markdown
Contributor Author

Thanks both. cbd8c4b addresses this round, on top of current dev (only CHANGELOG.md conflicted).

@digalaviz, on the blocker, I went with splitting the flags. exclude=True is still left out. exclude_if is now decided per value, the way pydantic decides it: a kept value is scored, and an omitted one is absent, like None, so it is never read or published. Your table now matches base (0.2222 / 0.0 / 1.0), and a required field that exclude_if omits no longer raises. I didn't fill omitted values back in from the annotation, since that would publish values the author chose not to serialize. Docs, CHANGELOG and the test you pointed at are updated.

On non_matches for an excluded ComparableField: on base 6abbf26, compare_with() already reports that value there, so evaluate() now just agrees with the configured path. A redaction placeholder sounds worthwhile, but it would change reporting for every StructuredModel, so I'd rather open a follow-up issue than fold it in here.

@vawsgit, all four blockers and both optional points are in; details inline.

Suite on the merged tree: 3011 passed, 2 skipped, 1 xfailed, on Python 3.12 with the bert and strands-agents extras installed (which is why there are 2 skips rather than the 12 under uv sync --frozen). The Strands Evals 1.6.0 contract suite from #410 also passes on this head: 776 passed, 1 xfailed.

@sromoam
sromoam requested a review from vawsgit October 19, 2026 16:56
@sromoam
sromoam requested a review from digalaviz October 19, 2026 16:56
if not hasattr(instance, name):
continue # model_construct without it
key = (
(field.serialization_alias or field.alias or name) if by_alias else name

@vawsgit vawsgit Oct 20, 2026 •

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.

Blocking (untrue CHANGELOG statement, wrong value scores 1.0). A field that _dump_whole finds in the dump is keyed by serialization_alias when serialize_by_alias=True. The nested StructuredModel never validates from that key, so the value is dropped.

Measured on head d258055 (inspect.getfile(stickler) = this PR's checkout). Setup: class C(StructuredModel): model_config = ConfigDict(serialize_by_alias=True); v: str = Field(None, serialization_alias="VV"), nested as c: C in class P(StructuredModel).

  • P.from_json({"c": {"v": "a"}}).c gives v=None VV='a'.
  • evaluate(P(c=C(v="a")), P(c=C(v="b"))).field_scores gives {'c': 1.0}, but P(c=C(v="a")).compare_with(P(c=C(v="b"))) gives {'c': 0.0}. The result is the same with a plain-BaseModel parent.

dev gives the same numbers, so this PR does not introduce the bug. The PR does claim to fix it: the CHANGELOG #378 entry says a serialization_alias "is keyed by field name, so evaluate() agrees with compare_with()", and that is false one level down. Fix: when key in data, write the value back under the key validation reads (field.alias or name, the rule the if key not in data branch already uses) and drop the serialization_alias key. Alternatively, narrow the CHANGELOG sentence to the top level.

Non-blocking. Suggest a follow-on issue: without serialize_by_alias, a field with alias="V" and no populate_by_name is keyed v, which validation does not read either. Q.from_json({"s": {"V": "1"}}).s.v is None, and compare_with scores "1" against "2" as 1.0. dev behaves the same way, and the PR does not claim to fix this case.

def whole(value: Any, dumped: Any) -> Any:
if isinstance(value, StructuredModel):
return ConfigurationHelper._dump_whole(value)
if isinstance(value, (list, tuple)) and any(

@vawsgit vawsgit Oct 20, 2026 •

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.

Blocking (untrue CHANGELOG/docstring statement, wrong value scores 1.0). whole() only descends into a list/tuple of StructuredModel. A Dict[str, StructuredModel] field keeps its plain model_dump(), so the exclude=True fields of the dict values are still dropped. The CHANGELOG #379 entry and this docstring both say the fields are put back "at any depth".

Measured on head d258055. Setup: Sub(v: str = ComparableField(default=""), hid: str = ComparableField(default="", exclude=True)), Mid(m: Dict[str, Sub] = {}), Top(mid: Mid).

  • Top.from_json({"mid": {"m": {"k": {"v": "1", "hid": "h"}}}}).mid.m["k"].hid gives ''.
  • The same document with hid: "WRONG" on one side: compare_with gives overall_score=1.0.
  • With l: List[Sub] in place of the dict, the PR head correctly gives 0.0.

dev also gives 1.0, so this is an incomplete fix, not a regression. facade._restore does walk dicts, so from_json() and evaluate() disagree. Fix: add a dict branch to whole() that mirrors the list branch. Alternatively, say in the CHANGELOG that dict values are not covered.

by_alias = instance.model_config.get("serialize_by_alias")
for name, field in type(instance).model_fields.items():
if not hasattr(instance, name):
continue # model_construct without it

@vawsgit vawsgit Oct 20, 2026 •

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.

Non-blocking. Suggest a follow-on issue (optional cleanup). _dump_whole rebuilds the dump-key and validation-key rules that facade._FieldPlan.dumped_key and facade._validation_key (src/stickler/auto/facade.py:571) already compute. The two copies disagree. This copy uses serialization_alias for a present key, and it ignores AliasChoices, validate_by_name and populate_by_name. That disagreement causes the field-loss comment on line 1140. One shared helper would keep from_json() and evaluate() on the same rule.

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

needs changes

All 4 earlier blockers are fixed on d258055, and both optional items are done. Two blockers remain. Neither is a regression against dev. Both block because the CHANGELOG and docstring claim behaviour the code does not have, and in both cases a wrong value scores 1.0.

  1. configuration_helper.py:1140. _dump_whole keys by serialization_alias under serialize_by_alias=True, so a StructuredModel nested one level down loses that value. evaluate(P(c=C(v="a")), P(c=C(v="b"))) gives {'c': 1.0}, while compare_with() gives 0.0. This contradicts the #378 CHANGELOG line "so evaluate() agrees with compare_with()". Fix the key rule, or narrow the CHANGELOG wording. #380 (comment)
  2. configuration_helper.py:1124. whole() walks lists and tuples but not dicts. An exclude=True field inside Dict[str, StructuredModel] values is still lost, so a wrong value scores 1.0. The List[Sub] equivalent correctly scores 0.0. This contradicts "at any depth" in the #379 CHANGELOG entry and the docstring. Add a dict branch, or narrow the wording. #380 (comment)

The other inline comments are non-blocking and are suggestions for follow-on issues. When squashing, use the fix(auto)!: title you mentioned.

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

needs changes

Measured on head d258055 and on dev 4f4f4b5, with the imported stickler path printed for each run. No commits were pushed after the 2026-10-20 review, so both blockers from that review are still open (inline comments on configuration_helper.py lines 1124 and 1140). This round found five new regressions against dev, also inline:

  1. configuration_helper.py:1145 _dump_whole and _restore re-validate excluded fields, so from_json() and evaluate() raise ValidationError on valid input.
  2. configuration_helper.py:1136 The added extra_fields key and default-valued excluded fields change which Union arm pydantic picks and break mode="before" validators.
  3. auto/builder.py:394 On the documented from_pydantic() + from_json(x.model_dump()) path, identical documents get false alarms.
  4. auto/facade.py:397 With a wrap model_serializer or a field serializer, identical documents get false alarms inside evaluate().
  5. auto/facade.py:399 own_keys propagates past a StructuredModel's own fields, so excluded secrets on plain models are scored and published in non_matches.

CHANGELOG.md also conflicts with current dev and needs a rebase.

if key not in data:
# Never dumped, so key it as validation reads it.
key = field.alias or name
data[key] = whole(getattr(instance, name), data.get(key, _ABSENT))

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.

Blocker (new regression): excluded fields are re-validated, so valid input raises.

_dump_whole (and _restore at auto/facade.py:423) puts excluded fields back into the dict and validates them again. That includes defaults, which pydantic never validates.

class Party(StructuredModel):
    name: str = ComparableField()
    internal_ref: str = ComparableField(exclude=True)

Nest it as Invoice.vendor. Then Invoice.from_json(inst.model_dump()) raises vendor.internal_ref Input should be a valid string, even when internal_ref='r1' was set: the dump drops the value and the refill re-validates the default None. On dev it returns the instance.

  • evaluate(Party(name='Acme'), Party(name='Acme')) raises. Dev gives {'name': 1.0, 'internal_ref': 1.0}.
  • Credential(token: str = Field(None, exclude=True)) under a StructuredModel makes evaluate(a, a) raise. Dev gives 1.0.
  • Excluded Json[...] fields and parse-style before-validators fail the same way.

None of the 43 new tests uses the non-Optional excluded spelling. Add one, and only refill values that were actually set, or skip re-validating defaults.

if not isinstance(data, dict):
return data # a model_serializer's own output, kept as is
by_alias = instance.model_config.get("serialize_by_alias")
for name, field in type(instance).model_fields.items():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Blocker (new regression): the extra keys change which Union arm is chosen and break before-validators.

_dump_whole writes an extra_fields key (even {}) and default-valued excluded fields into every nested dict that the parent re-validates.

  • Doc.party: Optional[Union[Person, Company]], where Person is a StructuredModel and Company is a plain model: Doc.from_json({'party': {'legal_name': 'ACME', 'tax_id': '123'}}) returns a Person. Dev returns a Company.
  • evaluate() on two Company parties with different tax_id scores party 1.0 with fa=2. Dev and compare_with() give 0.0.
  • A nested @field_validator('*', mode='before') that returns v.strip() now raises AttributeError in from_json(). Dev works.

The last case contradicts the CHANGELOG line 161 claim that "a mode="before" validator still receives one". Do not add keys the input did not contain.

skipped = False

for name, field_info in cls.model_fields.items():
if left_out(field_info):

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.

Blocker (new regression): the documented from_pydantic() recipe reports false alarms on identical documents.

When every field of a nested model is excluded, this line removes the model from the shadow model. pydantic's dump still writes its key, and only _restore drops it.

class Trace(BaseModel):
    steps: str = Field('', exclude=True)
class Out(BaseModel):
    answer: str
    trace: Optional[Trace] = None
    traces: List[Trace] = []

Pass identical documents through StructuredModel.from_pydantic(Out).from_json(doc.model_dump()). Head gives tp/fa/fp 1/2/2 and precision 0.333. Dev gives 3/0/0 and precision 1.0. This also happens with trace=None. The BulkStructuredModelEvaluator recipe at ultra-quick-start.md:194 reports cm_f1 0.8 on perfect predictions (dev: 1.0).

This contradicts CHANGELOG line 98 ("left out the same way") and auto/README.md:149 ("safe either way"). The shadow model must ignore the key, or the docs must say the recipe does not work for these models.

"""
if isinstance(value, BaseModel):
cls = type(value)
if not isinstance(dumped, dict) or _is_opaque(cls):

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.

Blocker (new regression): with a custom serializer, evaluate() reports false alarms on identical documents.

_restore does not walk the dump when the class has a wrap model_serializer (this line) or the field has a serializer (line 419). In those cases the key of a nested model that was left out survives.

class Lead(BaseModel):
    answer: str = 'a'
    trace: Trace = Trace()   # Trace as in the builder.py:394 comment
    @model_serializer(mode='wrap')
    def ser(self, handler): return handler(self)

evaluate(d, d) gives tp 1, fa 1, precision 0.5. Dev gives tp 2, fa 0, precision 1.0. Through eval_for(), the Strands Evals 1.6.0 test_pass flips from True to False.

cls = type(value)
if not isinstance(dumped, dict) or _is_opaque(cls):
return dumped
own_keys = own_keys or isinstance(value, StructuredModel)

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.

Blocker (new regression): excluded secrets are scored and published in non_matches.

own_keys keeps propagating below a StructuredModel's own ComparableFields. Excluded values are then refilled and scored on plain models under a StructuredModel, and on StructuredModels inside a plain model's Union/Any/Dict field.

  • Acct2(StructuredModel).cred: Optional[Cred2] with Cred2.token: Optional[str] = Field(None, exclude=True): running evaluate() with differing users puts 'SECRET-GT' in non_matches. Dev does not.
  • Plain M2 with u: Union[S, B], anyv: Any, ds: Dict[str, S], where only the excluded S.secret differs: head scores u 0.0, anyv 0.0, ds 0.818 and publishes both secrets. Dev scores 1.0 and publishes neither.

auto/README.md:170 says "On a plain model nothing is added back". Stop the propagation at the plain-model boundary.

if not hasattr(instance, name):
continue # model_construct without it
key = (
(field.serialization_alias or field.alias or name) if by_alias else name

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.

Blocker from the last round, still open and wider than first reported: nested fields are keyed by the dump key instead of the validation key.

  • With serialize_by_alias=True and a serialization_alias: evaluate(P(c=C(v='a')), P(c=C(v='b'))) gives {'c': 1.0}, while compare_with() gives 0.0.
  • The default config loses values too. With Address(alias_generator=to_camel).zip_code nested in Customer, evaluate gives {'address': 1.0} and compare_with gives 0.0.
  • validation_alias and AliasChoices fields are lost the same way, including excluded ones that line 1144 re-adds as field.alias or name.

facade._validation_key (facade.py:571) already computes the correct key, so use it here. The bug exists on dev, but this PR's CHANGELOG states that evaluate() agrees with compare_with().

def whole(value: Any, dumped: Any) -> Any:
if isinstance(value, StructuredModel):
return ConfigurationHelper._dump_whole(value)
if isinstance(value, (list, tuple)) and any(

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.

Blocker from the last round, still open and wider than first reported: whole() only descends into StructuredModels and lists or tuples of them.

  • H.d: Dict[str, S] with an excluded S.secret: a different secret scores d 1.0, while the same data in List[S] scores 0.5.
  • A plain Ans(value, reasoning: str = Field(exclude=True)) inside Doc(StructuredModel) inside WrapS(StructuredModel): WrapS.from_json(valid) and evaluate(w, w) raise ValidationError doc.answer.reasoning, while compare_with() gives 1.0.
  • List[List[Sub]] loses Sub's excluded field.

The CHANGELOG (line 96) and this docstring both say "at any depth". Descend into dict values, plain models, and nested lists, or narrow the claim.

@sromoam
sromoam marked this pull request as draft October 29, 2026 16:38
@sromoam

sromoam commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

Parked. Fixes for the 28 Oct review are on wip/380-review-fixes; picking this up after 1.0.1.

@sromoam

sromoam commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Deferring this to 1.1.0, so it stays out of 1.0.2; #378 and #379 are milestoned 1.1.0 too.

Before it's ready for another review:

  • @vawsgit's two open blockers from 20 Oct: nested fields are keyed by the dump key instead of the validation key, and Dict[str, StructuredModel] values aren't walked. Plus the five regressions from 28 Oct.
  • Merge current dev, which conflicts in CHANGELOG.md and src/stickler/auto/facade.py.

I'll pick it back up after 1.0.2 ships. Thanks @vawsgit and @digalaviz for the thorough rounds.

@sromoam sromoam modified the milestones: 1.1.0, 1.1.1 Nov 23, 2026
@sromoam

sromoam commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Closing this for now. #378 and #379 stay open in 1.1.1 and track the work, including vawsgit's open blockers from 28 Oct; a fresh PR will pick it up from current dev.

@sromoam sromoam closed this Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants