optpilot 0.1.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.
- optpilot/__init__.py +5 -0
- optpilot/__main__.py +3 -0
- optpilot/adapters.py +782 -0
- optpilot/candidate_files.py +257 -0
- optpilot/candidate_materialization.py +609 -0
- optpilot/cli.py +112 -0
- optpilot/config.py +1227 -0
- optpilot/container_utils.py +120 -0
- optpilot/environment.py +183 -0
- optpilot/evidence.py +478 -0
- optpilot/execution.py +1038 -0
- optpilot/method_runtime.py +831 -0
- optpilot/method_worker.py +289 -0
- optpilot/methods.py +61 -0
- optpilot/models.py +144 -0
- optpilot/package_index.py +238 -0
- optpilot/package_validation.py +136 -0
- optpilot/provenance.py +136 -0
- optpilot/registry.py +80 -0
- optpilot/run_sources.py +419 -0
- optpilot/runner.py +454 -0
- optpilot/scheduler.py +165 -0
- optpilot/schema_validation.py +141 -0
- optpilot/schemas/__init__.py +1 -0
- optpilot/schemas/defs/candidate.schema.json +119 -0
- optpilot/schemas/defs/common.schema.json +140 -0
- optpilot/schemas/defs/metrics.schema.json +171 -0
- optpilot/schemas/defs/runtime.schema.json +70 -0
- optpilot/schemas/environment.schema.json +91 -0
- optpilot/schemas/method.schema.json +67 -0
- optpilot/schemas/resource.schema.json +16 -0
- optpilot/schemas/study.schema.json +71 -0
- optpilot/setup.py +269 -0
- optpilot/spec.py +215 -0
- optpilot/storage.py +125 -0
- optpilot/worker.py +57 -0
- optpilot-0.1.0.dist-info/METADATA +266 -0
- optpilot-0.1.0.dist-info/RECORD +42 -0
- optpilot-0.1.0.dist-info/WHEEL +5 -0
- optpilot-0.1.0.dist-info/entry_points.txt +2 -0
- optpilot-0.1.0.dist-info/licenses/LICENSE +201 -0
- optpilot-0.1.0.dist-info/top_level.txt +1 -0
optpilot/adapters.py
ADDED
|
@@ -0,0 +1,782 @@
|
|
|
1
|
+
"""Environment adapter implementations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import hashlib
|
|
7
|
+
import importlib
|
|
8
|
+
import inspect
|
|
9
|
+
import csv
|
|
10
|
+
import os
|
|
11
|
+
import shlex
|
|
12
|
+
import sqlite3
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, Dict, List, Optional
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class PythonCallableEnvironmentAdapter:
|
|
20
|
+
def __init__(self, definition: Dict[str, Any], study_spec):
|
|
21
|
+
self.definition = definition
|
|
22
|
+
self.study_spec = study_spec
|
|
23
|
+
self._callable = None
|
|
24
|
+
|
|
25
|
+
def evaluate(self, candidate_runtime: Dict[str, Any], context: Dict[str, Any]) -> Dict[str, Any]:
|
|
26
|
+
if self._callable is None:
|
|
27
|
+
config = self.definition.get("config", {})
|
|
28
|
+
module = importlib.import_module(config["module"])
|
|
29
|
+
self._callable = getattr(module, config["callable"])
|
|
30
|
+
context = {**context, "settings": dict(self.definition.get("config", {}) or {})}
|
|
31
|
+
result = self._callable(candidate_runtime, context)
|
|
32
|
+
if not isinstance(result, dict):
|
|
33
|
+
raise TypeError("Environment callable must return a dict.")
|
|
34
|
+
metric_values = _extract_metric_values(result)
|
|
35
|
+
return {
|
|
36
|
+
"status": result.get("status", "success"),
|
|
37
|
+
"metric_values": metric_values,
|
|
38
|
+
"constraint_results": dict(result.get("constraint_results", {})),
|
|
39
|
+
"output_files": list(result.get("output_files", [])),
|
|
40
|
+
"event_summary": dict(result.get("event_summary", {})),
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ConfiguredEnvironmentAdapter:
|
|
45
|
+
"""Evaluate environments compiled from public `config: environment` files."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, definition: Dict[str, Any], study_spec):
|
|
48
|
+
self.definition = definition
|
|
49
|
+
self.study_spec = study_spec
|
|
50
|
+
self._callable = None
|
|
51
|
+
|
|
52
|
+
def evaluate(self, candidate_runtime: Dict[str, Any], context: Dict[str, Any]) -> Dict[str, Any]:
|
|
53
|
+
config = self.definition.get("config", {})
|
|
54
|
+
evaluate = config.get("evaluate", {})
|
|
55
|
+
metrics = config.get("metrics", {})
|
|
56
|
+
workspace = Path(candidate_runtime.get("workspace") or context["workspace"]).resolve()
|
|
57
|
+
workspace.mkdir(parents=True, exist_ok=True)
|
|
58
|
+
candidate_root = Path(candidate_runtime.get("candidateRoot", workspace)).resolve()
|
|
59
|
+
metrics_path = _workspace_path(workspace, metrics.get("path", "metrics.json"))
|
|
60
|
+
settings_path = _workspace_path(workspace, "settings.json")
|
|
61
|
+
candidate_path = _configured_candidate_path(workspace, candidate_root, candidate_runtime, config)
|
|
62
|
+
stdout_path = _workspace_path(workspace, "stdout.log")
|
|
63
|
+
stderr_path = _workspace_path(workspace, "stderr.log")
|
|
64
|
+
component_python = _component_python_executable(self.study_spec.environment.get("runtime", {}))
|
|
65
|
+
|
|
66
|
+
settings = dict(evaluate.get("config", {}) or {})
|
|
67
|
+
_write_json(settings_path, settings)
|
|
68
|
+
candidate_payload_path = _workspace_path(workspace, "candidate.json")
|
|
69
|
+
_write_json(candidate_payload_path, candidate_runtime)
|
|
70
|
+
context = {**context, "settings": settings, "settings_file": str(settings_path)}
|
|
71
|
+
|
|
72
|
+
eval_type = evaluate.get("type")
|
|
73
|
+
process_result = None
|
|
74
|
+
python_result = None
|
|
75
|
+
cwd = _workspace_path(workspace, evaluate.get("cwd", "."))
|
|
76
|
+
placeholders = {
|
|
77
|
+
"python": component_python,
|
|
78
|
+
"workspace": str(workspace),
|
|
79
|
+
"candidate_root": str(candidate_root),
|
|
80
|
+
"candidate_file": str(candidate_path),
|
|
81
|
+
"candidate": str(candidate_path),
|
|
82
|
+
"candidate_json": str(candidate_payload_path),
|
|
83
|
+
"settings_file": str(settings_path),
|
|
84
|
+
"metrics_file": str(metrics_path),
|
|
85
|
+
"trial_id": context["trial_id"],
|
|
86
|
+
"study_id": context["study_id"],
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if eval_type == "python":
|
|
90
|
+
python_result = self._evaluate_python(evaluate, candidate_runtime, context)
|
|
91
|
+
elif eval_type == "command":
|
|
92
|
+
command = _format_command(evaluate["command"], placeholders)
|
|
93
|
+
env = os.environ.copy()
|
|
94
|
+
declared_python_path = os.pathsep.join(str(path) for path in evaluate.get("pythonPath", []) or [] if path)
|
|
95
|
+
env.update({key: _format_string(str(value), placeholders) for key, value in evaluate.get("env", {}).items()})
|
|
96
|
+
if env.get("PYTHONPATH"):
|
|
97
|
+
env["PYTHONPATH"] = _absolute_pythonpath(env["PYTHONPATH"], Path.cwd())
|
|
98
|
+
if declared_python_path:
|
|
99
|
+
env["PYTHONPATH"] = (
|
|
100
|
+
declared_python_path
|
|
101
|
+
if not env.get("PYTHONPATH")
|
|
102
|
+
else declared_python_path + os.pathsep + env["PYTHONPATH"]
|
|
103
|
+
)
|
|
104
|
+
timeout = int(
|
|
105
|
+
evaluate.get(
|
|
106
|
+
"timeoutSeconds",
|
|
107
|
+
context.get("resource_profile", {}).get(
|
|
108
|
+
"timeoutSeconds",
|
|
109
|
+
self.study_spec.environment.get("runtimeContract", {}).get("timeoutSeconds", 600),
|
|
110
|
+
),
|
|
111
|
+
)
|
|
112
|
+
)
|
|
113
|
+
try:
|
|
114
|
+
process_result = subprocess.run(
|
|
115
|
+
command,
|
|
116
|
+
cwd=str(cwd),
|
|
117
|
+
env=env,
|
|
118
|
+
text=True,
|
|
119
|
+
capture_output=True,
|
|
120
|
+
timeout=timeout,
|
|
121
|
+
check=False,
|
|
122
|
+
)
|
|
123
|
+
except subprocess.TimeoutExpired as exc:
|
|
124
|
+
stdout_path.write_text(_coerce_process_text(exc.stdout), encoding="utf-8")
|
|
125
|
+
stderr_path.write_text(_coerce_process_text(exc.stderr), encoding="utf-8")
|
|
126
|
+
raise
|
|
127
|
+
stdout_path.write_text(process_result.stdout, encoding="utf-8")
|
|
128
|
+
stderr_path.write_text(process_result.stderr, encoding="utf-8")
|
|
129
|
+
if process_result.returncode != 0:
|
|
130
|
+
raise RuntimeError(
|
|
131
|
+
f"Configured environment command failed with exit code {process_result.returncode}: "
|
|
132
|
+
f"{process_result.stderr.strip()}"
|
|
133
|
+
)
|
|
134
|
+
else:
|
|
135
|
+
raise ValueError(f"Unsupported configured evaluate.type: {eval_type!r}")
|
|
136
|
+
|
|
137
|
+
metric_values, status, constraint_results, event_summary = self._extract_metrics(
|
|
138
|
+
metrics,
|
|
139
|
+
workspace,
|
|
140
|
+
cwd,
|
|
141
|
+
python_result,
|
|
142
|
+
process_result,
|
|
143
|
+
)
|
|
144
|
+
output_files = [
|
|
145
|
+
{"type": "json", "name": "settings", "path": str(settings_path)},
|
|
146
|
+
{"type": "json", "name": "candidate_payload", "path": str(candidate_payload_path)},
|
|
147
|
+
]
|
|
148
|
+
if process_result is not None:
|
|
149
|
+
output_files.extend(
|
|
150
|
+
[
|
|
151
|
+
{"type": "log", "name": "stdout", "path": str(stdout_path)},
|
|
152
|
+
{"type": "log", "name": "stderr", "path": str(stderr_path)},
|
|
153
|
+
]
|
|
154
|
+
)
|
|
155
|
+
if metrics_path.exists():
|
|
156
|
+
output_files.append({"type": "json", "name": "metrics", "path": str(metrics_path)})
|
|
157
|
+
if python_result is not None:
|
|
158
|
+
output_files.extend(list(python_result.get("output_files", []) or []))
|
|
159
|
+
output_files.extend(_collect_output_files(workspace, workspace, config.get("outputFiles", [])))
|
|
160
|
+
output_files = _dedupe_output_files(output_files)
|
|
161
|
+
|
|
162
|
+
records_report = _extract_records(workspace, config.get("records", []))
|
|
163
|
+
if records_report:
|
|
164
|
+
records_report_path = workspace / "records_to_extract_report.json"
|
|
165
|
+
_write_json(records_report_path, records_report)
|
|
166
|
+
output_files.append({"type": "json", "name": "records_to_extract_report", "path": str(records_report_path)})
|
|
167
|
+
event_summary["records"] = records_report
|
|
168
|
+
|
|
169
|
+
manifest_path = Path(candidate_runtime.get("manifestPath", workspace / "workspace_manifest.json")).resolve()
|
|
170
|
+
readonly_report = _check_readonly_files(workspace, manifest_path)
|
|
171
|
+
if readonly_report is not None:
|
|
172
|
+
readonly_report_path = workspace / "readonly_report.json"
|
|
173
|
+
_write_json(readonly_report_path, readonly_report)
|
|
174
|
+
output_files.append({"type": "json", "name": "readonly_report", "path": str(readonly_report_path)})
|
|
175
|
+
event_summary["readonly_violations"] = readonly_report["violations"]
|
|
176
|
+
|
|
177
|
+
event_summary.setdefault("adapter", "configured_environment")
|
|
178
|
+
event_summary.setdefault("evaluate_type", eval_type)
|
|
179
|
+
if process_result is not None:
|
|
180
|
+
event_summary.setdefault("return_code", process_result.returncode)
|
|
181
|
+
event_summary.setdefault("command", command)
|
|
182
|
+
event_summary.setdefault("cwd", str(cwd))
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
"status": status,
|
|
186
|
+
"metric_values": metric_values,
|
|
187
|
+
"constraint_results": constraint_results,
|
|
188
|
+
"output_files": output_files,
|
|
189
|
+
"event_summary": event_summary,
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
def _evaluate_python(
|
|
193
|
+
self,
|
|
194
|
+
evaluate: Dict[str, Any],
|
|
195
|
+
candidate_runtime: Dict[str, Any],
|
|
196
|
+
context: Dict[str, Any],
|
|
197
|
+
) -> Dict[str, Any]:
|
|
198
|
+
if self._callable is None:
|
|
199
|
+
for path in reversed(evaluate.get("pythonPath", []) or []):
|
|
200
|
+
if path and path not in sys.path:
|
|
201
|
+
sys.path.insert(0, path)
|
|
202
|
+
module_name, _, attr = str(evaluate["callable"]).partition(":")
|
|
203
|
+
if not module_name or not attr:
|
|
204
|
+
raise ValueError("evaluate.callable must use 'module:function' format.")
|
|
205
|
+
module = importlib.import_module(module_name)
|
|
206
|
+
self._callable = getattr(module, attr)
|
|
207
|
+
result = self._callable(candidate_runtime, context)
|
|
208
|
+
if not isinstance(result, dict):
|
|
209
|
+
raise TypeError("Configured Python evaluator must return a dict.")
|
|
210
|
+
return result
|
|
211
|
+
|
|
212
|
+
def _extract_metrics(
|
|
213
|
+
self,
|
|
214
|
+
metrics: Dict[str, Any],
|
|
215
|
+
workspace: Path,
|
|
216
|
+
cwd: Path,
|
|
217
|
+
python_result: Optional[Dict[str, Any]],
|
|
218
|
+
process_result,
|
|
219
|
+
):
|
|
220
|
+
source = metrics.get("source")
|
|
221
|
+
if source == "return":
|
|
222
|
+
if python_result is None:
|
|
223
|
+
raise ValueError("metrics.source return requires evaluate.type python.")
|
|
224
|
+
payload = python_result
|
|
225
|
+
elif source == "file":
|
|
226
|
+
path = _workspace_path(workspace, metrics["path"])
|
|
227
|
+
if not path.exists():
|
|
228
|
+
raise FileNotFoundError(f"Configured environment did not create metrics file: {path}")
|
|
229
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
230
|
+
elif source == "stdout":
|
|
231
|
+
if process_result is None:
|
|
232
|
+
raise ValueError("metrics.source stdout requires evaluate.type command.")
|
|
233
|
+
payload = json.loads(process_result.stdout)
|
|
234
|
+
elif source == "sqlite":
|
|
235
|
+
payload = _query_sqlite_metrics(_workspace_path(workspace, metrics["database"]), metrics["query"])
|
|
236
|
+
elif source == "custom":
|
|
237
|
+
payload = _run_custom_metrics_extractor(metrics, workspace, cwd, python_result, process_result)
|
|
238
|
+
else:
|
|
239
|
+
raise ValueError(f"Unsupported metrics.source: {source!r}")
|
|
240
|
+
if not isinstance(payload, dict):
|
|
241
|
+
raise TypeError("Configured environment metrics payload must be a JSON object/dict.")
|
|
242
|
+
return (
|
|
243
|
+
_extract_metric_values(payload),
|
|
244
|
+
str(payload.get("status", "success")),
|
|
245
|
+
dict(payload.get("constraint_results", {})),
|
|
246
|
+
dict(payload.get("event_summary", {})),
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
class CLIEnvironmentAdapter:
|
|
251
|
+
def __init__(self, definition: Dict[str, Any], study_spec):
|
|
252
|
+
self.definition = definition
|
|
253
|
+
self.study_spec = study_spec
|
|
254
|
+
|
|
255
|
+
def evaluate(self, candidate_runtime: Dict[str, Any], context: Dict[str, Any]) -> Dict[str, Any]:
|
|
256
|
+
config = self.definition.get("config", {})
|
|
257
|
+
workspace = Path(context["workspace"])
|
|
258
|
+
candidate_path = workspace / config.get("candidatePath", "cli_candidate.json")
|
|
259
|
+
settings_path = workspace / config.get("settingsPath", "cli_settings.json")
|
|
260
|
+
output_path = workspace / config.get("outputPath", "cli_result.json")
|
|
261
|
+
stdout_path = workspace / config.get("stdoutPath", "cli_stdout.log")
|
|
262
|
+
stderr_path = workspace / config.get("stderrPath", "cli_stderr.log")
|
|
263
|
+
|
|
264
|
+
_write_json(candidate_path, candidate_runtime)
|
|
265
|
+
settings = dict(config.get("settings", config.get("config", {})) or {})
|
|
266
|
+
_write_json(settings_path, settings)
|
|
267
|
+
context = {**context, "settings": settings, "settings_file": str(settings_path)}
|
|
268
|
+
|
|
269
|
+
placeholders = {
|
|
270
|
+
"python": _component_python_executable(self.study_spec.environment.get("runtime", {})),
|
|
271
|
+
"candidate_path": str(candidate_path),
|
|
272
|
+
"settings_path": str(settings_path),
|
|
273
|
+
"output_path": str(output_path),
|
|
274
|
+
"stdout_path": str(stdout_path),
|
|
275
|
+
"stderr_path": str(stderr_path),
|
|
276
|
+
"workspace": str(workspace),
|
|
277
|
+
"trial_id": context["trial_id"],
|
|
278
|
+
"study_id": context["study_id"],
|
|
279
|
+
}
|
|
280
|
+
command = _format_command(config["command"], placeholders)
|
|
281
|
+
cwd = _resolve_optional_path(config.get("workingDir"), self.study_spec)
|
|
282
|
+
env = os.environ.copy()
|
|
283
|
+
env.update({key: _format_string(str(value), placeholders) for key, value in config.get("env", {}).items()})
|
|
284
|
+
timeout = int(
|
|
285
|
+
config.get(
|
|
286
|
+
"timeoutSeconds",
|
|
287
|
+
context.get("resource_profile", {}).get(
|
|
288
|
+
"timeoutSeconds",
|
|
289
|
+
self.study_spec.environment.get("runtimeContract", {}).get("timeoutSeconds", 600),
|
|
290
|
+
),
|
|
291
|
+
)
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
try:
|
|
295
|
+
completed = subprocess.run(
|
|
296
|
+
command,
|
|
297
|
+
cwd=str(cwd) if cwd else None,
|
|
298
|
+
env=env,
|
|
299
|
+
text=True,
|
|
300
|
+
capture_output=True,
|
|
301
|
+
timeout=timeout,
|
|
302
|
+
check=False,
|
|
303
|
+
)
|
|
304
|
+
except subprocess.TimeoutExpired as exc:
|
|
305
|
+
stdout_path.write_text(_coerce_process_text(exc.stdout), encoding="utf-8")
|
|
306
|
+
stderr_path.write_text(_coerce_process_text(exc.stderr), encoding="utf-8")
|
|
307
|
+
raise
|
|
308
|
+
stdout_path.write_text(completed.stdout, encoding="utf-8")
|
|
309
|
+
stderr_path.write_text(completed.stderr, encoding="utf-8")
|
|
310
|
+
if completed.returncode != 0:
|
|
311
|
+
raise RuntimeError(
|
|
312
|
+
f"CLI environment command failed with exit code {completed.returncode}: {completed.stderr.strip()}"
|
|
313
|
+
)
|
|
314
|
+
if not output_path.exists():
|
|
315
|
+
raise FileNotFoundError(f"CLI environment did not create output file: {output_path}")
|
|
316
|
+
|
|
317
|
+
result = json.loads(output_path.read_text(encoding="utf-8"))
|
|
318
|
+
if not isinstance(result, dict):
|
|
319
|
+
raise TypeError("CLI environment output must be a JSON object.")
|
|
320
|
+
output_files = list(result.get("output_files", []))
|
|
321
|
+
output_files.extend(
|
|
322
|
+
[
|
|
323
|
+
{"type": "json", "name": "cli_candidate_input", "path": str(candidate_path)},
|
|
324
|
+
{"type": "json", "name": "cli_settings_input", "path": str(settings_path)},
|
|
325
|
+
{"type": "json", "name": "cli_result_output", "path": str(output_path)},
|
|
326
|
+
{"type": "log", "name": "cli_stdout", "path": str(stdout_path)},
|
|
327
|
+
{"type": "log", "name": "cli_stderr", "path": str(stderr_path)},
|
|
328
|
+
]
|
|
329
|
+
)
|
|
330
|
+
event_summary = dict(result.get("event_summary", {}))
|
|
331
|
+
event_summary.update(
|
|
332
|
+
{
|
|
333
|
+
"adapter": "cli",
|
|
334
|
+
"command": command,
|
|
335
|
+
"return_code": completed.returncode,
|
|
336
|
+
"timeout_seconds": timeout,
|
|
337
|
+
}
|
|
338
|
+
)
|
|
339
|
+
return {
|
|
340
|
+
"status": result.get("status", "success"),
|
|
341
|
+
"metric_values": dict(result.get("metric_values", {})),
|
|
342
|
+
"constraint_results": dict(result.get("constraint_results", {})),
|
|
343
|
+
"output_files": output_files,
|
|
344
|
+
"event_summary": event_summary,
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
class ReadOnlySQLiteQuery:
|
|
349
|
+
"""Read-only SQLite query capability for method-visible evidence data."""
|
|
350
|
+
|
|
351
|
+
WRITE_KEYWORDS = {
|
|
352
|
+
"attach",
|
|
353
|
+
"create",
|
|
354
|
+
"delete",
|
|
355
|
+
"detach",
|
|
356
|
+
"drop",
|
|
357
|
+
"insert",
|
|
358
|
+
"pragma",
|
|
359
|
+
"replace",
|
|
360
|
+
"update",
|
|
361
|
+
"vacuum",
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
def __init__(self, definition: Dict[str, Any], study_spec=None):
|
|
365
|
+
config = definition.get("config", definition)
|
|
366
|
+
database = config.get("path") or config.get("database")
|
|
367
|
+
if not database:
|
|
368
|
+
raise ValueError("ReadOnlySQLiteQuery requires config.path or config.database.")
|
|
369
|
+
if study_spec is not None:
|
|
370
|
+
self.database = study_spec.resolve_path(str(database))
|
|
371
|
+
else:
|
|
372
|
+
self.database = Path(str(database)).resolve()
|
|
373
|
+
self.max_rows = int(config.get("maxRows", 1000) or 1000)
|
|
374
|
+
|
|
375
|
+
def query(self, sql: str, params: Optional[List[Any]] = None, *, max_rows: Optional[int] = None) -> Dict[str, Any]:
|
|
376
|
+
statement = str(sql).strip()
|
|
377
|
+
if not statement:
|
|
378
|
+
raise ValueError("SQL query must be non-empty.")
|
|
379
|
+
_reject_mutating_sql(statement)
|
|
380
|
+
limit = int(max_rows or self.max_rows)
|
|
381
|
+
uri = f"file:{self.database}?mode=ro"
|
|
382
|
+
with sqlite3.connect(uri, uri=True) as connection:
|
|
383
|
+
connection.row_factory = sqlite3.Row
|
|
384
|
+
cursor = connection.execute(statement, list(params or []))
|
|
385
|
+
rows = cursor.fetchmany(limit + 1)
|
|
386
|
+
truncated = len(rows) > limit
|
|
387
|
+
rows = rows[:limit]
|
|
388
|
+
return {
|
|
389
|
+
"database": str(self.database),
|
|
390
|
+
"columns": list(rows[0].keys()) if rows else [],
|
|
391
|
+
"rows": [dict(row) for row in rows],
|
|
392
|
+
"row_count": len(rows),
|
|
393
|
+
"truncated": truncated,
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _format_command(command: Any, placeholders: Dict[str, str]) -> List[str]:
|
|
398
|
+
if isinstance(command, str):
|
|
399
|
+
return [_format_string(part, placeholders) for part in shlex.split(command)]
|
|
400
|
+
return [_format_string(str(part), placeholders) for part in command]
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _component_python_executable(runtime: Dict[str, Any]) -> str:
|
|
404
|
+
return str(runtime.get("pythonExecutable") or sys.executable)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _reject_mutating_sql(statement: str) -> None:
|
|
408
|
+
lowered = statement.lower()
|
|
409
|
+
stripped = lowered.lstrip()
|
|
410
|
+
if not (stripped.startswith("select") or stripped.startswith("with")):
|
|
411
|
+
raise ValueError("Only SELECT/WITH queries are allowed for read-only SQLite interfaces.")
|
|
412
|
+
for token in ReadOnlySQLiteQuery.WRITE_KEYWORDS:
|
|
413
|
+
if token in {part.strip(" ;\n\t\r(),") for part in lowered.split()}:
|
|
414
|
+
raise ValueError(f"SQL keyword {token!r} is not allowed in read-only SQLite interfaces.")
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _absolute_pythonpath(value: str, base_dir: Path) -> str:
|
|
418
|
+
entries = []
|
|
419
|
+
for item in value.split(os.pathsep):
|
|
420
|
+
if not item:
|
|
421
|
+
entries.append(item)
|
|
422
|
+
continue
|
|
423
|
+
path = Path(item)
|
|
424
|
+
entries.append(str(path if path.is_absolute() else (base_dir / path).resolve()))
|
|
425
|
+
return os.pathsep.join(entries)
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _format_string(value: str, placeholders: Dict[str, str]) -> str:
|
|
429
|
+
return value.format(**placeholders)
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _resolve_optional_path(value: Any, study_spec) -> Optional[Path]:
|
|
433
|
+
if not value:
|
|
434
|
+
return None
|
|
435
|
+
return study_spec.resolve_path(str(value))
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _configured_candidate_path(
|
|
439
|
+
workspace: Path,
|
|
440
|
+
candidate_root: Path,
|
|
441
|
+
candidate_runtime: Dict[str, Any],
|
|
442
|
+
config: Dict[str, Any],
|
|
443
|
+
) -> Path:
|
|
444
|
+
candidate = config.get("candidate", {})
|
|
445
|
+
required = candidate.get("required", []) or []
|
|
446
|
+
if len(required) == 1:
|
|
447
|
+
return _workspace_path(candidate_root, required[0])
|
|
448
|
+
files = candidate_runtime.get("files", [])
|
|
449
|
+
if isinstance(files, list) and len(files) == 1 and isinstance(files[0], dict):
|
|
450
|
+
candidate_path = files[0].get("path")
|
|
451
|
+
if candidate_path:
|
|
452
|
+
return _workspace_path(candidate_root, candidate_path)
|
|
453
|
+
return candidate_root
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def _write_json(path: Path, payload: Dict[str, Any]) -> None:
|
|
457
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
458
|
+
with path.open("w", encoding="utf-8") as handle:
|
|
459
|
+
json.dump(payload, handle, indent=2, sort_keys=True)
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def _coerce_process_text(value: Any) -> str:
|
|
463
|
+
if value is None:
|
|
464
|
+
return ""
|
|
465
|
+
if isinstance(value, bytes):
|
|
466
|
+
return value.decode("utf-8", errors="replace")
|
|
467
|
+
return str(value)
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def _workspace_path(workspace: Path, value: Any) -> Path:
|
|
471
|
+
path = Path(str(value))
|
|
472
|
+
workspace_resolved = workspace.resolve()
|
|
473
|
+
if path.is_absolute():
|
|
474
|
+
resolved = path.resolve()
|
|
475
|
+
if resolved != workspace_resolved and workspace_resolved not in resolved.parents:
|
|
476
|
+
raise ValueError(f"Workspace path escapes root: {value!r}")
|
|
477
|
+
return resolved
|
|
478
|
+
resolved = (workspace / path).resolve()
|
|
479
|
+
if resolved != workspace_resolved and workspace_resolved not in resolved.parents:
|
|
480
|
+
raise ValueError(f"Workspace path escapes root: {value!r}")
|
|
481
|
+
return resolved
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def _extract_metric_values(payload: Any) -> Dict[str, Any]:
|
|
485
|
+
if not isinstance(payload, dict):
|
|
486
|
+
raise TypeError("Workspace metric file must be a JSON object.")
|
|
487
|
+
if "metric_values" in payload:
|
|
488
|
+
metric_values = payload["metric_values"]
|
|
489
|
+
elif "metrics" in payload:
|
|
490
|
+
metric_values = payload["metrics"]
|
|
491
|
+
else:
|
|
492
|
+
excluded = {"status", "constraint_results", "output_files", "event_summary"}
|
|
493
|
+
metric_values = {key: value for key, value in payload.items() if key not in excluded}
|
|
494
|
+
if not isinstance(metric_values, dict):
|
|
495
|
+
raise TypeError("Workspace metrics must be a JSON object.")
|
|
496
|
+
return dict(metric_values)
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _query_sqlite_metrics(database: Path, query: str) -> Dict[str, Any]:
|
|
500
|
+
if not database.exists():
|
|
501
|
+
raise FileNotFoundError(f"SQLite metrics database does not exist: {database}")
|
|
502
|
+
with sqlite3.connect(str(database)) as connection:
|
|
503
|
+
connection.row_factory = sqlite3.Row
|
|
504
|
+
row = connection.execute(query).fetchone()
|
|
505
|
+
if row is None:
|
|
506
|
+
raise ValueError("SQLite metrics query returned no rows.")
|
|
507
|
+
return dict(row)
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def _extract_records(workspace: Path, records: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
|
511
|
+
if not records:
|
|
512
|
+
return None
|
|
513
|
+
streams = []
|
|
514
|
+
for record in records:
|
|
515
|
+
source = record.get("source")
|
|
516
|
+
name = str(record["name"])
|
|
517
|
+
if source == "custom":
|
|
518
|
+
rows, source_path = _run_custom_record_extractor(record, workspace)
|
|
519
|
+
else:
|
|
520
|
+
path = _workspace_path(workspace, record["path"])
|
|
521
|
+
rows = _read_record_rows(path, record)
|
|
522
|
+
source_path = str(path)
|
|
523
|
+
output_path = workspace / "extracted_records" / f"{name}.jsonl"
|
|
524
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
525
|
+
with output_path.open("w", encoding="utf-8") as handle:
|
|
526
|
+
for row in rows:
|
|
527
|
+
handle.write(json.dumps(row, sort_keys=True) + "\n")
|
|
528
|
+
streams.append(
|
|
529
|
+
{
|
|
530
|
+
"name": name,
|
|
531
|
+
"source": source,
|
|
532
|
+
"path": source_path,
|
|
533
|
+
"record_count": len(rows),
|
|
534
|
+
"contentRef": str(output_path),
|
|
535
|
+
}
|
|
536
|
+
)
|
|
537
|
+
return {"streams": streams}
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _run_custom_metrics_extractor(
|
|
541
|
+
metrics: Dict[str, Any],
|
|
542
|
+
workspace: Path,
|
|
543
|
+
cwd: Path,
|
|
544
|
+
python_result: Optional[Dict[str, Any]],
|
|
545
|
+
process_result,
|
|
546
|
+
) -> Dict[str, Any]:
|
|
547
|
+
component = _load_python_component(metrics["implementation"])
|
|
548
|
+
payload = {
|
|
549
|
+
"workspace": str(workspace),
|
|
550
|
+
"cwd": str(cwd),
|
|
551
|
+
"metrics": dict(metrics),
|
|
552
|
+
"config": dict(metrics.get("config", {})),
|
|
553
|
+
"python_result": python_result,
|
|
554
|
+
"process_result": _process_result_payload(process_result),
|
|
555
|
+
}
|
|
556
|
+
result = _invoke_custom_component(component, payload, method_name="extract")
|
|
557
|
+
if not isinstance(result, dict):
|
|
558
|
+
raise TypeError("Custom metrics extractor must return a dict.")
|
|
559
|
+
return result
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def _run_custom_record_extractor(record: Dict[str, Any], workspace: Path) -> tuple[List[Dict[str, Any]], str]:
|
|
563
|
+
component = _load_python_component(record["implementation"])
|
|
564
|
+
payload = {
|
|
565
|
+
"workspace": str(workspace),
|
|
566
|
+
"record": dict(record),
|
|
567
|
+
"config": dict(record.get("config", {})),
|
|
568
|
+
}
|
|
569
|
+
result = _invoke_custom_component(component, payload, method_name="extract")
|
|
570
|
+
source_path = str(workspace)
|
|
571
|
+
if isinstance(result, dict):
|
|
572
|
+
source_path = str(result.get("path") or result.get("source_path") or source_path)
|
|
573
|
+
rows = result.get("rows", result.get("records"))
|
|
574
|
+
else:
|
|
575
|
+
rows = result
|
|
576
|
+
if not isinstance(rows, list):
|
|
577
|
+
raise TypeError("Custom record extractor must return a list of rows or a dict containing rows.")
|
|
578
|
+
for row in rows:
|
|
579
|
+
if not isinstance(row, dict):
|
|
580
|
+
raise TypeError("Custom record extractor rows must be JSON objects.")
|
|
581
|
+
return rows, source_path
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def _load_python_component(implementation: str):
|
|
585
|
+
module_name, _, attr = str(implementation).partition(":")
|
|
586
|
+
if not module_name or not attr:
|
|
587
|
+
raise ValueError(f"Custom implementation must use module:object format: {implementation!r}")
|
|
588
|
+
module = importlib.import_module(module_name)
|
|
589
|
+
return getattr(module, attr)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def _invoke_custom_component(component, payload: Dict[str, Any], *, method_name: str):
|
|
593
|
+
target = component
|
|
594
|
+
if inspect.isclass(component):
|
|
595
|
+
target = component(payload.get("config", {}))
|
|
596
|
+
if hasattr(target, method_name):
|
|
597
|
+
return getattr(target, method_name)(payload)
|
|
598
|
+
if callable(target):
|
|
599
|
+
return target(payload)
|
|
600
|
+
raise TypeError(f"Custom component must be callable or define {method_name}().")
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def _process_result_payload(process_result) -> Optional[Dict[str, Any]]:
|
|
604
|
+
if process_result is None:
|
|
605
|
+
return None
|
|
606
|
+
return {
|
|
607
|
+
"returncode": process_result.returncode,
|
|
608
|
+
"stdout": process_result.stdout,
|
|
609
|
+
"stderr": process_result.stderr,
|
|
610
|
+
"args": list(process_result.args) if isinstance(process_result.args, list) else process_result.args,
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def _read_record_rows(path: Path, record: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
615
|
+
source = record.get("source")
|
|
616
|
+
if not path.exists():
|
|
617
|
+
raise FileNotFoundError(f"Record extraction source does not exist: {path}")
|
|
618
|
+
if source == "jsonl":
|
|
619
|
+
rows = []
|
|
620
|
+
with path.open("r", encoding="utf-8") as handle:
|
|
621
|
+
for line in handle:
|
|
622
|
+
if line.strip():
|
|
623
|
+
item = json.loads(line)
|
|
624
|
+
if not isinstance(item, dict):
|
|
625
|
+
raise TypeError(f"JSONL record in {path} must be an object.")
|
|
626
|
+
rows.append(item)
|
|
627
|
+
return rows
|
|
628
|
+
if source == "csv":
|
|
629
|
+
with path.open("r", encoding="utf-8", newline="") as handle:
|
|
630
|
+
return [dict(row) for row in csv.DictReader(handle)]
|
|
631
|
+
if source == "sqlite_table":
|
|
632
|
+
table = str(record["table"])
|
|
633
|
+
if not table.replace("_", "").isalnum():
|
|
634
|
+
raise ValueError(f"Unsafe SQLite table name for record extraction: {table!r}")
|
|
635
|
+
query = f"select * from {table}"
|
|
636
|
+
return _query_sqlite_records(path, query)
|
|
637
|
+
if source == "sqlite_query":
|
|
638
|
+
return _query_sqlite_records(path, str(record["query"]))
|
|
639
|
+
raise ValueError(f"Unsupported record extraction source: {source!r}")
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def _query_sqlite_records(database: Path, query: str) -> List[Dict[str, Any]]:
|
|
643
|
+
with sqlite3.connect(str(database)) as connection:
|
|
644
|
+
connection.row_factory = sqlite3.Row
|
|
645
|
+
rows = connection.execute(query).fetchall()
|
|
646
|
+
return [dict(row) for row in rows]
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def _collect_output_files(workspace: Path, cwd: Path, patterns: List[Any]) -> List[Dict[str, Any]]:
|
|
650
|
+
output_files: List[Dict[str, Any]] = []
|
|
651
|
+
seen = set()
|
|
652
|
+
workspace_resolved = workspace.resolve()
|
|
653
|
+
for rule in patterns:
|
|
654
|
+
if isinstance(rule, dict):
|
|
655
|
+
pattern = rule.get("path")
|
|
656
|
+
name = rule.get("name")
|
|
657
|
+
required = bool(rule.get("required", False))
|
|
658
|
+
else:
|
|
659
|
+
pattern = rule
|
|
660
|
+
name = None
|
|
661
|
+
required = False
|
|
662
|
+
pattern_text = str(pattern)
|
|
663
|
+
if Path(pattern_text).is_absolute() or ".." in Path(pattern_text).parts:
|
|
664
|
+
continue
|
|
665
|
+
matches = sorted(cwd.glob(pattern_text))
|
|
666
|
+
if required and not matches:
|
|
667
|
+
raise FileNotFoundError(f"Required output_file pattern matched no files: {pattern_text}")
|
|
668
|
+
for path in matches:
|
|
669
|
+
resolved = path.resolve()
|
|
670
|
+
if resolved.is_dir() or resolved in seen:
|
|
671
|
+
continue
|
|
672
|
+
if resolved != workspace_resolved and workspace_resolved not in resolved.parents:
|
|
673
|
+
continue
|
|
674
|
+
seen.add(resolved)
|
|
675
|
+
output_files.append(
|
|
676
|
+
{
|
|
677
|
+
"type": _output_file_type(str(resolved)),
|
|
678
|
+
"name": str(name or resolved.name),
|
|
679
|
+
"path": str(resolved),
|
|
680
|
+
}
|
|
681
|
+
)
|
|
682
|
+
return output_files
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
def _dedupe_output_files(output_files: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
686
|
+
deduped: List[Dict[str, Any]] = []
|
|
687
|
+
seen = set()
|
|
688
|
+
for output_file in output_files:
|
|
689
|
+
if not isinstance(output_file, dict):
|
|
690
|
+
deduped.append(output_file)
|
|
691
|
+
continue
|
|
692
|
+
key = output_file.get("path") or output_file.get("contentRef")
|
|
693
|
+
if key:
|
|
694
|
+
try:
|
|
695
|
+
marker = ("path", str(Path(str(key)).resolve()))
|
|
696
|
+
except OSError:
|
|
697
|
+
marker = ("path", str(key))
|
|
698
|
+
else:
|
|
699
|
+
marker = ("entry", json.dumps(output_file, sort_keys=True, default=str))
|
|
700
|
+
if marker in seen:
|
|
701
|
+
continue
|
|
702
|
+
seen.add(marker)
|
|
703
|
+
deduped.append(output_file)
|
|
704
|
+
return deduped
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def _output_file_type(path: str) -> str:
|
|
708
|
+
suffix = Path(path).suffix.lower()
|
|
709
|
+
if suffix == ".json":
|
|
710
|
+
return "json"
|
|
711
|
+
if suffix in {".log", ".txt", ".out", ".err"}:
|
|
712
|
+
return "log"
|
|
713
|
+
if suffix in {".db", ".sqlite", ".sqlite3"}:
|
|
714
|
+
return "sqlite"
|
|
715
|
+
if suffix in {".py", ".cpp", ".c", ".h", ".hpp", ".js", ".ts"}:
|
|
716
|
+
return "code"
|
|
717
|
+
return "file"
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
def _check_readonly_files(workspace: Path, manifest_path: Path) -> Optional[Dict[str, Any]]:
|
|
721
|
+
if not manifest_path.exists():
|
|
722
|
+
return None
|
|
723
|
+
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
|
724
|
+
readonly_files = manifest.get("readonly_files", [])
|
|
725
|
+
if not readonly_files:
|
|
726
|
+
return None
|
|
727
|
+
violations = []
|
|
728
|
+
checked = []
|
|
729
|
+
workspace_resolved = workspace.resolve()
|
|
730
|
+
for entry in readonly_files:
|
|
731
|
+
if not isinstance(entry, dict):
|
|
732
|
+
continue
|
|
733
|
+
relative_path = entry.get("path")
|
|
734
|
+
if not isinstance(relative_path, str):
|
|
735
|
+
continue
|
|
736
|
+
path = _workspace_path(workspace_resolved, relative_path)
|
|
737
|
+
expected_sha = entry.get("sha256")
|
|
738
|
+
expected_size = entry.get("sizeBytes")
|
|
739
|
+
if not path.exists():
|
|
740
|
+
violations.append(
|
|
741
|
+
{
|
|
742
|
+
"path": relative_path,
|
|
743
|
+
"type": "missing",
|
|
744
|
+
"expected_sha256": expected_sha,
|
|
745
|
+
"expected_sizeBytes": expected_size,
|
|
746
|
+
}
|
|
747
|
+
)
|
|
748
|
+
continue
|
|
749
|
+
actual_sha = _sha256_file(path)
|
|
750
|
+
actual_size = path.stat().st_size
|
|
751
|
+
checked.append(
|
|
752
|
+
{
|
|
753
|
+
"path": relative_path,
|
|
754
|
+
"sha256": actual_sha,
|
|
755
|
+
"sizeBytes": actual_size,
|
|
756
|
+
}
|
|
757
|
+
)
|
|
758
|
+
if expected_sha and actual_sha != expected_sha:
|
|
759
|
+
violations.append(
|
|
760
|
+
{
|
|
761
|
+
"path": relative_path,
|
|
762
|
+
"type": "modified",
|
|
763
|
+
"expected_sha256": expected_sha,
|
|
764
|
+
"actual_sha256": actual_sha,
|
|
765
|
+
"expected_sizeBytes": expected_size,
|
|
766
|
+
"actual_sizeBytes": actual_size,
|
|
767
|
+
}
|
|
768
|
+
)
|
|
769
|
+
return {
|
|
770
|
+
"checked_count": len(checked),
|
|
771
|
+
"violation_count": len(violations),
|
|
772
|
+
"checked": checked,
|
|
773
|
+
"violations": violations,
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
|
|
777
|
+
def _sha256_file(path: Path) -> str:
|
|
778
|
+
digest = hashlib.sha256()
|
|
779
|
+
with path.open("rb") as handle:
|
|
780
|
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
|
781
|
+
digest.update(chunk)
|
|
782
|
+
return digest.hexdigest()
|