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
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
"""Viability contract: one typed Propose->Validate->Repair cycle for candidates.
|
|
2
|
+
|
|
3
|
+
The engine cannot constrain a closed API model's decoding with a grammar, so the
|
|
4
|
+
only available form of "constrained decoding" is post-hoc: classify what is wrong
|
|
5
|
+
with a completion into a typed Violation, then apply a declarative repair policy.
|
|
6
|
+
This module supplies classification and mechanical repairs. validation.validate_candidate
|
|
7
|
+
composes them with graft/duplicate/novelty decisions; run_worker owns requests and evals.
|
|
8
|
+
|
|
9
|
+
Violation kinds (checked in this priority order per attempt):
|
|
10
|
+
empty -- thinking-only / no code extracted
|
|
11
|
+
syntax -- does not parse (incl. the mid-docstring completion family)
|
|
12
|
+
resource -- statically-fatal in the sandbox (multiprocessing + local workers)
|
|
13
|
+
interface -- dropped an entry-point the evaluator calls (repaired by graft)
|
|
14
|
+
duplicate -- normalized code already seen on the island
|
|
15
|
+
|
|
16
|
+
`empty`, `syntax`, `resource` are PRE-EVAL: caught before spending a sandbox run.
|
|
17
|
+
`interface` is repaired unconditionally by graft (no-op when nothing was dropped).
|
|
18
|
+
`duplicate` is checked after graft. The repair table below is declarative; the
|
|
19
|
+
RepairPolicy indirection is where a learned policy will later live (the journal
|
|
20
|
+
already records grafted / empty_responses / gate_rejections outcomes)."""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import ast
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Violation:
|
|
30
|
+
kind: str # empty | syntax | resource | interface | duplicate
|
|
31
|
+
detail: str = ""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _docstring_repair(child: str) -> str | None:
|
|
35
|
+
"""One observed cheap syntax family: the completion starts mid-docstring
|
|
36
|
+
(prose preamble swallowed the opening quotes). If prepending quotes makes the
|
|
37
|
+
module parse, return the repaired text; else None."""
|
|
38
|
+
if child.lstrip().startswith(('"""', "'''", "#", "import ", "from ", "def ",
|
|
39
|
+
"class ", "@")):
|
|
40
|
+
return None
|
|
41
|
+
fixed = '"""' + child
|
|
42
|
+
return fixed if _parses(fixed) else None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _parses(code: str) -> bool:
|
|
46
|
+
try:
|
|
47
|
+
ast.parse(code)
|
|
48
|
+
return True
|
|
49
|
+
except SyntaxError:
|
|
50
|
+
return False
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _strip_fences(child: str) -> str | None:
|
|
54
|
+
"""Stray markdown fence or backtick lines left inside the extracted code."""
|
|
55
|
+
kept = [line for line in child.split("\n") if not line.strip().startswith("```")]
|
|
56
|
+
return "\n".join(kept) if len(kept) != child.count("\n") + 1 else None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _expand_tabs(child: str) -> str | None:
|
|
60
|
+
return child.expandtabs(4) if "\t" in child else None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _dedent_module(child: str) -> str | None:
|
|
64
|
+
"""A module whose every code line carries the same leading indent."""
|
|
65
|
+
lines = [line for line in child.split("\n") if line.strip()]
|
|
66
|
+
if not lines:
|
|
67
|
+
return None
|
|
68
|
+
common = min(len(line) - len(line.lstrip(" ")) for line in lines)
|
|
69
|
+
if common == 0:
|
|
70
|
+
return None
|
|
71
|
+
return "\n".join(line[common:] if line[:common].isspace() else line.lstrip(" ")
|
|
72
|
+
for line in child.split("\n"))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
SYNTAX_REPAIRS = (("strip_fences", _strip_fences), ("expand_tabs", _expand_tabs),
|
|
76
|
+
("dedent_module", _dedent_module), ("prepend_docstring", _docstring_repair))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _syntax_repair(child: str) -> tuple[str, str] | None:
|
|
80
|
+
"""Try each repair alone, then cumulatively; return the first parsing variant and its name."""
|
|
81
|
+
for name, fn in SYNTAX_REPAIRS:
|
|
82
|
+
fixed = fn(child)
|
|
83
|
+
if fixed is not None and _parses(fixed):
|
|
84
|
+
return fixed, name
|
|
85
|
+
code, names = child, []
|
|
86
|
+
for name, fn in SYNTAX_REPAIRS:
|
|
87
|
+
fixed = fn(code)
|
|
88
|
+
if fixed is not None:
|
|
89
|
+
code, names = fixed, names + [name]
|
|
90
|
+
if _parses(code):
|
|
91
|
+
return code, "+".join(names)
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
_POOL_TYPES = {"multiprocessing.Pool", "multiprocessing.pool.Pool",
|
|
96
|
+
"concurrent.futures.ProcessPoolExecutor",
|
|
97
|
+
"concurrent.futures.process.ProcessPoolExecutor"}
|
|
98
|
+
_PROCESS_TYPES = {"multiprocessing.Process", "multiprocessing.context.Process",
|
|
99
|
+
"multiprocessing.context.SpawnProcess", "multiprocessing.context.ForkServerProcess"}
|
|
100
|
+
_POOL_METHODS = {"map", "imap", "imap_unordered", "starmap", "apply", "apply_async",
|
|
101
|
+
"map_async", "starmap_async", "submit"}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass
|
|
105
|
+
class _Scope:
|
|
106
|
+
parent: _Scope | None = None
|
|
107
|
+
kind: str = "module"
|
|
108
|
+
bindings: dict = field(default_factory=dict)
|
|
109
|
+
redirects: dict = field(default_factory=dict)
|
|
110
|
+
|
|
111
|
+
def bind(self, name, value):
|
|
112
|
+
scope = self.redirects.get(name, self)
|
|
113
|
+
scope.bindings.setdefault(name, []).append(value)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class _ResourceScan(ast.NodeVisitor):
|
|
117
|
+
"""Resolve only unambiguous imports/aliases, respecting lexical shadowing.
|
|
118
|
+
|
|
119
|
+
Bindings are collected before calls are inspected, so an import below a
|
|
120
|
+
function definition and aliases such as ``P = mp.Pool`` work. An ambiguous
|
|
121
|
+
reassignment is deliberately left for the evaluator, not called fatal here.
|
|
122
|
+
"""
|
|
123
|
+
def __init__(self):
|
|
124
|
+
self.scope = _Scope()
|
|
125
|
+
self.calls = []
|
|
126
|
+
self.parents = {}
|
|
127
|
+
self._visiting = None
|
|
128
|
+
|
|
129
|
+
def visit(self, node):
|
|
130
|
+
parent = self._visiting
|
|
131
|
+
self.parents[id(node)] = parent
|
|
132
|
+
self._visiting = node
|
|
133
|
+
try:
|
|
134
|
+
return super().visit(node)
|
|
135
|
+
finally:
|
|
136
|
+
self._visiting = parent
|
|
137
|
+
|
|
138
|
+
def _target(self, target, value=None):
|
|
139
|
+
if isinstance(target, ast.Name):
|
|
140
|
+
self.scope.bind(target.id, value)
|
|
141
|
+
elif isinstance(target, (ast.Tuple, ast.List)):
|
|
142
|
+
for item in target.elts:
|
|
143
|
+
self._target(item)
|
|
144
|
+
elif isinstance(target, ast.Starred):
|
|
145
|
+
self._target(target.value)
|
|
146
|
+
|
|
147
|
+
def visit_Name(self, node):
|
|
148
|
+
if isinstance(node.ctx, (ast.Store, ast.Del)):
|
|
149
|
+
self._target(node)
|
|
150
|
+
|
|
151
|
+
def visit_Import(self, node):
|
|
152
|
+
for alias in node.names:
|
|
153
|
+
self.scope.bind(alias.asname or alias.name.split(".")[0],
|
|
154
|
+
("path", alias.name if alias.asname else alias.name.split(".")[0]))
|
|
155
|
+
|
|
156
|
+
def visit_ImportFrom(self, node):
|
|
157
|
+
for alias in node.names:
|
|
158
|
+
self.scope.bind(alias.asname or alias.name,
|
|
159
|
+
("path", f"{node.module}.{alias.name}") if not node.level else None)
|
|
160
|
+
|
|
161
|
+
def visit_Assign(self, node):
|
|
162
|
+
self.visit(node.value)
|
|
163
|
+
for target in node.targets:
|
|
164
|
+
self._target(target, ("expr", node.value, self.scope))
|
|
165
|
+
|
|
166
|
+
def visit_AnnAssign(self, node):
|
|
167
|
+
if node.value is not None:
|
|
168
|
+
self.visit(node.value)
|
|
169
|
+
self._target(node.target, ("expr", node.value, self.scope))
|
|
170
|
+
|
|
171
|
+
def visit_NamedExpr(self, node):
|
|
172
|
+
self.visit(node.value)
|
|
173
|
+
self._target(node.target, ("expr", node.value, self.scope))
|
|
174
|
+
|
|
175
|
+
def visit_With(self, node):
|
|
176
|
+
for item in node.items:
|
|
177
|
+
self.visit(item.context_expr)
|
|
178
|
+
self._target(item.optional_vars, ("expr", item.context_expr, self.scope))
|
|
179
|
+
for statement in node.body:
|
|
180
|
+
self.visit(statement)
|
|
181
|
+
|
|
182
|
+
visit_AsyncWith = visit_With
|
|
183
|
+
|
|
184
|
+
def visit_Global(self, node):
|
|
185
|
+
root = self.scope
|
|
186
|
+
while root.parent is not None:
|
|
187
|
+
root = root.parent
|
|
188
|
+
self.scope.redirects.update((name, root) for name in node.names)
|
|
189
|
+
|
|
190
|
+
def visit_Nonlocal(self, node):
|
|
191
|
+
for name in node.names:
|
|
192
|
+
outer = self.scope.parent
|
|
193
|
+
while outer is not None and outer.parent is not None:
|
|
194
|
+
if name in outer.bindings:
|
|
195
|
+
self.scope.redirects[name] = outer
|
|
196
|
+
break
|
|
197
|
+
outer = outer.parent
|
|
198
|
+
|
|
199
|
+
def _nested(self, node, kind):
|
|
200
|
+
enclosing = self.scope
|
|
201
|
+
parent = enclosing
|
|
202
|
+
while parent.kind == "class":
|
|
203
|
+
parent = parent.parent
|
|
204
|
+
self.scope = _Scope(parent, kind)
|
|
205
|
+
if kind == "function":
|
|
206
|
+
args = node.args
|
|
207
|
+
for arg in [*args.posonlyargs, *args.args, *args.kwonlyargs, args.vararg, args.kwarg]:
|
|
208
|
+
if arg is not None:
|
|
209
|
+
self.scope.bind(arg.arg, None)
|
|
210
|
+
body = node.body if isinstance(node.body, list) else [node.body]
|
|
211
|
+
for statement in body:
|
|
212
|
+
self.visit(statement)
|
|
213
|
+
self.scope = enclosing
|
|
214
|
+
|
|
215
|
+
def visit_FunctionDef(self, node):
|
|
216
|
+
outer = self.scope
|
|
217
|
+
while outer.kind == "class":
|
|
218
|
+
outer = outer.parent
|
|
219
|
+
self.scope.bind(node.name, ("local", "function") if outer.kind == "function" else None)
|
|
220
|
+
for expression in [*node.decorator_list, *node.args.defaults, *node.args.kw_defaults]:
|
|
221
|
+
if expression is not None:
|
|
222
|
+
self.visit(expression)
|
|
223
|
+
self._nested(node, "function")
|
|
224
|
+
|
|
225
|
+
visit_AsyncFunctionDef = visit_FunctionDef
|
|
226
|
+
|
|
227
|
+
def visit_Lambda(self, node):
|
|
228
|
+
for expression in [*node.args.defaults, *node.args.kw_defaults]:
|
|
229
|
+
if expression is not None:
|
|
230
|
+
self.visit(expression)
|
|
231
|
+
self._nested(node, "function")
|
|
232
|
+
|
|
233
|
+
def visit_ClassDef(self, node):
|
|
234
|
+
self.scope.bind(node.name, None)
|
|
235
|
+
for expression in [*node.decorator_list, *node.bases, *(k.value for k in node.keywords)]:
|
|
236
|
+
self.visit(expression)
|
|
237
|
+
self._nested(node, "class")
|
|
238
|
+
|
|
239
|
+
def _comprehension(self, node):
|
|
240
|
+
self.visit(node.generators[0].iter)
|
|
241
|
+
enclosing = self.scope
|
|
242
|
+
parent = enclosing.parent if enclosing.kind == "class" else enclosing
|
|
243
|
+
self.scope = _Scope(parent, "comprehension")
|
|
244
|
+
for i, generator in enumerate(node.generators):
|
|
245
|
+
if i:
|
|
246
|
+
self.visit(generator.iter)
|
|
247
|
+
self._target(generator.target)
|
|
248
|
+
for condition in generator.ifs:
|
|
249
|
+
self.visit(condition)
|
|
250
|
+
for expression in ([node.key, node.value] if isinstance(node, ast.DictComp) else [node.elt]):
|
|
251
|
+
self.visit(expression)
|
|
252
|
+
self.scope = enclosing
|
|
253
|
+
|
|
254
|
+
visit_ListComp = visit_SetComp = visit_DictComp = visit_GeneratorExp = _comprehension
|
|
255
|
+
|
|
256
|
+
def visit_Call(self, node):
|
|
257
|
+
self.calls.append((node, self.scope))
|
|
258
|
+
self.generic_visit(node)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _resolve_resource(expr, scope, seen=frozenset()):
|
|
262
|
+
if isinstance(expr, ast.Lambda):
|
|
263
|
+
return "local", "lambda"
|
|
264
|
+
if isinstance(expr, ast.Name):
|
|
265
|
+
while scope is not None:
|
|
266
|
+
scope = scope.redirects.get(expr.id, scope)
|
|
267
|
+
if expr.id in scope.bindings:
|
|
268
|
+
key = (id(scope), expr.id)
|
|
269
|
+
if key in seen:
|
|
270
|
+
return None
|
|
271
|
+
values = set()
|
|
272
|
+
for binding in scope.bindings[expr.id]:
|
|
273
|
+
value = (_resolve_resource(binding[1], binding[2], seen | {key})
|
|
274
|
+
if binding is not None and binding[0] == "expr" else binding)
|
|
275
|
+
values.add(value)
|
|
276
|
+
return next(iter(values)) if len(values) == 1 else None
|
|
277
|
+
scope = scope.parent
|
|
278
|
+
elif isinstance(expr, ast.Attribute):
|
|
279
|
+
base = _resolve_resource(expr.value, scope, seen)
|
|
280
|
+
if base is not None and base[0] == "path":
|
|
281
|
+
return "path", f"{base[1]}.{expr.attr}"
|
|
282
|
+
if base == ("pool", "") and expr.attr in _POOL_METHODS:
|
|
283
|
+
return "worker_call", expr.attr
|
|
284
|
+
if base is not None and base[0] == "context":
|
|
285
|
+
if expr.attr == "Pool":
|
|
286
|
+
return "path", "multiprocessing.Pool"
|
|
287
|
+
if expr.attr == "Process":
|
|
288
|
+
return "process", base[1]
|
|
289
|
+
elif isinstance(expr, ast.Call):
|
|
290
|
+
callee = _resolve_resource(expr.func, scope, seen)
|
|
291
|
+
if callee is not None and callee[0] == "path":
|
|
292
|
+
if callee[1] in _POOL_TYPES:
|
|
293
|
+
return "pool", ""
|
|
294
|
+
if callee[1] == "multiprocessing.get_context":
|
|
295
|
+
method = next((kw.value for kw in expr.keywords if kw.arg == "method"),
|
|
296
|
+
expr.args[0] if expr.args else None)
|
|
297
|
+
# Explicit fork does not pickle a Process target; pool submissions
|
|
298
|
+
# still pickle workers under every start method.
|
|
299
|
+
if method is None or isinstance(method, ast.Constant) and method.value is None:
|
|
300
|
+
return "context", "default"
|
|
301
|
+
return "context", method.value if isinstance(method, ast.Constant) else "unknown"
|
|
302
|
+
return None
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _statement_block(node, parents):
|
|
306
|
+
while node is not None and not isinstance(node, ast.stmt):
|
|
307
|
+
node = parents.get(id(node))
|
|
308
|
+
parent = parents.get(id(node))
|
|
309
|
+
if parent is not None:
|
|
310
|
+
for field_name, value in ast.iter_fields(parent):
|
|
311
|
+
if isinstance(value, list) and any(item is node for item in value):
|
|
312
|
+
return (id(parent), field_name), node
|
|
313
|
+
return None, node
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _guaranteed_fork(node, scope, scan):
|
|
317
|
+
"""Only a preceding unconditional setter in this same block proves fork.
|
|
318
|
+
|
|
319
|
+
Setters in another function or a conditional branch do not establish the
|
|
320
|
+
runtime context here. A later competing/unknown setter removes the proof.
|
|
321
|
+
Pool workers and explicit spawn/forkserver contexts still require pickling.
|
|
322
|
+
"""
|
|
323
|
+
prior = [(call, call_scope) for call, call_scope in scan.calls
|
|
324
|
+
if (call.lineno, call.col_offset) < (node.lineno, node.col_offset)
|
|
325
|
+
and _resolve_resource(call.func, call_scope) == ("path", "multiprocessing.set_start_method")]
|
|
326
|
+
if not prior:
|
|
327
|
+
return False
|
|
328
|
+
setter, setter_scope = max(prior, key=lambda item: (item[0].lineno, item[0].col_offset))
|
|
329
|
+
if setter_scope is not scope:
|
|
330
|
+
return False
|
|
331
|
+
setter_block, statement = _statement_block(setter, scan.parents)
|
|
332
|
+
block, _ = _statement_block(node, scan.parents)
|
|
333
|
+
if (setter_block is None or setter_block != block
|
|
334
|
+
or not isinstance(statement, ast.Expr) or statement.value is not setter):
|
|
335
|
+
return False
|
|
336
|
+
# Default Process chooses its context at start(), not at construction. A
|
|
337
|
+
# later conflicting setter can therefore invalidate a previously built one.
|
|
338
|
+
for call, call_scope in scan.calls:
|
|
339
|
+
if call_scope is scope and (call.lineno, call.col_offset) > (setter.lineno, setter.col_offset) \
|
|
340
|
+
and _resolve_resource(call.func, call_scope) == ("path", "multiprocessing.set_start_method"):
|
|
341
|
+
later_method = next((kw.value for kw in call.keywords if kw.arg == "method"),
|
|
342
|
+
call.args[0] if call.args else None)
|
|
343
|
+
if not isinstance(later_method, ast.Constant) or later_method.value != "fork":
|
|
344
|
+
return False
|
|
345
|
+
# An arbitrary intervening helper could change the process-wide method.
|
|
346
|
+
# Permit ordinary multiprocessing setup, but do not guess through user calls.
|
|
347
|
+
setup_calls = {f"multiprocessing.{name}" for name in (
|
|
348
|
+
"Queue", "SimpleQueue", "Pipe", "Lock", "RLock", "Semaphore",
|
|
349
|
+
"BoundedSemaphore", "Condition", "Event", "Value", "Array",
|
|
350
|
+
"RawValue", "RawArray", "get_context")}
|
|
351
|
+
for call, call_scope in scan.calls:
|
|
352
|
+
if (call_scope is scope
|
|
353
|
+
and (setter.lineno, setter.col_offset) < (call.lineno, call.col_offset)
|
|
354
|
+
< (node.lineno, node.col_offset)):
|
|
355
|
+
callee = _resolve_resource(call.func, call_scope)
|
|
356
|
+
if callee is None or callee[0] != "path" or callee[1] not in setup_calls:
|
|
357
|
+
return False
|
|
358
|
+
method = next((kw.value for kw in setter.keywords if kw.arg == "method"),
|
|
359
|
+
setter.args[0] if setter.args else None)
|
|
360
|
+
return isinstance(method, ast.Constant) and method.value == "fork"
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _resource_fatal(tree: ast.AST) -> str | None:
|
|
364
|
+
"""Reject a local worker only when it is handed to a known process API."""
|
|
365
|
+
scan = _ResourceScan()
|
|
366
|
+
scan.visit(tree)
|
|
367
|
+
for node, scope in scan.calls:
|
|
368
|
+
callee = _resolve_resource(node.func, scope)
|
|
369
|
+
if callee is None:
|
|
370
|
+
continue
|
|
371
|
+
if callee[0] == "worker_call":
|
|
372
|
+
index, keyword = 0, "fn" if callee[1] == "submit" else "func"
|
|
373
|
+
elif callee[0] == "process":
|
|
374
|
+
if callee[1] == "fork" or callee[1] == "default" and _guaranteed_fork(node, scope, scan):
|
|
375
|
+
continue
|
|
376
|
+
index, keyword = 1, "target"
|
|
377
|
+
elif callee[0] == "path" and callee[1] in _PROCESS_TYPES:
|
|
378
|
+
if callee[1] in {"multiprocessing.Process", "multiprocessing.context.Process"} \
|
|
379
|
+
and _guaranteed_fork(node, scope, scan):
|
|
380
|
+
continue
|
|
381
|
+
index, keyword = 1, "target"
|
|
382
|
+
else:
|
|
383
|
+
continue
|
|
384
|
+
worker = next((kw.value for kw in node.keywords if kw.arg == keyword),
|
|
385
|
+
node.args[index] if len(node.args) > index else None)
|
|
386
|
+
resolved = _resolve_resource(worker, scope)
|
|
387
|
+
if resolved is not None and resolved[0] == "local":
|
|
388
|
+
return (f"multiprocessing cannot pickle a {resolved[1]} worker defined locally; "
|
|
389
|
+
"define the worker at module level or drop multiprocessing")
|
|
390
|
+
return None
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def precheck(child: str) -> Violation | None:
|
|
394
|
+
"""Pre-eval classification: empty / syntax / resource, in priority order.
|
|
395
|
+
Returns None when the candidate may proceed to graft + duplicate check."""
|
|
396
|
+
if not child.strip():
|
|
397
|
+
return Violation("empty")
|
|
398
|
+
try:
|
|
399
|
+
tree = ast.parse(child)
|
|
400
|
+
except SyntaxError as e:
|
|
401
|
+
return Violation("syntax", f"{e.msg} (line {e.lineno})")
|
|
402
|
+
res = _resource_fatal(tree)
|
|
403
|
+
if res is not None:
|
|
404
|
+
return Violation("resource", res)
|
|
405
|
+
return None
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
# Declarative repair table: kind -> mechanical repair fn (None => no mechanical
|
|
409
|
+
# fix, resample instead). `interface` is handled by graft in validation, not here;
|
|
410
|
+
# `duplicate`/`empty` have no mechanical repair. This dict is the policy surface a
|
|
411
|
+
# learned RepairPolicy will consume.
|
|
412
|
+
REPAIR_TABLE = {
|
|
413
|
+
"syntax": _syntax_repair,
|
|
414
|
+
"resource": None,
|
|
415
|
+
"empty": None,
|
|
416
|
+
"duplicate": None,
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def mechanical_repair(v: Violation, child: str) -> tuple[str, str] | None:
|
|
421
|
+
"""Apply the declared mechanical repair for a violation: (fixed code, repair name) or None."""
|
|
422
|
+
fn = REPAIR_TABLE.get(v.kind)
|
|
423
|
+
return fn(child) if fn is not None else None
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
# Backward-compatible facade: the old pre_eval_gate returned a reason string.
|
|
427
|
+
def pre_eval_gate(child: str) -> str | None:
|
|
428
|
+
v = precheck(child)
|
|
429
|
+
if v is None or v.kind == "empty":
|
|
430
|
+
return None
|
|
431
|
+
return f"{v.kind} error before eval: {v.detail}" if v.kind == "syntax" else v.detail
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Audited new search from a checkpoint's best source, with a fresh evaluation.
|
|
2
|
+
|
|
3
|
+
This transfers code, not scores, lessons, budgets, or a stopped research state.
|
|
4
|
+
The source checkpoint and journal stay unchanged.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import math
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from .run_lock import RunDirectoryLock
|
|
14
|
+
|
|
15
|
+
SCHEMA = 'sciel-warm-start/1'
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def validate_warm_start(value):
|
|
19
|
+
if not isinstance(value, dict) or set(value) != {'schema', 'source', 'source_sha256', 'parent'}:
|
|
20
|
+
raise ValueError('invalid warm_start fields')
|
|
21
|
+
source = value['source']
|
|
22
|
+
if (value['schema'] != SCHEMA or not isinstance(source, str) or not source.strip()
|
|
23
|
+
or hashlib.sha256(source.encode()).hexdigest() != value['source_sha256']):
|
|
24
|
+
raise ValueError('warm_start source identity differs')
|
|
25
|
+
parent = value['parent']
|
|
26
|
+
if not isinstance(parent, dict) or not all(parent.get(key) for key in (
|
|
27
|
+
'run_id', 'checkpoint_sha256', 'journal_sha256', 'task', 'task_hash', 'program_id')):
|
|
28
|
+
raise ValueError('warm_start parent provenance is missing')
|
|
29
|
+
return value
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def from_run(directory, task):
|
|
33
|
+
directory = Path(directory).resolve()
|
|
34
|
+
# Serialize against a running writer while taking the immutable source view.
|
|
35
|
+
lock = RunDirectoryLock(directory)
|
|
36
|
+
try:
|
|
37
|
+
raw = (directory / 'checkpoint.json').read_bytes()
|
|
38
|
+
saved = json.loads(raw)
|
|
39
|
+
provenance = saved.get('provenance') or {}
|
|
40
|
+
if provenance.get('schema') != 'sciel-checkpoint-provenance/1':
|
|
41
|
+
raise ValueError('warm start requires a checkpoint with bound provenance')
|
|
42
|
+
identity = saved.get('identity') or {}
|
|
43
|
+
if identity.get('task') != task:
|
|
44
|
+
raise ValueError('warm start task name differs')
|
|
45
|
+
from .journal_anchor import assert_no_uncheckpointed_research
|
|
46
|
+
assert_no_uncheckpointed_research(directory / 'sciel_events.jsonl', provenance.get('journal_anchor'))
|
|
47
|
+
journal = (directory / 'sciel_events.jsonl').read_bytes()
|
|
48
|
+
rows = [json.loads(line) for line in journal.splitlines()]
|
|
49
|
+
checkpoint_sha = hashlib.sha256(raw).hexdigest()
|
|
50
|
+
if not any(row.get('event') == 'checkpoint'
|
|
51
|
+
and row.get('checkpoint_sha256') == checkpoint_sha
|
|
52
|
+
and row.get('checkpoint_id') == provenance.get('checkpoint_id') for row in rows):
|
|
53
|
+
raise ValueError('warm start checkpoint digest is not recorded in the journal')
|
|
54
|
+
best = saved['db']['pop_best_id']
|
|
55
|
+
program = next(p for p in saved['db']['programs'] if p['id'] == best)
|
|
56
|
+
if type(program['score']) not in (int, float) or not math.isfinite(program['score']):
|
|
57
|
+
raise ValueError('warm start has no finite best score')
|
|
58
|
+
source = program['code']
|
|
59
|
+
value = dict(schema=SCHEMA, source=source,
|
|
60
|
+
source_sha256=hashlib.sha256(source.encode()).hexdigest(),
|
|
61
|
+
parent=dict(run_id=provenance['run_id'], path=str(directory),
|
|
62
|
+
checkpoint_sha256=checkpoint_sha, journal_sha256=hashlib.sha256(journal).hexdigest(),
|
|
63
|
+
task=task, task_hash=identity['task_hash'], program_id=best,
|
|
64
|
+
previous_score=program['score'], previous_known_cost=saved.get('cost_total'),
|
|
65
|
+
stopped_reason=(saved.get('research') or {}).get('stopped_reason'),
|
|
66
|
+
transfer='source_only_fresh_evaluation'))
|
|
67
|
+
return validate_warm_start(value)
|
|
68
|
+
finally:
|
|
69
|
+
lock.close()
|