datapi-selfheal 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sentinel/detector.py ADDED
@@ -0,0 +1,626 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ import time
6
+ from enum import StrEnum
7
+ from types import UnionType
8
+ from typing import TYPE_CHECKING, Any, Literal, Union, get_args, get_origin
9
+
10
+ from pydantic import BaseModel, ConfigDict, ValidationError
11
+
12
+ if TYPE_CHECKING:
13
+ from sentinel.llm_fallback import SchemaMappingProvider
14
+
15
+
16
+ class PrimitiveKind(StrEnum):
17
+ NULL = "<null>"
18
+ BOOL = "<bool>"
19
+ INT = "<int>"
20
+ FLOAT = "<float>"
21
+ STR = "<str>"
22
+ INT_STR = "<int_str>"
23
+ FLOAT_STR = "<float_str>"
24
+ BOOL_STR = "<bool_str>"
25
+ ISO_DATETIME = "<iso_datetime>"
26
+ EMPTY_LIST = "<empty_list>"
27
+ EMPTY_OBJECT = "<empty_object>"
28
+
29
+
30
+ type RedactedValue = (
31
+ PrimitiveKind | dict[str, RedactedValue] | list[RedactedValue]
32
+ )
33
+
34
+
35
+ class DriftKind(StrEnum):
36
+ MISSING_FIELD = "missing_field"
37
+ EXTRA_FIELD = "extra_field"
38
+ TYPE_MISMATCH = "type_mismatch"
39
+ NULLABILITY_DRIFT = "nullability_drift"
40
+ ENUM_DRIFT = "enum_drift"
41
+ INVALID_JSON = "invalid_json"
42
+
43
+
44
+ class DriftIssue(BaseModel):
45
+ model_config = ConfigDict(frozen=True)
46
+
47
+ kind: DriftKind
48
+ path: tuple[str | int, ...]
49
+ expected_type: str
50
+ observed_kind: str
51
+ candidate_source_path: tuple[str | int, ...] | None = None
52
+
53
+
54
+ class DriftReport(BaseModel):
55
+ model_config = ConfigDict(frozen=True)
56
+
57
+ model_name: str
58
+ has_drift: bool
59
+ issues: tuple[DriftIssue, ...]
60
+ redacted_snapshot: RedactedValue
61
+ flat_observed_kinds: dict[str, PrimitiveKind]
62
+ elapsed_ms: float
63
+
64
+
65
+ _INT_RE = re.compile(r"^[+-]?\d+$")
66
+ _FLOAT_RE = re.compile(r"^[+-]?(?:\d+\.\d+|\d+\.|\.\d+)(?:[eE][+-]?\d+)?$")
67
+ _ISO_DT_RE = re.compile(
68
+ r"^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)?$"
69
+ )
70
+
71
+
72
+ def classify_scalar(value: Any) -> PrimitiveKind:
73
+ if value is None:
74
+ return PrimitiveKind.NULL
75
+ if isinstance(value, bool):
76
+ return PrimitiveKind.BOOL
77
+ if isinstance(value, int):
78
+ return PrimitiveKind.INT
79
+ if isinstance(value, float):
80
+ return PrimitiveKind.FLOAT
81
+ if isinstance(value, str):
82
+ stripped = value.strip()
83
+ lower = stripped.lower()
84
+ if lower in ("true", "false"):
85
+ return PrimitiveKind.BOOL_STR
86
+ if _INT_RE.match(stripped):
87
+ return PrimitiveKind.INT_STR
88
+ if _FLOAT_RE.match(stripped):
89
+ return PrimitiveKind.FLOAT_STR
90
+ if _ISO_DT_RE.match(stripped):
91
+ return PrimitiveKind.ISO_DATETIME
92
+ return PrimitiveKind.STR
93
+ return PrimitiveKind.STR
94
+
95
+
96
+ def redact_payload(payload: Any) -> RedactedValue:
97
+ if isinstance(payload, dict):
98
+ if not payload:
99
+ return PrimitiveKind.EMPTY_OBJECT
100
+ return {str(k): redact_payload(v) for k, v in payload.items()}
101
+ if isinstance(payload, list):
102
+ if not payload:
103
+ return PrimitiveKind.EMPTY_LIST
104
+ return [redact_payload(item) for item in payload]
105
+ return classify_scalar(payload)
106
+
107
+
108
+ def _flatten_redacted(
109
+ node: RedactedValue, prefix: str = ""
110
+ ) -> dict[str, PrimitiveKind]:
111
+ flat: dict[str, PrimitiveKind] = {}
112
+ if isinstance(node, PrimitiveKind):
113
+ if prefix:
114
+ flat[prefix] = node
115
+ return flat
116
+ if isinstance(node, dict):
117
+ for key, child in node.items():
118
+ next_prefix = f"{prefix}.{key}" if prefix else key
119
+ flat.update(_flatten_redacted(child, next_prefix))
120
+ return flat
121
+ if isinstance(node, list):
122
+ for idx, child in enumerate(node):
123
+ next_prefix = f"{prefix}[{idx}]"
124
+ flat.update(_flatten_redacted(child, next_prefix))
125
+ return flat
126
+ return flat
127
+
128
+
129
+ def _lookup_path(payload: Any, path: tuple[str | int, ...]) -> tuple[bool, Any]:
130
+ curr = payload
131
+ for segment in path:
132
+ if isinstance(segment, int):
133
+ if isinstance(curr, list) and 0 <= segment < len(curr):
134
+ curr = curr[segment]
135
+ else:
136
+ return False, None
137
+ elif isinstance(curr, dict) and segment in curr:
138
+ curr = curr[segment]
139
+ else:
140
+ return False, None
141
+ return True, curr
142
+
143
+
144
+ def _describe_annotation(annotation: Any) -> str:
145
+ if annotation is None or annotation is type(None):
146
+ return "None"
147
+ origin = get_origin(annotation)
148
+ if origin is Literal:
149
+ lit_args = ", ".join(repr(a) for a in get_args(annotation))
150
+ return f"Literal[{lit_args}]"
151
+ if origin in (Union, UnionType):
152
+ parts = [_describe_annotation(arg) for arg in get_args(annotation)]
153
+ return " | ".join(parts)
154
+ if origin is list:
155
+ type_args = get_args(annotation)
156
+ inner = _describe_annotation(type_args[0]) if type_args else "Any"
157
+ return f"list[{inner}]"
158
+ if origin is dict:
159
+ type_args = get_args(annotation)
160
+ if len(type_args) == 2:
161
+ return (
162
+ f"dict[{_describe_annotation(type_args[0])}, "
163
+ f"{_describe_annotation(type_args[1])}]"
164
+ )
165
+ return "dict[Any, Any]"
166
+ if isinstance(annotation, type):
167
+ return annotation.__name__
168
+ return str(annotation)
169
+
170
+
171
+ def _resolve_expected_type(
172
+ model_cls: type[BaseModel], path: tuple[str | int, ...]
173
+ ) -> str:
174
+ curr_model: type[BaseModel] | None = model_cls
175
+ last_annotation: Any = None
176
+ for segment in path:
177
+ if isinstance(segment, int):
178
+ continue
179
+ if curr_model is not None and segment in curr_model.model_fields:
180
+ field_info = curr_model.model_fields[segment]
181
+ last_annotation = field_info.annotation
182
+ curr_model = None
183
+ if isinstance(last_annotation, type) and issubclass(
184
+ last_annotation, BaseModel
185
+ ):
186
+ curr_model = last_annotation
187
+ else:
188
+ origin = get_origin(last_annotation)
189
+ if origin in (Union, UnionType):
190
+ for arg in get_args(last_annotation):
191
+ if isinstance(arg, type) and issubclass(arg, BaseModel):
192
+ curr_model = arg
193
+ break
194
+ elif origin is list:
195
+ args = get_args(last_annotation)
196
+ if (
197
+ args
198
+ and isinstance(args[0], type)
199
+ and issubclass(args[0], BaseModel)
200
+ ):
201
+ curr_model = args[0]
202
+ else:
203
+ break
204
+ if last_annotation is not None:
205
+ return _describe_annotation(last_annotation)
206
+ return "unknown"
207
+
208
+
209
+ def _normalize_list_indices(path: tuple[str | int, ...]) -> tuple[str | int, ...]:
210
+ return tuple(0 if isinstance(seg, int) else seg for seg in path)
211
+
212
+
213
+ def _classify_list_kinds(items: list[Any], max_items: int = 256) -> str:
214
+ if not items:
215
+ return str(PrimitiveKind.EMPTY_LIST)
216
+ kinds = sorted({str(classify_scalar(item)) for item in items[:max_items]})
217
+ return f"list[{'|'.join(kinds)}]"
218
+
219
+
220
+ def _collect_extra_paths(
221
+ model_cls: type[BaseModel],
222
+ payload: Any,
223
+ prefix: tuple[str | int, ...] = (),
224
+ ) -> list[tuple[tuple[str | int, ...], str]]:
225
+ extras: list[tuple[tuple[str | int, ...], str]] = []
226
+ if not isinstance(payload, dict):
227
+ return extras
228
+ known_fields = model_cls.model_fields
229
+ for key, val in payload.items():
230
+ current_path = (*prefix, str(key))
231
+ if key not in known_fields:
232
+ if isinstance(val, dict):
233
+ for sub_key, sub_val in val.items():
234
+ sub_path = (*current_path, str(sub_key))
235
+ if isinstance(sub_val, dict):
236
+ for leaf_key, leaf_val in sub_val.items():
237
+ leaf_kind = (
238
+ _classify_list_kinds(leaf_val)
239
+ if isinstance(leaf_val, list)
240
+ else str(classify_scalar(leaf_val))
241
+ )
242
+ extras.append(((*sub_path, str(leaf_key)), leaf_kind))
243
+ else:
244
+ sub_kind = (
245
+ _classify_list_kinds(sub_val)
246
+ if isinstance(sub_val, list)
247
+ else str(classify_scalar(sub_val))
248
+ )
249
+ extras.append((sub_path, sub_kind))
250
+ elif isinstance(val, list):
251
+ extras.append((current_path, _classify_list_kinds(val)))
252
+ else:
253
+ extras.append((current_path, str(classify_scalar(val))))
254
+ else:
255
+ annotation = known_fields[key].annotation
256
+ nested_model = _extract_model_type(annotation)
257
+ if nested_model is not None and isinstance(val, dict):
258
+ extras.extend(_collect_extra_paths(nested_model, val, current_path))
259
+ elif nested_model is not None and isinstance(val, list):
260
+ for idx, item in enumerate(val):
261
+ if isinstance(item, dict):
262
+ extras.extend(
263
+ _collect_extra_paths(
264
+ nested_model, item, (*current_path, idx)
265
+ )
266
+ )
267
+ return extras
268
+
269
+
270
+ def _extract_model_type(annotation: Any) -> type[BaseModel] | None:
271
+ if isinstance(annotation, type) and issubclass(annotation, BaseModel):
272
+ return annotation
273
+ origin = get_origin(annotation)
274
+ if origin in (Union, UnionType, list):
275
+ for arg in get_args(annotation):
276
+ if isinstance(arg, type) and issubclass(arg, BaseModel):
277
+ return arg
278
+ return None
279
+
280
+
281
+ def _tokenize_key(name: str) -> list[str]:
282
+ s1 = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", name).lower()
283
+ return [tok for tok in re.split(r"[^a-z0-9]+", s1) if tok]
284
+
285
+
286
+ _STOP_SUFFIXES = {
287
+ "id",
288
+ "ms",
289
+ "sec",
290
+ "secs",
291
+ "seconds",
292
+ "cents",
293
+ "usd",
294
+ "eur",
295
+ "str",
296
+ "num",
297
+ "val",
298
+ "value",
299
+ "code",
300
+ "text",
301
+ "iso",
302
+ "ts",
303
+ "at",
304
+ "on",
305
+ "flag",
306
+ "is",
307
+ "has",
308
+ }
309
+
310
+ _SYNONYM_GROUPS: tuple[frozenset[str], ...] = (
311
+ frozenset({"amount", "amt", "total", "price", "cost", "charge"}),
312
+ frozenset({"currency", "curr", "ccy", "iso_currency"}),
313
+ frozenset({"customer", "cust", "client", "user", "buyer", "contact"}),
314
+ frozenset({"email", "mail", "email_address", "e_mail"}),
315
+ frozenset({"created", "created_at", "creation", "timestamp", "created_ts", "issued"}),
316
+ frozenset({"status", "state", "stage", "phase", "lifecycle"}),
317
+ frozenset({"temp", "temperature", "degrees", "celsius", "fahrenheit"}),
318
+ frozenset({"humidity", "relative_humidity", "moisture", "rh"}),
319
+ frozenset({"wind", "wind_speed", "gust", "velocity", "kph", "mph"}),
320
+ frozenset({"company", "org", "organization", "account", "firm"}),
321
+ frozenset({"phone", "mobile", "telephone", "tel", "cell"}),
322
+ frozenset({"active", "enabled", "is_active", "live", "verified"}),
323
+ frozenset({"description", "desc", "summary", "details", "note"}),
324
+ frozenset({"id", "identifier", "uid", "uuid", "key"}),
325
+ frozenset({"deal", "opportunity", "pipeline"}),
326
+ frozenset({"revenue", "arr", "mrr", "annual_revenue"}),
327
+ )
328
+
329
+
330
+ def _are_tokens_synonymous(t1: str, t2: str) -> bool:
331
+ if t1 == t2:
332
+ return True
333
+ if (len(t1) >= 3 and t2.startswith(t1)) or (len(t2) >= 3 and t1.startswith(t2)):
334
+ return True
335
+ for group in _SYNONYM_GROUPS:
336
+ if t1 in group and t2 in group:
337
+ return True
338
+ return False
339
+
340
+
341
+ def _type_compatible(expected_type: str, observed_kind: str) -> bool:
342
+ exp = expected_type.lower()
343
+ if observed_kind == PrimitiveKind.NULL:
344
+ return "none" in exp
345
+ if "list" in exp:
346
+ return observed_kind == PrimitiveKind.EMPTY_LIST or observed_kind.startswith(
347
+ "list["
348
+ )
349
+ if "int" in exp:
350
+ return observed_kind in (
351
+ PrimitiveKind.INT,
352
+ PrimitiveKind.INT_STR,
353
+ PrimitiveKind.FLOAT,
354
+ )
355
+ if "float" in exp:
356
+ return observed_kind in (
357
+ PrimitiveKind.FLOAT,
358
+ PrimitiveKind.INT,
359
+ PrimitiveKind.FLOAT_STR,
360
+ PrimitiveKind.INT_STR,
361
+ )
362
+ if "bool" in exp:
363
+ return observed_kind in (
364
+ PrimitiveKind.BOOL,
365
+ PrimitiveKind.BOOL_STR,
366
+ PrimitiveKind.INT,
367
+ )
368
+ if "str" in exp or "literal" in exp:
369
+ return observed_kind in (
370
+ PrimitiveKind.STR,
371
+ PrimitiveKind.ISO_DATETIME,
372
+ PrimitiveKind.INT_STR,
373
+ PrimitiveKind.FLOAT_STR,
374
+ PrimitiveKind.BOOL_STR,
375
+ )
376
+ return True
377
+
378
+
379
+ def _score_candidate_path(
380
+ missing_path: tuple[str | int, ...],
381
+ expected_type: str,
382
+ candidate_path: tuple[str | int, ...],
383
+ observed_kind: str,
384
+ ) -> float:
385
+ if not _type_compatible(expected_type, observed_kind):
386
+ return -1.0
387
+
388
+ missing_key = str(missing_path[-1])
389
+ missing_tokens = _tokenize_key(missing_key)
390
+ cand_all_tokens: list[str] = []
391
+ for seg in candidate_path:
392
+ if isinstance(seg, str):
393
+ cand_all_tokens.extend(_tokenize_key(seg))
394
+ cand_leaf_tokens = _tokenize_key(str(candidate_path[-1]))
395
+
396
+ if not missing_tokens or not cand_all_tokens:
397
+ return 0.0
398
+
399
+ matched_missing = 0
400
+ for m_tok in missing_tokens:
401
+ if any(_are_tokens_synonymous(m_tok, c_tok) for c_tok in cand_all_tokens):
402
+ matched_missing += 1
403
+
404
+ leaf_matches = sum(
405
+ 1
406
+ for m_tok in missing_tokens
407
+ if any(_are_tokens_synonymous(m_tok, c_tok) for c_tok in cand_leaf_tokens)
408
+ )
409
+
410
+ score = (matched_missing / len(missing_tokens)) * 0.7 + (
411
+ leaf_matches / max(len(missing_tokens), len(cand_leaf_tokens))
412
+ ) * 0.3
413
+
414
+ missing_core = [t for t in missing_tokens if t not in _STOP_SUFFIXES]
415
+ cand_core = [t for t in cand_all_tokens if t not in _STOP_SUFFIXES]
416
+ if missing_core and cand_core and missing_core == cand_core:
417
+ score += 0.35
418
+
419
+ if missing_path[:-1] == candidate_path[:-1]:
420
+ score += 0.1
421
+
422
+ return score
423
+
424
+
425
+ def _classify_validation_error(err: Any, observed_val: Any) -> DriftKind:
426
+ err_type = str(err.get("type", ""))
427
+ if err_type == "missing":
428
+ return DriftKind.MISSING_FIELD
429
+ if err_type == "extra_forbidden":
430
+ return DriftKind.EXTRA_FIELD
431
+ null_err_markers = (
432
+ "none",
433
+ "string_type",
434
+ "int_type",
435
+ "float_type",
436
+ "bool_type",
437
+ "literal_error",
438
+ "list_type",
439
+ "dict_type",
440
+ )
441
+ if observed_val is None and any(m in err_type for m in null_err_markers):
442
+ return DriftKind.NULLABILITY_DRIFT
443
+ if "literal_error" in err_type or "enum" in err_type:
444
+ return DriftKind.ENUM_DRIFT
445
+ return DriftKind.TYPE_MISMATCH
446
+
447
+
448
+ def detect_drift(
449
+ expected_model: type[BaseModel],
450
+ raw_json: str | bytes | dict[str, Any],
451
+ mapping_provider: SchemaMappingProvider | None = None,
452
+ ) -> DriftReport:
453
+ start_ns = time.perf_counter_ns()
454
+
455
+ if isinstance(raw_json, (str, bytes)):
456
+ try:
457
+ parsed: Any = json.loads(raw_json)
458
+ except ValueError:
459
+ elapsed_ms = (time.perf_counter_ns() - start_ns) / 1_000_000.0
460
+ return DriftReport(
461
+ model_name=expected_model.__name__,
462
+ has_drift=True,
463
+ issues=(
464
+ DriftIssue(
465
+ kind=DriftKind.INVALID_JSON,
466
+ path=(),
467
+ expected_type="json_object",
468
+ observed_kind=PrimitiveKind.STR,
469
+ ),
470
+ ),
471
+ redacted_snapshot=PrimitiveKind.STR,
472
+ flat_observed_kinds={},
473
+ elapsed_ms=elapsed_ms,
474
+ )
475
+ else:
476
+ parsed = raw_json
477
+
478
+ redacted = redact_payload(parsed)
479
+ flat_kinds = _flatten_redacted(redacted)
480
+ raw_extra_candidates = _collect_extra_paths(expected_model, parsed)
481
+ extra_candidates: list[tuple[tuple[str | int, ...], str]] = []
482
+ seen_extra: set[tuple[tuple[str | int, ...], str]] = set()
483
+ for cand_path, cand_kind in raw_extra_candidates:
484
+ norm_path = _normalize_list_indices(cand_path)
485
+ if (norm_path, cand_kind) not in seen_extra:
486
+ seen_extra.add((norm_path, cand_kind))
487
+ extra_candidates.append((norm_path, cand_kind))
488
+
489
+ raw_issues: list[DriftIssue] = []
490
+ seen_paths: set[tuple[DriftKind, tuple[str | int, ...]]] = set()
491
+
492
+ try:
493
+ expected_model.model_validate(parsed, strict=True)
494
+ except ValidationError as exc:
495
+ for err in exc.errors():
496
+ loc_tuple: tuple[str | int, ...] = tuple(
497
+ int(x) if isinstance(x, int) else str(x) for x in err.get("loc", ())
498
+ )
499
+ while len(loc_tuple) > 1 and isinstance(loc_tuple[-1], int):
500
+ loc_tuple = loc_tuple[:-1]
501
+ field_loc: tuple[str | int, ...] = _normalize_list_indices(loc_tuple)
502
+ found, observed_val = _lookup_path(parsed, loc_tuple)
503
+ kind = _classify_validation_error(err, observed_val if found else None)
504
+ expected_type = _resolve_expected_type(expected_model, field_loc)
505
+ if not found:
506
+ obs_kind_str = "missing"
507
+ elif isinstance(observed_val, list):
508
+ obs_kind_str = _classify_list_kinds(observed_val)
509
+ elif isinstance(observed_val, dict):
510
+ obs_kind_str = "object"
511
+ else:
512
+ obs_kind_str = str(classify_scalar(observed_val))
513
+
514
+ key = (kind, field_loc)
515
+ if key not in seen_paths:
516
+ seen_paths.add(key)
517
+ raw_issues.append(
518
+ DriftIssue(
519
+ kind=kind,
520
+ path=field_loc,
521
+ expected_type=expected_type,
522
+ observed_kind=obs_kind_str,
523
+ )
524
+ )
525
+
526
+ used_candidates: set[tuple[str | int, ...]] = set()
527
+ enriched_issues: list[DriftIssue] = []
528
+ unmatched_missing_indices: list[int] = []
529
+
530
+ for issue in raw_issues:
531
+ if issue.kind == DriftKind.MISSING_FIELD and extra_candidates:
532
+ best_path: tuple[str | int, ...] | None = None
533
+ best_score = 0.25
534
+ for cand_path, cand_kind in extra_candidates:
535
+ if cand_path in used_candidates:
536
+ continue
537
+ score = _score_candidate_path(
538
+ issue.path, issue.expected_type, cand_path, cand_kind
539
+ )
540
+ if score > best_score:
541
+ best_score = score
542
+ best_path = cand_path
543
+ if best_path is not None:
544
+ used_candidates.add(best_path)
545
+ enriched_issues.append(
546
+ DriftIssue(
547
+ kind=issue.kind,
548
+ path=issue.path,
549
+ expected_type=issue.expected_type,
550
+ observed_kind=issue.observed_kind,
551
+ candidate_source_path=best_path,
552
+ )
553
+ )
554
+ continue
555
+ unmatched_missing_indices.append(len(enriched_issues))
556
+ enriched_issues.append(issue)
557
+
558
+ if (
559
+ mapping_provider is not None
560
+ and unmatched_missing_indices
561
+ and extra_candidates
562
+ ):
563
+ from sentinel.llm_fallback import sanitize_candidate_paths
564
+
565
+ unused_cands = [
566
+ (p, k) for p, k in extra_candidates if p not in used_candidates
567
+ ]
568
+ sanitized_map = sanitize_candidate_paths(unused_cands)
569
+ if sanitized_map:
570
+ missing_req: dict[str, str] = {}
571
+ idx_by_key: dict[str, int] = {}
572
+ for idx in unmatched_missing_indices:
573
+ m_issue = enriched_issues[idx]
574
+ dot_key = ".".join(str(seg) for seg in m_issue.path)
575
+ missing_req[dot_key] = m_issue.expected_type
576
+ idx_by_key[dot_key] = idx
577
+ extra_kinds = {k: v[1] for k, v in sanitized_map.items()}
578
+ llm_matches = mapping_provider.resolve_opaque_mappings(
579
+ expected_model.__name__, missing_req, extra_kinds
580
+ )
581
+ valid_paths_by_tuple = {p: k for p, k in unused_cands}
582
+ for dot_key, cand_tuple in llm_matches.items():
583
+ if dot_key not in idx_by_key or cand_tuple in used_candidates:
584
+ continue
585
+ if cand_tuple not in valid_paths_by_tuple:
586
+ continue
587
+ target_idx = idx_by_key[dot_key]
588
+ target_issue = enriched_issues[target_idx]
589
+ if not _type_compatible(
590
+ target_issue.expected_type, valid_paths_by_tuple[cand_tuple]
591
+ ):
592
+ continue
593
+ used_candidates.add(cand_tuple)
594
+ enriched_issues[target_idx] = DriftIssue(
595
+ kind=target_issue.kind,
596
+ path=target_issue.path,
597
+ expected_type=target_issue.expected_type,
598
+ observed_kind=target_issue.observed_kind,
599
+ candidate_source_path=cand_tuple,
600
+ )
601
+
602
+ for cand_path, cand_kind in extra_candidates:
603
+ top_segment = cand_path[:1]
604
+ if (DriftKind.EXTRA_FIELD, cand_path) not in seen_paths and (
605
+ DriftKind.EXTRA_FIELD,
606
+ top_segment,
607
+ ) not in seen_paths:
608
+ seen_paths.add((DriftKind.EXTRA_FIELD, cand_path))
609
+ enriched_issues.append(
610
+ DriftIssue(
611
+ kind=DriftKind.EXTRA_FIELD,
612
+ path=cand_path,
613
+ expected_type="unexpected",
614
+ observed_kind=cand_kind,
615
+ )
616
+ )
617
+
618
+ elapsed_ms = (time.perf_counter_ns() - start_ns) / 1_000_000.0
619
+ return DriftReport(
620
+ model_name=expected_model.__name__,
621
+ has_drift=len(enriched_issues) > 0,
622
+ issues=tuple(enriched_issues),
623
+ redacted_snapshot=redacted,
624
+ flat_observed_kinds=flat_kinds,
625
+ elapsed_ms=elapsed_ms,
626
+ )