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/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.19.0"
|
|
File without changes
|
sciel/campaign/budget.py
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
"""A shared, durable cost ledger for bounded experimental API calls."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from contextlib import contextmanager
|
|
5
|
+
from decimal import Decimal
|
|
6
|
+
import fcntl
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
import time
|
|
13
|
+
import uuid
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CampaignStopped(RuntimeError):
|
|
17
|
+
"""Do not dispatch another chargeable request in this campaign."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class RequestNotDispatched(CampaignStopped):
|
|
21
|
+
"""The current request was rejected before reservation/provider dispatch.
|
|
22
|
+
|
|
23
|
+
This marker describes only this request. Earlier receipts may still be
|
|
24
|
+
charged or unresolved. An ordinary CampaignStopped makes no such promise.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def request_cost_bound(prompt, max_tokens, rates, *, response_format=None):
|
|
29
|
+
"""Same conservative bound as generation, including explicit schema bytes."""
|
|
30
|
+
from ..engine.llm.client import response_format_bytes
|
|
31
|
+
if type(prompt) is not str or type(max_tokens) is not int or max_tokens <= 0:
|
|
32
|
+
raise ValueError('request requires a text prompt and positive token cap')
|
|
33
|
+
schema_bytes = response_format_bytes(response_format)
|
|
34
|
+
return ((len(prompt.encode('utf-8')) + len(schema_bytes) + 1024) * money(rates['prompt'])
|
|
35
|
+
+ max_tokens * money(rates['completion'])
|
|
36
|
+
+ money(rates.get('request', 0))) * Decimal('1.10')
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _error_attr(value, name):
|
|
40
|
+
try:
|
|
41
|
+
return getattr(value, name, None)
|
|
42
|
+
except Exception:
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _error_json(value):
|
|
47
|
+
# Do not stringify SDK objects or read a streaming response to recover errors.
|
|
48
|
+
if type(value) is dict:
|
|
49
|
+
return value
|
|
50
|
+
if type(value) not in (str, bytes) or len(value) > 16384:
|
|
51
|
+
return None
|
|
52
|
+
try:
|
|
53
|
+
value = json.loads(value)
|
|
54
|
+
except (ValueError, UnicodeError, RecursionError):
|
|
55
|
+
return None
|
|
56
|
+
return value if type(value) is dict else None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
_PROVIDER_MESSAGE_HINTS = (
|
|
60
|
+
('schema_invalid', r'(?:invalid (?:json )?schema\b|(?:json )?schema is invalid\b)'),
|
|
61
|
+
('schema_complexity_limit', r'(?:(?:json )?schema (?:is )?too complex\b|'
|
|
62
|
+
r'(?:json )?schema (?:has|contains) too many (?:properties|parameters|enum values)\b)'),
|
|
63
|
+
('parameter_unsupported', r'(?:unsupported (?:request )?parameter\b|'
|
|
64
|
+
r'(?:unknown|unrecognized) (?:request )?(?:parameter|argument)\b)'),
|
|
65
|
+
('context_limit', r'(?:context (?:length|window) (?:limit )?exceeded\b|'
|
|
66
|
+
r'(?:this model\'s )?maximum context length (?:is|exceeded)\b|'
|
|
67
|
+
r'(?:input|prompt) (?:is )?too long for (?:the )?context (?:window|length)\b)'),
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _provider_message_hints(value):
|
|
72
|
+
"""Fixed lexical categories only, never an error quote or verified cause.
|
|
73
|
+
|
|
74
|
+
A short schema literal such as ``object`` can correctly force whole-field
|
|
75
|
+
redaction even in a useful provider message. Recognize a few narrow leading
|
|
76
|
+
assertions before that redaction, without emitting matched text, numbers,
|
|
77
|
+
parameter names or any other data from the message. Quoted/request-prefixed
|
|
78
|
+
phrases do not match; an unmarked echo is still possible, hence unverified.
|
|
79
|
+
Oversized and non-string fields receive no hint and are never stringified.
|
|
80
|
+
"""
|
|
81
|
+
if type(value) is not str or not value or len(value) > 8192:
|
|
82
|
+
return None
|
|
83
|
+
plain = ' '.join(value.split())
|
|
84
|
+
categories = [name for name, pattern in _PROVIDER_MESSAGE_HINTS
|
|
85
|
+
if re.match(pattern, plain, flags=re.IGNORECASE | re.ASCII)]
|
|
86
|
+
if not categories:
|
|
87
|
+
return None
|
|
88
|
+
return dict(schema='sciel-provider-message-hints/1', categories=categories,
|
|
89
|
+
source='bounded_provider_message_pattern', cause_verified=False)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def provider_error_metadata(exc, *, request=None):
|
|
93
|
+
"""Allowlisted, bounded diagnostics, never raw exceptions/headers/requests.
|
|
94
|
+
|
|
95
|
+
Legacy callers without the actual request context retain exactly the old
|
|
96
|
+
metadata shape. Details are provider assertions, not an inferred cause.
|
|
97
|
+
Detected credential literals/patterns and normalized prompt excerpts redact
|
|
98
|
+
the entire field. Prompt matching covers whole short inputs or >=16-character
|
|
99
|
+
excerpts; it does not prove removal of arbitrary encodings or paraphrases.
|
|
100
|
+
Fixed message hints may survive redaction, but never establish a root cause,
|
|
101
|
+
whether a request was processed or charged, or permission to retry.
|
|
102
|
+
"""
|
|
103
|
+
cause, status = _error_attr(exc, "__cause__"), _error_attr(exc, "status_code")
|
|
104
|
+
result = {"error_type": type(exc).__name__,
|
|
105
|
+
"error_status_code": status if type(status) is int and 100 <= status <= 599 else None,
|
|
106
|
+
"error_cause_type": type(cause).__name__ if cause is not None else None}
|
|
107
|
+
if type(request) is not dict:
|
|
108
|
+
return result
|
|
109
|
+
response = _error_attr(exc, 'response')
|
|
110
|
+
body = _error_json(_error_attr(exc, 'body'))
|
|
111
|
+
if body is None:
|
|
112
|
+
body = _error_json(_error_attr(response, 'content'))
|
|
113
|
+
if body is None:
|
|
114
|
+
return result
|
|
115
|
+
# Header values are used solely as redaction needles, never serialized.
|
|
116
|
+
remote_request = _error_attr(exc, 'request')
|
|
117
|
+
if remote_request is None:
|
|
118
|
+
remote_request = _error_attr(response, 'request')
|
|
119
|
+
headers = _error_attr(remote_request, 'headers')
|
|
120
|
+
secrets = []
|
|
121
|
+
for key in ('authorization', 'proxy-authorization', 'x-api-key', 'api-key', 'cookie'):
|
|
122
|
+
try:
|
|
123
|
+
value = headers.get(key) if headers is not None else None
|
|
124
|
+
except Exception:
|
|
125
|
+
value = None
|
|
126
|
+
if type(value) is str and value:
|
|
127
|
+
secrets.append(value)
|
|
128
|
+
if value.lower().startswith(('bearer ', 'basic ')):
|
|
129
|
+
secrets.append(value.split(' ', 1)[1])
|
|
130
|
+
messages = request.get('messages')
|
|
131
|
+
contents = [m.get('content') for m in messages if type(m) is dict] if type(messages) is list else []
|
|
132
|
+
texts, pending, nodes = [], contents + [request.get('response_format')], 0
|
|
133
|
+
while pending and nodes < 4096:
|
|
134
|
+
value = pending.pop(); nodes += 1
|
|
135
|
+
if type(value) is str and value:
|
|
136
|
+
texts.append(value)
|
|
137
|
+
elif type(value) is dict:
|
|
138
|
+
pending.extend(list(value.values())[:4096])
|
|
139
|
+
elif type(value) is list:
|
|
140
|
+
pending.extend(value[:4096])
|
|
141
|
+
# Fail closed if request coverage could not be completed within the bound.
|
|
142
|
+
complete_context = not pending
|
|
143
|
+
normalized = [' '.join(text.split()) for text in texts]
|
|
144
|
+
def clean(value, limit):
|
|
145
|
+
if type(value) is not str or not value:
|
|
146
|
+
return None
|
|
147
|
+
if len(value) > 8192:
|
|
148
|
+
return '[omitted: oversized diagnostic]'
|
|
149
|
+
decoded = re.sub(r'\\u([0-9a-fA-F]{4})', lambda m: chr(int(m[1], 16)), value)
|
|
150
|
+
if (not complete_context or any(secret in decoded for secret in secrets)
|
|
151
|
+
or re.search(r'(?i)(?:bearer|basic)\s+\S+|(?:api[_-]?key|authorization|password|secret|access[_-]?token)\s*[=:]|sk-[A-Za-z0-9_-]{8,}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.', decoded)):
|
|
152
|
+
return '[redacted]'
|
|
153
|
+
plain = ' '.join(decoded.replace('\\n', ' ').replace('\\r', ' ').replace('\\t', ' ').split())
|
|
154
|
+
# Whole short inputs and any 16-character request excerpt are sensitive.
|
|
155
|
+
if any((text in plain if len(text) < 16 else
|
|
156
|
+
any(plain[i:i+16] in text for i in range(max(0, len(plain)-15))))
|
|
157
|
+
for text in normalized):
|
|
158
|
+
return '[redacted]'
|
|
159
|
+
value = ''.join(char if char.isprintable() else ' ' for char in value)
|
|
160
|
+
return value if len(value) <= limit else value[:limit-3] + '...'
|
|
161
|
+
def fields(node):
|
|
162
|
+
if type(node) is not dict:
|
|
163
|
+
return {}
|
|
164
|
+
values = {}
|
|
165
|
+
hints = _provider_message_hints(node.get('message'))
|
|
166
|
+
if hints is not None:
|
|
167
|
+
values['message_hints'] = hints
|
|
168
|
+
for key, limit in (('code', 128), ('param', 128), ('message', 512), ('request_id', 128)):
|
|
169
|
+
value = node.get(key)
|
|
170
|
+
if key == 'code' and type(value) is int and abs(value) < 10**10:
|
|
171
|
+
values[key] = value
|
|
172
|
+
else:
|
|
173
|
+
value = clean(value, limit)
|
|
174
|
+
if value is not None:
|
|
175
|
+
values[key] = value
|
|
176
|
+
return values
|
|
177
|
+
error = body.get('error') if type(body.get('error')) is dict else body
|
|
178
|
+
details = fields(error)
|
|
179
|
+
request_id = clean(_error_attr(exc, 'request_id'), 128)
|
|
180
|
+
if request_id is not None:
|
|
181
|
+
details['request_id'] = request_id
|
|
182
|
+
metadata = error.get('metadata')
|
|
183
|
+
raw = _error_json(metadata.get('raw')) if type(metadata) is dict else None
|
|
184
|
+
if raw is not None:
|
|
185
|
+
nested = fields(raw.get('error') if type(raw.get('error')) is dict else raw)
|
|
186
|
+
if nested:
|
|
187
|
+
details['provider'] = nested
|
|
188
|
+
if details:
|
|
189
|
+
result['error_details'] = dict(schema='sciel-provider-error-details/1', **details)
|
|
190
|
+
return result
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def money(value):
|
|
194
|
+
if isinstance(value, bool):
|
|
195
|
+
raise ValueError("money must be a non-negative finite number")
|
|
196
|
+
try:
|
|
197
|
+
result = Decimal(str(value))
|
|
198
|
+
except ArithmeticError as exc:
|
|
199
|
+
raise ValueError("money must be a non-negative finite number") from exc
|
|
200
|
+
if not result.is_finite() or result < 0:
|
|
201
|
+
raise ValueError("money must be a non-negative finite number")
|
|
202
|
+
return result
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def validate_llm_config(cfg, pricing):
|
|
206
|
+
"""Reject an unusable ensemble or ambiguous price snapshot before any I/O."""
|
|
207
|
+
if not isinstance(cfg, dict) or not isinstance(pricing, dict):
|
|
208
|
+
raise ValueError("LLM config and pricing must be objects")
|
|
209
|
+
models, weights = cfg.get("models"), cfg.get("weights")
|
|
210
|
+
if (not isinstance(models, list) or not models
|
|
211
|
+
or any(not isinstance(m, str) or not m.strip() for m in models)
|
|
212
|
+
or len(set(models)) != len(models)):
|
|
213
|
+
raise ValueError("models must be a nonempty list of unique model IDs")
|
|
214
|
+
from ..engine.llm.client import validate_model_capabilities
|
|
215
|
+
validate_model_capabilities(cfg.get('model_capabilities', {}), models)
|
|
216
|
+
if (not isinstance(weights, list) or len(weights) != len(models)
|
|
217
|
+
or any(isinstance(w, bool) or not isinstance(w, (int, float))
|
|
218
|
+
or not math.isfinite(w) or w < 0 for w in weights)
|
|
219
|
+
or not math.isfinite(sum(weights)) or sum(weights) <= 0):
|
|
220
|
+
raise ValueError("weights must match models and have a positive finite sum")
|
|
221
|
+
if type(cfg.get("max_tokens")) is not int or cfg["max_tokens"] <= 0:
|
|
222
|
+
raise ValueError("max_tokens must be a positive integer")
|
|
223
|
+
for key, default, upper in (("temperature", .7, 2), ("timeout", 120, None)):
|
|
224
|
+
value = cfg.get(key, default)
|
|
225
|
+
if (isinstance(value, bool) or not isinstance(value, (int, float))
|
|
226
|
+
or not math.isfinite(value) or value < 0
|
|
227
|
+
or (key == "timeout" and value == 0)
|
|
228
|
+
or (upper is not None and value > upper)):
|
|
229
|
+
raise ValueError(f"invalid LLM {key}")
|
|
230
|
+
# This wrapper relies on OpenRouter's provider price caps. A generic compatible
|
|
231
|
+
# endpoint may silently ignore those fields, invalidating the reservation.
|
|
232
|
+
endpoint = cfg.get("api_base")
|
|
233
|
+
if not isinstance(endpoint, str) or endpoint.rstrip("/") != "https://openrouter.ai/api/v1":
|
|
234
|
+
raise ValueError("budgeted calls require the OpenRouter API endpoint")
|
|
235
|
+
rows = pricing.get("models")
|
|
236
|
+
if not isinstance(rows, list) or not rows:
|
|
237
|
+
raise ValueError("pricing must contain a nonempty models list")
|
|
238
|
+
prices = {}
|
|
239
|
+
for row in rows:
|
|
240
|
+
if (not isinstance(row, dict) or not isinstance(row.get("id"), str)
|
|
241
|
+
or not row["id"].strip() or row["id"] in prices):
|
|
242
|
+
raise ValueError("pricing model IDs must be nonempty and unique")
|
|
243
|
+
if row["id"] in models and "reasoning" in row:
|
|
244
|
+
reasoning = row["reasoning"]
|
|
245
|
+
if (type(reasoning) is not dict
|
|
246
|
+
or ("mandatory" in reasoning and type(reasoning["mandatory"]) is not bool)
|
|
247
|
+
or (reasoning.get("supported_efforts") is not None and
|
|
248
|
+
(type(reasoning["supported_efforts"]) is not list
|
|
249
|
+
or not reasoning["supported_efforts"]
|
|
250
|
+
or any(type(e) is not str or not e for e in reasoning["supported_efforts"])))):
|
|
251
|
+
raise ValueError("malformed selected-model reasoning metadata")
|
|
252
|
+
if (reasoning.get("mandatory") is True
|
|
253
|
+
or (reasoning.get("supported_efforts") is not None and "none" not in reasoning["supported_efforts"])):
|
|
254
|
+
raise ValueError("selected model is incompatible with fixed reasoning effort none")
|
|
255
|
+
rates = row.get("pricing")
|
|
256
|
+
if not isinstance(rates, dict) or not {"prompt", "completion"} <= rates.keys():
|
|
257
|
+
raise ValueError(f"missing text token prices for {row['id']}")
|
|
258
|
+
prices[row["id"]] = {key: money(rates.get(key, 0))
|
|
259
|
+
for key in ("prompt", "completion", "request")}
|
|
260
|
+
if any(model not in prices for model in models):
|
|
261
|
+
raise ValueError("pinned model prices are required for every ensemble model")
|
|
262
|
+
return prices
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
class CostLedger:
|
|
266
|
+
"""Reserve a conservative request bound before dispatch, including on restart.
|
|
267
|
+
|
|
268
|
+
Unknown outcomes keep their full reservation: a network failure is not proof
|
|
269
|
+
of a free request. A separate lock file makes atomic JSON replacement safe.
|
|
270
|
+
"""
|
|
271
|
+
def __init__(self, path, limit_usd):
|
|
272
|
+
self.path = Path(path)
|
|
273
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
274
|
+
self.limit = money(limit_usd)
|
|
275
|
+
if self.limit <= 0:
|
|
276
|
+
raise ValueError("campaign limit must be positive")
|
|
277
|
+
with self._locked() as state:
|
|
278
|
+
if not state:
|
|
279
|
+
state.update(schema="sciel-cost-ledger/1", limit_usd=str(self.limit),
|
|
280
|
+
calls={}, halted=None)
|
|
281
|
+
elif money(state["limit_usd"]) != self.limit:
|
|
282
|
+
raise ValueError("existing campaign limit cannot change on resume")
|
|
283
|
+
|
|
284
|
+
@contextmanager
|
|
285
|
+
def _locked(self):
|
|
286
|
+
with open(str(self.path) + ".lock", "a") as lock:
|
|
287
|
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
288
|
+
state = json.loads(self.path.read_text()) if self.path.exists() else {}
|
|
289
|
+
try:
|
|
290
|
+
yield state
|
|
291
|
+
temp = self.path.with_suffix(self.path.suffix + ".tmp")
|
|
292
|
+
with open(temp, "w") as out:
|
|
293
|
+
json.dump(state, out, indent=2)
|
|
294
|
+
out.write("\n")
|
|
295
|
+
out.flush()
|
|
296
|
+
os.fsync(out.fileno())
|
|
297
|
+
os.replace(temp, self.path)
|
|
298
|
+
finally:
|
|
299
|
+
fcntl.flock(lock, fcntl.LOCK_UN)
|
|
300
|
+
|
|
301
|
+
@staticmethod
|
|
302
|
+
def totals(state):
|
|
303
|
+
known = sum((money(c["cost_usd"]) for c in state["calls"].values()
|
|
304
|
+
if c.get("cost_usd") is not None), Decimal(0))
|
|
305
|
+
held = sum((money(c["reservation_usd"]) for c in state["calls"].values()
|
|
306
|
+
if c.get("cost_usd") is None), Decimal(0))
|
|
307
|
+
return known, held
|
|
308
|
+
|
|
309
|
+
def reserve(self, bound_usd, *, run_id, model):
|
|
310
|
+
bound = money(bound_usd)
|
|
311
|
+
with self._locked() as state:
|
|
312
|
+
known, held = self.totals(state)
|
|
313
|
+
if state.get("halted"):
|
|
314
|
+
raise RequestNotDispatched(state["halted"])
|
|
315
|
+
if known + held + bound > self.limit:
|
|
316
|
+
raise RequestNotDispatched("campaign cost limit leaves no room for this request")
|
|
317
|
+
ident = uuid.uuid4().hex
|
|
318
|
+
state["calls"][ident] = dict(run_id=run_id, model=model,
|
|
319
|
+
reservation_usd=str(bound), cost_usd=None, status="reserved",
|
|
320
|
+
created_at=time.time())
|
|
321
|
+
return ident
|
|
322
|
+
|
|
323
|
+
def settle(self, ident, actual_cost=None, *, halt_reason=None, **metadata):
|
|
324
|
+
overrun = False
|
|
325
|
+
protected = {"run_id", "model", "reservation_usd", "cost_usd", "status",
|
|
326
|
+
"created_at", "completed_at"}
|
|
327
|
+
if protected.intersection(metadata):
|
|
328
|
+
raise ValueError("settlement metadata cannot replace ledger accounting fields")
|
|
329
|
+
with self._locked() as state:
|
|
330
|
+
call = state["calls"][ident]
|
|
331
|
+
if call["status"] != "reserved":
|
|
332
|
+
raise ValueError("request already settled")
|
|
333
|
+
actual = None if actual_cost is None else money(actual_cost)
|
|
334
|
+
call.update(metadata)
|
|
335
|
+
call.update(status="unknown" if actual is None else "settled",
|
|
336
|
+
cost_usd=None if actual is None else str(actual),
|
|
337
|
+
completed_at=time.time())
|
|
338
|
+
if halt_reason and not state.get("halted"):
|
|
339
|
+
state["halted"] = str(halt_reason)
|
|
340
|
+
if actual is not None and actual > money(call["reservation_usd"]):
|
|
341
|
+
state["halted"] = "provider charge exceeded the reserved request bound"
|
|
342
|
+
overrun = True
|
|
343
|
+
halted = state.get("halted")
|
|
344
|
+
if overrun:
|
|
345
|
+
raise CampaignStopped("provider charge exceeded the reserved request bound")
|
|
346
|
+
# An already-dispatched peer still settles its charge after a stop, but
|
|
347
|
+
# must not resume search as if the shared campaign remained healthy.
|
|
348
|
+
return halted
|
|
349
|
+
|
|
350
|
+
def snapshot(self):
|
|
351
|
+
with self._locked() as state:
|
|
352
|
+
known, held = self.totals(state)
|
|
353
|
+
return {"limit_usd": str(self.limit), "known_cost_usd": str(known),
|
|
354
|
+
"reserved_or_unknown_usd": str(held),
|
|
355
|
+
"remaining_usd": str(max(Decimal(0), self.limit - known - held)),
|
|
356
|
+
"calls": len(state["calls"]), "halted": state.get("halted")}
|
|
357
|
+
|
|
358
|
+
def resume_local_pause(self, expected_reason, *, resolution):
|
|
359
|
+
"""Resume an audited local research pause without forgiving any charge.
|
|
360
|
+
|
|
361
|
+
Provider failures, unknown outcomes and overruns are not resumable here.
|
|
362
|
+
A local pause may be resolved only after every dispatched call settles.
|
|
363
|
+
"""
|
|
364
|
+
prefix = "local research pause:"
|
|
365
|
+
if (not isinstance(expected_reason, str) or not expected_reason.startswith(prefix)
|
|
366
|
+
or not isinstance(resolution, str) or not resolution.strip()):
|
|
367
|
+
raise ValueError("need the exact local pause reason and its resolution")
|
|
368
|
+
with self._locked() as state:
|
|
369
|
+
if state.get("halted") != expected_reason:
|
|
370
|
+
raise CampaignStopped("the local pause reason changed; halt preserved")
|
|
371
|
+
if any(c.get("status") != "settled" or c.get("cost_usd") is None
|
|
372
|
+
or money(c["cost_usd"]) > money(c["reservation_usd"])
|
|
373
|
+
for c in state["calls"].values()):
|
|
374
|
+
raise CampaignStopped("unsettled, unknown or overrun charges; halt preserved")
|
|
375
|
+
known, held = self.totals(state)
|
|
376
|
+
if held or known > self.limit:
|
|
377
|
+
raise CampaignStopped("invalid accounting balance; halt preserved")
|
|
378
|
+
state.setdefault("local_pause_resolutions", []).append({
|
|
379
|
+
"reason": expected_reason, "resolution": resolution,
|
|
380
|
+
"resumed_at": time.time(), "known_cost_usd": str(known),
|
|
381
|
+
"limit_usd": str(self.limit)})
|
|
382
|
+
state["halted"] = None
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
class BudgetedLLM:
|
|
386
|
+
"""OpenRouter text calls with pinned price caps and no hidden client retries."""
|
|
387
|
+
def __init__(self, cfg, pricing, ledger, run_id, api_key, client=None):
|
|
388
|
+
self.prices = validate_llm_config(cfg, pricing)
|
|
389
|
+
self.models = list(cfg["models"])
|
|
390
|
+
from ..engine.llm.client import validate_model_capabilities
|
|
391
|
+
self.model_capabilities = validate_model_capabilities(cfg.get('model_capabilities', {}), self.models)
|
|
392
|
+
self.weights = list(cfg["weights"])
|
|
393
|
+
self.temperature = cfg.get("temperature", .7)
|
|
394
|
+
self.max_tokens = cfg["max_tokens"]
|
|
395
|
+
self.ledger, self.run_id = ledger, run_id
|
|
396
|
+
from openai import OpenAI
|
|
397
|
+
self.client = client if client is not None else OpenAI(
|
|
398
|
+
base_url=cfg["api_base"], api_key=api_key,
|
|
399
|
+
timeout=cfg.get("timeout", 120), max_retries=0)
|
|
400
|
+
|
|
401
|
+
def choose_model(self, rng):
|
|
402
|
+
return rng.choices(self.models, weights=self.weights, k=1)[0]
|
|
403
|
+
|
|
404
|
+
def generate(self, prompt, model, temperature=None, *, response_format=None, max_tokens=None):
|
|
405
|
+
from ..engine.llm.client import (LLMResponse, validate_response_format, _response_metadata,
|
|
406
|
+
COST_PROVENANCE_SCHEMA, validate_resolved_model)
|
|
407
|
+
output_tokens = self.max_tokens if max_tokens is None else max_tokens
|
|
408
|
+
if type(output_tokens) is not int or output_tokens <= 0:
|
|
409
|
+
raise ValueError('max_tokens must be a positive integer or null')
|
|
410
|
+
format_value = validate_response_format(response_format)
|
|
411
|
+
options = {} if format_value is None else {'response_format': format_value}
|
|
412
|
+
if model not in self.models:
|
|
413
|
+
raise ValueError("request model is outside the frozen ensemble")
|
|
414
|
+
temp = self.temperature if temperature is None else temperature
|
|
415
|
+
if (isinstance(temp, bool) or not isinstance(temp, (int, float))
|
|
416
|
+
or not math.isfinite(temp) or not 0 <= temp <= 2):
|
|
417
|
+
raise ValueError("invalid LLM temperature")
|
|
418
|
+
rates = self.prices[model]
|
|
419
|
+
pin, pout = money(rates["prompt"]), money(rates["completion"])
|
|
420
|
+
# UTF-8 bytes upper-bound text token count; leave ample message overhead.
|
|
421
|
+
# Output cap includes reasoning tokens; metadata must permit fixed effort none.
|
|
422
|
+
bound = request_cost_bound(prompt, output_tokens, rates, response_format=format_value)
|
|
423
|
+
request = dict(
|
|
424
|
+
model=model, messages=[{"role": "user", "content": prompt}],
|
|
425
|
+
temperature=temp,
|
|
426
|
+
max_tokens=output_tokens,
|
|
427
|
+
extra_body={"reasoning": {"effort": "none"}, "provider": {
|
|
428
|
+
"allow_fallbacks": False, "require_parameters": True,
|
|
429
|
+
"max_price": {"prompt": float(pin * 1_000_000),
|
|
430
|
+
"completion": float(pout * 1_000_000),
|
|
431
|
+
"request": float(money(rates.get("request", 0)))}}}, **options)
|
|
432
|
+
from ..engine.llm.client import temperature_parameters
|
|
433
|
+
if not temperature_parameters(self, model, temperature):
|
|
434
|
+
del request['temperature']
|
|
435
|
+
ident = self.ledger.reserve(bound, run_id=self.run_id, model=model)
|
|
436
|
+
try:
|
|
437
|
+
response = self.client.chat.completions.create(**request)
|
|
438
|
+
except Exception as exc:
|
|
439
|
+
halt_reason = "provider request outcome is unknown; reservation retained; campaign stopped"
|
|
440
|
+
halted = self.ledger.settle(ident, halt_reason=halt_reason,
|
|
441
|
+
**provider_error_metadata(exc, request=request))
|
|
442
|
+
raise CampaignStopped(halted) from None
|
|
443
|
+
usage = getattr(response, "usage", None)
|
|
444
|
+
raw_cost = getattr(usage, "cost", None)
|
|
445
|
+
try:
|
|
446
|
+
cost = None if raw_cost is None else money(raw_cost)
|
|
447
|
+
except (ValueError, ArithmeticError):
|
|
448
|
+
cost = None
|
|
449
|
+
pt, ct = getattr(usage, "prompt_tokens", 0) or 0, getattr(usage, "completion_tokens", 0) or 0
|
|
450
|
+
halt_reason = "provider did not return a usable actual charge; reservation retained"
|
|
451
|
+
halted = self.ledger.settle(ident, cost, halt_reason=halt_reason if cost is None else None,
|
|
452
|
+
generation_id=getattr(response, "id", None),
|
|
453
|
+
prompt_tokens=pt, completion_tokens=ct)
|
|
454
|
+
if halted:
|
|
455
|
+
raise CampaignStopped(halted) from None
|
|
456
|
+
choices = getattr(response, "choices", None) or []
|
|
457
|
+
text = (choices[0].message.content or "") if choices else ""
|
|
458
|
+
try:
|
|
459
|
+
resolved_model = validate_resolved_model(getattr(response, 'model', None))
|
|
460
|
+
except Exception:
|
|
461
|
+
resolved_model = None
|
|
462
|
+
return LLMResponse(text=text, model=model, cost=float(cost),
|
|
463
|
+
prompt_tokens=pt, completion_tokens=ct,
|
|
464
|
+
resolved_model=resolved_model,
|
|
465
|
+
cost_provenance=dict(schema=COST_PROVENANCE_SCHEMA,
|
|
466
|
+
source='provider_reported', reported_cost=float(cost)),
|
|
467
|
+
**(_response_metadata(choices[0]) if choices else {}))
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Content identity for experiments using versioned local tasks and model files."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import importlib.metadata
|
|
6
|
+
import json
|
|
7
|
+
import platform
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import subprocess
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def file_sha(path):
|
|
13
|
+
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def object_sha(value):
|
|
17
|
+
return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"),
|
|
18
|
+
allow_nan=False).encode()).hexdigest()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def safe_config(value):
|
|
22
|
+
if isinstance(value, dict):
|
|
23
|
+
hidden = {"api_key", "token", "password", "secret", "authorization"}
|
|
24
|
+
return {k: "<redacted>" if k.lower() in hidden else safe_config(v)
|
|
25
|
+
for k, v in value.items()}
|
|
26
|
+
if isinstance(value, list):
|
|
27
|
+
return [safe_config(v) for v in value]
|
|
28
|
+
return value
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def runtime_identity():
|
|
32
|
+
names = ("numpy", "scipy", "torch", "PyYAML", "openai", "tenacity",
|
|
33
|
+
"pydantic", "huggingface-hub")
|
|
34
|
+
deps = {}
|
|
35
|
+
for name in names:
|
|
36
|
+
try:
|
|
37
|
+
deps[name] = importlib.metadata.version(name)
|
|
38
|
+
except importlib.metadata.PackageNotFoundError:
|
|
39
|
+
deps[name] = None
|
|
40
|
+
return {"python": platform.python_version(), "implementation": platform.python_implementation(),
|
|
41
|
+
"platform": platform.platform(), "machine": platform.machine(),
|
|
42
|
+
"dependencies": deps}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _build_metadata(path):
|
|
46
|
+
return any(part == "__pycache__" or part.endswith((".egg-info", ".dist-info"))
|
|
47
|
+
for part in Path(path).parts[:-1])
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _tree_files(root, subtree, *, suffixes=None, exclude_build_metadata=False):
|
|
51
|
+
root = Path(root)
|
|
52
|
+
return {str(p.relative_to(root)) for p in (root / subtree).rglob("*")
|
|
53
|
+
if p.is_file() and "__pycache__" not in p.relative_to(root).parts
|
|
54
|
+
and (suffixes is None or p.suffix in suffixes)
|
|
55
|
+
and (not exclude_build_metadata or not _build_metadata(p.relative_to(root)))}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def source_identity(root):
|
|
59
|
+
root = Path(root).resolve()
|
|
60
|
+
files = {name: file_sha(root / name) for name in sorted(_tree_files(
|
|
61
|
+
root, "src", suffixes=(".py", ".txt"), exclude_build_metadata=True))}
|
|
62
|
+
project_files = {"pyproject.toml": file_sha(root / "pyproject.toml")}
|
|
63
|
+
revision = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True).strip()
|
|
64
|
+
paths = ("src", "tasks", "configs", "models", "pyproject.toml")
|
|
65
|
+
changed = subprocess.check_output(["git", "diff", "--name-only", "-z", "HEAD", "--", *paths],
|
|
66
|
+
cwd=root, text=True).split("\0")
|
|
67
|
+
untracked = subprocess.check_output(["git", "ls-files", "--others", "--exclude-standard", "-z", "--",
|
|
68
|
+
*paths], cwd=root, text=True).split("\0")
|
|
69
|
+
# Generated package metadata is neither source identity nor a reason to reject
|
|
70
|
+
# an otherwise clean checkout. This also covers unignored dist-info directories.
|
|
71
|
+
dirty = any(name and not (Path(name).parts[0] == "src" and _build_metadata(name))
|
|
72
|
+
for name in changed + untracked)
|
|
73
|
+
return {"revision": revision, "files": files, "source_sha256": object_sha(files),
|
|
74
|
+
"project_files": project_files, "dirty": dirty}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def task_identity(task):
|
|
78
|
+
root = Path(task.root).resolve()
|
|
79
|
+
paths = [root / name for name in ("task.yaml", "evaluator.py", "initial_program.py")]
|
|
80
|
+
if (root / "assets").exists():
|
|
81
|
+
paths += [p for p in sorted((root / "assets").rglob("*")) if p.is_file()]
|
|
82
|
+
return {"task": task.qualified_name, "task_hash": task.task_hash,
|
|
83
|
+
"files": {str(p.relative_to(root)): file_sha(p) for p in paths}}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def verify_files(root, files, *, exact_root=None, suffixes=None, exclude_build_metadata=False):
|
|
87
|
+
"""Check content and, for frozen trees, also reject newly added files."""
|
|
88
|
+
for name, expected in files.items():
|
|
89
|
+
path = Path(root) / name
|
|
90
|
+
if not path.is_file() or file_sha(path) != expected:
|
|
91
|
+
raise ValueError(f"experimental identity drift: {name}")
|
|
92
|
+
if exact_root is not None:
|
|
93
|
+
actual = _tree_files(root, exact_root, suffixes=suffixes,
|
|
94
|
+
exclude_build_metadata=exclude_build_metadata)
|
|
95
|
+
if actual != set(files):
|
|
96
|
+
changed = sorted(actual.symmetric_difference(files))
|
|
97
|
+
raise ValueError(f"experimental identity drift: file set changed: {changed}")
|