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.
synthesizer/patcher.py ADDED
@@ -0,0 +1,944 @@
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ from collections import defaultdict
5
+ from types import UnionType
6
+ from typing import Any, Literal, Union, get_args, get_origin
7
+
8
+ import libcst as cst
9
+ from pydantic import BaseModel, ConfigDict, ValidationError
10
+
11
+ from sentinel.detector import DriftKind, DriftReport
12
+
13
+
14
+ class PatchAction(BaseModel):
15
+ model_config = ConfigDict(frozen=True)
16
+
17
+ target_model: str
18
+ target_field: str
19
+ drift_kind: DriftKind
20
+ expected_type: str
21
+ observed_kind: str
22
+ source_path: tuple[str | int, ...] | None = None
23
+ target_parent_path: tuple[str, ...] = ()
24
+ nested_path: tuple[str, ...] = ()
25
+
26
+
27
+ class PatchPlan(BaseModel):
28
+ model_config = ConfigDict(frozen=True)
29
+
30
+ model_name: str
31
+ actions: tuple[PatchAction, ...]
32
+
33
+
34
+ class PatchResult(BaseModel):
35
+ model_config = ConfigDict(frozen=True)
36
+
37
+ model_name: str
38
+ original_source: str
39
+ patched_source: str
40
+ plan: PatchPlan
41
+ applied: bool
42
+
43
+
44
+ class VerificationResult(BaseModel):
45
+ model_config = ConfigDict(frozen=True)
46
+
47
+ passed: bool
48
+ syntax_valid: bool
49
+ drifted_payload_valid: bool
50
+ legacy_payload_valid: bool
51
+ error_detail: str | None = None
52
+
53
+
54
+ def _resolve_target_model_at_path(
55
+ root_model: type[BaseModel] | None, path: tuple[str | int, ...]
56
+ ) -> str | None:
57
+ if root_model is None or len(path) < 2:
58
+ return None
59
+ curr_model: type[BaseModel] | None = root_model
60
+ for seg in path[:-1]:
61
+ if isinstance(seg, int):
62
+ continue
63
+ if curr_model is None or seg not in curr_model.model_fields:
64
+ return None
65
+ ann = curr_model.model_fields[seg].annotation
66
+ next_model: type[BaseModel] | None = None
67
+ if isinstance(ann, type) and issubclass(ann, BaseModel):
68
+ next_model = ann
69
+ else:
70
+ origin = get_origin(ann)
71
+ if origin in (Union, UnionType, list):
72
+ for arg in get_args(ann):
73
+ if isinstance(arg, type) and issubclass(arg, BaseModel):
74
+ next_model = arg
75
+ break
76
+ if next_model is None:
77
+ return None
78
+ curr_model = next_model
79
+ return curr_model.__name__ if curr_model is not None else None
80
+
81
+
82
+ def build_patch_plan(
83
+ report: DriftReport, root_model: type[BaseModel] | None = None
84
+ ) -> PatchPlan:
85
+ actions: list[PatchAction] = []
86
+ for issue in report.issues:
87
+ if issue.kind == DriftKind.EXTRA_FIELD or issue.kind == DriftKind.INVALID_JSON:
88
+ continue
89
+ if not issue.path:
90
+ continue
91
+ str_segments = tuple(str(s) for s in issue.path if not isinstance(s, int))
92
+ if not str_segments:
93
+ continue
94
+
95
+ child_model_name = _resolve_target_model_at_path(root_model, issue.path)
96
+ if child_model_name is not None and len(str_segments) >= 2:
97
+ prefix = issue.path[:-1]
98
+ src_path = issue.candidate_source_path
99
+ if src_path is None or (
100
+ len(src_path) > len(prefix) and src_path[: len(prefix)] == prefix
101
+ ):
102
+ rel_src = src_path[len(prefix) :] if src_path is not None else None
103
+ actions.append(
104
+ PatchAction(
105
+ target_model=child_model_name,
106
+ target_field=str_segments[-1],
107
+ drift_kind=issue.kind,
108
+ expected_type=issue.expected_type,
109
+ observed_kind=issue.observed_kind,
110
+ source_path=rel_src,
111
+ nested_path=str_segments[:-1],
112
+ )
113
+ )
114
+ else:
115
+ actions.append(
116
+ PatchAction(
117
+ target_model=report.model_name,
118
+ target_field=str_segments[-1],
119
+ drift_kind=issue.kind,
120
+ expected_type=issue.expected_type,
121
+ observed_kind=issue.observed_kind,
122
+ source_path=src_path,
123
+ target_parent_path=str_segments[:-1],
124
+ )
125
+ )
126
+ continue
127
+
128
+ field_name = str_segments[0]
129
+ actions.append(
130
+ PatchAction(
131
+ target_model=report.model_name,
132
+ target_field=field_name,
133
+ drift_kind=issue.kind,
134
+ expected_type=issue.expected_type,
135
+ observed_kind=issue.observed_kind,
136
+ source_path=issue.candidate_source_path,
137
+ )
138
+ )
139
+ return PatchPlan(model_name=report.model_name, actions=tuple(actions))
140
+
141
+
142
+ def _default_expr_for_type(expected_type: str) -> str:
143
+ exp = expected_type.lower()
144
+ if "none" in exp:
145
+ return "None"
146
+ if exp.startswith("list"):
147
+ return "[]"
148
+ if exp.startswith("dict"):
149
+ return "{}"
150
+ if exp == "bool":
151
+ return "False"
152
+ if exp == "int":
153
+ return "0"
154
+ if exp == "float":
155
+ return "0.0"
156
+ if exp == "str":
157
+ return "''"
158
+ return "None"
159
+
160
+
161
+ def _coercion_lines_for_action(action: PatchAction) -> list[str]:
162
+ f = action.target_field
163
+ exp = action.expected_type
164
+ exp_lower = exp.lower()
165
+ lines: list[str] = []
166
+
167
+ if action.target_parent_path and action.source_path is not None:
168
+ curr_expr = "normalized"
169
+ for p_attr in action.target_parent_path:
170
+ lines.append(f"if not isinstance({curr_expr}.get({p_attr!r}), dict):")
171
+ lines.append(f" {curr_expr}[{p_attr!r}] = {{}}")
172
+ curr_expr = f"{curr_expr}[{p_attr!r}]"
173
+
174
+ src_parts = [str(seg) for seg in action.source_path]
175
+ cond_parts = [f"{f!r} not in {curr_expr}"]
176
+ src_expr = "normalized"
177
+ for part in src_parts[:-1]:
178
+ cond_parts.append(f"isinstance({src_expr}.get({part!r}), dict)")
179
+ src_expr = f"{src_expr}[{part!r}]"
180
+ last_part = src_parts[-1]
181
+ cond_parts.append(f"{last_part!r} in {src_expr}")
182
+ lines.append(f"if {' and '.join(cond_parts)}:")
183
+ lines.append(f" {curr_expr}[{f!r}] = {src_expr}[{last_part!r}]")
184
+ if "int" in exp_lower and "list" not in exp_lower and "dict" not in exp_lower:
185
+ lines.append(f"if isinstance({curr_expr}.get({f!r}), str):")
186
+ lines.append(f" try: {curr_expr}[{f!r}] = int({curr_expr}[{f!r}])")
187
+ lines.append(" except (TypeError, ValueError): pass")
188
+ elif "float" in exp_lower and "list" not in exp_lower:
189
+ lines.append(f"if isinstance({curr_expr}.get({f!r}), str):")
190
+ lines.append(f" try: {curr_expr}[{f!r}] = float({curr_expr}[{f!r}])")
191
+ lines.append(" except (TypeError, ValueError): pass")
192
+ elif "bool" in exp_lower and "list" not in exp_lower:
193
+ lines.append(f"if isinstance({curr_expr}.get({f!r}), str):")
194
+ lines.append(
195
+ f" {curr_expr}[{f!r}] = {curr_expr}[{f!r}].strip().lower() "
196
+ "in ('true', '1', 'yes')"
197
+ )
198
+ return lines
199
+
200
+ if action.source_path is not None:
201
+ if len(action.source_path) == 1:
202
+ src_key = str(action.source_path[0])
203
+ lines.append(
204
+ f"if {f!r} not in normalized and {src_key!r} in normalized:"
205
+ )
206
+ lines.append(f" normalized[{f!r}] = normalized[{src_key!r}]")
207
+ elif len(action.source_path) == 2:
208
+ p0, p1 = str(action.source_path[0]), str(action.source_path[1])
209
+ cond = (
210
+ f"if {f!r} not in normalized "
211
+ f"and isinstance(normalized.get({p0!r}), dict) "
212
+ f"and {p1!r} in normalized[{p0!r}]:"
213
+ )
214
+ lines.append(cond)
215
+ lines.append(f" normalized[{f!r}] = normalized[{p0!r}][{p1!r}]")
216
+ elif len(action.source_path) == 3:
217
+ p0, p1, p2 = (
218
+ str(action.source_path[0]),
219
+ str(action.source_path[1]),
220
+ str(action.source_path[2]),
221
+ )
222
+ cond = (
223
+ f"if {f!r} not in normalized "
224
+ f"and isinstance(normalized.get({p0!r}), dict) "
225
+ f"and isinstance(normalized[{p0!r}].get({p1!r}), dict) "
226
+ f"and {p2!r} in normalized[{p0!r}][{p1!r}]:"
227
+ )
228
+ lines.append(cond)
229
+ lines.append(
230
+ f" normalized[{f!r}] = normalized[{p0!r}][{p1!r}][{p2!r}]"
231
+ )
232
+
233
+ if action.drift_kind == DriftKind.MISSING_FIELD and action.source_path is None:
234
+ default_expr = _default_expr_for_type(exp)
235
+ lines.append(f"if {f!r} not in normalized:")
236
+ lines.append(f" normalized[{f!r}] = {default_expr}")
237
+
238
+ if action.drift_kind == DriftKind.NULLABILITY_DRIFT:
239
+ if "none" not in exp_lower:
240
+ default_expr = _default_expr_for_type(exp)
241
+ lines.append(f"if normalized.get({f!r}) is None:")
242
+ lines.append(f" normalized[{f!r}] = {default_expr}")
243
+
244
+ if "list[" in exp_lower:
245
+ lines.append(
246
+ f"if {f!r} in normalized and not isinstance(normalized[{f!r}], list):"
247
+ )
248
+ lines.append(
249
+ f" normalized[{f!r}] = [] if normalized[{f!r}] is None else [normalized[{f!r}]]"
250
+ )
251
+ if "list[str]" in exp_lower:
252
+ lines.append(f"if isinstance(normalized.get({f!r}), list):")
253
+ lines.append(
254
+ f" normalized[{f!r}] = [str(item) for item in normalized[{f!r}]]"
255
+ )
256
+ elif "list[int]" in exp_lower:
257
+ lines.append(f"if isinstance(normalized.get({f!r}), list):")
258
+ comp = (
259
+ f" normalized[{f!r}] = ["
260
+ f"(item if isinstance(item, int) else "
261
+ f"(int(item) if isinstance(item, str) and item.strip().lstrip('+-').isdigit() "
262
+ f"else int(float(item)))) "
263
+ f"for item in normalized[{f!r}] "
264
+ f"if not isinstance(item, bool) and isinstance(item, (int, float, str))]"
265
+ )
266
+ lines.append(comp)
267
+ elif "list[float]" in exp_lower:
268
+ lines.append(f"if isinstance(normalized.get({f!r}), list):")
269
+ comp = (
270
+ f" normalized[{f!r}] = ["
271
+ f"float(item) for item in normalized[{f!r}] "
272
+ f"if not isinstance(item, bool) and isinstance(item, (int, float, str))]"
273
+ )
274
+ lines.append(comp)
275
+ elif "list[bool]" in exp_lower:
276
+ lines.append(f"if isinstance(normalized.get({f!r}), list):")
277
+ comp = (
278
+ f" normalized[{f!r}] = ["
279
+ f"item.strip().lower() in ('true', '1', 'yes') "
280
+ f"if isinstance(item, str) else bool(item) "
281
+ f"for item in normalized[{f!r}]]"
282
+ )
283
+ lines.append(comp)
284
+ elif "int" in exp_lower and "dict" not in exp_lower:
285
+ cond = (
286
+ f"if {f!r} in normalized "
287
+ f"and isinstance(normalized[{f!r}], (str, float)) "
288
+ f"and not isinstance(normalized[{f!r}], bool):"
289
+ )
290
+ lines.append(cond)
291
+ lines.append(" try:")
292
+ lines.append(
293
+ f" normalized[{f!r}] = int(normalized[{f!r}]) "
294
+ f"if isinstance(normalized[{f!r}], str) "
295
+ f"and normalized[{f!r}].strip().lstrip('+-').isdigit() "
296
+ f"else int(float(normalized[{f!r}]))"
297
+ )
298
+ lines.append(" except (ValueError, TypeError):")
299
+ lines.append(" pass")
300
+ elif "float" in exp_lower and "dict" not in exp_lower:
301
+ cond = (
302
+ f"if {f!r} in normalized "
303
+ f"and isinstance(normalized[{f!r}], (str, int)) "
304
+ f"and not isinstance(normalized[{f!r}], bool):"
305
+ )
306
+ lines.append(cond)
307
+ lines.append(" try:")
308
+ lines.append(f" normalized[{f!r}] = float(normalized[{f!r}])")
309
+ lines.append(" except (ValueError, TypeError):")
310
+ lines.append(" pass")
311
+ elif "bool" in exp_lower:
312
+ lines.append(f"if {f!r} in normalized and isinstance(normalized[{f!r}], str):")
313
+ lines.append(
314
+ f" if normalized[{f!r}].strip().lower() in ('true', '1', 'yes'):"
315
+ )
316
+ lines.append(f" normalized[{f!r}] = True")
317
+ lines.append(
318
+ f" elif normalized[{f!r}].strip().lower() in ('false', '0', 'no'):"
319
+ )
320
+ lines.append(f" normalized[{f!r}] = False")
321
+ cond = (
322
+ f"elif {f!r} in normalized "
323
+ f"and isinstance(normalized[{f!r}], int) "
324
+ f"and not isinstance(normalized[{f!r}], bool):"
325
+ )
326
+ lines.append(cond)
327
+ lines.append(f" normalized[{f!r}] = bool(normalized[{f!r}])")
328
+ elif exp_lower == "str" or exp_lower == "str | none":
329
+ cond = (
330
+ f"if {f!r} in normalized "
331
+ f"and normalized[{f!r}] is not None "
332
+ f"and not isinstance(normalized[{f!r}], str):"
333
+ )
334
+ lines.append(cond)
335
+ lines.append(f" if isinstance(normalized[{f!r}], dict):")
336
+ lines.append(
337
+ " for _k in ('id', 'code', 'value', 'name', 'email', 'address'):"
338
+ )
339
+ inner_cond = (
340
+ f" if _k in normalized[{f!r}] "
341
+ f"and isinstance(normalized[{f!r}][_k], str):"
342
+ )
343
+ lines.append(inner_cond)
344
+ lines.append(f" normalized[{f!r}] = normalized[{f!r}][_k]")
345
+ lines.append(" break")
346
+ lines.append(" else:")
347
+ lines.append(f" normalized[{f!r}] = str(normalized[{f!r}])")
348
+ lines.append(" else:")
349
+ lines.append(f" normalized[{f!r}] = str(normalized[{f!r}])")
350
+
351
+ return lines
352
+
353
+
354
+ def _update_model_config_expr(expr: cst.BaseExpression) -> cst.BaseExpression:
355
+ if (
356
+ isinstance(expr, cst.Call)
357
+ and isinstance(expr.func, cst.Name)
358
+ and expr.func.value == "ConfigDict"
359
+ ):
360
+ new_args: list[cst.Arg] = []
361
+ found_extra = False
362
+ for arg in expr.args:
363
+ if isinstance(arg.keyword, cst.Name) and arg.keyword.value == "extra":
364
+ found_extra = True
365
+ new_args.append(
366
+ arg.with_changes(value=cst.SimpleString("'ignore'"))
367
+ )
368
+ else:
369
+ new_args.append(arg)
370
+ if not found_extra:
371
+ if new_args and new_args[-1].comma == cst.MaybeSentinel.DEFAULT:
372
+ new_args[-1] = new_args[-1].with_changes(
373
+ comma=cst.Comma(whitespace_after=cst.SimpleWhitespace(" "))
374
+ )
375
+ new_args.append(
376
+ cst.Arg(
377
+ keyword=cst.Name("extra"),
378
+ value=cst.SimpleString("'ignore'"),
379
+ equal=cst.AssignEqual(
380
+ whitespace_before=cst.SimpleWhitespace(""),
381
+ whitespace_after=cst.SimpleWhitespace(""),
382
+ ),
383
+ )
384
+ )
385
+ return expr.with_changes(args=tuple(new_args))
386
+ return cst.parse_expression("ConfigDict(extra='ignore')")
387
+
388
+
389
+ def _build_validator_method_cst(actions: tuple[PatchAction, ...]) -> cst.FunctionDef:
390
+ body_lines: list[str] = [
391
+ "@model_validator(mode='before')",
392
+ "@classmethod",
393
+ "def _selfheal_normalize_drift(cls, data: Any) -> Any:",
394
+ " if not isinstance(data, dict):",
395
+ " return data",
396
+ " normalized: dict[str, Any] = dict(data)",
397
+ ]
398
+ seen_fields: set[tuple[str, DriftKind, tuple[str | int, ...] | None]] = set()
399
+ for action in actions:
400
+ dedup_id = (action.target_field, action.drift_kind, action.source_path)
401
+ if dedup_id in seen_fields:
402
+ continue
403
+ seen_fields.add(dedup_id)
404
+ for line in _coercion_lines_for_action(action):
405
+ body_lines.append(f" {line}")
406
+
407
+ body_lines.append(" return normalized")
408
+ module_snippet = cst.parse_module("\n".join(body_lines) + "\n")
409
+ func_def = module_snippet.body[0]
410
+ if not isinstance(func_def, cst.FunctionDef):
411
+ raise TypeError("Expected FunctionDef from synthesized validator snippet")
412
+ return func_def
413
+
414
+
415
+ class _ModelPatchTransformer(cst.CSTTransformer):
416
+ def __init__(self, plan: PatchPlan) -> None:
417
+ super().__init__()
418
+ self._plan = plan
419
+ self._actions_by_model: dict[str, list[PatchAction]] = defaultdict(list)
420
+ for action in plan.actions:
421
+ self._actions_by_model[action.target_model].append(action)
422
+ self._widen_to_str_by_model: dict[str, set[str]] = defaultdict(set)
423
+ self._widen_nullable_by_model: dict[str, set[str]] = defaultdict(set)
424
+ for action in plan.actions:
425
+ if action.drift_kind == DriftKind.ENUM_DRIFT:
426
+ self._widen_to_str_by_model[action.target_model].add(action.target_field)
427
+ elif (
428
+ action.drift_kind == DriftKind.NULLABILITY_DRIFT
429
+ and action.expected_type.lower().startswith("literal")
430
+ ):
431
+ self._widen_nullable_by_model[action.target_model].add(
432
+ action.target_field
433
+ )
434
+ self._has_any_import = False
435
+ self._has_model_validator_import = False
436
+
437
+ def visit_ImportFrom(self, node: cst.ImportFrom) -> bool:
438
+ if isinstance(node.module, cst.Name):
439
+ if node.module.value == "typing" and isinstance(node.names, tuple):
440
+ for alias in node.names:
441
+ if isinstance(alias.name, cst.Name) and alias.name.value == "Any":
442
+ self._has_any_import = True
443
+ elif node.module.value == "pydantic" and isinstance(node.names, tuple):
444
+ for alias in node.names:
445
+ if (
446
+ isinstance(alias.name, cst.Name)
447
+ and alias.name.value == "model_validator"
448
+ ):
449
+ self._has_model_validator_import = True
450
+ return True
451
+
452
+ def leave_ClassDef(
453
+ self, original_node: cst.ClassDef, updated_node: cst.ClassDef
454
+ ) -> cst.ClassDef:
455
+ class_name = updated_node.name.value
456
+ model_actions = tuple(self._actions_by_model.get(class_name, ()))
457
+ if not model_actions and class_name != self._plan.model_name:
458
+ return updated_node
459
+
460
+ widen_str = self._widen_to_str_by_model.get(class_name, set())
461
+ widen_null = self._widen_nullable_by_model.get(class_name, set())
462
+
463
+ new_stmts: list[cst.BaseStatement | cst.BaseSmallStatement] = []
464
+ for stmt in updated_node.body.body:
465
+ if isinstance(stmt, cst.SimpleStatementLine):
466
+ updated_line = self._transform_class_attribute_line(
467
+ stmt, widen_str, widen_null
468
+ )
469
+ new_stmts.append(updated_line)
470
+ elif (
471
+ isinstance(stmt, cst.FunctionDef)
472
+ and stmt.name.value == "_selfheal_normalize_drift"
473
+ ):
474
+ continue
475
+ else:
476
+ new_stmts.append(stmt)
477
+
478
+ if model_actions:
479
+ validator_fn = _build_validator_method_cst(model_actions)
480
+ new_stmts.append(validator_fn)
481
+
482
+ return updated_node.with_changes(
483
+ body=updated_node.body.with_changes(body=tuple(new_stmts))
484
+ )
485
+
486
+ def _transform_class_attribute_line(
487
+ self,
488
+ line: cst.SimpleStatementLine,
489
+ widen_str: set[str],
490
+ widen_null: set[str],
491
+ ) -> cst.SimpleStatementLine:
492
+ new_small_stmts: list[cst.BaseSmallStatement] = []
493
+ for small in line.body:
494
+ if isinstance(small, cst.AnnAssign) and isinstance(
495
+ small.target, cst.Name
496
+ ):
497
+ field_name = small.target.value
498
+ if field_name in widen_str:
499
+ small = small.with_changes(
500
+ annotation=cst.Annotation(annotation=cst.Name("str"))
501
+ )
502
+ elif field_name in widen_null:
503
+ small = small.with_changes(
504
+ annotation=cst.Annotation(
505
+ annotation=cst.parse_expression("str | None")
506
+ )
507
+ )
508
+ elif isinstance(small, cst.Assign):
509
+ for assign_target in small.targets:
510
+ if (
511
+ isinstance(assign_target.target, cst.Name)
512
+ and assign_target.target.value == "model_config"
513
+ ):
514
+ small = small.with_changes(
515
+ value=_update_model_config_expr(small.value)
516
+ )
517
+ new_small_stmts.append(small)
518
+ return line.with_changes(body=tuple(new_small_stmts))
519
+
520
+ def leave_Module(
521
+ self, original_node: cst.Module, updated_node: cst.Module
522
+ ) -> cst.Module:
523
+ if not self._plan.actions:
524
+ return updated_node
525
+
526
+ prepend_stmts: list[cst.BaseStatement] = []
527
+ if not self._has_any_import:
528
+ prepend_stmts.append(cst.parse_statement("from typing import Any\n"))
529
+ if not self._has_model_validator_import:
530
+ prepend_stmts.append(
531
+ cst.parse_statement("from pydantic import model_validator\n")
532
+ )
533
+
534
+ if not prepend_stmts:
535
+ return updated_node
536
+
537
+ insert_idx = 0
538
+ for idx, stmt in enumerate(updated_node.body):
539
+ if isinstance(stmt, cst.SimpleStatementLine) and any(
540
+ isinstance(s, cst.ImportFrom)
541
+ and isinstance(s.module, cst.Name)
542
+ and s.module.value == "__future__"
543
+ for s in stmt.body
544
+ ):
545
+ insert_idx = idx + 1
546
+ break
547
+
548
+ new_body = (
549
+ list(updated_node.body[:insert_idx])
550
+ + prepend_stmts
551
+ + list(updated_node.body[insert_idx:])
552
+ )
553
+ return updated_node.with_changes(body=tuple(new_body))
554
+
555
+
556
+ def synthesize_patch(
557
+ source_code: str,
558
+ report: DriftReport,
559
+ root_model: type[BaseModel] | None = None,
560
+ ) -> PatchResult:
561
+ plan = build_patch_plan(report, root_model=root_model)
562
+ if not report.has_drift:
563
+ return PatchResult(
564
+ model_name=report.model_name,
565
+ original_source=source_code,
566
+ patched_source=source_code,
567
+ plan=plan,
568
+ applied=False,
569
+ )
570
+
571
+ module = cst.parse_module(source_code)
572
+ transformer = _ModelPatchTransformer(plan)
573
+ patched_module = module.visit(transformer)
574
+ patched_code = patched_module.code
575
+
576
+ return PatchResult(
577
+ model_name=report.model_name,
578
+ original_source=source_code,
579
+ patched_source=patched_code,
580
+ plan=plan,
581
+ applied=patched_code != source_code,
582
+ )
583
+
584
+
585
+ def _default_value_for_type(expected_type: str) -> Any:
586
+ exp = expected_type.lower()
587
+ if "none" in exp:
588
+ return None
589
+ if exp.startswith("list"):
590
+ return []
591
+ if exp.startswith("dict"):
592
+ return {}
593
+ if exp == "bool":
594
+ return False
595
+ if exp == "int":
596
+ return 0
597
+ if exp == "float":
598
+ return 0.0
599
+ if exp == "str":
600
+ return ""
601
+ return None
602
+
603
+
604
+ def _coerce_value_for_type(val: Any, expected_type: str) -> Any:
605
+ """Coerce a runtime value in pure Python to match ``expected_type``."""
606
+ exp_lower = expected_type.lower()
607
+
608
+ if "list[" in exp_lower:
609
+ items = ([] if val is None else [val]) if not isinstance(val, list) else val
610
+ if "list[str]" in exp_lower:
611
+ return [str(item) for item in items]
612
+ if "list[int]" in exp_lower:
613
+ return [
614
+ item
615
+ if isinstance(item, int)
616
+ else (
617
+ int(item)
618
+ if isinstance(item, str)
619
+ and item.strip().lstrip("+-").isdigit()
620
+ else int(float(item))
621
+ )
622
+ for item in items
623
+ if not isinstance(item, bool) and isinstance(item, (int, float, str))
624
+ ]
625
+ if "list[float]" in exp_lower:
626
+ return [
627
+ float(item)
628
+ for item in items
629
+ if not isinstance(item, bool) and isinstance(item, (int, float, str))
630
+ ]
631
+ if "list[bool]" in exp_lower:
632
+ return [
633
+ item.strip().lower() in ("true", "1", "yes")
634
+ if isinstance(item, str)
635
+ else bool(item)
636
+ for item in items
637
+ ]
638
+ return items
639
+
640
+ if "int" in exp_lower and "dict" not in exp_lower:
641
+ if isinstance(val, (str, float)) and not isinstance(val, bool):
642
+ try:
643
+ if isinstance(val, str) and val.strip().lstrip("+-").isdigit():
644
+ return int(val)
645
+ return int(float(val))
646
+ except (ValueError, TypeError):
647
+ return val
648
+ return val
649
+
650
+ if "float" in exp_lower and "dict" not in exp_lower:
651
+ if isinstance(val, (str, int)) and not isinstance(val, bool):
652
+ try:
653
+ return float(val)
654
+ except (ValueError, TypeError):
655
+ return val
656
+ return val
657
+
658
+ if "bool" in exp_lower:
659
+ if isinstance(val, str):
660
+ lowered = val.strip().lower()
661
+ if lowered in ("true", "1", "yes"):
662
+ return True
663
+ if lowered in ("false", "0", "no"):
664
+ return False
665
+ elif isinstance(val, int) and not isinstance(val, bool):
666
+ return bool(val)
667
+ return val
668
+
669
+ if exp_lower in ("str", "str | none"):
670
+ if val is not None and not isinstance(val, str):
671
+ if isinstance(val, dict):
672
+ for k in ("id", "code", "value", "name", "email", "address"):
673
+ if k in val and isinstance(val[k], str):
674
+ return val[k]
675
+ return str(val)
676
+ return str(val)
677
+ return val
678
+
679
+ return val
680
+
681
+
682
+ def _extract_from_path(
683
+ root: dict[str, Any], source_path: tuple[str | int, ...]
684
+ ) -> tuple[bool, Any]:
685
+ if not source_path:
686
+ return False, None
687
+ curr: Any = root
688
+ for part in source_path[:-1]:
689
+ part_key = str(part)
690
+ if not isinstance(curr, dict):
691
+ return False, None
692
+ nxt = curr.get(part_key)
693
+ if not isinstance(nxt, dict):
694
+ return False, None
695
+ curr = nxt
696
+ last_key = str(source_path[-1])
697
+ if isinstance(curr, dict) and last_key in curr:
698
+ return True, curr[last_key]
699
+ return False, None
700
+
701
+
702
+ def _apply_action_in_memory(target: dict[str, Any], action: PatchAction) -> None:
703
+ """Apply a single PatchAction in-place on its target dict without exec()."""
704
+ field = action.target_field
705
+ exp = action.expected_type
706
+ exp_lower = exp.lower()
707
+
708
+ if action.target_parent_path and action.source_path is not None:
709
+ curr: dict[str, Any] = target
710
+ for p_attr in action.target_parent_path:
711
+ p_key = str(p_attr)
712
+ existing = curr.get(p_key)
713
+ if not isinstance(existing, dict):
714
+ existing = {}
715
+ curr[p_key] = existing
716
+ curr = existing
717
+
718
+ if field not in curr:
719
+ found, extracted = _extract_from_path(target, action.source_path)
720
+ if found:
721
+ curr[field] = extracted
722
+
723
+ if field in curr:
724
+ curr[field] = _coerce_value_for_type(curr[field], exp)
725
+ return
726
+
727
+ if action.source_path is not None and field not in target:
728
+ found, extracted = _extract_from_path(target, action.source_path)
729
+ if found:
730
+ target[field] = extracted
731
+
732
+ if action.drift_kind == DriftKind.MISSING_FIELD and action.source_path is None:
733
+ if field not in target:
734
+ target[field] = _default_value_for_type(exp)
735
+
736
+ if action.drift_kind == DriftKind.NULLABILITY_DRIFT and "none" not in exp_lower:
737
+ if target.get(field) is None:
738
+ target[field] = _default_value_for_type(exp)
739
+
740
+ if field in target:
741
+ target[field] = _coerce_value_for_type(target[field], exp)
742
+
743
+
744
+ def _apply_action_to_target(
745
+ target: dict[str, Any], action: PatchAction, preserve_parent: bool = False
746
+ ) -> None:
747
+ """Apply a single PatchAction in-place on its target dict."""
748
+ local_action = (
749
+ action.model_copy(update={"target_parent_path": ()})
750
+ if action.target_parent_path and not preserve_parent
751
+ else action
752
+ )
753
+ _apply_action_in_memory(target, local_action)
754
+
755
+
756
+ def _walk_and_apply(
757
+ node: Any, path_rest: tuple[str | int, ...], action: PatchAction
758
+ ) -> None:
759
+ if not path_rest:
760
+ if isinstance(node, dict):
761
+ _apply_action_to_target(node, action)
762
+ elif isinstance(node, list):
763
+ for item in node:
764
+ if isinstance(item, dict):
765
+ _apply_action_to_target(item, action)
766
+ return
767
+ seg = path_rest[0]
768
+ if isinstance(node, list):
769
+ next_rest = path_rest[1:] if isinstance(seg, int) else path_rest
770
+ for item in node:
771
+ _walk_and_apply(item, next_rest, action)
772
+ elif isinstance(seg, str) and isinstance(node, dict) and seg in node:
773
+ _walk_and_apply(node[seg], path_rest[1:], action)
774
+
775
+
776
+ def _matches_literal_discriminator(
777
+ data: dict[str, Any], model_cls: type[BaseModel]
778
+ ) -> bool:
779
+ """Return True if at least one Literal-typed field in model_cls matches data[key]."""
780
+ matched = False
781
+ for fname, finfo in model_cls.model_fields.items():
782
+ if get_origin(finfo.annotation) is Literal:
783
+ if fname not in data:
784
+ return False
785
+ if data[fname] not in get_args(finfo.annotation):
786
+ return False
787
+ matched = True
788
+ return matched
789
+
790
+
791
+ def _strip_value_for_annotation(value: Any, ann: Any) -> Any:
792
+ if ann is None:
793
+ return value
794
+ if isinstance(ann, type) and issubclass(ann, BaseModel):
795
+ return _strip_forbidden_extras(value, ann) if isinstance(value, dict) else value
796
+ origin = get_origin(ann)
797
+ if origin in (Union, UnionType):
798
+ non_none_args = [arg for arg in get_args(ann) if arg is not type(None)]
799
+ if len(non_none_args) == 1:
800
+ return _strip_value_for_annotation(value, non_none_args[0])
801
+ if isinstance(value, dict):
802
+ model_branches = [
803
+ arg
804
+ for arg in non_none_args
805
+ if isinstance(arg, type) and issubclass(arg, BaseModel)
806
+ ]
807
+ for branch in model_branches:
808
+ try:
809
+ branch.model_validate(value)
810
+ return value
811
+ except ValidationError:
812
+ continue
813
+ valid_stripped: list[dict[str, Any]] = []
814
+ for branch in model_branches:
815
+ candidate = _strip_forbidden_extras(value, branch)
816
+ try:
817
+ branch.model_validate(candidate)
818
+ valid_stripped.append(candidate)
819
+ except ValidationError:
820
+ continue
821
+ if len(valid_stripped) == 1:
822
+ return valid_stripped[0]
823
+ if not valid_stripped:
824
+ disc_branches = [
825
+ b for b in model_branches if _matches_literal_discriminator(value, b)
826
+ ]
827
+ if len(disc_branches) == 1:
828
+ return _strip_forbidden_extras(value, disc_branches[0])
829
+ return value
830
+ if origin is list and isinstance(value, list):
831
+ args = get_args(ann)
832
+ if args:
833
+ elem_ann = args[0]
834
+ return [_strip_value_for_annotation(item, elem_ann) for item in value]
835
+ return value
836
+
837
+
838
+ def _strip_forbidden_extras(
839
+ data: dict[str, Any], model_cls: type[BaseModel]
840
+ ) -> dict[str, Any]:
841
+ """Recursively strip unknown keys from dicts whose BaseModel configures extra='forbid'."""
842
+ forbid = model_cls.model_config.get("extra") == "forbid"
843
+ fields = model_cls.model_fields
844
+ out: dict[str, Any] = {}
845
+ for key, val in data.items():
846
+ if key in fields:
847
+ out[key] = _strip_value_for_annotation(val, fields[key].annotation)
848
+ elif not forbid:
849
+ out[key] = val
850
+ return out
851
+
852
+
853
+ def apply_patch_plan_in_memory(
854
+ payload: dict[str, Any],
855
+ plan: PatchPlan,
856
+ allowed_fields: set[str] | frozenset[str] | None = None,
857
+ root_model: type[BaseModel] | None = None,
858
+ ) -> dict[str, Any]:
859
+ normalized: dict[str, Any] = copy.deepcopy(payload)
860
+ for action in plan.actions:
861
+ if action.target_model == plan.model_name:
862
+ _apply_action_to_target(normalized, action, preserve_parent=True)
863
+ elif action.nested_path:
864
+ _walk_and_apply(normalized, action.nested_path, action)
865
+ if root_model is not None:
866
+ return _strip_forbidden_extras(normalized, root_model)
867
+ if allowed_fields is not None:
868
+ return {k: v for k, v in normalized.items() if k in allowed_fields}
869
+ return normalized
870
+
871
+
872
+ def verify_patch(
873
+ patch_result: PatchResult,
874
+ drifted_payload: dict[str, Any],
875
+ legacy_payload: dict[str, Any] | None = None,
876
+ ) -> VerificationResult:
877
+ try:
878
+ cst.parse_module(patch_result.patched_source)
879
+ except cst.ParserSyntaxError as exc:
880
+ return VerificationResult(
881
+ passed=False,
882
+ syntax_valid=False,
883
+ drifted_payload_valid=False,
884
+ legacy_payload_valid=False,
885
+ error_detail=f"Syntax error in patched CST: {exc}",
886
+ )
887
+
888
+ namespace: dict[str, Any] = {}
889
+ try:
890
+ exec(patch_result.patched_source, namespace)
891
+ except Exception as exc: # noqa: BLE001
892
+ return VerificationResult(
893
+ passed=False,
894
+ syntax_valid=True,
895
+ drifted_payload_valid=False,
896
+ legacy_payload_valid=False,
897
+ error_detail=f"Failed to execute patched module: {exc}",
898
+ )
899
+
900
+ model_cls = namespace.get(patch_result.model_name)
901
+ if not isinstance(model_cls, type) or not issubclass(model_cls, BaseModel):
902
+ return VerificationResult(
903
+ passed=False,
904
+ syntax_valid=True,
905
+ drifted_payload_valid=False,
906
+ legacy_payload_valid=False,
907
+ error_detail=f"Model {patch_result.model_name} not found in patched source",
908
+ )
909
+
910
+ try:
911
+ for obj in namespace.values():
912
+ if isinstance(obj, type) and issubclass(obj, BaseModel) and obj is not BaseModel:
913
+ obj.model_rebuild(_types_namespace=namespace, force=True)
914
+ model_cls.model_validate(drifted_payload, strict=True)
915
+ drifted_ok = True
916
+ except ValidationError as exc:
917
+ return VerificationResult(
918
+ passed=False,
919
+ syntax_valid=True,
920
+ drifted_payload_valid=False,
921
+ legacy_payload_valid=False,
922
+ error_detail=f"Drifted payload validation failed: {exc}",
923
+ )
924
+
925
+ legacy_ok = True
926
+ if legacy_payload is not None:
927
+ try:
928
+ model_cls.model_validate(legacy_payload, strict=True)
929
+ except ValidationError as exc:
930
+ return VerificationResult(
931
+ passed=False,
932
+ syntax_valid=True,
933
+ drifted_payload_valid=drifted_ok,
934
+ legacy_payload_valid=False,
935
+ error_detail=f"Legacy payload regression failed: {exc}",
936
+ )
937
+
938
+ return VerificationResult(
939
+ passed=drifted_ok and legacy_ok,
940
+ syntax_valid=True,
941
+ drifted_payload_valid=drifted_ok,
942
+ legacy_payload_valid=legacy_ok,
943
+ error_detail=None,
944
+ )