patchproof-core 0.3.1__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.
Files changed (56) hide show
  1. patchproof/__init__.py +44 -0
  2. patchproof/__main__.py +8 -0
  3. patchproof/benchmarks/__init__.py +17 -0
  4. patchproof/benchmarks/swe_bench.py +159 -0
  5. patchproof/cli.py +1254 -0
  6. patchproof/core/__init__.py +33 -0
  7. patchproof/core/agent_init.py +103 -0
  8. patchproof/core/anti_cheat.py +396 -0
  9. patchproof/core/applier.py +159 -0
  10. patchproof/core/ast_analyzer.py +254 -0
  11. patchproof/core/detector.py +78 -0
  12. patchproof/core/git_provider.py +298 -0
  13. patchproof/core/healer.py +104 -0
  14. patchproof/core/mutator.py +223 -0
  15. patchproof/core/normalizer.py +338 -0
  16. patchproof/core/polyglot_guard.py +167 -0
  17. patchproof/core/runtime_guard.py +188 -0
  18. patchproof/core/search_replace.py +222 -0
  19. patchproof/core/slicer.py +172 -0
  20. patchproof/core/sparse_tree.py +95 -0
  21. patchproof/docker/runner.Dockerfile +42 -0
  22. patchproof/exceptions.py +37 -0
  23. patchproof/factory/__init__.py +22 -0
  24. patchproof/factory/blast_radius.py +120 -0
  25. patchproof/factory/engine.py +134 -0
  26. patchproof/factory/models.py +75 -0
  27. patchproof/mcp.py +532 -0
  28. patchproof/models/__init__.py +57 -0
  29. patchproof/models/ast.py +78 -0
  30. patchproof/models/patch.py +106 -0
  31. patchproof/models/sandbox.py +417 -0
  32. patchproof/reporting/__init__.py +19 -0
  33. patchproof/reporting/asymmetric.py +88 -0
  34. patchproof/reporting/badge.py +86 -0
  35. patchproof/reporting/certificate.py +230 -0
  36. patchproof/reporting/diagnostic.py +330 -0
  37. patchproof/reporting/html_report.py +367 -0
  38. patchproof/reporting/in_toto.py +188 -0
  39. patchproof/reporting/markdown.py +179 -0
  40. patchproof/reporting/sbom.py +152 -0
  41. patchproof/sandbox/__init__.py +37 -0
  42. patchproof/sandbox/classifier.py +289 -0
  43. patchproof/sandbox/comparative.py +478 -0
  44. patchproof/sandbox/docker_cli.py +384 -0
  45. patchproof/sandbox/doctor.py +605 -0
  46. patchproof/sandbox/flakiness.py +87 -0
  47. patchproof/sandbox/network_bridge.py +145 -0
  48. patchproof/sandbox/parser.py +172 -0
  49. patchproof/sandbox/runner.py +424 -0
  50. patchproof/sandbox/setup_runner.py +261 -0
  51. patchproof_core-0.3.1.dist-info/METADATA +212 -0
  52. patchproof_core-0.3.1.dist-info/RECORD +56 -0
  53. patchproof_core-0.3.1.dist-info/WHEEL +5 -0
  54. patchproof_core-0.3.1.dist-info/entry_points.txt +2 -0
  55. patchproof_core-0.3.1.dist-info/licenses/LICENSE +13 -0
  56. patchproof_core-0.3.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,478 @@
