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,517 @@
|
|
|
1
|
+
"""The check context and running a gate's check (CHK-B10, CHK-B14; OVR-B7).
|
|
2
|
+
|
|
3
|
+
`run_check` is the call itself; the engine makes it inside the check worker (`run.check_worker`, CHK-B16),
|
|
4
|
+
and the deadline is also enforced on every command the check runs.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import dataclasses
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import shutil
|
|
15
|
+
import tempfile
|
|
16
|
+
import time
|
|
17
|
+
from collections.abc import Mapping, Sequence
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from tempergraph import git as gitmod
|
|
23
|
+
from tempergraph.contracts import CheckFinding, CheckResult, GateSpec
|
|
24
|
+
from tempergraph.run.commands import (
|
|
25
|
+
CommandRefusal,
|
|
26
|
+
CommandRun,
|
|
27
|
+
ResolvedCommand,
|
|
28
|
+
python_path_outside,
|
|
29
|
+
resolve_command,
|
|
30
|
+
run_command,
|
|
31
|
+
)
|
|
32
|
+
from tempergraph.security.scrub import DROPPED, REDACTED, clip, scrub
|
|
33
|
+
|
|
34
|
+
ORDER = {"PASS": 0, "MAYBE": 1, "FAIL": 2}
|
|
35
|
+
FINDING_TO_RESULT = {"pass": "PASS", "n_a": "PASS", "maybe": "MAYBE", "fail": "FAIL"}
|
|
36
|
+
FACT_KEY = re.compile(r"^[a-z0-9][a-z0-9_-]{0,39}$")
|
|
37
|
+
MAX_FACTS = 20
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, kw_only=True)
|
|
41
|
+
class GitFacts:
|
|
42
|
+
branch: str = ""
|
|
43
|
+
base: str = ""
|
|
44
|
+
head: str = ""
|
|
45
|
+
base_head: str = ""
|
|
46
|
+
own_base: str = "" # WSP-B23: the commit the run's own change is measured from; `base` when nothing was merged
|
|
47
|
+
clean: bool = True
|
|
48
|
+
pushed: bool = False
|
|
49
|
+
changed_paths: tuple[str, ...] = ()
|
|
50
|
+
commits_since_base: tuple[str, ...] = ()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def git_facts(workdir: Path, base: str = "", base_branch: str = "") -> GitFacts | None:
|
|
54
|
+
"""The workspace's git facts; None outside a git repository (WSP-B15 to WSP-B18). `base` is the run's base commit;
|
|
55
|
+
`base_head` is the commit the run's base branch `base_branch` points to now (local branch, else `origin`'s
|
|
56
|
+
remote-tracking branch, no fetch), empty for a run with no base branch or one that no ref names (CHK-B22)."""
|
|
57
|
+
if gitmod.toplevel(workdir) is None:
|
|
58
|
+
return None
|
|
59
|
+
fp = gitmod.fingerprint(workdir)
|
|
60
|
+
name = gitmod.branch(workdir)
|
|
61
|
+
own = gitmod.own_base(workdir, base, base_branch)
|
|
62
|
+
return GitFacts(branch=name, base=base, head=fp.head, base_head=gitmod.branch_commit(workdir, base_branch),
|
|
63
|
+
own_base=own, clean=not fp.status, pushed=gitmod.pushed(workdir, name),
|
|
64
|
+
changed_paths=tuple(gitmod.changed_paths(workdir, own or None)))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def changed_paths(workdir: Path, facts: GitFacts | None, baseline: Path | None) -> tuple[str, ...]:
|
|
68
|
+
"""What changed in the workspace: git's answer, or outside git the manifest against the thread's first one."""
|
|
69
|
+
if facts is not None:
|
|
70
|
+
return tuple(facts.changed_paths)
|
|
71
|
+
import json
|
|
72
|
+
|
|
73
|
+
from tempergraph.store import manifest
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
files = json.loads(baseline.read_text(encoding="utf-8")).get("files") if baseline is not None else None
|
|
77
|
+
except (OSError, ValueError, AttributeError):
|
|
78
|
+
files = None
|
|
79
|
+
return tuple(manifest.changed(workdir, files)) if isinstance(files, dict) else ()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(kw_only=True)
|
|
83
|
+
class CheckContext:
|
|
84
|
+
unit: str
|
|
85
|
+
workdir: Path
|
|
86
|
+
request: Mapping[str, Any]
|
|
87
|
+
item: str | None = None
|
|
88
|
+
visit: int = 1
|
|
89
|
+
attempt: int = 1
|
|
90
|
+
preview: bool = False
|
|
91
|
+
main_checkout: Path | None = None
|
|
92
|
+
artifacts: Mapping[str, Any] = field(default_factory=dict)
|
|
93
|
+
values: Mapping[str, Any] = field(default_factory=dict)
|
|
94
|
+
facts: Mapping[str, Any] = field(default_factory=dict)
|
|
95
|
+
git: GitFacts | None = field(default_factory=GitFacts) # None outside git (WSP-B15 to WSP-B18)
|
|
96
|
+
changed_paths: tuple[str, ...] = () # git's outside the state root, or the manifest's outside git
|
|
97
|
+
settings: Mapping[str, Any] = field(default_factory=dict)
|
|
98
|
+
criteria: tuple[dict[str, Any], ...] = ()
|
|
99
|
+
allow: tuple[str, ...] = ()
|
|
100
|
+
# CHK-B24, CHK-B25: the calls the attempt's session made, in order, each `{name, capability, target, ok}`;
|
|
101
|
+
# None where no record is trustworthy (a stand-in that reports tool names only, no call, a dropped tool line, the preview)
|
|
102
|
+
session: tuple[Mapping[str, Any], ...] | None = None
|
|
103
|
+
# VSR-B1, VSR-B2: the calls of the attempt and of each earlier attempt of the same visit and item that has a
|
|
104
|
+
# record, in the order the attempts ran; None where the attempt's own record is None and in a preview
|
|
105
|
+
visit_session: tuple[Mapping[str, Any], ...] | None = None
|
|
106
|
+
out_dir: Path | None = None
|
|
107
|
+
deadline_at: float = 0.0
|
|
108
|
+
runs: list[CommandRun] = field(default_factory=list)
|
|
109
|
+
reuse_store: Path | None = None # the thread's stored command runs (CHK-B12, CHK-B13 Reuse)
|
|
110
|
+
no_reuse_exit_codes: Mapping[str, tuple[int, ...]] = field(default_factory=dict) # per allow-list prefix
|
|
111
|
+
base_dir: Path | None = None # where a run at the base makes its checkout (CHK-B18); a temporary folder when None
|
|
112
|
+
alone: list[CommandRun] = field(default_factory=list) # KIL-B9, KIL-B10: the runs alone a `retry` made, answered from
|
|
113
|
+
base_checkout: Path | None = field(default=None, init=False) # the checkout this context made, until `cleanup`
|
|
114
|
+
_base_workdir: Path | None = field(default=None, init=False, repr=False)
|
|
115
|
+
_own_dir: Path | None = field(default=None, init=False, repr=False)
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def deadline_s(self) -> float:
|
|
119
|
+
return max(0.0, self.deadline_at - time.monotonic())
|
|
120
|
+
|
|
121
|
+
def read_text(self, path: str | Path, max_bytes: int = 1_000_000) -> str:
|
|
122
|
+
p = (self.workdir / path).resolve()
|
|
123
|
+
if not p.is_relative_to(self.workdir.resolve()):
|
|
124
|
+
raise PermissionError(f"{path} is outside the workspace")
|
|
125
|
+
with open(p, "rb") as fh:
|
|
126
|
+
return fh.read(max_bytes).decode("utf-8", errors="replace")
|
|
127
|
+
|
|
128
|
+
def resolve(self, text: str) -> ResolvedCommand | CommandRefusal:
|
|
129
|
+
return resolve_command(self.allow, text, self.workdir)
|
|
130
|
+
|
|
131
|
+
def run(self, cmd: ResolvedCommand | str, timeout_s: float | None = None, reuse: bool = False,
|
|
132
|
+
min_start_s: float = 0, at_base: bool = False, python_path: Sequence[str] = ()) -> CommandRun:
|
|
133
|
+
if isinstance(cmd, str):
|
|
134
|
+
got = self.resolve(cmd)
|
|
135
|
+
if isinstance(got, CommandRefusal):
|
|
136
|
+
return CommandRun(argv=(clip(scrub(cmd), 200),), not_started=True, at_base=at_base,
|
|
137
|
+
extra={"refused": got.reason})
|
|
138
|
+
cmd = got
|
|
139
|
+
if python_path_outside(python_path, self.workdir, exists=not at_base):
|
|
140
|
+
listed = [python_path] if isinstance(python_path, str) else [str(p) for p in python_path]
|
|
141
|
+
return CommandRun(argv=cmd.argv, not_started=True, at_base=at_base, python_path=listed,
|
|
142
|
+
extra={"refused": "python path outside the workspace"})
|
|
143
|
+
pp = list(python_path)
|
|
144
|
+
held = self._alone_hit(cmd, at_base, pp) # KIL-B10: before the key and the store, whatever the exit code
|
|
145
|
+
if held is not None:
|
|
146
|
+
return self._added(held)
|
|
147
|
+
if at_base:
|
|
148
|
+
return self._run_at_base(cmd, timeout_s, reuse, min_start_s, pp)
|
|
149
|
+
left = self.deadline_s
|
|
150
|
+
if left < min_start_s or left <= 0:
|
|
151
|
+
r = CommandRun(argv=cmd.argv, not_started=True, python_path=pp)
|
|
152
|
+
self.runs.append(r)
|
|
153
|
+
return r
|
|
154
|
+
key = reuse_key(cmd, self.workdir, pp) if reuse and self.reuse_store is not None else None
|
|
155
|
+
if key is not None:
|
|
156
|
+
hit = _stored(self.reuse_store, key)
|
|
157
|
+
if hit is not None:
|
|
158
|
+
hit.python_path = pp
|
|
159
|
+
self.runs.append(hit)
|
|
160
|
+
return hit
|
|
161
|
+
out_dir = self.out_dir or (self.workdir / ".tempergraph-check")
|
|
162
|
+
limit = min(timeout_s, left) if timeout_s else left
|
|
163
|
+
r = run_command(cmd, self.workdir, out_dir / f"{len(self.runs) + 1}.out", limit, main=self.main_checkout,
|
|
164
|
+
python_path=pp)
|
|
165
|
+
self.runs.append(r)
|
|
166
|
+
if r.timed_out: # KIL-B1: a kill leaves its row whether or not reuse was asked
|
|
167
|
+
if self.reuse_store is not None:
|
|
168
|
+
store_killed(self.reuse_store, key or reuse_key(cmd, self.workdir, pp), r)
|
|
169
|
+
elif key is not None and r.finished and r.exit_code not in self.no_reuse_exit_codes.get(cmd.prefix, ()):
|
|
170
|
+
_store(self.reuse_store, key, r)
|
|
171
|
+
return r
|
|
172
|
+
|
|
173
|
+
def _run_at_base(self, cmd: ResolvedCommand, timeout_s: float | None, reuse: bool, min_start_s: float,
|
|
174
|
+
pp: list[str]) -> CommandRun:
|
|
175
|
+
"""CHK-B18 to CHK-B20: the command in a clean checkout of `git.base`, reused within one visit."""
|
|
176
|
+
base = self.git.base if self.git is not None else ""
|
|
177
|
+
left = self.deadline_s
|
|
178
|
+
if left < min_start_s or left <= 0 or not gitmod.is_commit_id(base):
|
|
179
|
+
return self._added(CommandRun(argv=cmd.argv, not_started=True, at_base=True, python_path=pp))
|
|
180
|
+
key = base_reuse_key(cmd, self.workdir, base, self.unit, self.visit, pp) \
|
|
181
|
+
if reuse and self.reuse_store is not None else None
|
|
182
|
+
if key is not None:
|
|
183
|
+
hit = _stored(self.reuse_store, key, at_base=True)
|
|
184
|
+
if hit is not None:
|
|
185
|
+
hit.python_path = pp
|
|
186
|
+
return self._added(hit)
|
|
187
|
+
try:
|
|
188
|
+
if cmd.cwd and not gitmod.folder_in_commit(self.workdir, base, cmd.cwd):
|
|
189
|
+
return self._added(CommandRun(argv=cmd.argv, not_started=True, at_base=True, python_path=pp))
|
|
190
|
+
where = self._checkout(base)
|
|
191
|
+
except (gitmod.GitError, OSError):
|
|
192
|
+
return self._added(CommandRun(argv=cmd.argv, not_started=True, at_base=True, python_path=pp))
|
|
193
|
+
if python_path_outside(pp, where): # CRE-B7: the folders are the base checkout's own, never the workspace's
|
|
194
|
+
return CommandRun(argv=cmd.argv, not_started=True, at_base=True, python_path=pp,
|
|
195
|
+
extra={"refused": "python path outside the workspace"})
|
|
196
|
+
out_dir = self.out_dir or (self.workdir / ".tempergraph-check")
|
|
197
|
+
limit = min(timeout_s, left) if timeout_s else left
|
|
198
|
+
r = run_command(cmd, where, out_dir / f"{len(self.runs) + 1}.out", limit, main=self.main_checkout,
|
|
199
|
+
python_path=pp)
|
|
200
|
+
r.at_base = True
|
|
201
|
+
for path in {str(self.workdir), str(self.workdir.resolve())}: # a command at the base can print either folder
|
|
202
|
+
r.tail, r.program_path = r.tail.replace(path, "<workdir>"), r.program_path.replace(path, "<workdir>")
|
|
203
|
+
self._added(r)
|
|
204
|
+
if r.timed_out: # KIL-B1: a kill leaves its row whether or not reuse was asked
|
|
205
|
+
if self.reuse_store is not None:
|
|
206
|
+
store_killed(self.reuse_store,
|
|
207
|
+
key or base_reuse_key(cmd, self.workdir, base, self.unit, self.visit, pp), r, at_base=True)
|
|
208
|
+
elif key is not None and r.finished and r.exit_code not in self.no_reuse_exit_codes.get(cmd.prefix, ()):
|
|
209
|
+
_store(self.reuse_store, key, r, at_base=True)
|
|
210
|
+
return r
|
|
211
|
+
|
|
212
|
+
def _alone_hit(self, cmd: ResolvedCommand, at_base: bool, pp: list[str]) -> CommandRun | None:
|
|
213
|
+
"""The latest run alone of this place, argument list, folder and Python path, marked reused; None when none."""
|
|
214
|
+
argv = tuple(scrub(a) for a in cmd.argv)
|
|
215
|
+
for r in reversed(self.alone):
|
|
216
|
+
if r.at_base == at_base and tuple(r.argv) == argv and (r.cwd or None) == (cmd.cwd or None) \
|
|
217
|
+
and list(r.python_path) == pp:
|
|
218
|
+
return dataclasses.replace(r, reused=True)
|
|
219
|
+
return None
|
|
220
|
+
|
|
221
|
+
def _added(self, run: CommandRun) -> CommandRun:
|
|
222
|
+
self.runs.append(run)
|
|
223
|
+
return run
|
|
224
|
+
|
|
225
|
+
def _checkout(self, base: str) -> Path:
|
|
226
|
+
"""The folder of the workspace in the checkout of `base`, made once per context (CHK-B18)."""
|
|
227
|
+
if self._base_workdir is None:
|
|
228
|
+
if self.base_dir is None:
|
|
229
|
+
self._own_dir = Path(tempfile.mkdtemp(prefix="tempergraph-base-"))
|
|
230
|
+
root = self._own_dir or self.base_dir
|
|
231
|
+
assert root is not None
|
|
232
|
+
root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
233
|
+
dest = root / "base"
|
|
234
|
+
try:
|
|
235
|
+
self._base_workdir = gitmod.base_checkout(self.workdir, base, dest)
|
|
236
|
+
except gitmod.GitError:
|
|
237
|
+
shutil.rmtree(dest, ignore_errors=True)
|
|
238
|
+
raise
|
|
239
|
+
self.base_checkout = dest
|
|
240
|
+
return self._base_workdir
|
|
241
|
+
|
|
242
|
+
def cleanup(self) -> None:
|
|
243
|
+
"""CHK-B21: remove the base checkout this context made, and the folder it made for it."""
|
|
244
|
+
if self.base_checkout is not None:
|
|
245
|
+
shutil.rmtree(self.base_checkout, ignore_errors=True)
|
|
246
|
+
if self._own_dir is not None:
|
|
247
|
+
shutil.rmtree(self._own_dir, ignore_errors=True)
|
|
248
|
+
self.base_checkout = self._base_workdir = self._own_dir = None
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def base_reuse_key(cmd: ResolvedCommand, workdir: Path, base: str, unit: str, visit: int,
|
|
252
|
+
python_path: Sequence[str] = ()) -> str:
|
|
253
|
+
"""CHK-B20: argv, resolved program, the command's folder, the base commit, the unit, the visit and the python
|
|
254
|
+
path (CRE-B6); never the workspace's head, status or files."""
|
|
255
|
+
prog = shutil.which(cmd.argv[0]) if cmd.argv else None
|
|
256
|
+
parts: list[Any] = ["at_base", list(cmd.argv), cmd.cwd, prog, base, unit, visit]
|
|
257
|
+
if python_path:
|
|
258
|
+
parts.append(list(python_path))
|
|
259
|
+
return hashlib.sha256(json.dumps(parts).encode()).hexdigest()
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def reuse_key(cmd: ResolvedCommand, workdir: Path, python_path: Sequence[str] = ()) -> str:
|
|
263
|
+
"""CHK-B12, CHK-B13: argv, working folder, resolved program and the content of the tree, no history.
|
|
264
|
+
|
|
265
|
+
The tree is every file git tracks and every untracked file git does not ignore (every file outside a git
|
|
266
|
+
repository), outside the state root, each by path, bytes and executable bit, read once. A commit of unchanged
|
|
267
|
+
content leaves the key as it was; a tracked file removed from the tree is left out.
|
|
268
|
+
"""
|
|
269
|
+
h = hashlib.sha256()
|
|
270
|
+
prog = shutil.which(cmd.argv[0]) if cmd.argv else None
|
|
271
|
+
h.update(json.dumps([list(cmd.argv), cmd.cwd, prog]).encode())
|
|
272
|
+
if python_path:
|
|
273
|
+
h.update(json.dumps(["python_path", list(python_path)]).encode())
|
|
274
|
+
for path in sorted(_tree_files(workdir)):
|
|
275
|
+
f = workdir / path
|
|
276
|
+
try:
|
|
277
|
+
if not f.is_file():
|
|
278
|
+
continue
|
|
279
|
+
mode = f.stat().st_mode
|
|
280
|
+
body = hashlib.sha256(f.read_bytes()).digest()
|
|
281
|
+
except OSError:
|
|
282
|
+
continue # gone or unreadable while the key is made: not part of the tree
|
|
283
|
+
h.update(path.encode() + b"\0" + (b"x" if mode & 0o111 else b"-") + body)
|
|
284
|
+
return h.hexdigest()
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _tree_files(workdir: Path) -> list[str]:
|
|
288
|
+
"""The paths of the tree under `workdir`, relative to it and outside the state root (CHK-B13)."""
|
|
289
|
+
if gitmod.toplevel(workdir) is not None:
|
|
290
|
+
raw = gitmod.git(["ls-files", "-z", "--cached", "--others", "--exclude-standard"], workdir, check=False)
|
|
291
|
+
paths = {p for p in raw.split("\0") if p}
|
|
292
|
+
else:
|
|
293
|
+
paths = set()
|
|
294
|
+
for folder, dirs, files in os.walk(workdir):
|
|
295
|
+
dirs[:] = [d for d in dirs if d != ".git"]
|
|
296
|
+
rel = Path(folder).relative_to(workdir)
|
|
297
|
+
paths.update(str(rel / name) if rel.parts else name for name in files)
|
|
298
|
+
return [p for p in paths if not p.startswith(".tempergraph")] # not the state root
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _stored(store: Path | None, key: str, at_base: bool = False) -> CommandRun | None:
|
|
302
|
+
if store is None:
|
|
303
|
+
return None
|
|
304
|
+
try:
|
|
305
|
+
lines = store.read_text(encoding="utf-8").splitlines()
|
|
306
|
+
except OSError:
|
|
307
|
+
return None
|
|
308
|
+
for ln in reversed(lines):
|
|
309
|
+
try:
|
|
310
|
+
row = json.loads(ln)
|
|
311
|
+
except ValueError:
|
|
312
|
+
continue
|
|
313
|
+
if row.get("key") == key and bool(row.get("at_base")) == at_base: # a base key never matches a workspace run
|
|
314
|
+
if row.get("no_reuse"): # CHK-B13: a run alone whose exit code its prefix never reuses is kept, not returned
|
|
315
|
+
continue
|
|
316
|
+
r = row["run"]
|
|
317
|
+
if r.get("outcome") == "killed": # KIL-B3: a killed row is never returned as reused
|
|
318
|
+
continue
|
|
319
|
+
limit = r.get("limit_s") # a row with no `outcome` is a finished run (KIL-B3)
|
|
320
|
+
return CommandRun(argv=tuple(r.get("argv") or ()), program_path=str(r.get("program_path") or ""),
|
|
321
|
+
exit_code=r.get("exit_code"), finished=True, reused=True, at_base=at_base,
|
|
322
|
+
duration_s=float(r.get("duration_s") or 0), output_path=str(r.get("output_path") or ""),
|
|
323
|
+
tail=str(r.get("tail") or ""), python_path=list(r.get("python_path") or []),
|
|
324
|
+
outcome="finished", limit_s=float(limit) if limit is not None else None,
|
|
325
|
+
prefix=str(r.get("prefix") or ""), cwd=r.get("cwd") or None)
|
|
326
|
+
return None
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _store(store: Path | None, key: str, run: CommandRun, at_base: bool = False, no_reuse: bool = False) -> None:
|
|
330
|
+
if store is None:
|
|
331
|
+
return
|
|
332
|
+
try:
|
|
333
|
+
store.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
334
|
+
row: dict[str, Any] = {"key": key, "at_base": at_base, "run": run.to_json()}
|
|
335
|
+
if no_reuse:
|
|
336
|
+
row["no_reuse"] = True # the row is kept (KIL-B9) and `_stored` never returns it (CHK-B13, CHK-B20)
|
|
337
|
+
with open(store, "a", encoding="utf-8") as fh:
|
|
338
|
+
fh.write(json.dumps(row) + "\n")
|
|
339
|
+
except OSError:
|
|
340
|
+
pass # a lost store entry only costs a rerun of the command
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def store_killed(store: Path | None, key: str, run: CommandRun, at_base: bool = False) -> None:
|
|
344
|
+
"""KIL-B1: the row of a command killed at its limit, written before the call that ran it returns."""
|
|
345
|
+
_store(store, key, run, at_base=at_base)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def command_run_from(doc: Mapping[str, Any]) -> CommandRun:
|
|
349
|
+
"""A `CommandRun` read back from its `to_json` form."""
|
|
350
|
+
limit = doc.get("limit_s")
|
|
351
|
+
return CommandRun(
|
|
352
|
+
argv=tuple(doc.get("argv") or ()), program_path=str(doc.get("program_path") or ""),
|
|
353
|
+
exit_code=doc.get("exit_code"), finished=bool(doc.get("finished")), timed_out=bool(doc.get("timed_out")),
|
|
354
|
+
not_started=bool(doc.get("not_started")), reused=bool(doc.get("reused")), at_base=bool(doc.get("at_base")),
|
|
355
|
+
duration_s=float(doc.get("duration_s") or 0), output_path=str(doc.get("output_path") or ""),
|
|
356
|
+
tail=str(doc.get("tail") or ""), python_path=list(doc.get("python_path") or []),
|
|
357
|
+
outcome=str(doc.get("outcome") or ""), limit_s=float(limit) if limit is not None else None,
|
|
358
|
+
prefix=str(doc.get("prefix") or ""), cwd=doc.get("cwd") or None)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def run_alone(ctx: CheckContext, killed: Mapping[str, Any], out_path: Path, timeout_s: float) -> CommandRun | None:
|
|
362
|
+
"""KIL-B9: one killed command run by itself under `timeout_s`, in the workspace or, for a command that ran at the
|
|
363
|
+
base, in the context's checkout of it (removed by `ctx.cleanup`). Its row is written whatever the exit code. The
|
|
364
|
+
command is resolved again against the allow-list; one that no longer resolves, or does not start, gives None."""
|
|
365
|
+
argv = [str(a) for a in killed.get("argv") or []]
|
|
366
|
+
if any(REDACTED in a or a == DROPPED for a in argv): # the recorded arguments were scrubbed: not the command killed
|
|
367
|
+
return None
|
|
368
|
+
folder = killed.get("cwd")
|
|
369
|
+
cmd = ctx.resolve((f"cd {folder} && " if folder else "") + " ".join(argv))
|
|
370
|
+
pp = [str(p) for p in killed.get("python_path") or []]
|
|
371
|
+
at_base = bool(killed.get("at_base"))
|
|
372
|
+
if isinstance(cmd, CommandRefusal) or python_path_outside(pp, ctx.workdir, exists=not at_base):
|
|
373
|
+
return None
|
|
374
|
+
where = ctx.workdir
|
|
375
|
+
base = ""
|
|
376
|
+
if at_base:
|
|
377
|
+
base = ctx.git.base if ctx.git is not None else ""
|
|
378
|
+
if not gitmod.is_commit_id(base):
|
|
379
|
+
return None
|
|
380
|
+
try:
|
|
381
|
+
if cmd.cwd and not gitmod.folder_in_commit(ctx.workdir, base, cmd.cwd):
|
|
382
|
+
return None
|
|
383
|
+
where = ctx._checkout(base)
|
|
384
|
+
except (gitmod.GitError, OSError):
|
|
385
|
+
return None
|
|
386
|
+
if python_path_outside(pp, where):
|
|
387
|
+
return None
|
|
388
|
+
r = run_command(cmd, where, out_path, timeout_s, main=ctx.main_checkout, python_path=pp)
|
|
389
|
+
if r.exit_code is None and not r.timed_out:
|
|
390
|
+
return None # it did not start
|
|
391
|
+
r.at_base = at_base
|
|
392
|
+
if at_base:
|
|
393
|
+
for path in {str(ctx.workdir), str(ctx.workdir.resolve())}:
|
|
394
|
+
r.tail, r.program_path = r.tail.replace(path, "<workdir>"), r.program_path.replace(path, "<workdir>")
|
|
395
|
+
key = base_reuse_key(cmd, ctx.workdir, base, ctx.unit, ctx.visit, pp) if at_base else reuse_key(cmd, ctx.workdir, pp)
|
|
396
|
+
_store(ctx.reuse_store, key, r, at_base=at_base,
|
|
397
|
+
no_reuse=bool(r.finished and r.exit_code in ctx.no_reuse_exit_codes.get(cmd.prefix, ())))
|
|
398
|
+
return r
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def killed_commands(runs: Sequence[Mapping[str, Any]], store: Path | None
|
|
402
|
+
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
|
403
|
+
"""KIL-B4, KIL-B6, KIL-B7: from a check result's `runs`, the entries of the commands killed at their limit, in
|
|
404
|
+
order, with no argument text, and the killed runs themselves (argument list, Python path, output path) for the
|
|
405
|
+
judge node. `last_finished_s` is the `duration_s` of the latest finished row of the store with the same argument
|
|
406
|
+
list and folder, in the workspace or at the base, None when no row has one."""
|
|
407
|
+
killed = [r for r in runs if r.get("timed_out")]
|
|
408
|
+
if not killed:
|
|
409
|
+
return [], []
|
|
410
|
+
rows: list[Mapping[str, Any]] = []
|
|
411
|
+
if store is not None:
|
|
412
|
+
try:
|
|
413
|
+
lines = store.read_text(encoding="utf-8").splitlines()
|
|
414
|
+
except OSError:
|
|
415
|
+
lines = []
|
|
416
|
+
for ln in lines:
|
|
417
|
+
try:
|
|
418
|
+
row = json.loads(ln)
|
|
419
|
+
except ValueError:
|
|
420
|
+
continue
|
|
421
|
+
if isinstance(row, dict) and isinstance(row.get("run"), dict):
|
|
422
|
+
rows.append(row)
|
|
423
|
+
entries: list[dict[str, Any]] = []
|
|
424
|
+
for r in killed:
|
|
425
|
+
at_base = bool(r.get("at_base"))
|
|
426
|
+
last: float | None = None
|
|
427
|
+
for row in reversed(rows):
|
|
428
|
+
run = row["run"]
|
|
429
|
+
if run.get("outcome") == "killed" or run.get("timed_out") or not run.get("finished", True):
|
|
430
|
+
continue
|
|
431
|
+
if list(run.get("argv") or []) == list(r.get("argv") or []) \
|
|
432
|
+
and (run.get("cwd") or None) == (r.get("cwd") or None):
|
|
433
|
+
last = float(run.get("duration_s") or 0)
|
|
434
|
+
break
|
|
435
|
+
limit = r.get("limit_s")
|
|
436
|
+
entries.append({"prefix": str(r.get("prefix") or ""), "cwd": r.get("cwd") or None, "at_base": at_base,
|
|
437
|
+
"limit_s": limit, "elapsed_s": float(r.get("duration_s") or 0), "last_finished_s": last})
|
|
438
|
+
return entries, [dict(r) for r in killed]
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def normalise(res: CheckResult) -> tuple[CheckResult, list[str]]:
|
|
442
|
+
"""CHK-B14: the worse of `result` and the worst finding; bounded, scrubbed facts."""
|
|
443
|
+
notes: list[str] = []
|
|
444
|
+
worst = res.result
|
|
445
|
+
for f in res.findings:
|
|
446
|
+
r = FINDING_TO_RESULT.get(f.status, "MAYBE")
|
|
447
|
+
if ORDER[r] > ORDER[worst]:
|
|
448
|
+
worst = r # type: ignore[assignment]
|
|
449
|
+
if worst != res.result:
|
|
450
|
+
notes.append(f"check_result_mismatch: {res.result} -> {worst}")
|
|
451
|
+
facts = {}
|
|
452
|
+
for k, v in list(res.facts.items())[:MAX_FACTS]:
|
|
453
|
+
if FACT_KEY.match(str(k)):
|
|
454
|
+
facts[str(k)] = clip(scrub(str(v)), 200)
|
|
455
|
+
else:
|
|
456
|
+
notes.append(f"fact_key_invalid: {clip(str(k), 40)}")
|
|
457
|
+
findings = [CheckFinding(status=f.status, criterion=f.criterion, place=clip(scrub(f.place), 200),
|
|
458
|
+
fix=clip(scrub(f.fix), 200), message=clip(scrub(f.message), 200), kind=f.kind)
|
|
459
|
+
for f in res.findings]
|
|
460
|
+
out = CheckResult(result=worst, evidence=scrub(res.evidence)[:8000], environmental=res.environmental,
|
|
461
|
+
untracked_only=res.untracked_only, findings=findings, facts=facts, runs=list(res.runs))
|
|
462
|
+
return out, notes
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def run_check(gate: GateSpec, ctx: CheckContext) -> tuple[CheckResult, list[str]]:
|
|
466
|
+
"""Call the gate's check; a raising check is an environmental FAIL, never a pass."""
|
|
467
|
+
if gate.check is None:
|
|
468
|
+
return CheckResult(result="PASS", evidence=""), []
|
|
469
|
+
ctx.deadline_at = time.monotonic() + gate.check_timeout_s
|
|
470
|
+
fn = gate.check.resolve()
|
|
471
|
+
try:
|
|
472
|
+
try:
|
|
473
|
+
res = fn(ctx)
|
|
474
|
+
except Exception as exc: # noqa: BLE001 - a check's own failure is a result
|
|
475
|
+
# CHK-B15, CHK-B14, CHK-B10, CHK-B17: a raising check is a workflow fault, not an environmental one; a retry is spent
|
|
476
|
+
return CheckResult(result="FAIL", evidence=f"check raised {type(exc).__name__}"), [
|
|
477
|
+
f"check_raised: {type(exc).__name__}"]
|
|
478
|
+
if not isinstance(res, CheckResult):
|
|
479
|
+
return CheckResult(result="FAIL", evidence="check returned no CheckResult"), ["check_result_invalid"]
|
|
480
|
+
res.runs = [r.to_json() for r in ctx.runs]
|
|
481
|
+
return normalise(res)
|
|
482
|
+
finally:
|
|
483
|
+
ctx.cleanup() # CHK-B21: the base checkout is removed whether the check returned or raised
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def failing(res: CheckResult) -> list[dict[str, str]]:
|
|
487
|
+
"""BUD-B16: the failing findings of a check result, as the rows a pause payload shows."""
|
|
488
|
+
return [{"criterion": f.criterion or "", "place": f.place or "", "message": f.message or "", "fix": f.fix or ""}
|
|
489
|
+
for f in res.findings if f.status == "fail"]
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
MAX_FAILED = 20
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def failed_ids(res: CheckResult) -> list[str]:
|
|
496
|
+
"""CHK-B26: the criterion ids of the findings with status `fail`, each once, in the check's order, at most 20."""
|
|
497
|
+
out: list[str] = []
|
|
498
|
+
for f in res.findings:
|
|
499
|
+
if f.status == "fail" and f.criterion and f.criterion not in out:
|
|
500
|
+
out.append(str(f.criterion))
|
|
501
|
+
return out[:MAX_FAILED]
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def repeat_key(findings: Sequence[Mapping[str, Any]], evidence: str) -> tuple[Any, ...]:
|
|
505
|
+
"""BUD-B16: what two failures must share to be the same: the failing findings by criterion, place and message,
|
|
506
|
+
or the scrubbed evidence text when the check returned no finding."""
|
|
507
|
+
rows = sorted((str(f.get("criterion") or ""), str(f.get("place") or ""), str(f.get("message") or ""))
|
|
508
|
+
for f in findings)
|
|
509
|
+
return ("findings", tuple(rows)) if rows else ("evidence", str(evidence or "").strip())
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def to_json(res: CheckResult) -> dict[str, Any]:
|
|
513
|
+
return {"result": res.result, "evidence": res.evidence, "environmental": res.environmental,
|
|
514
|
+
"untracked_only": res.untracked_only,
|
|
515
|
+
"findings": [{"status": f.status, "criterion": f.criterion, "place": f.place, "fix": f.fix,
|
|
516
|
+
"message": f.message, "kind": f.kind} for f in res.findings],
|
|
517
|
+
"facts": res.facts, "runs": res.runs}
|