Repository navigation
Conversation
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.
vawsgit
left a comment
There was a problem hiding this comment.
needs changes
src/stickler/auto/facade.py:372: an excluded field that holds a model is rebuilt without thePydanticSerializationErrorguard, soevaluate()now raises wheredevreturned a score.src/stickler/auto/facade.py:374: the excluded-field rebuild also applies toStructuredModel.extra_fields, which writes anextra_fieldskey into the dump and nests it inside the instance's ownextra_fields.
Measured with PYTHONPATH pinned to a worktree at cbd3aa0 and compared against dev at 43a573d.
| key = ( | ||
| (field.serialization_alias or field.alias or name) if by_alias else name | ||
| ) | ||
| if name in rebuild: |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| ) | ||
| if name in rebuild: | ||
| out[key] = _wire(getattr(value, name), own_keys) | ||
| elif key not in out: |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Security Scan ResultsASH Security Scan Report
Scan Metadata
SummaryScanner ResultsThe table below shows findings by scanner, with status based on severity thresholds and dependencies:
Top 3 HotspotsFiles with the highest number of security findings:
Detailed FindingsShow 5 actionable findingsFinding 1: SECRET-HEX-HIGH-ENTROPY-STRING
Description: Code Snippet: Finding 2: B108
Description: Code Snippet: Finding 3: B307
Description: Code Snippet: Finding 4: B307
Description: Code Snippet: Finding 5: B102
Description: Code Snippet: Report generated by Automated Security Helper (ASH) at 2026-10-28T23:03:17+00:00 |
- 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.
There was a problem hiding this comment.
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())). WithDict[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)). Forsetandfrozensetthe only thing keeping them aligned is that pydantic-core and thezipiterate 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_ifis conditional, so the field is present in one dump and absent in the other. Present againstNonescores 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:
- Keep the design and make it loud. Move the entry to
### Changedwith the- **Breaking:**prefix, and state in the entry itself that excluded fields are now compared and their values appear innon_matchesand HTML reports. The entry is the right place rather thanauto/README.mdalone, since someone taking a patch upgrade reads the changelog. - 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.
| elif entry.excluded: | ||
| item = _dump_excluded(cls, entry, raw, own_keys) | ||
| if item is not _MISSING: | ||
| out[key] = item |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| - **`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)) | ||
|
|
There was a problem hiding this comment.
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.
# Conflicts: # CHANGELOG.md
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.
|
Thanks @digalaviz, this was the right call to raise. In The rule and its reasoning are defined in a new Excluded fields section in A On your notes:
|
digalaviz
left a comment
There was a problem hiding this comment.
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=Trueis static, "never in the output", which is exactly the case for leaving the field out.exclude_ifis conditional, so keep the field in the shadow model and let_dumpfill it from the annotation. That machinery already exists here:_dump_excludeddoes it for aStructuredModel. - 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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: | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
#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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| later on subscripting | ||
| ([#350](https://github.com/awslabs/stickler/issues/350)) | ||
|
|
||
| - **Breaking:** on the zero-config path (`stickler.evaluate()`, `eval_for()`, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Fair point. The new commit is fix(auto)!: with a BREAKING CHANGE: footer, and the squash title will be fix(auto)!: ....
|
needs changes Blockers, each posted as an inline comment:
Two optional items (efficiency, commit subject) are also inline. Numbers were measured against |
vawsgit
left a comment
There was a problem hiding this comment.
needs changes
I measured on head ec3cf4b. Four blockers, each reproduced against dev. Details are in the inline comments.
src/stickler/auto/facade.py:399. When a plain-modelexclude_iffield does not fire,_restorere-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 wherenot own_keys and entry.excluded.src/stickler/auto/builder.py:358. A nested plain model whose fields are all excluded now raisesTypeError: needs at least one field, so the parent can no longer be evaluated. Ondev, the same input returned{'answer': 1.0, 'trace': 1.0}.configuration_helper.py:1099.StructuredModel.from_json()now passes a nested model instance instead of a dict. A user'smodel_validator(mode='before')that reads the nested dict raisesTypeError. This public behaviour change is not listed as breaking in the CHANGELOG.src/stickler/auto/facade.py:384. Under aStructuredModel,own_keyskeepsserialization_aliaskeys, but pydantic validation never readsserialization_alias. #378 is therefore still open:evaluate()scores a wrong value 1.0, whilecompare_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).
|
Thanks both. @digalaviz, on the blocker, I went with splitting the flags. On @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 |
# Conflicts: # CHANGELOG.md
| if not hasattr(instance, name): | ||
| continue # model_construct without it | ||
| key = ( | ||
| (field.serialization_alias or field.alias or name) if by_alias else name |
There was a problem hiding this comment.
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"}}).cgivesv=None VV='a'.evaluate(P(c=C(v="a")), P(c=C(v="b"))).field_scoresgives{'c': 1.0}, butP(c=C(v="a")).compare_with(P(c=C(v="b")))gives{'c': 0.0}. The result is the same with a plain-BaseModelparent.
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( |
There was a problem hiding this comment.
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"].hidgives''.- The same document with
hid: "WRONG"on one side:compare_withgivesoverall_score=1.0. - With
l: List[Sub]in place of the dict, the PR head correctly gives0.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 |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
configuration_helper.py:1140._dump_wholekeys byserialization_aliasunderserialize_by_alias=True, so aStructuredModelnested one level down loses that value.evaluate(P(c=C(v="a")), P(c=C(v="b")))gives{'c': 1.0}, whilecompare_with()gives 0.0. This contradicts the #378 CHANGELOG line "soevaluate()agrees withcompare_with()". Fix the key rule, or narrow the CHANGELOG wording. #380 (comment)configuration_helper.py:1124.whole()walks lists and tuples but not dicts. Anexclude=Truefield insideDict[str, StructuredModel]values is still lost, so a wrong value scores 1.0. TheList[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
left a comment
There was a problem hiding this comment.
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:
configuration_helper.py:1145_dump_wholeand_restorere-validate excluded fields, sofrom_json()andevaluate()raiseValidationErroron valid input.configuration_helper.py:1136The addedextra_fieldskey and default-valued excluded fields change which Union arm pydantic picks and breakmode="before"validators.auto/builder.py:394On the documentedfrom_pydantic()+from_json(x.model_dump())path, identical documents get false alarms.auto/facade.py:397With a wrapmodel_serializeror a field serializer, identical documents get false alarms insideevaluate().auto/facade.py:399own_keyspropagates past a StructuredModel's own fields, so excluded secrets on plain models are scored and published innon_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)) |
There was a problem hiding this comment.
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 makesevaluate(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(): |
There was a problem hiding this comment.
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]], wherePersonis a StructuredModel andCompanyis a plain model:Doc.from_json({'party': {'legal_name': 'ACME', 'tax_id': '123'}})returns aPerson. Dev returns aCompany.evaluate()on twoCompanyparties with differenttax_idscoresparty1.0 with fa=2. Dev andcompare_with()give 0.0.- A nested
@field_validator('*', mode='before')that returnsv.strip()now raisesAttributeErrorinfrom_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): |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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]withCred2.token: Optional[str] = Field(None, exclude=True): runningevaluate()with differing users puts'SECRET-GT'innon_matches. Dev does not.- Plain
M2withu: Union[S, B],anyv: Any,ds: Dict[str, S], where only the excludedS.secretdiffers: 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 |
There was a problem hiding this comment.
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=Trueand aserialization_alias:evaluate(P(c=C(v='a')), P(c=C(v='b')))gives{'c': 1.0}, whilecompare_with()gives 0.0. - The default config loses values too. With
Address(alias_generator=to_camel).zip_codenested inCustomer,evaluategives{'address': 1.0}andcompare_withgives 0.0. validation_aliasandAliasChoicesfields are lost the same way, including excluded ones that line 1144 re-adds asfield.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( |
There was a problem hiding this comment.
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 excludedS.secret: a different secret scoresd1.0, while the same data inList[S]scores 0.5.- A plain
Ans(value, reasoning: str = Field(exclude=True))insideDoc(StructuredModel)insideWrapS(StructuredModel):WrapS.from_json(valid)andevaluate(w, w)raiseValidationError doc.answer.reasoning, whilecompare_with()gives 1.0. List[List[Sub]]losesSub'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.
|
Parked. Fixes for the 28 Oct review are on |
|
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:
I'll pick it back up after 1.0.2 ships. Thanks @vawsgit and @digalaviz for the thorough rounds. |
Closes #378. Closes #379.
stickler.evaluate()andeval_for()scored a wrong value as1.0when a field never reached the inferred shadow model:serialize_by_alias=True,model_dumpwrote alias keys, and the shadow model reads field names.Field(exclude=True)orexclude_iffield was left out of the dump but kept in the shadow model.Either way the field was blank on both sides, and blank against blank counts as a match. A required field raised
ValidationErrorinstead.Change
#378, alias keys.
_dumpinauto/facade.pykeeps pydantic's ownmodel_dump(mode="json"), so serializers andser_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. AStructuredModel, and everything under it, keeps its own key spelling, because it validates through its own config. The walk doesn't enter aRootModel, amodel_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()".excludemarks a field as outside the model's output, typically a reasoning trace or internal notes on aresponse_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.pyleaves the field out of the shadow model andexplain(), at any depth, so it never reachesfield_scores,non_matchesor a report, and a required one is no longer required.exclude_ifis decided per value, as pydantic decides it: a value it keeps is scored, and a value it leaves out is absent, likeNone.StructuredModelis used as configured: itsComparableFields declare what is compared, andexcludeonly affects serialization. Inside one,_dumpadds the excluded field back from its annotation, soevaluate()scores it ascompare_with()does instead of1.0.StructuredModel.from_json()passed a nestedStructuredModelon as itsmodel_dump(), which dropped its excluded fields andextra_fields. It still passes the dump, so amode="before"validator sees a dict, and now puts the excluded fields andextra_fieldsback at any depth, so a nested excluded field is scored bycompare_with()too.Docs
docs/API-Reference/auto.md: a new Excluded fields section defines the rule, the reasoning, theStructuredModelcontrast, and how to score one anyway.ultra-quick-start.md: a row in the "How it decides" table.auto/README.md: the honesty rule and the dump-walk notes.CHANGELOG.md: Fields declared Field(exclude=True) are never compared, so a wrong value scores 1.0 #379 under Changed as Breaking; Plain models with serialize_by_alias=True raise or score a wrong prediction 1.0 #378 and thefrom_jsonfix under Fixed.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 fromfield_scores,explain()andnon_matches; no weight; not required; nested, list, dict, set and nested-list cases;exclude_iffiring and not; a model with only excluded fields raises clearly.TestExcludedFieldsOnAStructuredModel:evaluate()matchescompare_with(), nested under a plain model, thefrom_jsonfix, serializers, and values that fail to dump.Full suite at
cbd8c4b, merged with currentdev: 3011 passed, 2 skipped, 1 xfailed on Python 3.12 with thebertandstrands-agentsextras installed (12 skips underuv sync --frozen), withinspect.getfile(stickler)pointing at this checkout. The Strands Evals 1.6.0 contract suite from #410 passes on this head (776 passed, 1 xfailed).