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,145 @@
1
+ """Dual-Mode Ephemeral Bridge Sandbox subsystem.
2
+
3
+ Manages isolated intra-sandbox Docker bridge networks allowing multi-service sidecars
4
+ (e.g., PostgreSQL, Redis) while strictly dropping external internet egress via kernel iptables.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import subprocess
11
+ import uuid
12
+ from collections.abc import Iterator
13
+ from contextlib import contextmanager
14
+
15
+ from patchproof.exceptions import SandboxSecurityError
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ NETWORK_PREFIX = "patchproof-net-"
20
+ DEFAULT_DOCKER_TIMEOUT = 10.0
21
+
22
+
23
+ class EphemeralNetworkBridge:
24
+ """Manages creation, verification, and teardown of ephemeral internal Docker networks."""
25
+
26
+ def __init__(self, timeout_seconds: float = DEFAULT_DOCKER_TIMEOUT) -> None:
27
+ self.timeout_seconds = timeout_seconds
28
+
29
+ def create_bridge(self, network_name: str | None = None) -> str:
30
+ """Create an ephemeral internal bridge network with zero external internet egress.
31
+
32
+ Raises:
33
+ SandboxSecurityError: If network creation fails or network is not strictly internal.
34
+ """
35
+ if network_name is None:
36
+ name = f"{NETWORK_PREFIX}{uuid.uuid4().hex[:12]}"
37
+ else:
38
+ name = network_name
39
+
40
+ if not name.startswith(NETWORK_PREFIX):
41
+ raise SandboxSecurityError(
42
+ f"Custom network name must begin with '{NETWORK_PREFIX}' prefix: {name}"
43
+ )
44
+
45
+ cmd = [
46
+ "docker",
47
+ "network",
48
+ "create",
49
+ "--internal",
50
+ "--opt",
51
+ "com.docker.network.bridge.enable_icc=true",
52
+ name,
53
+ ]
54
+
55
+ try:
56
+ res = subprocess.run(
57
+ cmd,
58
+ capture_output=True,
59
+ text=True,
60
+ timeout=self.timeout_seconds,
61
+ shell=False,
62
+ close_fds=True,
63
+ check=False,
64
+ )
65
+ if res.returncode != 0:
66
+ raise SandboxSecurityError(
67
+ f"Failed to create ephemeral bridge network '{name}': {res.stderr.strip()}"
68
+ )
69
+ except (subprocess.TimeoutExpired, OSError) as err:
70
+ raise SandboxSecurityError(
71
+ f"Failed to execute docker network create for '{name}': {err}"
72
+ ) from err
73
+
74
+ # Verify internal isolation guarantee via inspection
75
+ if not self._verify_internal(name):
76
+ self.remove_bridge(name)
77
+ raise SandboxSecurityError(
78
+ f"Network '{name}' is not strictly internal. Potential internet egress detected."
79
+ )
80
+
81
+ logger.info("Created ephemeral internal network bridge: %s", name)
82
+ return name
83
+
84
+ def _verify_internal(self, network_name: str) -> bool:
85
+ """Inspect network and verify that Docker has configured it with internal=true."""
86
+ inspect_cmd = [
87
+ "docker",
88
+ "network",
89
+ "inspect",
90
+ network_name,
91
+ "--format",
92
+ "{{.Internal}}",
93
+ ]
94
+ try:
95
+ res = subprocess.run(
96
+ inspect_cmd,
97
+ capture_output=True,
98
+ text=True,
99
+ timeout=self.timeout_seconds,
100
+ shell=False,
101
+ close_fds=True,
102
+ check=False,
103
+ )
104
+ if res.returncode == 0:
105
+ return res.stdout.strip().lower() == "true"
106
+ except (subprocess.TimeoutExpired, OSError) as err:
107
+ logger.warning("Network inspection failed for %s: %s", network_name, err)
108
+ return False
109
+
110
+ def remove_bridge(self, network_name: str) -> None:
111
+ """Safely remove a verified PatchProof ephemeral bridge network.
112
+
113
+ Raises:
114
+ SandboxSecurityError: If attempting to remove an unmanaged or host network.
115
+ """
116
+ if not network_name.startswith(NETWORK_PREFIX):
117
+ raise SandboxSecurityError(
118
+ f"Refusing to remove network '{network_name}': not managed by PatchProof"
119
+ )
120
+
121
+ rm_cmd = ["docker", "network", "rm", network_name]
122
+ try:
123
+ subprocess.run(
124
+ rm_cmd,
125
+ capture_output=True,
126
+ text=True,
127
+ timeout=self.timeout_seconds,
128
+ shell=False,
129
+ close_fds=True,
130
+ check=False,
131
+ )
132
+ logger.info("Cleaned up ephemeral bridge network: %s", network_name)
133
+ except (subprocess.TimeoutExpired, OSError) as err:
134
+ logger.warning("Failed to remove network %s: %s", network_name, err)
135
+
136
+
137
+ @contextmanager
138
+ def ephemeral_network_bridge(network_name: str | None = None) -> Iterator[str]:
139
+ """Context manager creating a strictly internal network bridge and guaranteeing cleanup."""
140
+ bridge = EphemeralNetworkBridge()
141
+ name = bridge.create_bridge(network_name)
142
+ try:
143
+ yield name
144
+ finally:
145
+ bridge.remove_bridge(name)
@@ -0,0 +1,172 @@
1
+ """Structured test output parser for Pytest container execution results."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from patchproof.models.sandbox import (
8
+ TestCaseResult,
9
+ TestOutcome,
10
+ TestRunReport,
11
+ )
12
+
13
+ VERBOSE_TEST_LINE_RE = re.compile(
14
+ r"^(?P<name>\S+?::.*?)\s+(?P<outcome>PASSED|FAILED|SKIPPED|XFAIL|XPASS|ERROR)"
15
+ r"(?:\s+\(.*?\))?(?:\s+\[\s*\d+%\])?\s*$"
16
+ )
17
+
18
+ SHORT_SUMMARY_LINE_RE = re.compile(
19
+ r"^(?P<outcome>PASSED|FAILED|SKIPPED|XFAIL|XPASS|ERROR)\s+(?P<name>\S+?::.*?)(?:\s+-\s+(?P<msg>.*))?$"
20
+ )
21
+
22
+ COLLECTION_ERROR_SIGNATURES = (
23
+ "error collecting ",
24
+ "error during collection",
25
+ "errors during collection",
26
+ "interrupted: 1 error during collection",
27
+ )
28
+
29
+ OUTCOME_MAP: dict[str, TestOutcome] = {
30
+ "PASSED": TestOutcome.PASS,
31
+ "FAILED": TestOutcome.FAIL,
32
+ "ERROR": TestOutcome.ERROR,
33
+ "SKIPPED": TestOutcome.SKIPPED,
34
+ "XFAIL": TestOutcome.XFAIL,
35
+ "XPASS": TestOutcome.XPASS,
36
+ }
37
+
38
+
39
+ class PytestOutputParser:
40
+ """Parses raw container stdout/stderr streams into structured TestRunReport models."""
41
+
42
+ def parse(
43
+ self,
44
+ stdout: str,
45
+ stderr: str = "",
46
+ exit_code: int = 0,
47
+ duration_seconds: float = 0.0,
48
+ ) -> TestRunReport:
49
+ """Parse pytest execution streams into an immutable TestRunReport."""
50
+ combined_text = f"{stdout}\n{stderr}"
51
+ collection_failed, collection_error = self._detect_collection_failure(combined_text)
52
+
53
+ test_cases_map: dict[str, TestCaseResult] = {}
54
+ failure_messages: dict[str, str] = self._extract_failure_messages(stdout)
55
+
56
+ # 1. Parse individual test lines (verbose output)
57
+ for line in stdout.splitlines():
58
+ line_clean = line.strip()
59
+ match = VERBOSE_TEST_LINE_RE.match(line_clean)
60
+ if match:
61
+ name = match.group("name")
62
+ outcome_str = match.group("outcome")
63
+ outcome = OUTCOME_MAP.get(outcome_str, TestOutcome.ERROR)
64
+ msg = failure_messages.get(name)
65
+
66
+ test_cases_map[name] = TestCaseResult(
67
+ name=name,
68
+ outcome=outcome,
69
+ duration_seconds=0.0,
70
+ failure_message=msg,
71
+ )
72
+
73
+ # 2. Parse short test summary info if present
74
+ in_short_summary = False
75
+ for line in stdout.splitlines():
76
+ line_clean = line.strip()
77
+ if "short test summary info" in line_clean:
78
+ in_short_summary = True
79
+ continue
80
+ if in_short_summary and line_clean.startswith("==="):
81
+ in_short_summary = False
82
+ continue
83
+
84
+ if in_short_summary:
85
+ match = SHORT_SUMMARY_LINE_RE.match(line_clean)
86
+ if match:
87
+ name = match.group("name")
88
+ outcome_str = match.group("outcome")
89
+ outcome = OUTCOME_MAP.get(outcome_str, TestOutcome.ERROR)
90
+ msg = match.group("msg") or failure_messages.get(name)
91
+
92
+ if name not in test_cases_map:
93
+ test_cases_map[name] = TestCaseResult(
94
+ name=name,
95
+ outcome=outcome,
96
+ duration_seconds=0.0,
97
+ failure_message=msg,
98
+ )
99
+ elif msg and not test_cases_map[name].failure_message:
100
+ test_cases_map[name] = TestCaseResult(
101
+ name=name,
102
+ outcome=test_cases_map[name].outcome,
103
+ duration_seconds=test_cases_map[name].duration_seconds,
104
+ failure_message=msg,
105
+ )
106
+
107
+ test_cases_tuple = tuple(test_cases_map.values())
108
+
109
+ return TestRunReport(
110
+ test_cases=test_cases_tuple,
111
+ exit_code=exit_code,
112
+ duration_seconds=round(duration_seconds, 3),
113
+ total_collected=len(test_cases_tuple),
114
+ collection_failed=collection_failed,
115
+ collection_error=collection_error,
116
+ )
117
+
118
+ def _detect_collection_failure(self, text: str) -> tuple[bool, str | None]:
119
+ """Detect whether test discovery failed during the run."""
120
+ text_lower = text.lower()
121
+ for sig in COLLECTION_ERROR_SIGNATURES:
122
+ if sig in text_lower:
123
+ # Extract collection error lines
124
+ err_lines: list[str] = []
125
+ capturing = False
126
+ for line in text.splitlines():
127
+ if "error collecting" in line.lower() or "=== errors ===" in line.lower():
128
+ capturing = True
129
+ if capturing:
130
+ err_lines.append(line)
131
+ if len(err_lines) >= 30:
132
+ break
133
+ error_snippet = "\n".join(err_lines) if err_lines else "Collection error detected"
134
+ return True, error_snippet.strip()
135
+ return False, None
136
+
137
+ def _extract_failure_messages(self, stdout: str) -> dict[str, str]:
138
+ """Extract failure traceback messages associated with test identifiers."""
139
+ messages: dict[str, str] = {}
140
+ lines = stdout.splitlines()
141
+ current_test: str | None = None
142
+ current_msg_lines: list[str] = []
143
+
144
+ in_failures = False
145
+ for line in lines:
146
+ if "=== FAILURES ===" in line or "=== ERRORS ===" in line:
147
+ in_failures = True
148
+ continue
149
+ if (
150
+ in_failures
151
+ and line.startswith("===")
152
+ and "FAILURES" not in line
153
+ and "ERRORS" not in line
154
+ ):
155
+ in_failures = False
156
+ if current_test:
157
+ messages[current_test] = "\n".join(current_msg_lines).strip()
158
+ break
159
+
160
+ if in_failures:
161
+ if line.startswith("___") and line.endswith("___"):
162
+ if current_test:
163
+ messages[current_test] = "\n".join(current_msg_lines).strip()
164
+ current_msg_lines = []
165
+ current_test = line.strip("_ ")
166
+ elif current_test:
167
+ current_msg_lines.append(line)
168
+
169
+ if current_test and current_msg_lines:
170
+ messages[current_test] = "\n".join(current_msg_lines).strip()
171
+
172
+ return messages