swarmauri_evaluator_subprocess 0.1.1.dev3__tar.gz

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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] [Jacob Stewart]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,24 @@
1
+ Metadata-Version: 2.3
2
+ Name: swarmauri_evaluator_subprocess
3
+ Version: 0.1.1.dev3
4
+ Summary: A subprocess-based evaluator for executing and measuring program performance in isolated subprocesses
5
+ License: Apache-2.0
6
+ Keywords: subprocess,evaluation,sandboxing,program execution,resource limits,performance measurement,testing,security,swarm,ai,swarmauri
7
+ Author: SwarmAuri Team
8
+ Author-email: info@swarmauri.com
9
+ Requires-Python: >=3.10,<3.13
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Natural Language :: English
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Development Status :: 3 - Alpha
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Classifier: Topic :: Software Development :: Testing
19
+ Classifier: Topic :: System :: Monitoring
20
+ Requires-Dist: swarmauri_base
21
+ Requires-Dist: swarmauri_core
22
+ Description-Content-Type: text/markdown
23
+
24
+ pip install swarmauri_evaluator_subprocess
@@ -0,0 +1 @@
1
+ pip install swarmauri_evaluator_subprocess
@@ -0,0 +1,78 @@
1
+ [project]
2
+ name = "swarmauri_evaluator_subprocess"
3
+ version = "0.1.1.dev3"
4
+ description = "A subprocess-based evaluator for executing and measuring program performance in isolated subprocesses"
5
+ license = "Apache-2.0"
6
+ readme = "README.md"
7
+ repository = "https://github.com/swarmauri/swarmauri-sdk/pkgs/standards/swarmauri_evaluator_subprocess/"
8
+ requires-python = ">=3.10,<3.13"
9
+ classifiers = [
10
+ "License :: OSI Approved :: Apache Software License",
11
+ "Natural Language :: English",
12
+ "Programming Language :: Python :: 3.10",
13
+ "Programming Language :: Python :: 3.11",
14
+ "Programming Language :: Python :: 3.12",
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "Topic :: Software Development :: Libraries",
18
+ "Topic :: Software Development :: Testing",
19
+ "Topic :: System :: Monitoring",
20
+ ]
21
+ authors = [{ name = "SwarmAuri Team", email = "info@swarmauri.com" }]
22
+ keywords = [
23
+ "subprocess",
24
+ "evaluation",
25
+ "sandboxing",
26
+ "program execution",
27
+ "resource limits",
28
+ "performance measurement",
29
+ "testing",
30
+ "security",
31
+ "swarm",
32
+ "ai",
33
+ "swarmauri",
34
+ ]
35
+ dependencies = ["swarmauri_core", "swarmauri_base"]
36
+
37
+
38
+ [tool.pytest.ini_options]
39
+ norecursedirs = ["combined", "scripts"]
40
+ markers = [
41
+ "test: standard test",
42
+ "unit: Unit tests",
43
+ "i9n: Integration tests",
44
+ "r8n: Regression tests",
45
+ "timeout: mark test to timeout after X seconds",
46
+ "xpass: Expected passes",
47
+ "xfail: Expected failures",
48
+ "acceptance: Acceptance tests",
49
+ "perf: Performance tests that measure execution time and resource usage",
50
+ ]
51
+ timeout = 300
52
+ log_cli = true
53
+ log_cli_level = "INFO"
54
+ log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
55
+ log_cli_date_format = "%Y-%m-%d %H:%M:%S"
56
+ asyncio_default_fixture_loop_scope = "function"
57
+
58
+
59
+ [dependency-groups]
60
+ dev = [
61
+ "pytest>=8.0",
62
+ "pytest-asyncio>=0.24.0",
63
+ "pytest-xdist>=3.6.1",
64
+ "pytest-json-report>=1.5.0",
65
+ "python-dotenv",
66
+ "requests>=2.32.3",
67
+ "flake8>=7.0",
68
+ "pytest-timeout>=2.3.1",
69
+ "ruff>=0.9.9",
70
+ "pytest-benchmark>=4.0.0",
71
+ ]
72
+
73
+ [build-system]
74
+ requires = ["poetry-core>=1.0.0"]
75
+ build-backend = "poetry.core.masonry.api"
76
+
77
+ [project.entry-points.'swarmauri.evaluators']
78
+ SubprocessEvaluator = "swarmauri_evaluator_subprocess:SubprocessEvaluator"
@@ -0,0 +1,397 @@
1
+ import logging
2
+ import os
3
+ import resource
4
+ import shlex
5
+ import signal
6
+ import subprocess
7
+ import tempfile
8
+ import time
9
+ from typing import Any, Dict, List, Literal, Optional, Tuple
10
+
11
+ from pydantic import Field
12
+ from swarmauri_base.evaluators.EvaluatorBase import EvaluatorBase
13
+ from swarmauri_base.ComponentBase import ComponentBase
14
+ from swarmauri_core.programs.IProgram import IProgram as Program
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ @ComponentBase.register_model()
20
+ class SubprocessEvaluator(EvaluatorBase):
21
+ """
22
+ Evaluator that runs programs in isolated subprocesses and measures their performance.
23
+
24
+ This evaluator executes programs in sandboxed subprocesses, capturing stdout, stderr,
25
+ exit code, and runtime metrics. It provides security through resource limits and
26
+ timeout constraints to prevent malicious or poorly written code from affecting
27
+ the host system.
28
+ """
29
+
30
+ type: Literal["SubprocessEvaluator"] = "SubprocessEvaluator"
31
+
32
+ # Execution constraints
33
+ timeout: float = Field(
34
+ default=30.0, description="Maximum execution time in seconds"
35
+ )
36
+ max_memory_mb: int = Field(default=512, description="Maximum memory usage in MB")
37
+ max_processes: int = Field(default=64, description="Maximum number of processes")
38
+ max_file_size_mb: int = Field(default=10, description="Maximum file size in MB")
39
+ working_dir: Optional[str] = Field(
40
+ default=None, description="Working directory for execution"
41
+ )
42
+ env_vars: Dict[str, str] = Field(
43
+ default_factory=dict, description="Environment variables for the subprocess"
44
+ )
45
+
46
+ # Scoring parameters
47
+ success_exit_codes: List[int] = Field(
48
+ default=[0], description="Exit codes considered successful"
49
+ )
50
+ score_on_timeout: float = Field(
51
+ default=0.0, description="Score to assign on timeout"
52
+ )
53
+ score_on_error: float = Field(
54
+ default=0.0, description="Score to assign on execution error"
55
+ )
56
+
57
+ def _compute_score(
58
+ self, program: Program, **kwargs
59
+ ) -> Tuple[float, Dict[str, Any]]:
60
+ """
61
+ Execute the program in a subprocess and compute a score based on its performance.
62
+
63
+ Args:
64
+ program: The program to evaluate
65
+ **kwargs: Additional parameters that may include:
66
+ - args: List of command-line arguments to pass to the program
67
+ - input_data: String to provide as stdin to the program
68
+ - expected_output: Expected stdout for comparison
69
+ - custom_timeout: Override the default timeout value
70
+
71
+ Returns:
72
+ A tuple containing:
73
+ - float: A scalar fitness score (1.0 for success, lower for failures)
74
+ - Dict[str, Any]: Metadata about the execution including stdout, stderr,
75
+ exit code, and runtime information
76
+ """
77
+ # Extract additional parameters
78
+ args = kwargs.get("args", [])
79
+ input_data = kwargs.get("input_data", "")
80
+ expected_output = kwargs.get("expected_output", None)
81
+ custom_timeout = kwargs.get("timeout", self.timeout)
82
+
83
+ # Prepare command based on program type
84
+ cmd = self._prepare_command(program, args)
85
+
86
+ # Create a temporary working directory if none specified
87
+ use_temp_dir = self.working_dir is None
88
+ working_dir = self.working_dir
89
+
90
+ if use_temp_dir:
91
+ temp_dir = tempfile.TemporaryDirectory()
92
+ working_dir = temp_dir.name
93
+ logger.debug(f"Created temporary working directory: {working_dir}")
94
+
95
+ try:
96
+ # Execute the program in a subprocess with resource limits
97
+ start_time = time.time()
98
+ result = self._execute_subprocess(
99
+ cmd,
100
+ input_data=input_data,
101
+ timeout=custom_timeout,
102
+ working_dir=working_dir,
103
+ )
104
+ execution_time = time.time() - start_time
105
+
106
+ # Calculate score based on execution results
107
+ score, metadata = self._calculate_score(
108
+ result, expected_output, execution_time
109
+ )
110
+
111
+ # Add program and execution details to metadata
112
+ metadata.update(
113
+ {
114
+ "command": cmd,
115
+ "args": args,
116
+ "working_dir": working_dir,
117
+ }
118
+ )
119
+
120
+ return score, metadata
121
+
122
+ except Exception as e:
123
+ logger.error(f"Error during program execution: {str(e)}")
124
+ return self.score_on_error, {
125
+ "error": str(e),
126
+ "command": cmd,
127
+ "args": args,
128
+ "working_dir": working_dir,
129
+ }
130
+ finally:
131
+ # Clean up temporary directory if we created one
132
+ if use_temp_dir:
133
+ temp_dir.cleanup()
134
+ logger.debug(f"Cleaned up temporary working directory: {working_dir}")
135
+
136
+ def _prepare_command(self, program: Program, args: List[str]) -> List[str]:
137
+ """
138
+ Prepare the command to execute based on the program type.
139
+
140
+ Args:
141
+ program: The program to execute
142
+ args: Additional command-line arguments
143
+
144
+ Returns:
145
+ List of command components ready for subprocess execution
146
+ """
147
+ # Get the program path
148
+ program_path = program.get_path()
149
+
150
+ if not program_path:
151
+ raise ValueError("Program path is not available")
152
+
153
+ if not os.path.exists(program_path):
154
+ raise FileNotFoundError(f"Program file not found: {program_path}")
155
+
156
+ # Make executable if needed
157
+ if not os.access(program_path, os.X_OK) and program.is_executable():
158
+ os.chmod(program_path, 0o755)
159
+ logger.debug(f"Made program file executable: {program_path}")
160
+
161
+ # Determine the appropriate command based on file type
162
+ if program.is_executable():
163
+ # Direct executable
164
+ cmd = [program_path] + args
165
+ elif program_path.endswith(".py"):
166
+ # Python script
167
+ cmd = ["python", program_path] + args
168
+ elif program_path.endswith(".sh"):
169
+ # Shell script
170
+ cmd = ["bash", program_path] + args
171
+ else:
172
+ # Default to executing directly with arguments
173
+ cmd = [program_path] + args
174
+
175
+ logger.debug(f"Prepared command: {' '.join(cmd)}")
176
+ return cmd
177
+
178
+ def _execute_subprocess(
179
+ self,
180
+ cmd: List[str],
181
+ input_data: str = "",
182
+ timeout: float = None,
183
+ working_dir: str = None,
184
+ ) -> Dict[str, Any]:
185
+ """
186
+ Execute a command in a sandboxed subprocess with resource limits.
187
+
188
+ Args:
189
+ cmd: Command to execute as a list of strings
190
+ input_data: Data to provide to the process via stdin
191
+ timeout: Maximum execution time in seconds
192
+ working_dir: Working directory for the subprocess
193
+
194
+ Returns:
195
+ Dictionary containing execution results including stdout, stderr, and exit code
196
+ """
197
+
198
+ # Set resource limits in a preexec function
199
+ def limit_resources():
200
+ # Set CPU time limit (slightly less than wall time)
201
+ if timeout:
202
+ resource.setrlimit(
203
+ resource.RLIMIT_CPU, (int(timeout * 0.9), int(timeout))
204
+ )
205
+
206
+ # Set memory limit
207
+ memory_bytes = self.max_memory_mb * 1024 * 1024
208
+ resource.setrlimit(resource.RLIMIT_AS, (memory_bytes, memory_bytes))
209
+
210
+ # Set file size limit
211
+ file_size_bytes = self.max_file_size_mb * 1024 * 1024
212
+ resource.setrlimit(
213
+ resource.RLIMIT_FSIZE, (file_size_bytes, file_size_bytes)
214
+ )
215
+
216
+ # Set process limit
217
+ resource.setrlimit(
218
+ resource.RLIMIT_NPROC, (self.max_processes, self.max_processes)
219
+ )
220
+
221
+ # Ignore keyboard interrupt in subprocess
222
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
223
+
224
+ # Prepare environment
225
+ env = os.environ.copy()
226
+ env.update(self.env_vars)
227
+
228
+ # Log execution attempt
229
+ cmd_str = " ".join(shlex.quote(arg) for arg in cmd)
230
+ logger.debug(f"Executing: {cmd_str}")
231
+ logger.debug(f"Working directory: {working_dir}")
232
+
233
+ # Execute the subprocess
234
+ process = None
235
+ stdout_data = ""
236
+ stderr_data = ""
237
+ exit_code = None
238
+ timed_out = False
239
+
240
+ try:
241
+ process = subprocess.Popen(
242
+ cmd,
243
+ stdin=subprocess.PIPE,
244
+ stdout=subprocess.PIPE,
245
+ stderr=subprocess.PIPE,
246
+ cwd=working_dir,
247
+ env=env,
248
+ preexec_fn=limit_resources,
249
+ text=True,
250
+ bufsize=1,
251
+ )
252
+
253
+ # Communicate with the process, respecting timeout
254
+ stdout_data, stderr_data = process.communicate(
255
+ input=input_data, timeout=timeout
256
+ )
257
+ exit_code = process.returncode
258
+
259
+ except subprocess.TimeoutExpired:
260
+ if process:
261
+ # Kill the process and all its children
262
+ try:
263
+ process.kill()
264
+ # Attempt to collect any output that was produced before timeout
265
+ stdout_data, stderr_data = process.communicate()
266
+ except Exception as e:
267
+ logger.warning(f"Error while killing timed-out process: {e}")
268
+
269
+ timed_out = True
270
+ exit_code = -1 # Use -1 to indicate timeout
271
+ logger.warning(f"Process timed out after {timeout} seconds")
272
+
273
+ except Exception as e:
274
+ if process and process.poll() is None:
275
+ try:
276
+ process.kill()
277
+ except Exception:
278
+ pass
279
+
280
+ logger.error(f"Error during subprocess execution: {str(e)}")
281
+ exit_code = -2 # Use -2 to indicate execution error
282
+ stderr_data = f"{stderr_data}\nExecution error: {str(e)}"
283
+
284
+ return {
285
+ "stdout": stdout_data,
286
+ "stderr": stderr_data,
287
+ "exit_code": exit_code,
288
+ "timed_out": timed_out,
289
+ }
290
+
291
+ def _calculate_score(
292
+ self,
293
+ result: Dict[str, Any],
294
+ expected_output: Optional[str],
295
+ execution_time: float,
296
+ ) -> Tuple[float, Dict[str, Any]]:
297
+ """
298
+ Calculate a score based on execution results.
299
+
300
+ Args:
301
+ result: Dictionary containing execution results
302
+ expected_output: Expected output for comparison (if provided)
303
+ execution_time: Time taken for execution in seconds
304
+
305
+ Returns:
306
+ A tuple containing:
307
+ - float: Score between 0.0 and 1.0
308
+ - Dict: Metadata with detailed evaluation metrics
309
+ """
310
+ metadata = {
311
+ "stdout": result["stdout"],
312
+ "stderr": result["stderr"],
313
+ "exit_code": result["exit_code"],
314
+ "execution_time": execution_time,
315
+ "timed_out": result["timed_out"],
316
+ }
317
+
318
+ # Handle timeout case
319
+ if result["timed_out"]:
320
+ logger.warning("Program execution timed out")
321
+ return self.score_on_timeout, {**metadata, "reason": "timeout"}
322
+
323
+ # Check exit code
324
+ exit_code = result["exit_code"]
325
+ exit_code_success = exit_code in self.success_exit_codes
326
+
327
+ if not exit_code_success:
328
+ logger.debug(f"Program exited with non-success code: {exit_code}")
329
+ return 0.5, {**metadata, "reason": f"exit_code_{exit_code}"}
330
+
331
+ # If expected output is provided, compare with actual output
332
+ if expected_output is not None:
333
+ output_match = expected_output.strip() == result["stdout"].strip()
334
+ metadata["output_match"] = output_match
335
+
336
+ if not output_match:
337
+ return 0.7, {**metadata, "reason": "output_mismatch"}
338
+
339
+ # If we get here, the program executed successfully
340
+ return 1.0, {**metadata, "reason": "success"}
341
+
342
+ def aggregate_scores(
343
+ self, scores: List[float], metadata_list: List[Dict[str, Any]]
344
+ ) -> Tuple[float, Dict[str, Any]]:
345
+ """
346
+ Aggregate multiple evaluation scores and their metadata.
347
+
348
+ This implementation extends the base aggregation with subprocess-specific metrics.
349
+
350
+ Args:
351
+ scores: List of individual scores to aggregate
352
+ metadata_list: List of metadata dictionaries corresponding to each score
353
+
354
+ Returns:
355
+ A tuple containing:
356
+ - float: The aggregated score
357
+ - Dict[str, Any]: Aggregated metadata with execution statistics
358
+ """
359
+ # Use the base implementation for basic aggregation
360
+ aggregated_score, aggregated_metadata = super().aggregate_scores(
361
+ scores, metadata_list
362
+ )
363
+
364
+ # Add subprocess-specific aggregated metrics
365
+ if metadata_list:
366
+ # Count success/failure reasons
367
+ reason_counts = {}
368
+ for meta in metadata_list:
369
+ reason = meta.get("reason", "unknown")
370
+ reason_counts[reason] = reason_counts.get(reason, 0) + 1
371
+
372
+ # Calculate timeout rate
373
+ timeout_count = sum(
374
+ 1 for meta in metadata_list if meta.get("timed_out", False)
375
+ )
376
+ timeout_rate = timeout_count / len(metadata_list) if metadata_list else 0
377
+
378
+ # Calculate exit code statistics
379
+ exit_codes = [
380
+ meta.get("exit_code") for meta in metadata_list if "exit_code" in meta
381
+ ]
382
+ success_exit_count = sum(
383
+ 1 for code in exit_codes if code in self.success_exit_codes
384
+ )
385
+ success_rate = success_exit_count / len(exit_codes) if exit_codes else 0
386
+
387
+ # Add to aggregated metadata
388
+ aggregated_metadata.update(
389
+ {
390
+ "reason_counts": reason_counts,
391
+ "timeout_rate": timeout_rate,
392
+ "success_rate": success_rate,
393
+ "total_executions": len(metadata_list),
394
+ }
395
+ )
396
+
397
+ return aggregated_score, aggregated_metadata
@@ -0,0 +1,16 @@
1
+ from .SubprocessEvaluator import SubprocessEvaluator
2
+
3
+ __all__ = ["SubprocessEvaluator"]
4
+
5
+ try:
6
+ # For Python 3.8 and newer
7
+ from importlib.metadata import version, PackageNotFoundError
8
+ except ImportError:
9
+ # For older Python versions, use the backport
10
+ from importlib_metadata import version, PackageNotFoundError
11
+
12
+ try:
13
+ __version__ = version("swarmauri_evaluator_subprocess")
14
+ except PackageNotFoundError:
15
+ # If the package is not installed (for example, during development)
16
+ __version__ = "0.0.0"