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,279 @@
|
|
|
1
|
+
"""Reading run events: the run log in `seq` order, the activity journal, `--follow`, narrator lines and the
|
|
2
|
+
in-process observers (EVT-B8, EVT-B9, EVT-B10 to EVT-B16, EVT-B17, EVT-B18, EVT-B7, EVT-B19, EVT-B22, EVT-B23, EVT-B24; ADR `observers-read-files-not-sockets`, ADR `in-process-observers-and-wider-hook-events`).
|
|
3
|
+
|
|
4
|
+
Readers here create nothing and call no model (OVR-B15); they skip unknown kinds and fields (OVR-B14).
|
|
5
|
+
Observers never change a run or its exit code (OVR-B4, EVT-B5).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import json
|
|
12
|
+
import queue
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
from collections.abc import Callable, Iterator, Mapping
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from importlib.metadata import entry_points
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, Protocol, runtime_checkable
|
|
20
|
+
|
|
21
|
+
QUEUE_SIZE = 1_000
|
|
22
|
+
NARRATED = frozenset({"unit_entered", "check", "gate", "route", "pause", "human", "budget", "stop_requested"})
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# -- reading ----------------------------------------------------------------------------------------
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _lines(path: Path, offset: int = 0) -> tuple[list[dict[str, Any]], int]:
|
|
29
|
+
"""Complete JSON lines from byte `offset`; a partial last line is left for the next read."""
|
|
30
|
+
try:
|
|
31
|
+
with open(path, "rb") as fh:
|
|
32
|
+
fh.seek(offset)
|
|
33
|
+
data = fh.read()
|
|
34
|
+
except OSError:
|
|
35
|
+
return [], offset
|
|
36
|
+
out: list[dict[str, Any]] = []
|
|
37
|
+
end = data.rfind(b"\n")
|
|
38
|
+
if end < 0:
|
|
39
|
+
return out, offset
|
|
40
|
+
for line in data[: end + 1].splitlines():
|
|
41
|
+
if not line.strip():
|
|
42
|
+
continue
|
|
43
|
+
try:
|
|
44
|
+
rec = json.loads(line)
|
|
45
|
+
except ValueError:
|
|
46
|
+
continue
|
|
47
|
+
if isinstance(rec, dict):
|
|
48
|
+
out.append(rec)
|
|
49
|
+
return out, offset + end + 1
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def records(path: Path, since: int | None = None) -> list[dict[str, Any]]:
|
|
53
|
+
"""Every run-log record after `since`, in `seq` order; the schema line is not a record."""
|
|
54
|
+
recs, _ = _lines(path)
|
|
55
|
+
return [r for r in recs if isinstance(r.get("seq"), int) and (since is None or r["seq"] > since)]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def follow(path: Path, held: Callable[[], bool], since: int | None = None, *, poll_s: float = 0.25,
|
|
59
|
+
timeout_s: float | None = None, sleep: Callable[[float], None] = time.sleep) -> Iterator[dict[str, Any]]:
|
|
60
|
+
"""Records after `since` as they are written; ends once the newest segment's `run_exit` is read and no
|
|
61
|
+
lock is held (EVT-B22, EVT-B23, EVT-B24, EVT-B3). Each record is yielded once."""
|
|
62
|
+
offset, last, ended = 0, since, False
|
|
63
|
+
start = time.monotonic()
|
|
64
|
+
while True:
|
|
65
|
+
recs, offset = _lines(path, offset)
|
|
66
|
+
for r in recs:
|
|
67
|
+
seq = r.get("seq")
|
|
68
|
+
if not isinstance(seq, int):
|
|
69
|
+
continue
|
|
70
|
+
if r.get("kind") == "run_started":
|
|
71
|
+
ended = False
|
|
72
|
+
elif r.get("kind") == "run_exit":
|
|
73
|
+
ended = True
|
|
74
|
+
if last is not None and seq <= last:
|
|
75
|
+
continue
|
|
76
|
+
last = seq
|
|
77
|
+
yield r
|
|
78
|
+
if not held() and (ended or not recs):
|
|
79
|
+
return # the segment exited, or the process is gone without a `run_exit` (orphaned)
|
|
80
|
+
if timeout_s is not None and time.monotonic() - start >= timeout_s:
|
|
81
|
+
return
|
|
82
|
+
sleep(poll_s)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def activity(path: Path, since: int | None = None) -> list[dict[str, Any]]:
|
|
86
|
+
"""One session's activity journal lines after line number `since`."""
|
|
87
|
+
lines, _ = _lines(path)
|
|
88
|
+
return [ln for ln in lines if since is None or (isinstance(ln.get("n"), int) and ln["n"] > since)]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def follow_activity(path: Path, live: Path, held: Callable[[], bool], since: int | None = None, *,
|
|
92
|
+
poll_s: float = 0.25, timeout_s: float | None = None,
|
|
93
|
+
sleep: Callable[[float], None] = time.sleep) -> Iterator[dict[str, Any]]:
|
|
94
|
+
"""Journal lines as they are flushed; ends at the session's `result` or `truncated` line, when its live
|
|
95
|
+
file is removed at session end, or when no lock is held."""
|
|
96
|
+
offset, last, seen_live, done = 0, since, False, False
|
|
97
|
+
start = time.monotonic()
|
|
98
|
+
while True:
|
|
99
|
+
lines, offset = _lines(path, offset)
|
|
100
|
+
seen_live = seen_live or live.exists()
|
|
101
|
+
for ln in lines:
|
|
102
|
+
if ln.get("ev") in ("result", "truncated"):
|
|
103
|
+
done = True
|
|
104
|
+
n = ln.get("n")
|
|
105
|
+
if last is not None and isinstance(n, int) and n <= last:
|
|
106
|
+
continue
|
|
107
|
+
if isinstance(n, int):
|
|
108
|
+
last = n
|
|
109
|
+
yield ln
|
|
110
|
+
if not lines and (done or (seen_live and not live.exists()) or not held()):
|
|
111
|
+
return
|
|
112
|
+
if timeout_s is not None and time.monotonic() - start >= timeout_s:
|
|
113
|
+
return
|
|
114
|
+
sleep(poll_s)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
# -- narrator lines ---------------------------------------------------------------------------------
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def route_unit(node: Any) -> str | None:
|
|
121
|
+
"""A graph node by its unit: `draft.step` is `draft`, a human node is `human`, the end is `end`."""
|
|
122
|
+
if not isinstance(node, str) or not node:
|
|
123
|
+
return None
|
|
124
|
+
if node.endswith(".human"):
|
|
125
|
+
return "human"
|
|
126
|
+
if node == "__end__":
|
|
127
|
+
return "end"
|
|
128
|
+
return node.split(".", 1)[0]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def narrate(r: Mapping[str, Any]) -> str:
|
|
132
|
+
"""One line for a run-log record, as a monitor's narrator shows it (RDD-B7 to RDD-B11, RDD-B13, RDD-B15 `events_tail`)."""
|
|
133
|
+
kind = str(r.get("kind"))
|
|
134
|
+
where = r.get("unit") or ""
|
|
135
|
+
if r.get("item"):
|
|
136
|
+
where = f"{where}[{r['item']}]"
|
|
137
|
+
if r.get("attempt") is not None and kind not in ("unit_entered",):
|
|
138
|
+
where = f"{where}#{r['attempt']}" if where else ""
|
|
139
|
+
text: str
|
|
140
|
+
if kind == "unit_entered":
|
|
141
|
+
text = f"entered {where} (visit {r.get('visit')}, from {r.get('entered_from')})"
|
|
142
|
+
elif kind == "check":
|
|
143
|
+
env = " environmental" if r.get("environmental") else ""
|
|
144
|
+
text = f"check {where}: {r.get('result')}{env}"
|
|
145
|
+
elif kind == "judgement":
|
|
146
|
+
text = f"judge {where}: {r.get('met', '?')}/{r.get('total', '?')} met"
|
|
147
|
+
elif kind == "gate":
|
|
148
|
+
target = route_unit(r.get("route_target"))
|
|
149
|
+
text = f"gate {where}: {r.get('verdict')}" + (f" -> {target}" if target else "")
|
|
150
|
+
elif kind == "pause":
|
|
151
|
+
text = f"paused at {where} ({r.get('pause_kind') or r.get('session_kind')}): {r.get('resume') or ''}".rstrip()
|
|
152
|
+
elif kind == "human":
|
|
153
|
+
text = f"decision at {where}: {r.get('decision')}"
|
|
154
|
+
elif kind == "budget":
|
|
155
|
+
text = f"budget {r.get('counter')}: {r.get('used')}/{r.get('limit')} ({r.get('cause')})"
|
|
156
|
+
elif kind == "stop_requested":
|
|
157
|
+
text = f"stop requested ({r.get('mode')})"
|
|
158
|
+
elif kind == "route":
|
|
159
|
+
text = f"route {where} -> {route_unit(r.get('target') or r.get('route_target'))}"
|
|
160
|
+
elif kind == "session_opened":
|
|
161
|
+
text = f"session {r.get('session_key')} on {r.get('executor')} ({r.get('model') or r.get('alias')})"
|
|
162
|
+
elif kind == "run_started":
|
|
163
|
+
text = f"segment {r.get('segment')} started ({r.get('origin')})"
|
|
164
|
+
elif kind == "run_exit":
|
|
165
|
+
text = f"segment {r.get('segment')} exited {r.get('exit_code')} ({r.get('reason')})"
|
|
166
|
+
else:
|
|
167
|
+
text = f"{kind} {where}".rstrip()
|
|
168
|
+
return f"{r.get('seq')} {r.get('ts')} {text}"
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def tail(recs: list[dict[str, Any]], n: int = 20) -> list[str]:
|
|
172
|
+
return [narrate(r) for r in recs if r.get("kind") in NARRATED][-n:]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# -- in-process observers (EVT-B22, EVT-B23, EVT-B24) ----------------------------------------------------------------
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@runtime_checkable
|
|
179
|
+
class RunObserver(Protocol):
|
|
180
|
+
name: str
|
|
181
|
+
|
|
182
|
+
def on_record(self, record: dict[str, Any]) -> None: ...
|
|
183
|
+
|
|
184
|
+
def on_activity(self, session_key: str, line: dict[str, Any]) -> None: ...
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def register_observers(entry_point_group: str = "tempergraph.observers",
|
|
188
|
+
names: tuple[str, ...] | None = None) -> tuple[list[RunObserver], list[str]]:
|
|
189
|
+
"""Observers installed under the entry-point group; only those named (operator config) are loaded.
|
|
190
|
+
Returns the observers and the names that are not installed (a preflight warning, EVT-B25)."""
|
|
191
|
+
wanted = set(names or ())
|
|
192
|
+
found: dict[str, RunObserver] = {}
|
|
193
|
+
for ep in entry_points(group=entry_point_group):
|
|
194
|
+
if ep.name not in wanted:
|
|
195
|
+
continue
|
|
196
|
+
try:
|
|
197
|
+
obj = ep.load()
|
|
198
|
+
inst = obj() if isinstance(obj, type) else obj
|
|
199
|
+
except Exception: # noqa: BLE001 - a broken observer never stops a run
|
|
200
|
+
continue
|
|
201
|
+
if isinstance(inst, RunObserver):
|
|
202
|
+
found[ep.name] = inst
|
|
203
|
+
missing = sorted(wanted - set(found))
|
|
204
|
+
return list(found.values()), missing
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@dataclass
|
|
208
|
+
class _Lane:
|
|
209
|
+
observer: RunObserver
|
|
210
|
+
q: queue.Queue[tuple[str, Any] | None] = field(default_factory=lambda: queue.Queue(QUEUE_SIZE))
|
|
211
|
+
dropped: int = 0
|
|
212
|
+
disabled: bool = False
|
|
213
|
+
error: str | None = None
|
|
214
|
+
thread: threading.Thread | None = None
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class ObserverHub:
|
|
218
|
+
"""Each observer on its own thread behind a bounded queue: a full queue drops and counts, an exception
|
|
219
|
+
disables that observer for the segment and is recorded once as an `engine_error` of scope `observer`."""
|
|
220
|
+
|
|
221
|
+
def __init__(self, observers: list[RunObserver]) -> None:
|
|
222
|
+
self.lanes = [_Lane(o) for o in observers]
|
|
223
|
+
self._errors: queue.Queue[tuple[str, str]] = queue.Queue()
|
|
224
|
+
for lane in self.lanes:
|
|
225
|
+
lane.thread = threading.Thread(target=self._pump, args=(lane,), daemon=True,
|
|
226
|
+
name=f"observer-{lane.observer.name}")
|
|
227
|
+
lane.thread.start()
|
|
228
|
+
|
|
229
|
+
def _pump(self, lane: _Lane) -> None:
|
|
230
|
+
while True:
|
|
231
|
+
item = lane.q.get()
|
|
232
|
+
if item is None:
|
|
233
|
+
return
|
|
234
|
+
if lane.disabled:
|
|
235
|
+
continue
|
|
236
|
+
what, payload = item
|
|
237
|
+
try:
|
|
238
|
+
if what == "record":
|
|
239
|
+
lane.observer.on_record(payload)
|
|
240
|
+
else:
|
|
241
|
+
lane.observer.on_activity(payload[0], payload[1])
|
|
242
|
+
except Exception as exc: # noqa: BLE001 - EVT-B5
|
|
243
|
+
lane.disabled = True
|
|
244
|
+
lane.error = type(exc).__name__
|
|
245
|
+
self._errors.put((lane.observer.name, lane.error))
|
|
246
|
+
|
|
247
|
+
def _put(self, item: tuple[str, Any]) -> None:
|
|
248
|
+
for lane in self.lanes:
|
|
249
|
+
if lane.disabled:
|
|
250
|
+
continue
|
|
251
|
+
try:
|
|
252
|
+
lane.q.put_nowait(item)
|
|
253
|
+
except queue.Full:
|
|
254
|
+
lane.dropped += 1
|
|
255
|
+
|
|
256
|
+
def on_record(self, record: dict[str, Any]) -> None:
|
|
257
|
+
self._put(("record", dict(record)))
|
|
258
|
+
|
|
259
|
+
def on_activity(self, session_key: str, line: dict[str, Any]) -> None:
|
|
260
|
+
self._put(("activity", (session_key, dict(line))))
|
|
261
|
+
|
|
262
|
+
def take_errors(self) -> list[tuple[str, str]]:
|
|
263
|
+
out = []
|
|
264
|
+
while True:
|
|
265
|
+
try:
|
|
266
|
+
out.append(self._errors.get_nowait())
|
|
267
|
+
except queue.Empty:
|
|
268
|
+
return out
|
|
269
|
+
|
|
270
|
+
def close(self, timeout_s: float = 5.0) -> dict[str, dict[str, Any]]:
|
|
271
|
+
"""Drain and stop every lane; returns per observer its dropped count and whether it was disabled."""
|
|
272
|
+
for lane in self.lanes:
|
|
273
|
+
with contextlib.suppress(queue.Full):
|
|
274
|
+
lane.q.put(None, timeout=timeout_s)
|
|
275
|
+
for lane in self.lanes:
|
|
276
|
+
if lane.thread is not None:
|
|
277
|
+
lane.thread.join(timeout_s)
|
|
278
|
+
return {lane.observer.name: {"dropped": lane.dropped, "disabled": lane.disabled, "error": lane.error}
|
|
279
|
+
for lane in self.lanes}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""The finalizer contract (FIN-B6 to FIN-B10): one call after the last pass, no model, never the request text."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
from tempergraph.run import checks as checkmod
|
|
13
|
+
from tempergraph.run.commands import CommandRefusal, CommandRun, ResolvedCommand, resolve_command, run_command
|
|
14
|
+
from tempergraph.security.scrub import clip, scrub
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from tempergraph.run.nodes import RunContext
|
|
18
|
+
|
|
19
|
+
FINALIZER_LIMIT_S = 600
|
|
20
|
+
COMMAND_LIMIT_S = 120
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(kw_only=True)
|
|
24
|
+
class FinalizerContext:
|
|
25
|
+
task_id: str
|
|
26
|
+
thread_id: str
|
|
27
|
+
workflow: str
|
|
28
|
+
branch: str
|
|
29
|
+
base: str
|
|
30
|
+
workdir: Path
|
|
31
|
+
artifacts: Mapping[str, Any]
|
|
32
|
+
values: Mapping[str, Any]
|
|
33
|
+
facts: Mapping[str, Any]
|
|
34
|
+
open_warnings: int
|
|
35
|
+
degraded: bool
|
|
36
|
+
run_options: Mapping[str, Any]
|
|
37
|
+
git: checkmod.GitFacts | None # None outside a git repository (WSP-B15 to WSP-B18)
|
|
38
|
+
allow: tuple[str, ...] = ()
|
|
39
|
+
main: Path | None = None
|
|
40
|
+
out_dir: Path | None = None
|
|
41
|
+
runs: list[CommandRun] = field(default_factory=list)
|
|
42
|
+
settings: Mapping[str, Any] = field(default_factory=dict) # FIN-B12: the workflow's resolved settings
|
|
43
|
+
|
|
44
|
+
def resolve(self, text: str) -> ResolvedCommand | CommandRefusal:
|
|
45
|
+
return resolve_command(self.allow, text, self.workdir)
|
|
46
|
+
|
|
47
|
+
def run(self, cmd: ResolvedCommand | str, timeout_s: float = COMMAND_LIMIT_S) -> CommandRun:
|
|
48
|
+
if isinstance(cmd, str):
|
|
49
|
+
got = self.resolve(cmd)
|
|
50
|
+
if isinstance(got, CommandRefusal):
|
|
51
|
+
return CommandRun(argv=(clip(scrub(cmd), 200),), not_started=True, extra={"refused": got.reason})
|
|
52
|
+
cmd = got
|
|
53
|
+
out = (self.out_dir or self.workdir) / f"{len(self.runs) + 1}.out"
|
|
54
|
+
r = run_command(cmd, self.workdir, out, timeout_s, main=self.main)
|
|
55
|
+
self.runs.append(r)
|
|
56
|
+
return r
|
|
57
|
+
|
|
58
|
+
@staticmethod
|
|
59
|
+
def scrub(text: str) -> str:
|
|
60
|
+
return scrub(text)
|
|
61
|
+
|
|
62
|
+
@staticmethod
|
|
63
|
+
def clip(text: str, n: int) -> str:
|
|
64
|
+
return clip(text, n)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(kw_only=True)
|
|
68
|
+
class FinalizerResult:
|
|
69
|
+
outcome: str
|
|
70
|
+
reason: str = ""
|
|
71
|
+
url: str | None = None
|
|
72
|
+
manual_steps: list[str] = field(default_factory=list)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def recorded_pull_request(result: Mapping[str, Any] | None, workdir: Path | None) -> dict[str, Any] | None:
|
|
76
|
+
"""FIN-B11: the code host, repository, number and end commit of the pull request the `finalized` result's url
|
|
77
|
+
names; none for no url or a url that names no pull request. It holds no text."""
|
|
78
|
+
from tempergraph import git
|
|
79
|
+
from tempergraph.improve.proposals import pull_ref
|
|
80
|
+
|
|
81
|
+
ref = pull_ref((result or {}).get("url"))
|
|
82
|
+
if ref is None:
|
|
83
|
+
return None
|
|
84
|
+
commit = ""
|
|
85
|
+
if workdir is not None:
|
|
86
|
+
try:
|
|
87
|
+
commit = git.head(workdir)
|
|
88
|
+
except Exception: # noqa: BLE001 - a workspace that is gone has no end commit to record
|
|
89
|
+
commit = ""
|
|
90
|
+
return {"host": ref[0], "repo": ref[1], "number": ref[2], "commit": commit}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def run_finalizer(ctx: RunContext, state: Mapping[str, Any]) -> dict[str, Any]:
|
|
94
|
+
spec = ctx.spec
|
|
95
|
+
if spec.finalizer is None:
|
|
96
|
+
return {"outcome": "none"}
|
|
97
|
+
ws = state.get("workspace") or {}
|
|
98
|
+
workdir = Path(ws.get("path") or ctx.state_root.parent)
|
|
99
|
+
open_warnings = sum(len((j or {}).get("notes") or []) for j in (state.get("judgements") or {}).values())
|
|
100
|
+
fctx = FinalizerContext(
|
|
101
|
+
task_id=ctx.task_id, thread_id=ctx.thread, workflow=spec.name, branch=str(ws.get("branch") or ""),
|
|
102
|
+
base=str(ws.get("base_branch") or ""), workdir=workdir, artifacts=state.get("artifacts") or {},
|
|
103
|
+
values=state.get("values") or {}, facts=state.get("facts") or {}, open_warnings=open_warnings,
|
|
104
|
+
degraded=False, run_options={"mode": ws.get("mode")}, git=checkmod.git_facts(workdir),
|
|
105
|
+
allow=tuple(spec.allow_commands), main=ctx.main_checkout, settings=dict(ctx.settings),
|
|
106
|
+
out_dir=ctx.state_root / "runs" / spec.name / ctx.task_id / "finalizer")
|
|
107
|
+
box: dict[str, Any] = {}
|
|
108
|
+
fn = spec.finalizer.resolve()
|
|
109
|
+
|
|
110
|
+
def call() -> None:
|
|
111
|
+
try:
|
|
112
|
+
box["result"] = fn(fctx)
|
|
113
|
+
except Exception as exc: # noqa: BLE001 - recorded as `error`
|
|
114
|
+
box["error"] = type(exc).__name__
|
|
115
|
+
|
|
116
|
+
t0 = time.monotonic()
|
|
117
|
+
th = threading.Thread(target=call, name="finalizer", daemon=True)
|
|
118
|
+
th.start()
|
|
119
|
+
th.join(FINALIZER_LIMIT_S)
|
|
120
|
+
dur = round(time.monotonic() - t0, 3)
|
|
121
|
+
if th.is_alive():
|
|
122
|
+
return {"outcome": "error", "reason": "timed_out", "duration_s": dur}
|
|
123
|
+
if "error" in box:
|
|
124
|
+
return {"outcome": "error", "reason": box["error"], "duration_s": dur}
|
|
125
|
+
res = box.get("result")
|
|
126
|
+
if not isinstance(res, FinalizerResult):
|
|
127
|
+
return {"outcome": "invalid", "reason": clip(scrub(repr(res)), 200), "duration_s": dur}
|
|
128
|
+
outcome = res.outcome if res.outcome in spec.finalizer_outcomes else "invalid"
|
|
129
|
+
reason = clip(scrub(res.reason if outcome != "invalid" else res.outcome), 200)
|
|
130
|
+
return {"outcome": outcome, "reason": reason, "url": res.url, "manual_steps": [clip(scrub(m), 300) for m in
|
|
131
|
+
res.manual_steps[:5]],
|
|
132
|
+
"duration_s": dur}
|