1
+ """Comparative execution engine orchestrating dual-run baseline-versus-patched evaluations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import pathlib
8
+ import shutil
9
+ import tempfile
10
+ from concurrent.futures import ThreadPoolExecutor
11
+
12
+ from patchproof.core.applier import apply_patch
13
+ from patchproof.core.git_provider import export_git_tree, is_git_repository
14
+ from patchproof.core.normalizer import parse_patch
15
+ from patchproof.core.runtime_guard import generate_runtime_guard_plugin
16
+ from patchproof.core.search_replace import SEARCH_START, parse_search_replace
17
+ from patchproof.core.sparse_tree import (
18
+ compute_minimal_common_ancestor,
19
+ extract_patch_modified_paths,
20
+ should_use_sparse_extraction,
21
+ )
22
+ from patchproof.exceptions import (
23
+ DockerUnavailableError,
24
+ InvalidPatchFormatError,
25
+ PatchApplicationError,
26
+ SandboxSecurityError,
27
+ UnsupportedDockerEngineError,
28
+ )
29
+ from patchproof.models.patch import CanonicalPatch
30
+ from patchproof.models.sandbox import (
31
+ ComparativeExecutionResult,
32
+ ComparativeTestCase,
33
+ ContainerConfig,
34
+ ContainerEnvironment,
35
+ ExecutionResult,
36
+ PatchVerdict,
37
+ RegressionClassification,
38
+ SandboxFailureReason,
39
+ )
40
+ from patchproof.sandbox.classifier import RegressionClassifier
41
+ from patchproof.sandbox.flakiness import disambiguate_flakiness
42
+ from patchproof.sandbox.parser import PytestOutputParser
43
+ from patchproof.sandbox.runner import ContainerRunner
44
+
45
+ logger = logging.getLogger(__name__)
46
+
47
+ STAGING_IGNORE_PATTERNS = (
48
+ ".git",
49
+ ".venv",
50
+ "env",
51
+ "__pycache__",
52
+ ".pytest_cache",
53
+ ".mypy_cache",
54
+ ".ruff_cache",
55
+ )
56
+
57
+ BASELINE_INFRASTRUCTURE_FAILURES = (
58
+ SandboxFailureReason.TIMEOUT,
59
+ SandboxFailureReason.OOM_KILLED,
60
+ SandboxFailureReason.DOCKER_UNAVAILABLE,
61
+ SandboxFailureReason.UNSUPPORTED_ENGINE,
62
+ SandboxFailureReason.SETUP_ERROR,
63
+ )
64
+
65
+
66
+ def safe_copy_repository(
67
+ src_repo_path: str | pathlib.Path,
68
+ dst_staging_path: str | pathlib.Path,
69
+ ignore_patterns: tuple[str, ...] = STAGING_IGNORE_PATTERNS,
70
+ ) -> None:
71
+ """Safely copy repository source to an ephemeral staging directory.
72
+
73
+ Rejects and fails closed on any symlinks pointing outside the repository root.
74
+ Never copies git directories, virtual environments, or build caches.
75
+
76
+ Raises:
77
+ SandboxSecurityError: If any symlink points outside the repository root.
78
+ """
79
+ src_root = pathlib.Path(src_repo_path).resolve()
80
+ dst_root = pathlib.Path(dst_staging_path).resolve()
81
+
82
+ # Pre-scan for malicious symlinks escaping repository root
83
+ for root_dir, dirs, files in os.walk(src_root, followlinks=False):
84
+ current_path = pathlib.Path(root_dir)
85
+ # Filter ignored directory names in-place
86
+ dirs[:] = [d for d in dirs if d not in ignore_patterns]
87
+
88
+ for item_name in dirs + files:
89
+ item_path = current_path / item_name
90
+ if item_path.is_symlink():
91
+ resolved_target = item_path.resolve()
92
+ try:
93
+ resolved_target.relative_to(src_root)
94
+ except ValueError as err:
95
+ raise SandboxSecurityError(
96
+ f"Symlink traversal detected: '{item_path}' points outside "
97
+ f"repository root to '{resolved_target}'"
98
+ ) from err
99
+
100
+ shutil.copytree(
101
+ src_root,
102
+ dst_root,
103
+ ignore=shutil.ignore_patterns(*ignore_patterns),
104
+ dirs_exist_ok=True,
105
+ )
106
+
107
+
108
+ def safe_cleanup_staging(staging_dir: pathlib.Path) -> None:
109
+ """Safely remove ephemeral staging directory with boundary verification."""
110
+ try:
111
+ resolved = staging_dir.resolve()
112
+ temp_root = pathlib.Path(tempfile.gettempdir()).resolve()
113
+
114
+ # Invariant 1: Must be inside system temporary directory
115
+ resolved.relative_to(temp_root)
116
+
117
+ # Invariant 2: Must bear patchproof-staging prefix
118
+ if not resolved.name.startswith("patchproof-staging-"):
119
+ logger.error("Refusing cleanup: missing patchproof-staging prefix: %s", resolved)
120
+ return
121
+
122
+ # Invariant 3: Must not be a root or shallow path
123
+ if resolved == temp_root or str(resolved) == temp_root.root or len(resolved.parts) <= 2:
124
+ logger.error("Refusing cleanup: broad path detected: %s", resolved)
125
+ return
126
+
127
+ shutil.rmtree(resolved, ignore_errors=True)
128
+ except (ValueError, OSError) as err:
129
+ logger.warning("Staging cleanup error for %s: %s", staging_dir, err)
130
+
131
+
132
+ class ComparativeRunner:
133
+ """Orchestrates isolated baseline and patched container runs and classifies regressions."""
134
+
135
+ def __init__(
136
+ self,
137
+ runner: ContainerRunner | None = None,
138
+ parser: PytestOutputParser | None = None,
139
+ classifier: RegressionClassifier | None = None,
140
+ ) -> None:
141
+ self.runner = runner or ContainerRunner()
142
+ self.parser = parser or PytestOutputParser()
143
+ self.classifier = classifier or RegressionClassifier()
144
+
145
+ def run(
146
+ self,
147
+ config: ContainerConfig,
148
+ patch: CanonicalPatch | str,
149
+ disambiguate_flakes: bool = False,
150
+ allow_test_edits: bool = False,
151
+ ) -> ComparativeExecutionResult:
152
+ """Execute baseline and patched container runs, isolating workspaces and verifying.
153
+
154
+ 1. Validates the patch format.
155
+ 2. Prepares ephemeral staging workspaces for baseline and patched runs.
156
+ 3. Copies repository into baseline staging workspace (auditing symlinks).
157
+ 4. Copies repository into patched staging workspace.
158
+ 5. Executes baseline tests against baseline staging workspace.
159
+ 6. Applies patch to the patched staging workspace.
160
+ 7. Executes patched tests against patched staging workspace.
161
+ 8. Reconciles test results and produces immutable ComparativeExecutionResult.
162
+ 9. Guaranteed cleanup of all staging workspaces in finally block.
163
+ """
164
+ # Step 1: Pre-validate patch format
165
+ canonical_patch: CanonicalPatch
166
+ if isinstance(patch, str):
167
+ try:
168
+ if SEARCH_START in patch:
169
+ canonical_patch = parse_search_replace(patch)
170
+ else:
171
+ canonical_patch = parse_patch(patch)
172
+ except InvalidPatchFormatError as err:
173
+ dummy_res = ExecutionResult(
174
+ exit_code=1,
175
+ stderr=str(err),
176
+ duration_seconds=0.0,
177
+ failure_reason=SandboxFailureReason.SETUP_ERROR,
178
+ )
179
+ return ComparativeExecutionResult(
180
+ baseline_result=dummy_res,
181
+ patched_result=dummy_res,
182
+ verdict=PatchVerdict.REJECTED,
183
+ summary=f"Invalid patch format: {err}",
184
+ )
185
+ else:
186
+ canonical_patch = patch
187
+
188
+ # Step 1b: Anti-cheat patch integrity audit
189
+ from patchproof.core.anti_cheat import audit_patch_integrity
190
+
191
+ anti_cheat_report = audit_patch_integrity(
192
+ patch=canonical_patch,
193
+ repo_root=config.host_repo_path,
194
+ allow_test_edits=allow_test_edits,
195
+ )
196
+
197
+ # Step 2: Prepare ephemeral staging workspaces
198
+ baseline_staging = pathlib.Path(tempfile.mkdtemp(prefix="patchproof-staging-base-"))
199
+ patched_staging = pathlib.Path(tempfile.mkdtemp(prefix="patchproof-staging-patch-"))
200
+
201
+ # Determine if sparse tree extraction applies for monorepos
202
+ subtree_target: str | None = None
203
+ modified_paths = extract_patch_modified_paths(canonical_patch)
204
+ if modified_paths and should_use_sparse_extraction(modified_paths):
205
+ subtree_target = compute_minimal_common_ancestor(modified_paths)
206
+
207
+ try:
208
+ # Step 2: Populate staging repositories concurrently
209
+ git_isolated = False
210
+ if is_git_repository(config.host_repo_path):
211
+ try:
212
+ with ThreadPoolExecutor(max_workers=2) as executor:
213
+ fut_base = executor.submit(
214
+ export_git_tree,
215
+ config.host_repo_path,
216
+ "HEAD",
217
+ baseline_staging,
218
+ subtree=subtree_target,
219
+ )
220
+ fut_patch = executor.submit(
221
+ export_git_tree,
222
+ config.host_repo_path,
223
+ "HEAD",
224
+ patched_staging,
225
+ subtree=subtree_target,
226
+ )
227
+ base_ok = fut_base.result()
228
+ patch_ok = fut_patch.result()
229
+ git_isolated = base_ok and patch_ok
230
+ except SandboxSecurityError as err:
231
+ dummy_res = ExecutionResult(
232
+ exit_code=1,
233
+ stderr=f"Security violation during staging: {err}",
234
+ duration_seconds=0.0,
235
+ failure_reason=SandboxFailureReason.SETUP_ERROR,
236
+ )
237
+ return ComparativeExecutionResult(
238
+ baseline_result=dummy_res,
239
+ patched_result=dummy_res,
240
+ verdict=PatchVerdict.REJECTED,
241
+ summary=f"Security violation during staging: {err}",
242
+ )
243
+
244
+ if not git_isolated:
245
+ # Fallback to concurrent safe_copy_repository for non-git or bare environments
246
+ try:
247
+ def _do_copy(src: str | pathlib.Path, dst: pathlib.Path) -> bool:
248
+ safe_copy_repository(src, dst)
249
+ return True
250
+
251
+ with ThreadPoolExecutor(max_workers=2) as copy_executor:
252
+ fut_base = copy_executor.submit(
253
+ _do_copy, config.host_repo_path, baseline_staging
254
+ )
255
+ fut_patch = copy_executor.submit(
256
+ _do_copy, config.host_repo_path, patched_staging
257
+ )
258
+ fut_base.result()
259
+ fut_patch.result()
260
+ except SandboxSecurityError as err:
261
+ dummy_res = ExecutionResult(
262
+ exit_code=1,
263
+ stderr=f"Security violation during staging: {err}",
264
+ duration_seconds=0.0,
265
+ failure_reason=SandboxFailureReason.SETUP_ERROR,
266
+ )
267
+ return ComparativeExecutionResult(
268
+ baseline_result=dummy_res,
269
+ patched_result=dummy_res,
270
+ verdict=PatchVerdict.REJECTED,
271
+ summary=f"Security violation during staging: {err}",
272
+ )
273
+
274
+ # Inject PatchProof dynamic runtime assertion guard into staging trees
275
+ guard_source = generate_runtime_guard_plugin()
276
+ (baseline_staging / "patchproof_runtime_guard.py").write_text(
277
+ guard_source, encoding="utf-8"
278
+ )
279
+ (patched_staging / "patchproof_runtime_guard.py").write_text(
280
+ guard_source, encoding="utf-8"
281
+ )
282
+
283
+ # Enable auto-loading of runtime guard plugin in pytest
284
+ current_env = dict(config.environment.env_vars)
285
+ existing_pytest_opts = current_env.get("PYTEST_ADDOPTS", "")
286
+ combined_opts = f"{existing_pytest_opts} -p patchproof_runtime_guard".strip()
287
+ guarded_env = ContainerEnvironment(
288
+ env_vars=(
289
+ *tuple((k, v) for k, v in current_env.items() if k != "PYTEST_ADDOPTS"),
290
+ ("PYTEST_ADDOPTS", combined_opts),
291
+ )
292
+ )
293
+
294
+ # Step 3: Execute baseline test container
295
+ baseline_config = config.model_copy(
296
+ update={"host_repo_path": str(baseline_staging), "environment": guarded_env}
297
+ )
298
+ try:
299
+ base_raw = self.runner.run(baseline_config)
300
+ except DockerUnavailableError as err:
301
+ dummy_res = ExecutionResult(
302
+ exit_code=1,
303
+ stderr=str(err),
304
+ duration_seconds=0.0,
305
+ failure_reason=SandboxFailureReason.DOCKER_UNAVAILABLE,
306
+ )
307
+ return ComparativeExecutionResult(
308
+ baseline_result=dummy_res,
309
+ patched_result=dummy_res,
310
+ verdict=PatchVerdict.INFRASTRUCTURE_FAILURE,
311
+ summary=f"Infrastructure failure: Docker daemon is unavailable ({err})",
312
+ )
313
+ except UnsupportedDockerEngineError as err:
314
+ dummy_res = ExecutionResult(
315
+ exit_code=1,
316
+ stderr=str(err),
317
+ duration_seconds=0.0,
318
+ failure_reason=SandboxFailureReason.UNSUPPORTED_ENGINE,
319
+ )
320
+ return ComparativeExecutionResult(
321
+ baseline_result=dummy_res,
322
+ patched_result=dummy_res,
323
+ verdict=PatchVerdict.INFRASTRUCTURE_FAILURE,
324
+ summary=f"Infrastructure failure: Unsupported Docker engine ({err})",
325
+ )
326
+
327
+ base_report = self.parser.parse(
328
+ stdout=base_raw.stdout,
329
+ stderr=base_raw.stderr,
330
+ exit_code=base_raw.exit_code,
331
+ duration_seconds=base_raw.duration_seconds,
332
+ )
333
+ baseline_result = base_raw.model_copy(update={"test_report": base_report})
334
+
335
+ # Early abort only if baseline execution suffered infrastructure or collection failure
336
+ if (
337
+ baseline_result.failure_reason in BASELINE_INFRASTRUCTURE_FAILURES
338
+ or base_report.collection_failed
339
+ ):
340
+ return self.classifier.classify(baseline_result, baseline_result)
341
+
342
+ # Step 4: Apply patch to patched staging workspace
343
+ try:
344
+ apply_patch(canonical_patch, patched_staging)
345
+ except (PatchApplicationError, SandboxSecurityError) as err:
346
+ synthetic_patched = ExecutionResult(
347
+ exit_code=1,
348
+ stderr=f"Patch application failed: {err}",
349
+ duration_seconds=0.0,
350
+ failure_reason=SandboxFailureReason.SETUP_ERROR,
351
+ )
352
+ return self.classifier.classify(baseline_result, synthetic_patched)
353
+
354
+ # Step 5: Execute patched test container
355
+ patched_config = config.model_copy(
356
+ update={"host_repo_path": str(patched_staging), "environment": guarded_env}
357
+ )
358
+ try:
359
+ patched_raw = self.runner.run(patched_config)
360
+ except DockerUnavailableError as err:
361
+ dummy_res = ExecutionResult(
362
+ exit_code=1,
363
+ stderr=str(err),
364
+ duration_seconds=0.0,
365
+ failure_reason=SandboxFailureReason.DOCKER_UNAVAILABLE,
366
+ )
367
+ return ComparativeExecutionResult(
368
+ baseline_result=baseline_result,
369
+ patched_result=dummy_res,
370
+ verdict=PatchVerdict.INFRASTRUCTURE_FAILURE,
371
+ summary=f"Patched run infrastructure failure: Docker unavailable ({err})",
372
+ )
373
+ except UnsupportedDockerEngineError as err:
374
+ dummy_res = ExecutionResult(
375
+ exit_code=1,
376
+ stderr=str(err),
377
+ duration_seconds=0.0,
378
+ failure_reason=SandboxFailureReason.UNSUPPORTED_ENGINE,
379
+ )
380
+ return ComparativeExecutionResult(
381
+ baseline_result=baseline_result,
382
+ patched_result=dummy_res,
383
+ verdict=PatchVerdict.INFRASTRUCTURE_FAILURE,
384
+ summary=f"Patched run infrastructure failure: Unsupported engine ({err})",
385
+ )
386
+
387
+ patch_report = self.parser.parse(
388
+ stdout=patched_raw.stdout,
389
+ stderr=patched_raw.stderr,
390
+ exit_code=patched_raw.exit_code,
391
+ duration_seconds=patched_raw.duration_seconds,
392
+ )
393
+ patched_result = patched_raw.model_copy(update={"test_report": patch_report})
394
+
395
+ # Step 6: Reconcile and classify results
396
+ initial_result = self.classifier.classify(baseline_result, patched_result)
397
+
398
+ # Step 7: Flakiness Disambiguation for introduced regressions
399
+ if disambiguate_flakes and initial_result.introduced_regressions_count > 0:
400
+ new_comparisons: list[ComparativeTestCase] = []
401
+ remaining_regressions = 0
402
+ flaky_count = 0
403
+
404
+ for tc in initial_result.test_comparisons:
405
+ if tc.classification == RegressionClassification.INTRODUCED_REGRESSION:
406
+
407
+ def _single_runner(test_id: str) -> tuple[bool, float]:
408
+ retry_cfg = patched_config.model_copy(
409
+ update={"entrypoint_command": ("pytest", "-q", test_id)}
410
+ )
411
+ try:
412
+ r = self.runner.run(retry_cfg)
413
+ return (r.exit_code == 0, r.duration_seconds)
414
+ except Exception:
415
+ return (False, 0.0)
416
+
417
+ flake_rep = disambiguate_flakiness(tc.test_name, _single_runner, attempts=3)
418
+ if flake_rep.is_flaky:
419
+ flaky_count += 1
420
+ new_comparisons.append(
421
+ tc.model_copy(
422
+ update={
423
+ "classification": RegressionClassification.FLAKY_REGRESSION,
424
+ "message": f"Flaky: {flake_rep.summary}",
425
+ }
426
+ )
427
+ )
428
+ else:
429
+ remaining_regressions += 1
430
+ new_comparisons.append(tc)
431
+ else:
432
+ new_comparisons.append(tc)
433
+
434
+ if flaky_count > 0:
435
+ new_verdict = (
436
+ PatchVerdict.REJECTED
437
+ if remaining_regressions > 0
438
+ else PatchVerdict.SUSPICIOUS
439
+ )
440
+ new_summary = (
441
+ f"Patch verified with {flaky_count} flaky test(s) detected; "
442
+ f"{remaining_regressions} confirmed regression(s)"
443
+ )
444
+ initial_result = initial_result.model_copy(
445
+ update={
446
+ "test_comparisons": tuple(new_comparisons),
447
+ "introduced_regressions_count": remaining_regressions,
448
+ "flaky_tests_count": flaky_count,
449
+ "verdict": new_verdict,
450
+ "summary": new_summary,
451
+ }
452
+ )
453
+
454
+ if anti_cheat_report.tampering_detected:
455
+ tamper_verdict = (
456
+ PatchVerdict.REJECTED
457
+ if anti_cheat_report.tests_deleted_count > 0
458
+ else PatchVerdict.SUSPICIOUS
459
+ )
460
+ tamper_summary = (
461
+ f"Test tampering detected ({anti_cheat_report.summary}); "
462
+ f"raw test verdict: {initial_result.verdict.value}"
463
+ )
464
+ return initial_result.model_copy(
465
+ update={
466
+ "test_tampering_detected": True,
467
+ "tampering_details": tuple(v.details for v in anti_cheat_report.violations),
468
+ "verdict": tamper_verdict,
469
+ "summary": tamper_summary,
470
+ }
471
+ )
472
+
473
+ return initial_result
474
+
475
+ finally:
476
+ # Guaranteed staging workspaces cleanup
477
+ safe_cleanup_staging(baseline_staging)
478
+ safe_cleanup_staging(patched_staging)