sciel 0.23.2__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.
- sciel/__init__.py +1 -0
- sciel/campaign/__init__.py +0 -0
- sciel/campaign/budget.py +467 -0
- sciel/campaign/identity.py +97 -0
- sciel/campaign/memory.py +298 -0
- sciel/campaign/no_regression.py +118 -0
- sciel/candidate_modules/__init__.py +239 -0
- sciel/causal/__init__.py +4 -0
- sciel/causal/estimators.py +70 -0
- sciel/causal/ledger.py +134 -0
- sciel/causal/sequential.py +102 -0
- sciel/cli/__init__.py +0 -0
- sciel/cli/live.py +144 -0
- sciel/cli/main.py +335 -0
- sciel/cli/profile.py +65 -0
- sciel/cli/start.py +189 -0
- sciel/cli/supervise.py +202 -0
- sciel/components/__init__.py +0 -0
- sciel/components/bets/__init__.py +0 -0
- sciel/components/code_novelty.py +105 -0
- sciel/components/containers.py +374 -0
- sciel/components/policy/__init__.py +0 -0
- sciel/components/policy/base.py +52 -0
- sciel/components/policy/code_embed.py +472 -0
- sciel/components/policy/controller.py +166 -0
- sciel/components/policy/mode_bandit.py +93 -0
- sciel/components/policy/mode_features.py +30 -0
- sciel/components/policy/mode_policy_mlp.py +102 -0
- sciel/components/policy/pop_features.py +29 -0
- sciel/components/policy/preset_weights.py +127 -0
- sciel/components/policy/three_head.py +167 -0
- sciel/components/policy/tilt.py +40 -0
- sciel/components/selection/__init__.py +0 -0
- sciel/components/selection/kernels.py +206 -0
- sciel/components/selection/novelty_chain.py +82 -0
- sciel/config.py +155 -0
- sciel/config_validation.py +180 -0
- sciel/culture/__init__.py +3 -0
- sciel/culture/methods.py +52 -0
- sciel/culture/repertoire.py +90 -0
- sciel/demo/__init__.py +5 -0
- sciel/demo/circles.py +54 -0
- sciel/diagnostics/__init__.py +1 -0
- sciel/diagnostics/methods_observer.py +427 -0
- sciel/diagnostics/paired_eval.py +244 -0
- sciel/engine/__init__.py +0 -0
- sciel/engine/admission.py +358 -0
- sciel/engine/assay.py +81 -0
- sciel/engine/bootstrap.py +270 -0
- sciel/engine/capacity.py +425 -0
- sciel/engine/checkpoint.py +133 -0
- sciel/engine/checkpoint_identity.py +230 -0
- sciel/engine/checkpoint_restore.py +248 -0
- sciel/engine/container_db.py +212 -0
- sciel/engine/cooperative_io.py +420 -0
- sciel/engine/db.py +259 -0
- sciel/engine/decisions.py +85 -0
- sciel/engine/determinism.py +24 -0
- sciel/engine/evaluation.py +199 -0
- sciel/engine/evaluation_timing.py +114 -0
- sciel/engine/evaluator_fifo.py +209 -0
- sciel/engine/eviction_planner.py +22 -0
- sciel/engine/factory.py +104 -0
- sciel/engine/incubator.py +201 -0
- sciel/engine/initialization.py +354 -0
- sciel/engine/journal_anchor.py +26 -0
- sciel/engine/knockout.py +91 -0
- sciel/engine/lifecycle.py +251 -0
- sciel/engine/llm/__init__.py +0 -0
- sciel/engine/llm/anthropic_api.py +78 -0
- sciel/engine/llm/claude_code.py +149 -0
- sciel/engine/llm/client.py +443 -0
- sciel/engine/llm/codex.py +368 -0
- sciel/engine/llm/codex_protocol.py +252 -0
- sciel/engine/llm/errors.py +132 -0
- sciel/engine/llm/mock.py +109 -0
- sciel/engine/llm/trace.py +133 -0
- sciel/engine/loop.py +98 -0
- sciel/engine/loop_contracts.py +105 -0
- sciel/engine/novelty.py +376 -0
- sciel/engine/observed_changes.py +404 -0
- sciel/engine/observed_schema.py +189 -0
- sciel/engine/operators.py +107 -0
- sciel/engine/output_measurements.py +44 -0
- sciel/engine/output_novelty.py +256 -0
- sciel/engine/parallel.py +472 -0
- sciel/engine/parallel_calls.py +330 -0
- sciel/engine/parallel_control.py +51 -0
- sciel/engine/parallel_recovery.py +363 -0
- sciel/engine/parallel_schedule.py +215 -0
- sciel/engine/parallel_store.py +433 -0
- sciel/engine/population_view.py +113 -0
- sciel/engine/portfolio_allocation.py +74 -0
- sciel/engine/probe.py +75 -0
- sciel/engine/prompt/__init__.py +0 -0
- sciel/engine/prompt/budget.py +20 -0
- sciel/engine/prompt/build.py +202 -0
- sciel/engine/prompt/parse.py +54 -0
- sciel/engine/prompt/patch.py +101 -0
- sciel/engine/prompt/sources.py +10 -0
- sciel/engine/prompt/templates/cross.txt +26 -0
- sciel/engine/prompt/templates/diff.txt +24 -0
- sciel/engine/prompt/templates/error_repair.txt +23 -0
- sciel/engine/prompt/templates/fix.txt +8 -0
- sciel/engine/prompt/templates/full_rewrite.txt +24 -0
- sciel/engine/prompt/templates/idea.txt +27 -0
- sciel/engine/provider_abandonment.py +15 -0
- sciel/engine/recovery.py +85 -0
- sciel/engine/repeat_execution.py +177 -0
- sciel/engine/repeat_journal.py +91 -0
- sciel/engine/repeat_learning.py +20 -0
- sciel/engine/repeat_planning.py +128 -0
- sciel/engine/repeat_policy.py +131 -0
- sciel/engine/repeat_promotion.py +147 -0
- sciel/engine/repeat_state.py +253 -0
- sciel/engine/repeat_support.py +175 -0
- sciel/engine/research_artifacts.py +323 -0
- sciel/engine/research_candidate.py +84 -0
- sciel/engine/research_cells_context.py +168 -0
- sciel/engine/research_culture.py +119 -0
- sciel/engine/research_queue.py +129 -0
- sciel/engine/research_search_evidence.py +160 -0
- sciel/engine/research_targets.py +204 -0
- sciel/engine/research_tool_signals.py +57 -0
- sciel/engine/run_lock.py +37 -0
- sciel/engine/runtime.py +165 -0
- sciel/engine/schedule.py +179 -0
- sciel/engine/siblings.py +135 -0
- sciel/engine/source_identity.py +16 -0
- sciel/engine/step_cycle.py +217 -0
- sciel/engine/step_plan.py +405 -0
- sciel/engine/telemetry.py +168 -0
- sciel/engine/types.py +87 -0
- sciel/engine/validation.py +444 -0
- sciel/engine/viability.py +431 -0
- sciel/engine/warm_start.py +69 -0
- sciel/engine/worker.py +294 -0
- sciel/engine/worker_feedback.py +131 -0
- sciel/eval/__init__.py +0 -0
- sciel/eval/_candidate_worker.py +131 -0
- sciel/eval/_repeat_runner.py +229 -0
- sciel/eval/_runner.py +280 -0
- sciel/eval/_scorer_worker.py +24 -0
- sciel/eval/candidate_backend.py +209 -0
- sciel/eval/candidate_config.py +58 -0
- sciel/eval/candidate_evidence.py +52 -0
- sciel/eval/candidate_receipts.py +272 -0
- sciel/eval/candidate_registry.py +2 -0
- sciel/eval/cascade.py +55 -0
- sciel/eval/facade.py +153 -0
- sciel/eval/native_geometry.py +251 -0
- sciel/eval/near_output.py +147 -0
- sciel/eval/output_identity.py +308 -0
- sciel/eval/packing_geometry.py +185 -0
- sciel/eval/registry.py +251 -0
- sciel/eval/repeat_docker.py +187 -0
- sciel/eval/repeat_draw.py +466 -0
- sciel/eval/repeat_io.py +51 -0
- sciel/eval/sandbox.py +350 -0
- sciel/eval/scorer_container.py +186 -0
- sciel/eval/task_prompt.py +82 -0
- sciel/eval/trusted_scoring/__init__.py +1 -0
- sciel/eval/trusted_scoring/adapter.py +125 -0
- sciel/eval/trusted_scoring/beat.py +191 -0
- sciel/eval/trusted_scoring/circle.py +102 -0
- sciel/eval/trusted_scoring/heil.py +107 -0
- sciel/eval/trusted_scoring/transport.py +120 -0
- sciel/evidence/__init__.py +1 -0
- sciel/evidence/change_audit.py +243 -0
- sciel/evidence/eligibility.py +110 -0
- sciel/evidence/measurement.py +186 -0
- sciel/evidence/restart_optimizer_trace.py +189 -0
- sciel/evidence/restart_trace.py +54 -0
- sciel/evidence/restart_trace_recorder.py +253 -0
- sciel/evidence/restart_trace_source.py +31 -0
- sciel/evidence/restart_trace_validation.py +234 -0
- sciel/evidence/restart_trace_values.py +231 -0
- sciel/local_task.py +142 -0
- sciel/methods/__init__.py +11 -0
- sciel/methods/__main__.py +397 -0
- sciel/methods/_loader.py +99 -0
- sciel/methods/_runner.py +225 -0
- sciel/methods/budget.py +322 -0
- sciel/methods/campaign.py +372 -0
- sciel/methods/configuration.py +139 -0
- sciel/methods/coordinator.py +368 -0
- sciel/methods/coordinator_context.py +108 -0
- sciel/methods/coordinator_contracts.py +42 -0
- sciel/methods/coordinator_episode.py +251 -0
- sciel/methods/coordinator_exchange.py +156 -0
- sciel/methods/coordinator_execution.py +170 -0
- sciel/methods/coordinator_planning.py +156 -0
- sciel/methods/coordinator_policy.py +193 -0
- sciel/methods/engine_bridge.py +342 -0
- sciel/methods/evidence.py +384 -0
- sciel/methods/examples.py +255 -0
- sciel/methods/executor.py +519 -0
- sciel/methods/funding.py +119 -0
- sciel/methods/materialize.py +248 -0
- sciel/methods/models.py +242 -0
- sciel/methods/proposals.py +289 -0
- sciel/methods/provider_budget.py +71 -0
- sciel/methods/registry.py +500 -0
- sciel/methods/registry_records.py +117 -0
- sciel/methods/resource_values.py +129 -0
- sciel/methods/tasks.py +203 -0
- sciel/methods/technical.py +167 -0
- sciel/methods/transport.py +217 -0
- sciel/population.py +15 -0
- sciel/research_tools/__init__.py +2 -0
- sciel/research_tools/artifact_manifest.py +207 -0
- sciel/research_tools/artifact_reading.py +34 -0
- sciel/research_tools/canonical_diagnostics.py +241 -0
- sciel/research_tools/canonical_evidence.py +94 -0
- sciel/research_tools/cells.py +394 -0
- sciel/research_tools/comparison_assessment.py +89 -0
- sciel/research_tools/config.py +174 -0
- sciel/research_tools/continuations.py +289 -0
- sciel/research_tools/controller.py +236 -0
- sciel/research_tools/controller_jobs.py +315 -0
- sciel/research_tools/controller_state.py +204 -0
- sciel/research_tools/decision_projection.py +116 -0
- sciel/research_tools/episode_evidence.py +129 -0
- sciel/research_tools/episode_execution.py +249 -0
- sciel/research_tools/episode_results.py +224 -0
- sciel/research_tools/experiment_protocol.py +271 -0
- sciel/research_tools/followups.py +442 -0
- sciel/research_tools/job_worker.py +240 -0
- sciel/research_tools/jobs.py +364 -0
- sciel/research_tools/library.py +357 -0
- sciel/research_tools/lifecycle.py +377 -0
- sciel/research_tools/lifecycle_delivery.py +198 -0
- sciel/research_tools/lifecycle_evidence.py +324 -0
- sciel/research_tools/observation_cards.py +179 -0
- sciel/research_tools/planning.py +152 -0
- sciel/research_tools/projection_data.py +169 -0
- sciel/research_tools/projection_validation.py +133 -0
- sciel/research_tools/prompt_builder.py +393 -0
- sciel/research_tools/prompt_sections.py +377 -0
- sciel/research_tools/replay_feedback.py +153 -0
- sciel/research_tools/research_steps.py +222 -0
- sciel/research_tools/result_contract.py +73 -0
- sciel/research_tools/result_projection.py +319 -0
- sciel/research_tools/retained_observations.py +227 -0
- sciel/research_tools/sequential_research.py +371 -0
- sciel/research_tools/shared_evidence.py +408 -0
- sciel/research_tools/sharing.py +287 -0
- sciel/research_tools/stage_data.py +68 -0
- sciel/research_tools/tool_actions.py +241 -0
- sciel/research_tools/tool_artifacts.py +175 -0
- sciel/research_tools/tool_protocol.py +41 -0
- sciel/research_tools/transfer_jobs.py +190 -0
- sciel/reward.py +181 -0
- sciel/rl/__init__.py +3 -0
- sciel/rl/critic.py +104 -0
- sciel/rl/policy.py +235 -0
- sciel/rl/returns.py +56 -0
- sciel/rng.py +38 -0
- sciel/run_log.py +212 -0
- sciel/solvers/__init__.py +1 -0
- sciel/solvers/circle_anytime.py +257 -0
- sciel/solvers/circle_lp_initializer.py +132 -0
- sciel/solvers/circle_relocation.py +121 -0
- sciel/stats.py +217 -0
- sciel/swm/__init__.py +6 -0
- sciel/swm/archive.py +91 -0
- sciel/swm/diffusion.py +61 -0
- sciel/swm/embedding.py +94 -0
- sciel/swm/model.py +200 -0
- sciel/swm/niches.py +46 -0
- sciel/swm/sets.py +63 -0
- sciel/swm/tabular.py +66 -0
- sciel/swm/targets.py +63 -0
- sciel/swm/world.py +500 -0
- sciel/task.py +21 -0
- sciel/taskbuilder/__init__.py +118 -0
- sciel/taskbuilder/audit.py +92 -0
- sciel/taskbuilder/draft.py +69 -0
- sciel/taskbuilder/materials.py +88 -0
- sciel/theory/__init__.py +7 -0
- sciel/theory/assumptions.py +131 -0
- sciel/theory/claims.py +138 -0
- sciel/theory/experiments.py +106 -0
- sciel/theory/findings.py +148 -0
- sciel/theory/procedures.py +89 -0
- sciel/theory/schools.py +64 -0
- sciel/theory/strategies.py +85 -0
- sciel/theory/trials.py +107 -0
- sciel/tui/__init__.py +0 -0
- sciel/tui/board.py +52 -0
- sciel/ui/__init__.py +1 -0
- sciel/ui/activity.py +112 -0
- sciel/ui/engine.py +169 -0
- sciel/ui/render.py +165 -0
- sciel/ui/state.py +343 -0
- sciel/ui/static/engine.js +162 -0
- sciel/ui/static/index.html +397 -0
- sciel/ui/terminal.py +455 -0
- sciel/ui/views.py +307 -0
- sciel/ui/web.py +144 -0
- sciel-0.23.2.dist-info/METADATA +508 -0
- sciel-0.23.2.dist-info/RECORD +305 -0
- sciel-0.23.2.dist-info/WHEEL +5 -0
- sciel-0.23.2.dist-info/entry_points.txt +2 -0
- sciel-0.23.2.dist-info/top_level.txt +1 -0
sciel/campaign/memory.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
"""Optional, sampled process memory telemetry; never a memory resource limit.
|
|
2
|
+
|
|
3
|
+
The observer lives outside the measured process. RSS sums may double count shared
|
|
4
|
+
pages; USS is reported only for samples where every observed process supports it.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections import Counter
|
|
9
|
+
from contextlib import ExitStack
|
|
10
|
+
import errno
|
|
11
|
+
import math
|
|
12
|
+
import os
|
|
13
|
+
import platform
|
|
14
|
+
import signal
|
|
15
|
+
import subprocess
|
|
16
|
+
import time
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _psutil():
|
|
20
|
+
try:
|
|
21
|
+
import psutil
|
|
22
|
+
except ImportError as exc:
|
|
23
|
+
raise RuntimeError("Memory measurement requires optional dependency psutil") from exc
|
|
24
|
+
return psutil
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _positive(value, name):
|
|
28
|
+
if not math.isfinite(value) or value <= 0:
|
|
29
|
+
raise ValueError(f"{name} must be finite and positive")
|
|
30
|
+
return float(value)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ProcessTreeSampler:
|
|
34
|
+
"""Call ``sample`` periodically, then ``report``; no process is killed here.
|
|
35
|
+
|
|
36
|
+
Descendants already observed remain tracked if their parent exits. Identity is
|
|
37
|
+
(PID, creation time), so PID reuse cannot turn another process into a descendant.
|
|
38
|
+
This class is deliberately synchronous; its owner controls lifecycle/cadence.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, pid, *, interval_seconds=.02):
|
|
42
|
+
self.interval_seconds = _positive(interval_seconds, "interval_seconds")
|
|
43
|
+
self.backend = _psutil()
|
|
44
|
+
self.started = time.monotonic()
|
|
45
|
+
self.root_pid = pid
|
|
46
|
+
self.processes = {}
|
|
47
|
+
self.errors = Counter()
|
|
48
|
+
self.counts = Counter()
|
|
49
|
+
self.peaks = {f"sampled_peak_{scope}_{metric}_bytes": None
|
|
50
|
+
for scope in ("root", "observed_tree") for metric in ("rss", "uss")}
|
|
51
|
+
self.last_sample_time = None
|
|
52
|
+
self.max_sample_gap_seconds = 0.
|
|
53
|
+
self.max_observed_processes = 0
|
|
54
|
+
self.root_identity = None
|
|
55
|
+
try:
|
|
56
|
+
process = self.backend.Process(pid)
|
|
57
|
+
self.root_identity = (pid, process.create_time())
|
|
58
|
+
self.processes[self.root_identity] = process
|
|
59
|
+
except self.backend.Error as exc:
|
|
60
|
+
self._error("root_identity", exc)
|
|
61
|
+
|
|
62
|
+
def _error(self, operation, exc):
|
|
63
|
+
self.errors[f"{operation}:{type(exc).__name__}"] += 1
|
|
64
|
+
|
|
65
|
+
def sample(self):
|
|
66
|
+
now = time.monotonic()
|
|
67
|
+
if self.last_sample_time is not None:
|
|
68
|
+
self.max_sample_gap_seconds = max(self.max_sample_gap_seconds, now - self.last_sample_time)
|
|
69
|
+
self.last_sample_time = now
|
|
70
|
+
self.counts["polls"] += 1
|
|
71
|
+
discovery_ok = True
|
|
72
|
+
# Discover from every still-observed descendant, including reparented ones.
|
|
73
|
+
for identity, process in list(self.processes.items()):
|
|
74
|
+
try:
|
|
75
|
+
if not process.is_running() or process.create_time() != identity[1]:
|
|
76
|
+
continue
|
|
77
|
+
for child in process.children(recursive=True):
|
|
78
|
+
self.processes.setdefault((child.pid, child.create_time()), child)
|
|
79
|
+
except self.backend.Error as exc:
|
|
80
|
+
discovery_ok = False
|
|
81
|
+
self._error("discover", exc)
|
|
82
|
+
rss, uss, root_rss, root_uss = [], [], None, None
|
|
83
|
+
live = 0
|
|
84
|
+
for identity, process in list(self.processes.items()):
|
|
85
|
+
try:
|
|
86
|
+
if not process.is_running() or process.create_time() != identity[1]:
|
|
87
|
+
continue
|
|
88
|
+
live += 1
|
|
89
|
+
value = process.memory_info().rss
|
|
90
|
+
rss.append(value)
|
|
91
|
+
if identity == self.root_identity:
|
|
92
|
+
root_rss = value
|
|
93
|
+
try:
|
|
94
|
+
value = getattr(process.memory_full_info(), "uss", None)
|
|
95
|
+
if value is None:
|
|
96
|
+
self.counts["uss_unsupported_observations"] += 1
|
|
97
|
+
else:
|
|
98
|
+
uss.append(value)
|
|
99
|
+
if identity == self.root_identity:
|
|
100
|
+
root_uss = value
|
|
101
|
+
except self.backend.Error as exc:
|
|
102
|
+
self._error("uss", exc)
|
|
103
|
+
except self.backend.Error as exc:
|
|
104
|
+
self._error("rss", exc)
|
|
105
|
+
self.max_observed_processes = max(self.max_observed_processes, live)
|
|
106
|
+
values = {"root_rss": root_rss, "root_uss": root_uss,
|
|
107
|
+
"observed_tree_rss": sum(rss) if rss else None,
|
|
108
|
+
"observed_tree_uss": sum(uss) if live and len(uss) == live else None}
|
|
109
|
+
for name, value in values.items():
|
|
110
|
+
if value is not None:
|
|
111
|
+
self.counts[f"{name}_samples"] += 1
|
|
112
|
+
field = f"sampled_peak_{name}_bytes"
|
|
113
|
+
self.peaks[field] = max(self.peaks[field] or 0, value)
|
|
114
|
+
if not discovery_ok or len(rss) != live:
|
|
115
|
+
self.counts["incomplete_observed_tree_samples"] += 1
|
|
116
|
+
return {"elapsed_seconds": now - self.started, "observed_processes": live,
|
|
117
|
+
"discovery_ok": discovery_ok, **{f"{k}_bytes": v for k, v in values.items()}}
|
|
118
|
+
|
|
119
|
+
def report(self):
|
|
120
|
+
return {"schema": "sciel-sampled-process-memory/1", "root_pid": self.root_pid,
|
|
121
|
+
"platform": platform.platform(), "psutil_version": self.backend.__version__,
|
|
122
|
+
"requested_interval_seconds": self.interval_seconds,
|
|
123
|
+
"max_sample_gap_seconds": self.max_sample_gap_seconds,
|
|
124
|
+
"elapsed_seconds": time.monotonic() - self.started,
|
|
125
|
+
"scope": "root process and discovered descendants; observer excluded",
|
|
126
|
+
**self.peaks, "sample_counts": dict(self.counts),
|
|
127
|
+
"max_observed_processes": self.max_observed_processes,
|
|
128
|
+
"observed_process_identities": [list(p) for p in self.processes],
|
|
129
|
+
"errors": dict(self.errors), "complete_tree_coverage_guaranteed": False,
|
|
130
|
+
"limitations": [
|
|
131
|
+
"Sampled maxima, not exact peaks; allocations between polls can be missed.",
|
|
132
|
+
"Short-lived or inaccessible descendants may be missed; process reads are not simultaneous.",
|
|
133
|
+
"Observed-tree RSS sums can double count shared pages; USS availability is platform/permission dependent.",
|
|
134
|
+
"Missing measurements are null, never inferred zero; telemetry is not a memory cap."]}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _child_state(proc):
|
|
138
|
+
"""Observe our direct child without releasing its PID on supported POSIX."""
|
|
139
|
+
if proc.returncode is not None:
|
|
140
|
+
return "reaped"
|
|
141
|
+
names = ("waitid", "P_PID", "WEXITED", "WNOHANG", "WNOWAIT")
|
|
142
|
+
if os.name != "posix" or not all(hasattr(os, name) for name in names):
|
|
143
|
+
return "unsupported"
|
|
144
|
+
try:
|
|
145
|
+
status = os.waitid(os.P_PID, proc.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT)
|
|
146
|
+
except ChildProcessError:
|
|
147
|
+
return "unowned"
|
|
148
|
+
except OSError as exc:
|
|
149
|
+
if exc.errno in {errno.ENOSYS, errno.EINVAL, errno.ENOTSUP}:
|
|
150
|
+
return "unsupported"
|
|
151
|
+
raise
|
|
152
|
+
return "exited" if status is not None and status.si_pid else "running"
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _group_has_live_members(pgid):
|
|
156
|
+
"""Check a still-reserved PGID; do not treat inaccessible members as absent."""
|
|
157
|
+
backend = _psutil()
|
|
158
|
+
for process in backend.process_iter():
|
|
159
|
+
try:
|
|
160
|
+
if os.getpgid(process.pid) == pgid and process.status() != backend.STATUS_ZOMBIE:
|
|
161
|
+
return True
|
|
162
|
+
except (ProcessLookupError, backend.NoSuchProcess):
|
|
163
|
+
continue
|
|
164
|
+
return False
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _observed_executing(process, identity, backend):
|
|
168
|
+
return (process.is_running() and process.create_time() == identity[1]
|
|
169
|
+
and process.status() != backend.STATUS_ZOMBIE)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _cleanup(proc, sampler, timeout):
|
|
173
|
+
"""Signal the owned group before reaping; otherwise use observed identities."""
|
|
174
|
+
errors = []
|
|
175
|
+
deadline = time.monotonic() + timeout
|
|
176
|
+
group_killed = False
|
|
177
|
+
try:
|
|
178
|
+
state = _child_state(proc)
|
|
179
|
+
except OSError as exc:
|
|
180
|
+
state = "unknown"
|
|
181
|
+
errors.append(f"ownership_probe:{type(exc).__name__}")
|
|
182
|
+
# WNOWAIT keeps our exited child waitable, reserving its PID/PGID until the
|
|
183
|
+
# group signal. Do not use a bare killpg(pid, 0) as an ownership check after
|
|
184
|
+
# poll()/wait(): a new, unrelated group may already have reused that number.
|
|
185
|
+
group_skip_reason = None
|
|
186
|
+
if os.name == "posix" and state in {"running", "exited"}:
|
|
187
|
+
try:
|
|
188
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
189
|
+
group_killed = True
|
|
190
|
+
except ProcessLookupError:
|
|
191
|
+
pass
|
|
192
|
+
except PermissionError:
|
|
193
|
+
# macOS can return EPERM when only the retained zombie leader is in
|
|
194
|
+
# the group. It is benign only after an explicit, successful scan.
|
|
195
|
+
try:
|
|
196
|
+
empty = state == "exited" and not _group_has_live_members(proc.pid)
|
|
197
|
+
except (OSError, _psutil().Error):
|
|
198
|
+
empty = False
|
|
199
|
+
if empty:
|
|
200
|
+
group_skip_reason = "no_live_group_members"
|
|
201
|
+
else:
|
|
202
|
+
errors.append("group_kill:PermissionError")
|
|
203
|
+
except OSError as exc:
|
|
204
|
+
errors.append(f"group_kill:{type(exc).__name__}")
|
|
205
|
+
else:
|
|
206
|
+
group_skip_reason = f"direct_child_{state}"
|
|
207
|
+
for identity, process in (sampler.processes.items() if sampler else ()):
|
|
208
|
+
try:
|
|
209
|
+
if _observed_executing(process, identity, sampler.backend):
|
|
210
|
+
process.kill()
|
|
211
|
+
except sampler.backend.NoSuchProcess:
|
|
212
|
+
pass
|
|
213
|
+
except sampler.backend.Error as exc:
|
|
214
|
+
errors.append(f"descendant_kill:{type(exc).__name__}")
|
|
215
|
+
if proc.poll() is None:
|
|
216
|
+
try:
|
|
217
|
+
proc.kill()
|
|
218
|
+
except OSError as exc:
|
|
219
|
+
errors.append(f"leader_kill:{type(exc).__name__}")
|
|
220
|
+
try:
|
|
221
|
+
proc.wait(timeout=max(0., deadline - time.monotonic()))
|
|
222
|
+
except subprocess.TimeoutExpired:
|
|
223
|
+
errors.append("leader_reap:TimeoutExpired")
|
|
224
|
+
# A successful kill call is not evidence that an escaped descendant stopped.
|
|
225
|
+
# Verify observed identities become absent/nonexecuting within the same bound.
|
|
226
|
+
pending = dict(sampler.processes) if sampler else {}
|
|
227
|
+
unverified = []
|
|
228
|
+
while pending:
|
|
229
|
+
for identity, process in list(pending.items()):
|
|
230
|
+
try:
|
|
231
|
+
if _observed_executing(process, identity, sampler.backend):
|
|
232
|
+
continue
|
|
233
|
+
except sampler.backend.NoSuchProcess:
|
|
234
|
+
pass
|
|
235
|
+
except sampler.backend.Error as exc:
|
|
236
|
+
errors.append(f"observed_exit:{type(exc).__name__}")
|
|
237
|
+
unverified.append(identity)
|
|
238
|
+
pending.pop(identity)
|
|
239
|
+
remaining = deadline - time.monotonic()
|
|
240
|
+
if pending and remaining <= 0:
|
|
241
|
+
errors.append("observed_exit:TimeoutExpired")
|
|
242
|
+
break
|
|
243
|
+
if pending:
|
|
244
|
+
time.sleep(min(.01, remaining))
|
|
245
|
+
unverified.extend(pending)
|
|
246
|
+
return {"group_killed": group_killed, "group_skip_reason": group_skip_reason,
|
|
247
|
+
"leader_reaped": proc.poll() is not None,
|
|
248
|
+
"observed_termination_verified": sampler is not None and not unverified,
|
|
249
|
+
"unverified_observed_identities": [list(identity) for identity in unverified],
|
|
250
|
+
"errors": errors,
|
|
251
|
+
"scope": "owned unreaped child's private group and bounded verification that observed identities stopped executing; zombies are nonexecuting, only the direct child is reaped, and unobserved children cannot be guaranteed"}
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def run_measured(argv, *, timeout, interval_seconds=.02, cwd=None, env=None,
|
|
255
|
+
stdout_path=None, stderr_path=None, on_sample=None, cleanup_timeout=5.):
|
|
256
|
+
"""Run one fresh process, synchronously sample it, and always clean up.
|
|
257
|
+
|
|
258
|
+
``on_sample(sample_dict)`` is optional and runs in the observer after each poll.
|
|
259
|
+
Exceptions/KeyboardInterrupt from it propagate after process cleanup. Output
|
|
260
|
+
paths are opened exclusively; environment and command arguments are not logged.
|
|
261
|
+
Without paths, output is discarded to avoid unbounded in-memory pipe buffers.
|
|
262
|
+
This function owns/reaps its child; other SIGCHLD handlers must not reap it.
|
|
263
|
+
POSIX WNOWAIT preserves ownership until group cleanup. Where unavailable,
|
|
264
|
+
cleanup uses the direct child and observed identities, never an unbound PGID.
|
|
265
|
+
"""
|
|
266
|
+
timeout = _positive(timeout, "timeout")
|
|
267
|
+
interval_seconds = _positive(interval_seconds, "interval_seconds")
|
|
268
|
+
cleanup_timeout = _positive(cleanup_timeout, "cleanup_timeout")
|
|
269
|
+
_psutil() # Fail before launching anything if optional telemetry is unavailable.
|
|
270
|
+
with ExitStack() as stack:
|
|
271
|
+
stdout = stack.enter_context(open(stdout_path, "xb")) if stdout_path else subprocess.DEVNULL
|
|
272
|
+
stderr = stack.enter_context(open(stderr_path, "xb")) if stderr_path else subprocess.DEVNULL
|
|
273
|
+
started = time.monotonic()
|
|
274
|
+
proc = subprocess.Popen(argv, cwd=cwd, env=env, stdout=stdout, stderr=stderr,
|
|
275
|
+
start_new_session=(os.name == "posix"))
|
|
276
|
+
sampler = None
|
|
277
|
+
timed_out = False
|
|
278
|
+
try:
|
|
279
|
+
sampler = ProcessTreeSampler(proc.pid, interval_seconds=interval_seconds)
|
|
280
|
+
while True:
|
|
281
|
+
sample = sampler.sample()
|
|
282
|
+
if on_sample is not None:
|
|
283
|
+
on_sample(sample)
|
|
284
|
+
state = _child_state(proc)
|
|
285
|
+
if state in {"exited", "reaped"} or (
|
|
286
|
+
state in {"unowned", "unsupported"} and proc.poll() is not None):
|
|
287
|
+
break
|
|
288
|
+
remaining = timeout - (time.monotonic() - started)
|
|
289
|
+
if remaining <= 0:
|
|
290
|
+
timed_out = True
|
|
291
|
+
break
|
|
292
|
+
time.sleep(min(interval_seconds, remaining))
|
|
293
|
+
finally:
|
|
294
|
+
# Constructor failure follows the same ownership-safe cleanup path.
|
|
295
|
+
cleanup = _cleanup(proc, sampler, cleanup_timeout)
|
|
296
|
+
return {"returncode": proc.returncode, "timed_out": timed_out,
|
|
297
|
+
"elapsed_seconds": time.monotonic() - started,
|
|
298
|
+
"memory": sampler.report(), "cleanup": cleanup}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Prospective zero-margin screening. No finite screen guarantees future quality."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import copy
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
POLICY = {
|
|
10
|
+
"margin": 0,
|
|
11
|
+
"min_pairs": 3,
|
|
12
|
+
"contrasts": [["grid", "pool"], ["pool_presets_fixed", "pool_presets"]],
|
|
13
|
+
"futility": "first_complete_valid_pair_below_control",
|
|
14
|
+
"success": "all_planned_pairs_valid_nonnegative_and_mechanisms_active",
|
|
15
|
+
"automatic_default_promotion": False,
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def evaluate_policy(manifest, observations):
|
|
20
|
+
"""Derive decisions and future withdrawals from verified, started jobs.
|
|
21
|
+
|
|
22
|
+
The caller validates file/job/protocol identity and supplies an observation
|
|
23
|
+
for *every* started job (even an interrupted or ledger-only job). ``valid``
|
|
24
|
+
means all independent numeric draws passed, not merely that a score exists.
|
|
25
|
+
Missing observations are never scores of zero. Failed draws remain in the
|
|
26
|
+
separate descriptive analysis, but cannot establish a valid paired result.
|
|
27
|
+
"""
|
|
28
|
+
jobs = manifest["jobs"]
|
|
29
|
+
seeds = manifest["seeds"]
|
|
30
|
+
expected_arms = {arm for pair in POLICY["contrasts"] for arm in pair}
|
|
31
|
+
if (len(seeds) != POLICY["min_pairs"] or len(set(seeds)) != len(seeds)
|
|
32
|
+
or any(type(seed) is not int or seed < 0 for seed in seeds)):
|
|
33
|
+
raise ValueError("strict screening requires three unique non-negative seeds")
|
|
34
|
+
by_id = {job["id"]: job for job in jobs}
|
|
35
|
+
by_pair = {(job["arm"], job["seed"]): job for job in jobs}
|
|
36
|
+
if (len(by_id) != len(jobs) or len(by_pair) != len(jobs)
|
|
37
|
+
or set(by_pair) != {(arm, seed) for arm in expected_arms for seed in seeds}):
|
|
38
|
+
raise ValueError("strict screening requires exactly the two frozen contrasts")
|
|
39
|
+
if set(observations) - set(by_id):
|
|
40
|
+
raise ValueError("observation does not belong to the frozen jobs")
|
|
41
|
+
for ident, observation in observations.items():
|
|
42
|
+
if any(type(observation.get(key)) is not bool
|
|
43
|
+
for key in ("complete", "valid", "mechanism_activated")):
|
|
44
|
+
raise ValueError("observation states must be explicit booleans")
|
|
45
|
+
if observation["valid"] and not observation["complete"]:
|
|
46
|
+
raise ValueError("an incomplete observation cannot be valid")
|
|
47
|
+
if observation["complete"] and observation["valid"]:
|
|
48
|
+
score = observation.get("primary_score")
|
|
49
|
+
digest = observation.get("result_sha256")
|
|
50
|
+
if (isinstance(score, bool) or not isinstance(score, (int, float))
|
|
51
|
+
or not math.isfinite(score) or score < 0):
|
|
52
|
+
raise ValueError("valid pairs require finite non-negative scores")
|
|
53
|
+
if not isinstance(digest, str) or re.fullmatch(r"[0-9a-f]{64}", digest) is None:
|
|
54
|
+
raise ValueError("valid pairs require the verified result SHA256")
|
|
55
|
+
contrasts, withdrawals = [], []
|
|
56
|
+
for control, candidate in POLICY["contrasts"]:
|
|
57
|
+
pairs, first_loss = [], None
|
|
58
|
+
for seed in seeds:
|
|
59
|
+
pair_jobs = [by_pair[(arm, seed)] for arm in (control, candidate)]
|
|
60
|
+
pair_obs = [observations.get(job["id"]) for job in pair_jobs]
|
|
61
|
+
if not all(obs and obs["complete"] and obs["valid"] for obs in pair_obs):
|
|
62
|
+
continue
|
|
63
|
+
base, test = pair_obs
|
|
64
|
+
pair = {"seed": seed, "control": base["primary_score"],
|
|
65
|
+
"candidate": test["primary_score"],
|
|
66
|
+
"difference": test["primary_score"] - base["primary_score"],
|
|
67
|
+
"mechanisms_active": all(obs["mechanism_activated"] for obs in pair_obs),
|
|
68
|
+
"evidence": [{"job_id": job["id"],
|
|
69
|
+
"result_sha256": obs["result_sha256"],
|
|
70
|
+
"primary_score": obs["primary_score"]}
|
|
71
|
+
for job, obs in zip(pair_jobs, pair_obs)]}
|
|
72
|
+
pairs.append(pair)
|
|
73
|
+
# Deliberately no epsilon or averaging a loss against another seed.
|
|
74
|
+
if test["primary_score"] < base["primary_score"] and first_loss is None:
|
|
75
|
+
first_loss = pair
|
|
76
|
+
decision = "inconclusive"
|
|
77
|
+
if first_loss is not None:
|
|
78
|
+
decision = "rejected_observed_regression"
|
|
79
|
+
later_seeds = seeds[seeds.index(first_loss["seed"]) + 1:]
|
|
80
|
+
for job in jobs:
|
|
81
|
+
if job["arm"] in (control, candidate) and job["seed"] in later_seeds:
|
|
82
|
+
if job["id"] in observations:
|
|
83
|
+
raise ValueError("a contrast continued after its prospective futility stop")
|
|
84
|
+
withdrawals.append({"job": copy.deepcopy(job), "control": control,
|
|
85
|
+
"candidate": candidate, "trigger_seed": first_loss["seed"],
|
|
86
|
+
"evidence": copy.deepcopy(first_loss["evidence"])})
|
|
87
|
+
elif len(pairs) == len(seeds) and all(pair["mechanisms_active"] for pair in pairs):
|
|
88
|
+
decision = "screen_pass"
|
|
89
|
+
contrasts.append({"control": control, "candidate": candidate, "decision": decision,
|
|
90
|
+
"n_pairs": len(pairs), "pairs": pairs,
|
|
91
|
+
"first_regression_seed": first_loss["seed"] if first_loss else None,
|
|
92
|
+
"automatic_default_promotion": False})
|
|
93
|
+
return {"schema": "sciel-zero-regression-disposition/1",
|
|
94
|
+
"protocol_sha256": manifest["protocol_sha256"], "policy": copy.deepcopy(POLICY),
|
|
95
|
+
"contrasts": contrasts, "withdrawals": withdrawals,
|
|
96
|
+
"interpretation": "Prospective futility screening on one task; screen_pass is not a guarantee of no future regression and never promotes defaults."}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def verify_disposition(previous, current):
|
|
100
|
+
"""Resume may add pairs/withdrawals, never undo or rewrite their evidence."""
|
|
101
|
+
for key in ("schema", "protocol_sha256", "policy"):
|
|
102
|
+
if previous.get(key) != current.get(key):
|
|
103
|
+
raise ValueError("strict disposition identity changed")
|
|
104
|
+
old = previous.get("withdrawals")
|
|
105
|
+
new = current.get("withdrawals")
|
|
106
|
+
if not isinstance(old, list) or not isinstance(new, list):
|
|
107
|
+
raise ValueError("strict disposition withdrawals must be lists")
|
|
108
|
+
if len({row["job"]["id"] for row in old}) != len(old):
|
|
109
|
+
raise ValueError("duplicate historical withdrawal")
|
|
110
|
+
lookup = {row["job"]["id"]: row for row in new}
|
|
111
|
+
if len(lookup) != len(new) or any(lookup.get(row["job"]["id"]) != row for row in old):
|
|
112
|
+
raise ValueError("strict disposition lost or modified prior futility evidence")
|
|
113
|
+
pairs = {(row["control"], row["candidate"], pair["seed"]): pair
|
|
114
|
+
for row in current["contrasts"] for pair in row["pairs"]}
|
|
115
|
+
for row in previous["contrasts"]:
|
|
116
|
+
for pair in row["pairs"]:
|
|
117
|
+
if pairs.get((row["control"], row["candidate"], pair["seed"])) != pair:
|
|
118
|
+
raise ValueError("strict disposition lost or modified a prior compared pair")
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Load source files under fresh names that a spawned Python worker can import.
|
|
2
|
+
|
|
3
|
+
The name contains its original absolute path, source digest and a per-load nonce.
|
|
4
|
+
Importing this package in a fresh interpreter installs the same narrow finder;
|
|
5
|
+
no parent-only registry, source copy, bytecode cache or process-mode override is
|
|
6
|
+
needed. This provides importability, not isolation or a sandbox.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import copy
|
|
11
|
+
import hashlib
|
|
12
|
+
import importlib
|
|
13
|
+
import importlib.abc
|
|
14
|
+
import importlib.util
|
|
15
|
+
import os
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
import re
|
|
18
|
+
import signal
|
|
19
|
+
import sys
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
import types
|
|
23
|
+
import uuid
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
_PREFIX = __name__ + "."
|
|
27
|
+
_IDENTITY = re.compile(r"_p((?:[0-9a-f]{2})+)_s([0-9a-f]{64})_n([0-9a-f]{32})", re.ASCII)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
_NAMED = re.compile(re.escape(_PREFIX) + r"_p((?:[0-9a-f]{2})+)_s[0-9a-f]{64}_n[0-9a-f]{32}", re.ASCII)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def readable(text):
|
|
34
|
+
"""Text with each candidate module name replaced by the last two parts of its file path, as an error reads it."""
|
|
35
|
+
def name(match):
|
|
36
|
+
try:
|
|
37
|
+
parts = Path(os.fsdecode(bytes.fromhex(match.group(1)))).parts
|
|
38
|
+
except ValueError:
|
|
39
|
+
return match.group(0)
|
|
40
|
+
return "/".join(parts[-2:])
|
|
41
|
+
return _NAMED.sub(name, text) if isinstance(text, str) else text
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _identity(fullname):
|
|
45
|
+
"""Decode only this namespace's canonical, single-level module identities."""
|
|
46
|
+
if not fullname.startswith(_PREFIX):
|
|
47
|
+
return None
|
|
48
|
+
match = _IDENTITY.fullmatch(fullname[len(_PREFIX):])
|
|
49
|
+
if match is None:
|
|
50
|
+
raise ModuleNotFoundError("Invalid SCiEL candidate module identity", name=fullname)
|
|
51
|
+
encoded, expected_sha, _nonce = match.groups()
|
|
52
|
+
path = os.fsdecode(bytes.fromhex(encoded))
|
|
53
|
+
if ("\0" in path or not os.path.isabs(path) or os.path.normpath(path) != path
|
|
54
|
+
or os.fsencode(path).hex() != encoded):
|
|
55
|
+
raise ModuleNotFoundError("Invalid SCiEL candidate source path", name=fullname)
|
|
56
|
+
return path, expected_sha
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class _SourceLoader(importlib.abc.Loader):
|
|
60
|
+
def __init__(self, path, expected_sha):
|
|
61
|
+
self.path = path
|
|
62
|
+
self.expected_sha = expected_sha
|
|
63
|
+
|
|
64
|
+
def create_module(self, spec):
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
def _source(self):
|
|
68
|
+
source = Path(self.path).read_bytes()
|
|
69
|
+
if hashlib.sha256(source).hexdigest() != self.expected_sha:
|
|
70
|
+
raise ImportError("SCiEL candidate source changed after loading: " + self.path)
|
|
71
|
+
return source
|
|
72
|
+
|
|
73
|
+
def get_filename(self, fullname):
|
|
74
|
+
return self.path
|
|
75
|
+
|
|
76
|
+
def get_source(self, fullname):
|
|
77
|
+
return importlib.util.decode_source(self._source())
|
|
78
|
+
|
|
79
|
+
def get_code(self, fullname):
|
|
80
|
+
# Compiling the bytes directly honors Python encoding cookies and skips
|
|
81
|
+
# both reading and writing timestamp-based .pyc files.
|
|
82
|
+
return compile(self._source(), self.path, "exec", dont_inherit=True)
|
|
83
|
+
|
|
84
|
+
def exec_module(self, module):
|
|
85
|
+
# Normal importlib has already registered the module before execution,
|
|
86
|
+
# as required by dataclasses, recursive imports and ordinary pickling.
|
|
87
|
+
module.__file__ = self.path
|
|
88
|
+
module.__cached__ = None
|
|
89
|
+
exec(self.get_code(module.__name__), module.__dict__)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class _CandidateFinder(importlib.abc.MetaPathFinder):
|
|
93
|
+
_sciel_candidate_namespace = __name__
|
|
94
|
+
|
|
95
|
+
def find_spec(self, fullname, path=None, target=None):
|
|
96
|
+
identity = _identity(fullname)
|
|
97
|
+
if identity is None:
|
|
98
|
+
return None
|
|
99
|
+
original, expected_sha = identity
|
|
100
|
+
return importlib.util.spec_from_file_location(
|
|
101
|
+
fullname, original, loader=_SourceLoader(original, expected_sha))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _install():
|
|
105
|
+
# Import/reload must not install duplicate hooks. The hook handles no names
|
|
106
|
+
# outside this package and cannot redirect ordinary application imports.
|
|
107
|
+
if not any(getattr(finder, "_sciel_candidate_namespace", None) == __name__
|
|
108
|
+
for finder in sys.meta_path):
|
|
109
|
+
sys.meta_path.insert(0, _CandidateFinder())
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# The evaluation runner names the program it scores; time spent importing it and in its
|
|
113
|
+
# module-level functions is that program's own, the rest of the stage is scoring overhead.
|
|
114
|
+
_NOTHING = object()
|
|
115
|
+
_TIMED = {"path": None, "seconds": 0.0, "called": False, "depth": 0, "calls": 0,
|
|
116
|
+
"kept": _NOTHING, "kept_used": False}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class StageBudgetExceeded(BaseException):
|
|
120
|
+
"""Raised inside the timed program when its stage budget runs out. A BaseException, so the `except Exception`
|
|
121
|
+
of a search loop does not swallow it; it is re-raised every half second until the program's entry function
|
|
122
|
+
unwinds."""
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def time_program(program_path):
|
|
126
|
+
_TIMED.update(path=str(Path(program_path).resolve(strict=True)), seconds=0.0, called=False, depth=0, calls=0,
|
|
127
|
+
kept=_NOTHING, kept_used=False)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def program_seconds():
|
|
131
|
+
"""Seconds spent in the timed program, or None when none of its functions ran in this process."""
|
|
132
|
+
return _TIMED["seconds"] if _TIMED["called"] else None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def keep(result):
|
|
136
|
+
"""Record a copy of result as the timed program's answer so far (sciel.task.keep)."""
|
|
137
|
+
_TIMED["kept"] = copy.deepcopy(result)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def kept_used():
|
|
141
|
+
"""Whether an entry function of the timed program returned its kept result at the end of its budget."""
|
|
142
|
+
return _TIMED["kept_used"]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _expire(signum, frame):
|
|
146
|
+
raise StageBudgetExceeded
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _arm():
|
|
150
|
+
"""Interrupt the program when its stage budget runs out (SCIEL_INTERRUPT_SECONDS, which the sandbox sets at most
|
|
151
|
+
SCIEL_STAGE_SECONDS): (previous SIGALRM handler,) or None when no budget is set or no timer can be armed here.
|
|
152
|
+
The import of the program counts against its first call."""
|
|
153
|
+
try:
|
|
154
|
+
budget = float(os.environ["SCIEL_INTERRUPT_SECONDS"])
|
|
155
|
+
except (KeyError, ValueError):
|
|
156
|
+
return None
|
|
157
|
+
if not hasattr(signal, "setitimer") or threading.current_thread() is not threading.main_thread():
|
|
158
|
+
return None
|
|
159
|
+
if not _TIMED["calls"]:
|
|
160
|
+
budget -= _TIMED["seconds"]
|
|
161
|
+
previous = signal.signal(signal.SIGALRM, _expire)
|
|
162
|
+
signal.setitimer(signal.ITIMER_REAL, max(0.05, budget), 0.5)
|
|
163
|
+
return (previous,)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _disarm(armed):
|
|
167
|
+
if armed is not None:
|
|
168
|
+
signal.setitimer(signal.ITIMER_REAL, 0)
|
|
169
|
+
signal.signal(signal.SIGALRM, armed[0] if armed[0] is not None else signal.SIG_DFL)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _timed(fn):
|
|
173
|
+
def call(*args, **kwargs):
|
|
174
|
+
outer = not _TIMED["depth"]
|
|
175
|
+
if outer:
|
|
176
|
+
_TIMED["kept"] = _NOTHING
|
|
177
|
+
_TIMED["depth"] += 1
|
|
178
|
+
_TIMED["called"] = True
|
|
179
|
+
started = time.monotonic()
|
|
180
|
+
armed = _arm() if outer else None
|
|
181
|
+
try:
|
|
182
|
+
try:
|
|
183
|
+
return fn(*args, **kwargs)
|
|
184
|
+
finally:
|
|
185
|
+
_disarm(armed)
|
|
186
|
+
except StageBudgetExceeded:
|
|
187
|
+
# Only the entry function the evaluator called answers for the program: it returns the last kept result,
|
|
188
|
+
# or fails as an ordinary exception the evaluator reports.
|
|
189
|
+
if not outer:
|
|
190
|
+
raise
|
|
191
|
+
if _TIMED["kept"] is _NOTHING:
|
|
192
|
+
raise TimeoutError(
|
|
193
|
+
"the program ran past its stage budget (SCIEL_STAGE_SECONDS) and was interrupted without a "
|
|
194
|
+
"kept result; call sciel.task.keep(best) whenever the best improves, and the last kept result "
|
|
195
|
+
"is scored when the budget runs out") from None
|
|
196
|
+
_TIMED["kept_used"] = True
|
|
197
|
+
return _TIMED["kept"]
|
|
198
|
+
finally:
|
|
199
|
+
_TIMED["depth"] -= 1
|
|
200
|
+
if not _TIMED["depth"]:
|
|
201
|
+
_TIMED["calls"] += 1
|
|
202
|
+
_TIMED["seconds"] += time.monotonic() - started
|
|
203
|
+
for key in ("__module__", "__name__", "__qualname__", "__doc__", "__wrapped__"):
|
|
204
|
+
setattr(call, key, fn if key == "__wrapped__" else getattr(fn, key))
|
|
205
|
+
return call
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def load_candidate(program_path, module_name="program"):
|
|
209
|
+
"""Execute exact source in a fresh module importable by spawn/forkserver.
|
|
210
|
+
|
|
211
|
+
``module_name`` is retained as a caller compatibility label; the actual
|
|
212
|
+
module name is collision-free and must not be replaced by that alias.
|
|
213
|
+
Source must remain at its original path, unchanged, while workers use it.
|
|
214
|
+
Existing ambient import paths are preserved. This does not add the source
|
|
215
|
+
directory to ``sys.path``, isolate conflicting sibling-module names or add
|
|
216
|
+
package-relative import support to a standalone candidate file.
|
|
217
|
+
"""
|
|
218
|
+
if not isinstance(module_name, str) or not module_name:
|
|
219
|
+
raise ValueError("candidate module label must be a nonempty string")
|
|
220
|
+
original = str(Path(program_path).resolve(strict=True))
|
|
221
|
+
source = Path(original).read_bytes()
|
|
222
|
+
identity = ("_p" + os.fsencode(original).hex()
|
|
223
|
+
+ "_s" + hashlib.sha256(source).hexdigest()
|
|
224
|
+
+ "_n" + uuid.uuid4().hex)
|
|
225
|
+
if original != _TIMED["path"]:
|
|
226
|
+
# import_module also removes a partly initialized module if execution raises.
|
|
227
|
+
return importlib.import_module(_PREFIX + identity)
|
|
228
|
+
started = time.monotonic()
|
|
229
|
+
try:
|
|
230
|
+
module = importlib.import_module(_PREFIX + identity)
|
|
231
|
+
finally:
|
|
232
|
+
_TIMED["seconds"] += time.monotonic() - started
|
|
233
|
+
for name, value in list(vars(module).items()):
|
|
234
|
+
if isinstance(value, types.FunctionType) and value.__module__ == module.__name__:
|
|
235
|
+
setattr(module, name, _timed(value))
|
|
236
|
+
return module
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
_install()
|
sciel/causal/__init__.py
ADDED