tempergraph 0.7.1__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.
- tempergraph/__init__.py +8 -0
- tempergraph/__main__.py +5 -0
- tempergraph/api.py +428 -0
- tempergraph/audit/__init__.py +305 -0
- tempergraph/audit/catalog.py +342 -0
- tempergraph/audit/definition.py +387 -0
- tempergraph/audit/history.py +414 -0
- tempergraph/audit/history_rules.py +268 -0
- tempergraph/audit/history_rules_more.py +244 -0
- tempergraph/audit/host.py +270 -0
- tempergraph/audit/owned.py +96 -0
- tempergraph/audit/prompts.py +89 -0
- tempergraph/audit/report.py +248 -0
- tempergraph/audit/revisit.py +220 -0
- tempergraph/audit/surface.py +224 -0
- tempergraph/audit/text_health.py +176 -0
- tempergraph/audit/tools.py +391 -0
- tempergraph/author/__init__.py +2 -0
- tempergraph/author/blueprint.py +346 -0
- tempergraph/author/compare.py +122 -0
- tempergraph/author/criteria_lint.py +200 -0
- tempergraph/author/draw.py +112 -0
- tempergraph/author/inventory.py +210 -0
- tempergraph/author/literals.py +138 -0
- tempergraph/author/scaffold.py +568 -0
- tempergraph/author/session.py +439 -0
- tempergraph/author/trial.py +391 -0
- tempergraph/author/verify.py +353 -0
- tempergraph/builtin/__init__.py +1 -0
- tempergraph/builtin/upgrade.py +288 -0
- tempergraph/catalog.py +134 -0
- tempergraph/check_helpers.py +99 -0
- tempergraph/cli/__init__.py +1 -0
- tempergraph/cli/audit.py +190 -0
- tempergraph/cli/author.py +361 -0
- tempergraph/cli/improve.py +564 -0
- tempergraph/cli/improve_review.py +111 -0
- tempergraph/cli/install.py +35 -0
- tempergraph/cli/main.py +1261 -0
- tempergraph/cli/observe_cli.py +544 -0
- tempergraph/cli/outcome.py +77 -0
- tempergraph/cli/schedule_cli.py +1090 -0
- tempergraph/cli/upgrade.py +126 -0
- tempergraph/cli/workflows.py +96 -0
- tempergraph/compiler/__init__.py +6 -0
- tempergraph/compiler/graph.py +305 -0
- tempergraph/compiler/state.py +229 -0
- tempergraph/constants.py +72 -0
- tempergraph/contracts.py +1025 -0
- tempergraph/data/executor_compat.json +11 -0
- tempergraph/data/promotion.json +35 -0
- tempergraph/data/release.json +20 -0
- tempergraph/detach.py +65 -0
- tempergraph/docs.py +90 -0
- tempergraph/durability/__init__.py +2 -0
- tempergraph/durability/alias.py +66 -0
- tempergraph/durability/carry.py +591 -0
- tempergraph/durability/checkpoint.py +179 -0
- tempergraph/durability/control.py +109 -0
- tempergraph/durability/engine_file.py +301 -0
- tempergraph/durability/lock.py +138 -0
- tempergraph/durability/status.py +390 -0
- tempergraph/engine_identity.py +42 -0
- tempergraph/executor_compat.py +56 -0
- tempergraph/executors/__init__.py +4 -0
- tempergraph/executors/binding.py +91 -0
- tempergraph/executors/capabilities.py +95 -0
- tempergraph/executors/claude.py +603 -0
- tempergraph/executors/launcher.py +394 -0
- tempergraph/executors/mcpconfig.py +156 -0
- tempergraph/executors/mcpproxy.py +216 -0
- tempergraph/executors/preflight.py +196 -0
- tempergraph/executors/registry.py +71 -0
- tempergraph/executors/scripted.py +18 -0
- tempergraph/executors/session.py +107 -0
- tempergraph/executors/standins.py +118 -0
- tempergraph/executors/summary.py +110 -0
- tempergraph/executors/viewcatalog.py +27 -0
- tempergraph/git.py +403 -0
- tempergraph/identity.py +65 -0
- tempergraph/improve/__init__.py +5 -0
- tempergraph/improve/analysis.py +437 -0
- tempergraph/improve/artifact.py +477 -0
- tempergraph/improve/autonomy.py +192 -0
- tempergraph/improve/bindings.py +191 -0
- tempergraph/improve/calibration.py +1016 -0
- tempergraph/improve/causes.py +416 -0
- tempergraph/improve/child.py +651 -0
- tempergraph/improve/codehost.py +520 -0
- tempergraph/improve/digest.py +472 -0
- tempergraph/improve/escape.py +100 -0
- tempergraph/improve/filing.py +1047 -0
- tempergraph/improve/harvest.py +158 -0
- tempergraph/improve/issue_context.py +192 -0
- tempergraph/improve/lenses.py +204 -0
- tempergraph/improve/lessons.py +233 -0
- tempergraph/improve/loop_report.py +138 -0
- tempergraph/improve/loop_summary.py +85 -0
- tempergraph/improve/lost.py +119 -0
- tempergraph/improve/measure.py +121 -0
- tempergraph/improve/params.py +98 -0
- tempergraph/improve/pause_facts.py +134 -0
- tempergraph/improve/pr_later.py +186 -0
- tempergraph/improve/prebinding.py +130 -0
- tempergraph/improve/promotion.py +413 -0
- tempergraph/improve/proposals.py +934 -0
- tempergraph/improve/record.py +322 -0
- tempergraph/improve/release.py +89 -0
- tempergraph/improve/reliability.py +457 -0
- tempergraph/improve/repeat.py +115 -0
- tempergraph/improve/review.py +910 -0
- tempergraph/improve/suites.py +586 -0
- tempergraph/improve/trials.py +525 -0
- tempergraph/install/__init__.py +11 -0
- tempergraph/install/bootstrap.py +133 -0
- tempergraph/install/environment.py +173 -0
- tempergraph/install/launch.py +37 -0
- tempergraph/install/python.py +53 -0
- tempergraph/install/reconcile.py +52 -0
- tempergraph/install/selfcheck.py +29 -0
- tempergraph/install/shim.py +81 -0
- tempergraph/install/update.py +400 -0
- tempergraph/model/__init__.py +0 -0
- tempergraph/model/diagram.py +185 -0
- tempergraph/model/flow.py +324 -0
- tempergraph/model/prompt_lint.py +203 -0
- tempergraph/model/retire.py +52 -0
- tempergraph/model/subworkflow.py +274 -0
- tempergraph/model/text.py +67 -0
- tempergraph/model/validate.py +1158 -0
- tempergraph/observe/__init__.py +1 -0
- tempergraph/observe/attention.py +196 -0
- tempergraph/observe/detail.py +773 -0
- tempergraph/observe/forget.py +138 -0
- tempergraph/observe/hooks.py +272 -0
- tempergraph/observe/labels.py +95 -0
- tempergraph/observe/overlay.py +46 -0
- tempergraph/observe/report.py +402 -0
- tempergraph/observe/risk_report.py +110 -0
- tempergraph/observe/rows.py +444 -0
- tempergraph/observe/sinks.py +793 -0
- tempergraph/observe/supervision_cost.py +797 -0
- tempergraph/observe/supervision_report.py +295 -0
- tempergraph/observe/switch_report.py +140 -0
- tempergraph/package/__init__.py +2 -0
- tempergraph/package/change_report.py +116 -0
- tempergraph/package/changelog.py +263 -0
- tempergraph/package/docs_check.py +115 -0
- tempergraph/package/importer.py +90 -0
- tempergraph/package/inventory.py +111 -0
- tempergraph/package/loader.py +250 -0
- tempergraph/package/manifest.py +256 -0
- tempergraph/package/readiness.py +124 -0
- tempergraph/package/registry.py +383 -0
- tempergraph/package/rules.py +128 -0
- tempergraph/package/scan.py +65 -0
- tempergraph/package/selftest.py +348 -0
- tempergraph/package/stamp.py +213 -0
- tempergraph/package/transforms.py +481 -0
- tempergraph/package/upgrade.py +625 -0
- tempergraph/provenance.py +183 -0
- tempergraph/py.typed +0 -0
- tempergraph/release.py +17 -0
- tempergraph/render/__init__.py +0 -0
- tempergraph/render/output.py +72 -0
- tempergraph/render/prompt.py +166 -0
- tempergraph/render/template.py +86 -0
- tempergraph/run/__init__.py +2 -0
- tempergraph/run/asking.py +233 -0
- tempergraph/run/audit.py +63 -0
- tempergraph/run/check_worker.py +167 -0
- tempergraph/run/checks.py +517 -0
- tempergraph/run/commands.py +210 -0
- tempergraph/run/complexity.py +268 -0
- tempergraph/run/contest.py +76 -0
- tempergraph/run/council.py +368 -0
- tempergraph/run/council_run.py +527 -0
- tempergraph/run/events.py +279 -0
- tempergraph/run/finalize.py +132 -0
- tempergraph/run/gate.py +747 -0
- tempergraph/run/guard.py +89 -0
- tempergraph/run/judging.py +357 -0
- tempergraph/run/ladder.py +230 -0
- tempergraph/run/log.py +600 -0
- tempergraph/run/mapping.py +183 -0
- tempergraph/run/nodes.py +2304 -0
- tempergraph/run/outcome.py +255 -0
- tempergraph/run/outcome_record.py +292 -0
- tempergraph/run/outcome_trust.py +99 -0
- tempergraph/run/rerun.py +351 -0
- tempergraph/run/reserve.py +85 -0
- tempergraph/run/resources.py +76 -0
- tempergraph/run/risk.py +231 -0
- tempergraph/run/runner.py +1579 -0
- tempergraph/run/scriptcache.py +178 -0
- tempergraph/run/selfcheck.py +105 -0
- tempergraph/run/session_record.py +72 -0
- tempergraph/run/subrun.py +278 -0
- tempergraph/run/supervision.py +125 -0
- tempergraph/run/tool_access.py +101 -0
- tempergraph/schedule/__init__.py +25 -0
- tempergraph/schedule/credentials.py +167 -0
- tempergraph/schedule/echo.py +169 -0
- tempergraph/schedule/exact.py +275 -0
- tempergraph/schedule/export.py +164 -0
- tempergraph/schedule/launch.py +89 -0
- tempergraph/schedule/ledger.py +133 -0
- tempergraph/schedule/loop.py +176 -0
- tempergraph/schedule/model.py +440 -0
- tempergraph/schedule/policies.py +414 -0
- tempergraph/schedule/store.py +150 -0
- tempergraph/schedule/tick.py +377 -0
- tempergraph/schedule/token.py +81 -0
- tempergraph/schedule/triggers.py +210 -0
- tempergraph/schedule/words.py +423 -0
- tempergraph/security/__init__.py +0 -0
- tempergraph/security/launch.py +25 -0
- tempergraph/security/scrub.py +58 -0
- tempergraph/settings.py +950 -0
- tempergraph/store/__init__.py +0 -0
- tempergraph/store/codelog.py +73 -0
- tempergraph/store/layout.py +198 -0
- tempergraph/store/logs.py +325 -0
- tempergraph/store/manifest.py +99 -0
- tempergraph/store/migrate.py +188 -0
- tempergraph/workspace.py +874 -0
- tempergraph-0.7.1.dist-info/METADATA +70 -0
- tempergraph-0.7.1.dist-info/RECORD +232 -0
- tempergraph-0.7.1.dist-info/WHEEL +5 -0
- tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
- tempergraph-0.7.1.dist-info/top_level.txt +2 -0
- tempergraph_pytest_plugin.py +64 -0
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""Command resolution and the workflow command runner (CHK-B11, CHK-B12, CHK-B13; SEC-B7 "Workflow command runner").
|
|
2
|
+
|
|
3
|
+
A command reaches a process only as list argv resolved against the workflow's allow-list, with standard
|
|
4
|
+
input closed, output to a file, credentials removed from the environment and the process tree ended at
|
|
5
|
+
its limit.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import signal
|
|
15
|
+
import subprocess
|
|
16
|
+
import time
|
|
17
|
+
from collections.abc import Mapping, Sequence
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from tempergraph.security.launch import has_shell_metacharacter
|
|
22
|
+
from tempergraph.security.scrub import head_tail, scrub
|
|
23
|
+
|
|
24
|
+
CREDENTIAL_VARS = re.compile(r"(TOKEN|SECRET|PASSWORD|API_KEY|CREDENTIAL|_AUTH)", re.I)
|
|
25
|
+
TAIL_LINES = 40
|
|
26
|
+
TAIL_CHARS = 8000
|
|
27
|
+
_CD_RE = re.compile(r"^cd\s+([A-Za-z0-9_./-]+)\s*&&\s*(.+)$")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
REPOSITORY = "@repository" # in an allow-list or a step's commands: the commands the repository declares
|
|
31
|
+
REPO_FILE = "tempergraph.commands.json"
|
|
32
|
+
REPO_COMMANDS_MAX = 50
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _plain(text: str) -> bool:
|
|
36
|
+
words = text.split()
|
|
37
|
+
return bool(words) and not has_shell_metacharacter(text) and not any(
|
|
38
|
+
w.startswith("/") or ".." in w.split("/") for w in words)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def repository_commands(workdir: Path) -> list[str]:
|
|
42
|
+
"""CHK-B11: the command prefixes a repository declares in `tempergraph.commands.json` at its root, as a
|
|
43
|
+
list or as a map of names to commands. An entry that is not plain words is dropped, never run."""
|
|
44
|
+
try:
|
|
45
|
+
doc = json.loads((workdir / REPO_FILE).read_text(encoding="utf-8"))
|
|
46
|
+
except (OSError, ValueError):
|
|
47
|
+
return []
|
|
48
|
+
got = doc.get("commands") if isinstance(doc, dict) and doc.get("schema_version") == 1 else None
|
|
49
|
+
items = list(got.values()) if isinstance(got, dict) else got if isinstance(got, list) else []
|
|
50
|
+
out = [" ".join(c.split()) for c in items if isinstance(c, str) and _plain(c)]
|
|
51
|
+
return list(dict.fromkeys(out))[:REPO_COMMANDS_MAX]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def expand(commands: Sequence[str], workdir: Path) -> tuple[str, ...]:
|
|
55
|
+
"""A step's commands with `@repository` replaced by what the repository declares."""
|
|
56
|
+
out: list[str] = []
|
|
57
|
+
for c in commands:
|
|
58
|
+
out.extend(repository_commands(workdir) if c == REPOSITORY else [c])
|
|
59
|
+
return tuple(dict.fromkeys(out))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True, kw_only=True)
|
|
63
|
+
class ResolvedCommand:
|
|
64
|
+
argv: tuple[str, ...]
|
|
65
|
+
prefix: str
|
|
66
|
+
cwd: str | None = None
|
|
67
|
+
documented: bool = False
|
|
68
|
+
resolver: str = "allow_list"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True, kw_only=True)
|
|
72
|
+
class CommandRefusal:
|
|
73
|
+
reason: str
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(kw_only=True)
|
|
77
|
+
class CommandRun:
|
|
78
|
+
argv: tuple[str, ...]
|
|
79
|
+
program_path: str = ""
|
|
80
|
+
exit_code: int | None = None
|
|
81
|
+
finished: bool = False
|
|
82
|
+
timed_out: bool = False
|
|
83
|
+
not_started: bool = False
|
|
84
|
+
reused: bool = False
|
|
85
|
+
at_base: bool = False # CHK-B18: run in a checkout of the run's base commit
|
|
86
|
+
duration_s: float = 0.0
|
|
87
|
+
output_path: str = ""
|
|
88
|
+
tail: str = ""
|
|
89
|
+
extra: dict[str, object] = field(default_factory=dict)
|
|
90
|
+
python_path: list[str] = field(default_factory=list) # CRE-B5: the workspace folders first on PYTHONPATH
|
|
91
|
+
outcome: str = "" # KIL-B2: `killed` at the limit, `finished` otherwise, empty for a run that did not start
|
|
92
|
+
limit_s: float | None = None # KIL-B2: the seconds the command was given
|
|
93
|
+
prefix: str = "" # KIL-B2: the declared prefix the command was resolved under
|
|
94
|
+
cwd: str | None = None # KIL-B2: the command's folder, None for none
|
|
95
|
+
|
|
96
|
+
def to_json(self) -> dict[str, object]:
|
|
97
|
+
return {"argv": list(self.argv), "program_path": self.program_path, "exit_code": self.exit_code,
|
|
98
|
+
"finished": self.finished, "timed_out": self.timed_out, "not_started": self.not_started,
|
|
99
|
+
"reused": self.reused, "at_base": self.at_base, "duration_s": round(self.duration_s, 3), "output_path": self.output_path,
|
|
100
|
+
"tail": self.tail, "python_path": list(self.python_path), "outcome": self.outcome,
|
|
101
|
+
"limit_s": self.limit_s, "prefix": self.prefix, "cwd": self.cwd}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def python_path_outside(python_path: object, workdir: Path, exists: bool = True) -> bool:
|
|
105
|
+
"""CRE-B4: True unless `python_path` is a list of relative folders that exist inside `workdir`; with `exists`
|
|
106
|
+
False a folder need not exist, for a run at the base, whose folders are checked in the base checkout."""
|
|
107
|
+
if not isinstance(python_path, (list, tuple)):
|
|
108
|
+
return True
|
|
109
|
+
root = workdir.resolve()
|
|
110
|
+
for p in python_path:
|
|
111
|
+
if not isinstance(p, str) or not p or p.startswith("/") or Path(p).is_absolute() \
|
|
112
|
+
or ".." in Path(p).parts:
|
|
113
|
+
return True
|
|
114
|
+
target = (workdir / p).resolve()
|
|
115
|
+
if (exists and not target.is_dir()) or not target.is_relative_to(root):
|
|
116
|
+
return True
|
|
117
|
+
return False
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def python_path_value(python_path: Sequence[str], workdir: Path, existing: str | None) -> str:
|
|
121
|
+
"""CRE-B3: the absolute folders in order, then the engine environment's own `PYTHONPATH` entries."""
|
|
122
|
+
parts = [str(workdir.resolve() / p) for p in python_path]
|
|
123
|
+
if existing:
|
|
124
|
+
parts.append(existing)
|
|
125
|
+
return os.pathsep.join(parts)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def resolve_command(allow: Sequence[str], text: str, workdir: Path) -> ResolvedCommand | CommandRefusal:
|
|
129
|
+
"""CHK-B11 without a custom resolver: a declared prefix with plain-word arguments."""
|
|
130
|
+
text = text.strip()
|
|
131
|
+
cwd = None
|
|
132
|
+
m = _CD_RE.match(text)
|
|
133
|
+
if m:
|
|
134
|
+
folder, text = m.group(1), m.group(2).strip()
|
|
135
|
+
target = (workdir / folder).resolve()
|
|
136
|
+
if folder.startswith("/") or ".." in Path(folder).parts or not target.is_relative_to(workdir.resolve()):
|
|
137
|
+
return CommandRefusal(reason="change of directory outside the repository")
|
|
138
|
+
cwd = folder
|
|
139
|
+
if has_shell_metacharacter(text):
|
|
140
|
+
return CommandRefusal(reason="shell metacharacter")
|
|
141
|
+
words = text.split()
|
|
142
|
+
if not words:
|
|
143
|
+
return CommandRefusal(reason="empty")
|
|
144
|
+
if any(w.startswith("/") or ".." in w.split("/") for w in words):
|
|
145
|
+
return CommandRefusal(reason="absolute or parent path")
|
|
146
|
+
for prefix in sorted((a for a in allow if a != REPOSITORY), key=len, reverse=True):
|
|
147
|
+
if text == prefix or text.startswith(prefix + " "):
|
|
148
|
+
return ResolvedCommand(argv=tuple(words), prefix=prefix, cwd=cwd)
|
|
149
|
+
if REPOSITORY in allow: # documented by the repository itself (CHK-B11)
|
|
150
|
+
for prefix in sorted(repository_commands(workdir), key=len, reverse=True):
|
|
151
|
+
if text == prefix or text.startswith(prefix + " "):
|
|
152
|
+
return ResolvedCommand(argv=tuple(words), prefix=prefix, cwd=cwd, documented=True,
|
|
153
|
+
resolver="repository")
|
|
154
|
+
return CommandRefusal(reason="not declared")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def command_env(base: dict[str, str] | None = None) -> dict[str, str]:
|
|
158
|
+
env = {k: v for k, v in (os.environ if base is None else base).items() if not CREDENTIAL_VARS.search(k)}
|
|
159
|
+
env["GIT_TERMINAL_PROMPT"] = "0"
|
|
160
|
+
env["GH_PROMPT_DISABLED"] = "1"
|
|
161
|
+
return env
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _placeholders(text: str, workdir: Path, main: Path | None) -> str:
|
|
165
|
+
for path, word in ((workdir, "<workdir>"), (main, "<main>"), (Path.home(), "<home>")):
|
|
166
|
+
if path is not None:
|
|
167
|
+
text = text.replace(str(path), word)
|
|
168
|
+
return text
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def run_command(cmd: ResolvedCommand, workdir: Path, out_path: Path, timeout_s: float, *,
|
|
172
|
+
main: Path | None = None, finished_codes: Sequence[int] | None = None,
|
|
173
|
+
env_extra: Mapping[str, str] | None = None, python_path: Sequence[str] = ()) -> CommandRun:
|
|
174
|
+
out_path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
175
|
+
cwd = workdir / cmd.cwd if cmd.cwd else workdir
|
|
176
|
+
t0 = time.monotonic()
|
|
177
|
+
run = CommandRun(argv=tuple(scrub(a) for a in cmd.argv), output_path=str(out_path),
|
|
178
|
+
python_path=list(python_path), limit_s=max(0.1, timeout_s), prefix=cmd.prefix, cwd=cmd.cwd)
|
|
179
|
+
env = {**command_env(), **(env_extra or {})}
|
|
180
|
+
if python_path:
|
|
181
|
+
env["PYTHONPATH"] = python_path_value(python_path, workdir, env.get("PYTHONPATH"))
|
|
182
|
+
with open(out_path, "wb") as fh:
|
|
183
|
+
try:
|
|
184
|
+
proc = subprocess.Popen( # noqa: S603 - resolved list argv (CHK-B12, CHK-B13)
|
|
185
|
+
list(cmd.argv), cwd=cwd, stdin=subprocess.DEVNULL, stdout=fh, stderr=subprocess.STDOUT,
|
|
186
|
+
env=env, start_new_session=(os.name == "posix"))
|
|
187
|
+
except OSError as exc:
|
|
188
|
+
run.extra["error"] = type(exc).__name__
|
|
189
|
+
run.duration_s = time.monotonic() - t0
|
|
190
|
+
return run
|
|
191
|
+
try:
|
|
192
|
+
proc.wait(timeout=max(0.1, timeout_s))
|
|
193
|
+
except subprocess.TimeoutExpired:
|
|
194
|
+
run.timed_out = True
|
|
195
|
+
if os.name == "posix":
|
|
196
|
+
with contextlib.suppress(ProcessLookupError, PermissionError):
|
|
197
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
198
|
+
else:
|
|
199
|
+
proc.kill()
|
|
200
|
+
proc.wait()
|
|
201
|
+
os.chmod(out_path, 0o600)
|
|
202
|
+
run.duration_s = time.monotonic() - t0
|
|
203
|
+
run.exit_code = proc.returncode
|
|
204
|
+
run.outcome = "killed" if run.timed_out else "finished"
|
|
205
|
+
normal = proc.returncode is not None and proc.returncode >= 0 and not run.timed_out
|
|
206
|
+
run.finished = normal and (finished_codes is None or proc.returncode in finished_codes)
|
|
207
|
+
text = out_path.read_text(encoding="utf-8", errors="replace")
|
|
208
|
+
tail = "\n".join(text.splitlines()[-TAIL_LINES:])
|
|
209
|
+
run.tail = head_tail(_placeholders(scrub(tail), workdir, main), TAIL_CHARS)
|
|
210
|
+
return run
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""Complexity switches: measures, the rules file and zones (CXR-B9, CXR-B12, CXR-B5). Model-free.
|
|
2
|
+
|
|
3
|
+
The switch's own step node evaluates once per run and keeps the result on its attempt record; the gate's pick
|
|
4
|
+
reads it there, so the gate stays a pure function of state.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import concurrent.futures
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
from collections.abc import Mapping
|
|
14
|
+
from datetime import UTC, datetime, timedelta
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from tempergraph.contracts import ComplexitySpec, MeasureContext, MeasureSpec, SwitchSpec, WorkflowSpec
|
|
19
|
+
|
|
20
|
+
STOCK_ARITY = {"fact": 2, "input": 1, "setting": 1, "count_items": 2, "count_lines": 3, "changed_paths": 0}
|
|
21
|
+
MEASURE_TIMEOUT_S = 1.0
|
|
22
|
+
EXPLORE_MAX_RATE, EXPLORE_MAX_PER_WEEK = 0.25, 5
|
|
23
|
+
NO_EXPLORE_ORIGINS = frozenset({"schedule", "trial"})
|
|
24
|
+
FAULT = "fault"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class MeasureFault(Exception):
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def default_rules_path(switch: str) -> str:
|
|
32
|
+
return f"routing/{switch}.json"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def override_path(state_root: Path, workflow: str, switch: str) -> Path:
|
|
36
|
+
"""A repository's whole-file override of a switch's rules (CXR-B10, CXR-B1)."""
|
|
37
|
+
return state_root / "routing" / workflow / f"{switch}.json"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def check_rules(rules: Any, sw: SwitchSpec) -> list[str]:
|
|
41
|
+
"""Why a rules document cannot be used: the schema, an undeclared arm or measure, a bound of no kind."""
|
|
42
|
+
comp = sw.complexity
|
|
43
|
+
assert comp is not None
|
|
44
|
+
names = {m.name for m in comp.measures}
|
|
45
|
+
arms = list(sw.arms)
|
|
46
|
+
out: list[str] = []
|
|
47
|
+
if not isinstance(rules, Mapping) or rules.get("schema_version") != 1:
|
|
48
|
+
return ["not a schema_version 1 object"]
|
|
49
|
+
by_arm = rules.get("arms")
|
|
50
|
+
if not isinstance(by_arm, Mapping) or not by_arm:
|
|
51
|
+
return ["`arms` is missing"]
|
|
52
|
+
for arm, body in by_arm.items():
|
|
53
|
+
if arm not in arms:
|
|
54
|
+
out.append(f"arm {arm!r} is not declared")
|
|
55
|
+
continue
|
|
56
|
+
if arm == arms[-1]:
|
|
57
|
+
out.append(f"the safe arm {arm!r} takes no bounds")
|
|
58
|
+
when = body.get("when") if isinstance(body, Mapping) else None
|
|
59
|
+
if not isinstance(when, Mapping) or not when:
|
|
60
|
+
out.append(f"arm {arm!r} needs `when`")
|
|
61
|
+
continue
|
|
62
|
+
for measure, bound in when.items():
|
|
63
|
+
if measure not in names:
|
|
64
|
+
out.append(f"measure {measure!r} is not declared")
|
|
65
|
+
if not isinstance(bound, Mapping) or not set(bound) or set(bound) - {"max", "min", "in"}:
|
|
66
|
+
out.append(f"bound of {arm}.{measure} takes max, min or in")
|
|
67
|
+
margin = rules.get("margin") or {}
|
|
68
|
+
if not isinstance(margin, Mapping):
|
|
69
|
+
return out + ["`margin` is not an object"]
|
|
70
|
+
for measure, band in margin.items():
|
|
71
|
+
if measure not in names:
|
|
72
|
+
out.append(f"margin measure {measure!r} is not declared")
|
|
73
|
+
if not (isinstance(band, Mapping) and _num(band.get("from")) is not None and _num(band.get("to")) is not None):
|
|
74
|
+
out.append(f"margin of {measure} needs numbers `from` and `to`")
|
|
75
|
+
return out
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def load_rules(spec: WorkflowSpec, switch: str, state_root: Path | None) -> dict[str, Any]:
|
|
79
|
+
"""The rules in force: the repository's override when present, else the package's. Returns
|
|
80
|
+
`{rules, digest, source, error}`; `rules` is None on any error (zone `fault` at run time)."""
|
|
81
|
+
sw = spec.units[switch].switch
|
|
82
|
+
assert sw is not None and sw.complexity is not None
|
|
83
|
+
path: Path | None = None
|
|
84
|
+
source = "package"
|
|
85
|
+
if state_root is not None and override_path(state_root, spec.name, switch).is_file():
|
|
86
|
+
path, source = override_path(state_root, spec.name, switch), "repository"
|
|
87
|
+
elif spec.package_root is not None:
|
|
88
|
+
path = spec.package_root / (sw.complexity.rules or default_rules_path(switch))
|
|
89
|
+
if path is None or not path.is_file():
|
|
90
|
+
return {"rules": None, "digest": None, "source": source, "error": "the rules file is missing"}
|
|
91
|
+
raw = path.read_bytes()
|
|
92
|
+
digest = hashlib.sha256(raw).hexdigest()[:16]
|
|
93
|
+
try:
|
|
94
|
+
rules = json.loads(raw.decode("utf-8"))
|
|
95
|
+
except ValueError:
|
|
96
|
+
return {"rules": None, "digest": digest, "source": source, "error": "the rules file is not JSON"}
|
|
97
|
+
problems = check_rules(rules, sw)
|
|
98
|
+
if problems:
|
|
99
|
+
return {"rules": None, "digest": digest, "source": source, "error": "; ".join(problems)}
|
|
100
|
+
return {"rules": rules, "digest": digest, "source": source, "error": None}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _num(v: Any) -> float | None:
|
|
104
|
+
if isinstance(v, bool):
|
|
105
|
+
return None
|
|
106
|
+
if isinstance(v, (int, float)):
|
|
107
|
+
return float(v)
|
|
108
|
+
if isinstance(v, str):
|
|
109
|
+
try:
|
|
110
|
+
return float(v.strip())
|
|
111
|
+
except ValueError:
|
|
112
|
+
return None
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _shown(v: Any) -> Any:
|
|
117
|
+
n = _num(v)
|
|
118
|
+
if n is None:
|
|
119
|
+
return str(v)[:60]
|
|
120
|
+
return int(n) if n.is_integer() else n
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _stock(m: MeasureSpec, mctx: MeasureContext, spec: WorkflowSpec, state: Mapping[str, Any]) -> Any:
|
|
124
|
+
kind, args = m.stock[0], m.stock[1:]
|
|
125
|
+
if kind == "fact":
|
|
126
|
+
v = (mctx.facts.get(args[0]) or {}).get(args[1])
|
|
127
|
+
if v is None:
|
|
128
|
+
raise MeasureFault(f"no fact {args[0]}.{args[1]}")
|
|
129
|
+
return v
|
|
130
|
+
if kind == "input":
|
|
131
|
+
v = (mctx.request.get("inputs") or {}).get(args[0])
|
|
132
|
+
if v is None:
|
|
133
|
+
raise MeasureFault(f"no input {args[0]}")
|
|
134
|
+
return v
|
|
135
|
+
if kind == "setting":
|
|
136
|
+
if args[0] not in mctx.settings:
|
|
137
|
+
raise MeasureFault(f"no setting {args[0]}")
|
|
138
|
+
return mctx.settings[args[0]]
|
|
139
|
+
if kind == "changed_paths":
|
|
140
|
+
return len(tuple(getattr(mctx.git, "changed_paths", ()) or ()))
|
|
141
|
+
pointer = (mctx.artifacts.get(args[0]) or {}).get(args[1])
|
|
142
|
+
if not pointer:
|
|
143
|
+
raise MeasureFault(f"no artifact {args[0]}.{args[1]}")
|
|
144
|
+
if kind == "count_lines":
|
|
145
|
+
pattern = re.compile(args[2])
|
|
146
|
+
return sum(1 for ln in mctx.read_text(str(pointer)).splitlines() if pattern.search(ln))
|
|
147
|
+
if kind == "count_items":
|
|
148
|
+
from tempergraph.run import mapping
|
|
149
|
+
|
|
150
|
+
for name, u in spec.units.items():
|
|
151
|
+
if u.map is not None and tuple(u.map.items_from) == (args[0], args[1]):
|
|
152
|
+
try:
|
|
153
|
+
return len(mapping.read_items(spec, name, state, mctx.workdir))
|
|
154
|
+
except mapping.MapFault as exc:
|
|
155
|
+
if exc.code == "map_empty":
|
|
156
|
+
return 0
|
|
157
|
+
raise MeasureFault(str(exc)) from None
|
|
158
|
+
got = json.loads(mctx.read_text(str(pointer)))
|
|
159
|
+
if not isinstance(got, list):
|
|
160
|
+
raise MeasureFault("not a list")
|
|
161
|
+
return len(got)
|
|
162
|
+
raise MeasureFault(f"unknown stock measure {kind}")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def measure(m: MeasureSpec, mctx: MeasureContext, spec: WorkflowSpec, state: Mapping[str, Any]) -> Any:
|
|
166
|
+
"""One measure's value, or `FAULT` when it raises, runs over a second or returns another type (CXR-B9)."""
|
|
167
|
+
def run() -> Any:
|
|
168
|
+
if m.call is not None:
|
|
169
|
+
return m.call.resolve()(mctx)
|
|
170
|
+
return _stock(m, mctx, spec, state)
|
|
171
|
+
|
|
172
|
+
pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
|
173
|
+
try:
|
|
174
|
+
got = pool.submit(run).result(timeout=MEASURE_TIMEOUT_S)
|
|
175
|
+
except Exception: # noqa: BLE001 - any raise, and a timeout, is a fault
|
|
176
|
+
return FAULT
|
|
177
|
+
finally:
|
|
178
|
+
pool.shutdown(wait=False)
|
|
179
|
+
if isinstance(got, bool) or not isinstance(got, (int, float, str)):
|
|
180
|
+
return FAULT
|
|
181
|
+
return _shown(got)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _holds(value: Any, bound: Mapping[str, Any]) -> bool:
|
|
185
|
+
n = _num(value)
|
|
186
|
+
if "in" in bound and str(value) not in [str(x) for x in bound["in"]] and value not in list(bound["in"]):
|
|
187
|
+
return False
|
|
188
|
+
if "max" in bound and (n is None or n > float(bound["max"])):
|
|
189
|
+
return False
|
|
190
|
+
return not ("min" in bound and (n is None or n < float(bound["min"])))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _in_band(value: Any, band: Mapping[str, Any]) -> bool:
|
|
194
|
+
n = _num(value)
|
|
195
|
+
return n is not None and float(band["from"]) <= n <= float(band["to"])
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def explores(comp: ComplexitySpec, thread: str, switch: str, stage: str, origin: str, explored_recent: int) -> bool:
|
|
199
|
+
"""CXR-B12, CXR-B5: a deterministic draw on the thread, a weekly limit, and never in a pipeline, a scheduled
|
|
200
|
+
fire or a trial."""
|
|
201
|
+
ex = comp.explore
|
|
202
|
+
if not ex or stage == "pipeline" or origin in NO_EXPLORE_ORIGINS:
|
|
203
|
+
return False
|
|
204
|
+
rate = min(float(ex.get("rate") or 0), EXPLORE_MAX_RATE)
|
|
205
|
+
per_week = min(int(ex.get("per_week") or 0), EXPLORE_MAX_PER_WEEK)
|
|
206
|
+
draw = int(hashlib.sha256(f"{thread}\0{switch}".encode()).hexdigest(), 16) % 1000
|
|
207
|
+
return draw < rate * 1000 and explored_recent < per_week
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def explored_recent(state_root: Path, workflow: str, switch: str, now: datetime | None = None) -> int:
|
|
211
|
+
"""Explored runs of the workflow that started in the last 7 days, read from the run logs."""
|
|
212
|
+
since = (now or datetime.now(UTC)) - timedelta(days=7)
|
|
213
|
+
n = 0
|
|
214
|
+
for log in (state_root / "runs" / workflow).glob("*/run.jsonl"):
|
|
215
|
+
try:
|
|
216
|
+
lines = log.read_text(encoding="utf-8").splitlines()
|
|
217
|
+
except OSError:
|
|
218
|
+
continue
|
|
219
|
+
for ln in lines:
|
|
220
|
+
if '"explore"' not in ln:
|
|
221
|
+
continue
|
|
222
|
+
try:
|
|
223
|
+
r = json.loads(ln)
|
|
224
|
+
at = datetime.fromisoformat(str(r.get("ts")).replace("Z", "+00:00"))
|
|
225
|
+
except ValueError:
|
|
226
|
+
continue
|
|
227
|
+
if r.get("kind") == "route" and r.get("unit") == switch and r.get("zone") == "explore" and at >= since:
|
|
228
|
+
n += 1
|
|
229
|
+
break
|
|
230
|
+
return n
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def evaluate(spec: WorkflowSpec, switch: str, state: Mapping[str, Any], mctx: MeasureContext, *,
|
|
234
|
+
state_root: Path | None, thread: str, origin: str = "cli", recent: int = 0) -> dict[str, Any]:
|
|
235
|
+
"""The zone and the arm it gives (CXR-B10, CXR-B1), with every measure's value, for the `route` record."""
|
|
236
|
+
sw = spec.units[switch].switch
|
|
237
|
+
assert sw is not None and sw.complexity is not None
|
|
238
|
+
comp = sw.complexity
|
|
239
|
+
arms = list(sw.arms)
|
|
240
|
+
safe = arms[-1]
|
|
241
|
+
loaded = load_rules(spec, switch, state_root)
|
|
242
|
+
values = {m.name: measure(m, mctx, spec, state) for m in comp.measures}
|
|
243
|
+
out: dict[str, Any] = {"measures": values, "rules_digest": loaded["digest"], "rules_source": loaded["source"]}
|
|
244
|
+
rules = loaded["rules"]
|
|
245
|
+
if rules is None or FAULT in values.values():
|
|
246
|
+
if loaded["error"]:
|
|
247
|
+
out["rules_error"] = loaded["error"]
|
|
248
|
+
return {**out, "zone": "fault", "arm": safe}
|
|
249
|
+
margin = rules.get("margin") or {}
|
|
250
|
+
in_margin = {name for name, band in margin.items() if _in_band(values.get(name), band)}
|
|
251
|
+
|
|
252
|
+
def eligible(lenient: bool) -> str | None:
|
|
253
|
+
for arm in arms[:-1]:
|
|
254
|
+
when = (rules["arms"].get(arm) or {}).get("when")
|
|
255
|
+
if when and all((lenient and name in in_margin) or _holds(values.get(name), bound)
|
|
256
|
+
for name, bound in when.items()):
|
|
257
|
+
return arm
|
|
258
|
+
return None
|
|
259
|
+
|
|
260
|
+
if in_margin:
|
|
261
|
+
arm = eligible(lenient=True)
|
|
262
|
+
if arm is not None and explores(comp, thread, switch, mctx.stage, origin, recent):
|
|
263
|
+
return {**out, "zone": "explore", "arm": arm}
|
|
264
|
+
return {**out, "zone": "margin", "arm": safe}
|
|
265
|
+
arm = eligible(lenient=False)
|
|
266
|
+
if arm is not None:
|
|
267
|
+
return {**out, "zone": "simple", "arm": arm}
|
|
268
|
+
return {**out, "zone": "complex", "arm": safe}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""The contest's pick and the records it writes (CTS-B1, CTS-B7, CTS-B9; EVT-B15). Model-free and pure.
|
|
2
|
+
|
|
3
|
+
Every slot that was graded and not put out is a `Candidate`. The slots are ordered by derived verdict (PROCEED first),
|
|
4
|
+
then fewer unmet warnings, more criteria MET, higher judge confidence, lower cost and earlier place in the declared
|
|
5
|
+
order; the first is the winner. This module reads numbers and words only: it starts nothing and reads no file.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping, Sequence
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
VERDICT_RANK = {"PROCEED": 0, "RETRY": 1, "BACK": 2, "ESCALATE": 3, "STOP": 4} # the order of CTS-B7: PROCEED first
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Candidate:
|
|
19
|
+
"""One slot that was graded and not put out: its derived verdict and the keys the pick compares."""
|
|
20
|
+
|
|
21
|
+
slot: str
|
|
22
|
+
order: int # the slot's place in the declared order, counted from 0
|
|
23
|
+
verdict: str
|
|
24
|
+
unmet_warnings: int = 0
|
|
25
|
+
met: int = 0
|
|
26
|
+
confidence: float = 0.0
|
|
27
|
+
cost: float = 0.0
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def rank_key(c: Candidate) -> tuple[int, int, int, float, float, int]:
|
|
31
|
+
"""Smaller sorts first: verdict, unmet warnings, more MET, higher confidence, lower cost, earlier slot."""
|
|
32
|
+
return (VERDICT_RANK.get(c.verdict, len(VERDICT_RANK)), c.unmet_warnings, -c.met, -c.confidence, c.cost, c.order)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def ordered(candidates: Sequence[Candidate]) -> list[Candidate]:
|
|
36
|
+
return sorted(candidates, key=rank_key)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def pick(candidates: Sequence[Candidate]) -> Candidate | None:
|
|
40
|
+
"""The winner, or None when no slot is left to pick from."""
|
|
41
|
+
got = ordered(candidates)
|
|
42
|
+
return got[0] if got else None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def keys_of(judgement: Mapping[str, Any]) -> dict[str, Any]:
|
|
46
|
+
"""The three keys the pick compares after the verdict, from a slot's judgement: the criteria of severity warning it
|
|
47
|
+
did not meet (`notes`), the criteria it met, and the judge's confidence."""
|
|
48
|
+
met = sum(1 for s in judgement.get("statuses") or [] if isinstance(s, Mapping) and s.get("status") == "MET")
|
|
49
|
+
conf = judgement.get("confidence")
|
|
50
|
+
return {"unmet_warnings": len(judgement.get("notes") or []), "met": met,
|
|
51
|
+
"confidence": float(conf) if isinstance(conf, int | float) and not isinstance(conf, bool) else 0.0}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def retry_write(unit: str, scope: str, winner: str | None) -> dict[str, Any]:
|
|
55
|
+
"""The `maps` write of a RETRY of the contest `unit` (CTS-B8, CTS-B4): under `best` with a winner the contest becomes
|
|
56
|
+
one step, the winner's slot (`single`), for the rest of the visit; under `all`, or with no winner (every slot put out
|
|
57
|
+
by its check), every slot runs again with its own notes."""
|
|
58
|
+
if scope == "best" and winner:
|
|
59
|
+
return {"maps": {unit: {"single": winner}}}
|
|
60
|
+
return {"maps": {unit: {"single": None}}}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def retry_slots(names: Sequence[str], single: str | None) -> list[str]:
|
|
64
|
+
"""The slots a retry runs: the one slot a `best` retry kept, else every slot (CTS-B8)."""
|
|
65
|
+
return [single] if single is not None and single in names else list(names)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def slot_row(place: int, name: str, *, attempt: int | None = None, check: str | None = None,
|
|
69
|
+
verdict: str | None = None, keys: Mapping[str, Any] | None = None, cost: float = 0.0,
|
|
70
|
+
skipped: bool = False) -> dict[str, Any]:
|
|
71
|
+
"""One slot of the `contest` run record (EVT-B15): its place in the declared order from 1, its name, the check result,
|
|
72
|
+
the derived verdict, the rank keys and the cost, or `skipped` for a slot the attempt's cost cap kept from starting."""
|
|
73
|
+
if skipped:
|
|
74
|
+
return {"slot": place, "name": name, "skipped": True}
|
|
75
|
+
return {"slot": place, "name": name, "attempt": attempt, "check": check, "verdict": verdict,
|
|
76
|
+
"keys": dict(keys) if keys is not None else None, "cost": round(cost, 6)}
|