Classification Logic
Stickler classifies every field comparison into one of five confusion-matrix categories. These categories drive all derived metrics (precision, recall, F1) and aggregate reporting.
Core Definitions
| Category | Abbr. | Definition |
|---|---|---|
| True Positive | TP | GT and EST are both non-null and match above the threshold |
| False Alarm | FA | GT is null, EST is non-null |
| True Negative | TN | GT and EST are both null |
| False Negative | FN | GT is non-null, EST is null |
| False Discovery | FD | GT and EST are both non-null but match below the threshold |
False Alarm (FA) and False Discovery (FD) together make up the broader False Positive (FP) count:
FP = FA + FD
Classification by Data Type
Simple Values (Strings, Numbers, Booleans)
| Ground Truth | Prediction | Classification | Notes |
|---|---|---|---|
"value" |
"value" |
TP | Exact match |
"value" |
"similar" |
FD | Both non-null, below threshold |
"value" |
null |
FN | Missing prediction |
null |
"value" |
FA | Spurious prediction |
null |
null |
TN | Correctly absent |
"" |
null |
TN | Empty string treated as null |
NaN |
NaN |
TN | Float NaN treated as null |
Lists
The list contract
This table is the single statement of how Stickler treats a list field. Other pages link here rather than restate it. The Known gaps note under it lists where the code does not yet follow it.
| Aspect | Rule |
|---|---|
| Pairing | A list field's elements are paired one-to-one by the Hungarian algorithm, maximising total similarity, so their order does not matter: ["a", "b"] vs ["b", "a"] scores 1.0. An element that is itself a list (List[List[str]]) is compared as one whole value, so order inside it does count. On the zero-config path (stickler.evaluate() on a plain pydantic class) that inner list, and a list held in an Any field, must match exactly, order included. None and NaN elements are removed first (None elements in a list); reports keep original indices. Pair similarity is the field's comparator, or GT[i].compare(Pred[j]) for List[StructuredModel] (fields absent on both sides excluded). |
| Bar | List[StructuredModel]: the element class's match_threshold; a runtime match_threshold does not change it. A field threshold there raises ValueError in Python, and JSON Schema ignores it. Primitive, dict and plain-model lists on a StructuredModel declared in Python: the field's threshold, else a threshold named on the comparator, else 0.5 when declared with ComparableField(), or the class match_threshold (0.7 unless set) when declared without it (tags: List[str]). JSON Schema and the zero-config path have their own defaults (JSON Schema, zero-config). A pair that meets the bar is a TP. |
Counts (the list node's overall) |
Paired element: TP if it meets the bar, else FD. Unpaired GT element: FN. Unpaired prediction: FA. An empty, None or all-None list is null: both null is one TN (score 1.0); one side null gives one FN or FA per present element (score 0.0). |
| Recursion | Only TP pairs of StructuredModel items are descended into. FD, FN and FA items are atomic. aggregate holds the leaves of TP items only, so FD, FN and FA items are left out of it when any sibling was accepted. With no accepted item it falls back to the list node's own counts (why). |
| Score | sum(pair scores) / max(n_gt, n_pred), never clipped as a whole against a field threshold. For primitive, dict and plain-model lists the pair score is the element similarity, zeroed below the bar when clip_under_threshold is on. On a StructuredModel declared in Python it defaults to on for primitive lists and off for dict and plain-model lists. JSON Schema and the zero-config path have their own defaults (JSON Schema, zero-config). For List[StructuredModel] the pair score is GT[i].compare_with(Pred[j])["overall_score"], which applies each field's own threshold and can differ from the pairing similarity. Currently clip_under_threshold has no effect there, so an FD pair keeps its score: a known gap. Worked example. |
| Reports | field_comparisons: one row per element of a primitive, dict or plain-model list, whatever its classification (a dict or plain-model element is not expanded into its keys or fields); for List[StructuredModel], one row per leaf of a TP item and one object row per FD, FN or FA item. non_matches has the same rows, but only the FD, FN and FA ones. A field_comparisons row's match is true when its own classification is TP or TN: a value or object row met its bar; a list row had every element paired as a TP, with no FD, FA or FN at the element level. Failures deeper down get their own rows. |
Known gaps. Four behaviours are defects, not the contract: clip_under_threshold having no effect on List[StructuredModel]; inside a list item, a field_comparisons row reporting the clipped score, and a nested list or object getting one row; a None list being reported differently from [] in field_comparisons (one row for the whole field against a non-empty list, and one row against another None, where every other pair of null lists, such as [] vs [], gets none); and inside a list item, the cases listed under Nested lists below counting differently than at top level.
None elements in a list
A None element marks an absence, not an object or a value, so it is left out before matching. This holds for a list field of models (List[Optional[Model]]) or of primitives (List[Optional[str]]), at any depth, and for a float NaN element, which counts as None. An empty string element is still a value. A list inside a list (List[List[str]]) or a dict value is compared as one whole value, so its Nones are part of that value.
| GT | EST | Result |
|---|---|---|
[A, None] |
[A, None] |
1 TP |
[A, B, C] |
[A, None, C] |
2 TP, 1 FN: B was missed |
[A] |
[None] |
1 FN, as [A] vs [] |
[None] |
[A] |
1 FA, as [] vs [A] |
[None] |
[None] |
TN, as [] vs [] |
This follows the null rules above: an absent value against a present one is an FN or FA, and two absences are not evidence of a match. Counting a None as an element would credit two Nones as a TP, and would count a missed row as an FD (or, in a list of models, a TP), so the miss would keep recall at 1.0. Elements keep their original positions in reports: in [A, None, C], C is reported as [2].
- Positional lists are not supported either way. Matching ignores order, so a
Nonecannot mean "slot 3 is empty":[None, A]and[A, None]already compare as identical. Put the position in the data instead, for example apage_numberfield, and matching pairs elements by it. - To score an absence, give it content. If ground truth marks a row as unreadable and agreeing on that should earn credit, model it as a value, such as
Line(status="illegible"). ANonecarries nothing to compare.
Example: Mixed Matching
GT = ["red", "blue", "green"]
EST = ["red", "yellow", "orange", "blue"]
The assignment pairs as many elements as the shorter list allows, so it makes three pairs here and leaves one prediction over:
| GT | EST | Score | Classification |
|---|---|---|---|
"red" |
"red" |
1.00 | TP |
"blue" |
"blue" |
1.00 | TP |
"green" |
"orange" |
0.17 | FD |
"yellow" |
FA |
Result: TP=2, FD=1, FA=1, FN=0, and so FP=2
Note that "green" is an FD and not an FN. It did get a partner, and a low
score is what the FD category is for. Only an element the assignment could not
pair at all is FN or FA, which is why FN is zero whenever GT is the shorter
list.
Example: Below-Threshold Matches
GT = ["apple", "banana", "cherry"]
EST = ["appx", "bnn", "chry"] (threshold = 0.7)
All pairs match below 0.7 -- each is FD.
Result: TP=0, FA=0, FN=0, FD=3
Nested Objects
Nested objects are evaluated recursively, field by field, with >= as described in Meeting a Threshold.
| Condition | Classification |
|---|---|
| Both have the field, similarity >= threshold | TP |
| Both have the field, similarity < threshold | FD |
| Only GT has the field | FN |
| Only EST has the field | FA |
Example
GT = {name: "John", age: 30, address: "123 Main St"}
EST = {name: "John", age: 31, phone: "555-1234"}
name: exact match -- TPage: both present, mismatch -- FDaddress: only in GT -- FNphone: only in EST -- FA
Result: TP=1, FA=1, FN=1, FD=1
Objects of different classes
Two objects of different classes are always an FD, whatever their attributes say. Identical field names and identical values do not make them a match:
Pet(name="rex") vs Cat(name="rex") -> FD
This is the one FD in the table above that is not a threshold decision. Every
other row compares a similarity against a cutoff; this one is settled before any
comparator runs, because the class is part of the value's identity rather than
metadata about it. A Cat is not a Pet that happens to score well.
The rule uses the EXACT class, so a subclass against its base is also an FD. A subclass carries fields the base does not, so the two do not describe the same shape, and scoring them on their shared fields would report a near-match for what is really a schema difference.
Stickler warns once per field rather than raising. Which class arrives is a property of the prediction, so raising would end a bulk run on document N after succeeding on N-1.
A correctly annotated field never reaches this rule: pydantic refuses a Dog for
an Optional[Cat] field when the object is constructed. It applies where the
annotation permitted more than one class (Union[Cat, Dog], Any, object) or
where a subclass arrived for its base, which Optional[Pet] accepts.
Enforced for plain BaseModel objects, not yet for StructuredModel
As of this release the rule is applied to plain pydantic.BaseModel objects
and to the elements of a list of them. Two StructuredModel objects of
different classes are still scored field by field and can report TP:
Pet(name="rex") vs Cat(name="rex") plain BaseModel 0.0 FD
StructuredModel 1.0 TP
That is the older behaviour rather than a deliberate exception, and closing it is
tracked in #327. Until then, treat a heterogeneous StructuredModel pair as
unverified rather than as endorsed: annotate the field with a single model type
if you need the guarantee today.
The same gap lets a pair in a list of models count a TP even when it scores
0.0. Pairing uses compare(), which skips the fields the prediction lacks,
so in a List[Union[Search, Browse]] field, [Search(query="hotels")]
against [Browse(url="x.com")] counts a TP, with query an FN under
aggregate, while the field scores 0.0. A model paired with an element
that is not a model, such as a string, dict or list, is a TP the same way:
in an Any, object or List[Any] field, at top level or in a list
element, [Inner(a="x", b=None)] against ["a"] counts a TP, with a an
FN and b a TN under aggregate. So does [Inner(a="x", b=None)]
against [{"a": "x"}]. A plain pydantic element is the exception: scoring
a model against one raises TypeError. These pairs, and one against a
model of another class such as [Other(c="z")], count a TP also when the
list element's class overrides compare_with() to return a fixed score.
Such an element never scores its fields. So in a field read by value, such
as Any or object (see Nested lists below), where scoring two lists
would raise, the field counts one TP or FD from its comparator instead.
That covers [Inner(a="x", b=None)] against a list of plain pydantic
models, and a ground-truth list holding a value without compare_with(),
such as [Inner(a="x", b=None), "b"] against ["a", "b"]. Where scoring
two models of one class would raise, such as two models whose fields hold
those lists, the field counts one TP or FD from the ground-truth model's
own compare_with(). That runs when the model's class also returns a
fixed score, and raises the same way when it recurses. A field that goes
to the dispatcher directly, such as List[Any], raises on these pairs,
unless the list's first element's class does not declare it as a model
or a list, as with a subclass's field after its base. Then it counts
them the same way.
Whether a refused object should still pair inside a list, or should instead be counted as a missed ground truth plus an invented prediction, is the open question in #321.
Derived Metrics
From the base counts:
| Metric | Formula | Meaning |
|---|---|---|
| Precision | TP / (TP + FP) | Fraction of predictions that are correct |
| Recall | TP / (TP + FN) | Fraction of ground-truth values found (FD in neither term; see below) |
| F1 Score | 2 * Precision * Recall / (Precision + Recall) | Harmonic mean of precision and recall |
| Accuracy | (TP + TN) / (TP + TN + FP + FN) | Overall correctness |
An FD is invisible to recall under that formula, because it appears in
neither term. The mixed-matching example above scores recall 1.000 even though
"green" was never found, since it is an FD and not an FN. Set
recall_with_fd=True for TP / (TP + FN + FD), which scores the same example
0.667. HungarianMatcher.calculate_metrics always uses that second formula.
See FD and recall.
These are computed at every node of the result tree, from that node's own counts, and which counts those are depends on which node you read. overall classifies that node's direct children: for a list field, whether each pairing was genuine or spurious; at the root, its own fields, which means the two units can mix in a single count. aggregate gives leaf detail, and for a list of objects that means only the items that were comparable, since a list item below the element class's match_threshold is one FD and is not descended into; unmatched FN and FA items are left out too when a sibling was accepted (Recursion). A single nested StructuredModel field is not gated this way: its leaves are always reported. See Which node answers which question.
Edge Cases
Null vs. empty equivalence -- Empty strings (""), empty lists ([]), empty objects ({}), and float NaN are treated as null. Comparing any of these with null yields TN.
TN in object matching -- A TN is absence of evidence, not evidence of a match. Fields absent on both sides are excluded from the weighted object similarity used by Hungarian matching. If every field is absent, the similarity is defined as 1.0.
Threshold boundary -- A similarity score exactly equal to the threshold counts as a match (TP). So does a score less than 1e-10 under it, at every gate listed in Meeting a Threshold, so a rounding error such as 0.7 + 0.1 (0.7999999999999999) against 0.8 does not turn a TP into an FD.
List order -- The order of a list field's elements does not matter. The Hungarian algorithm finds the optimal pairing regardless of element position. A nested list element is compared as one whole value (Pairing).
Nested lists -- For List[StructuredModel], the Hungarian algorithm pairs objects at the list level, then each TP pair is evaluated recursively (Recursion): every field the ground-truth element's class declares is classified by the same dispatcher as a top-level field, so it follows the rules on this page. A field annotated as a model, a list, or an Optional model or union of models, such as Optional[Inner], List[str], Optional[Union[A, B]] or Union[A, B, List[str]], goes to the dispatcher directly. Any other field, such as Any, object, Union[A, B], Sequence[str] or Optional[Annotated[Inner, Field(...)]], is read by its value first. If the classes in one list annotate a field differently, the first matched ground-truth element that declares it decides which, or, when the list's first element is not matched, each pair's own class does. These cases are counted differently from top level:
- A field the predicted element's class does not declare (an extra field) is not counted, where at top level it adds an FA to the root
overall. - In a field read by value, a model of another class than the ground truth's is one TP or FD, from the ground-truth model's
compare_with()score against the field's threshold, andaggregatecounts it the same way rather than per field. That score reads a field the prediction lacks asNone, soSearch(query="hotels")againstBrowse(url="x.com")scores0.0and is an FD. A ground-truth field leftNonematches the missing one, soInner(a="x", b=None)againstOther(c="z")scores0.5, fromb, and is a TP at the default threshold of0.5. It scores only the ground truth's own fields, soPet(name="tom")against its subclassCat(name="tom", lives=9)scores1.0and is a TP, as the warning under Objects of different classes says. A field that goes to the dispatcher directly counts such a pair as top level does. - When a field holds models in some pairs and
Noneor a primitive in others,aggregatekeeps one shape. In a field read by value, every pair counts as one leaf, so the models' own fields are not broken out, and a model of another class has the same effect. In a field that goes to the dispatcher directly, such asOptional[Inner], the models' fields are kept and the other pairs are left out. So[Inner(a="x", b=None), Inner(a="y", b=None)]against[Inner(a="x", b=None), None]givesaggregate1 TP and 1 FN in anAnyfield and 1 TP and 1 TN in anOptional[Inner]one, where the same pairs at top level give 1 TP, 1 TN and 1 FN. - In a field read by value, an empty list is null, as the null-vs-empty rule above says, so in an
AnyfieldNoneagainst[]is a TN and"x"against[]an FN. The same field at top level, andnon_matches, read[]as a value, giving an FA and an FD.
Missing vs. null fields -- A missing field and a field explicitly set to null are handled the same way: if the other side has a non-null value, the result is FN or FA accordingly.
See Also
- Understanding Results -- interpreting the full result dictionary
- Hungarian Matching -- details on the list-pairing algorithm