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,444 @@
|
|
|
1
|
+
"""The machine index (CST-B8), the per-user stats rows (OBS-B15, CST-B9 `run`) and their readers.
|
|
2
|
+
|
|
3
|
+
Rows are written from the run log at each `run_exit`, by :func:`on_run_exit`, which the run log's writer calls
|
|
4
|
+
after the record is on disk; the index is touched at `run_started` by :func:`on_run_started`. Both are best
|
|
5
|
+
effort and never change a run (OVR-B4). `stats` and `attention` only read (OVR-B15).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import statistics
|
|
14
|
+
import time
|
|
15
|
+
import uuid
|
|
16
|
+
from collections import defaultdict
|
|
17
|
+
from collections.abc import Iterable, Iterator
|
|
18
|
+
from datetime import UTC, datetime
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from tempergraph.docs import append_jsonl, write_json
|
|
23
|
+
from tempergraph.store.layout import ensure_home, home_path, now_iso
|
|
24
|
+
|
|
25
|
+
INDEX_LOCK_S = 2.0
|
|
26
|
+
TOKENS = ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "thinking_tokens")
|
|
27
|
+
BY = ("machine", "user", "repo", "workflow", "version", "executor", "model", "ticket", "exit", "month", "parent",
|
|
28
|
+
"schedule", "level", "decider", "host")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _parts(log: Path) -> tuple[Path, str, str]:
|
|
32
|
+
"""`<state root>/runs/<workflow>/<task>/run.jsonl` → (state root, workflow, task)."""
|
|
33
|
+
return log.parents[3], log.parent.parent.name, log.parent.name
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# -- machine index ---------------------------------------------------------------------------------------------
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@contextlib.contextmanager
|
|
40
|
+
def _locked(path: Path, wait_s: float = INDEX_LOCK_S) -> Iterator[bool]:
|
|
41
|
+
lock = path.with_suffix(".lock")
|
|
42
|
+
deadline = time.monotonic() + wait_s
|
|
43
|
+
fd = None
|
|
44
|
+
while fd is None:
|
|
45
|
+
try:
|
|
46
|
+
fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
47
|
+
except FileExistsError:
|
|
48
|
+
with contextlib.suppress(OSError):
|
|
49
|
+
if time.time() - lock.stat().st_mtime > 30: # a holder that died long ago
|
|
50
|
+
lock.unlink()
|
|
51
|
+
continue
|
|
52
|
+
if time.monotonic() >= deadline:
|
|
53
|
+
yield False
|
|
54
|
+
return
|
|
55
|
+
time.sleep(0.05)
|
|
56
|
+
try:
|
|
57
|
+
yield True
|
|
58
|
+
finally:
|
|
59
|
+
os.close(fd)
|
|
60
|
+
with contextlib.suppress(OSError):
|
|
61
|
+
lock.unlink()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def read_index(home: Path | None = None) -> list[dict[str, Any]]:
|
|
65
|
+
path = (home or home_path()) / "index.json"
|
|
66
|
+
try:
|
|
67
|
+
doc = json.loads(path.read_text(encoding="utf-8"))
|
|
68
|
+
except (OSError, ValueError):
|
|
69
|
+
return []
|
|
70
|
+
roots = doc.get("roots") if isinstance(doc, dict) else None
|
|
71
|
+
return [r for r in roots if isinstance(r, dict) and r.get("path")] if isinstance(roots, list) else []
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def touch_index(state_root: Path, home: Path | None = None, now: str | None = None) -> bool:
|
|
75
|
+
"""Adds or refreshes this state root in `~/.tempergraph/index.json` under a lock (CST-B8, LOS-B6)."""
|
|
76
|
+
home = ensure_home(home)
|
|
77
|
+
path = home / "index.json"
|
|
78
|
+
stamp = now or now_iso()
|
|
79
|
+
with _locked(path) as got:
|
|
80
|
+
if not got:
|
|
81
|
+
return False
|
|
82
|
+
roots = read_index(home)
|
|
83
|
+
key = str(state_root.resolve())
|
|
84
|
+
for r in roots:
|
|
85
|
+
if r["path"] == key:
|
|
86
|
+
r["last_run_at"] = stamp
|
|
87
|
+
break
|
|
88
|
+
else:
|
|
89
|
+
roots.append({"path": key, "repository": state_root.resolve().parent.name, "first_seen": stamp,
|
|
90
|
+
"last_run_at": stamp})
|
|
91
|
+
write_json(path, {"schema_version": 1, "roots": roots})
|
|
92
|
+
return True
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def index_roots(home: Path | None = None) -> list[dict[str, Any]]:
|
|
96
|
+
"""Every indexed state root with `missing` when its folder is gone; the index is never changed by a reader."""
|
|
97
|
+
return [{**r, "missing": not Path(r["path"]).is_dir()} for r in read_index(home)]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# -- stats rows ------------------------------------------------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _machine(home: Path) -> dict[str, Any]:
|
|
104
|
+
try:
|
|
105
|
+
return dict(json.loads((home / "machine.json").read_text(encoding="utf-8")))
|
|
106
|
+
except (OSError, ValueError):
|
|
107
|
+
return {}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _git_user(state_root: Path) -> str | None:
|
|
111
|
+
from tempergraph import git
|
|
112
|
+
|
|
113
|
+
try:
|
|
114
|
+
name = git.git(["config", "user.name"], state_root.parent, check=False).strip()
|
|
115
|
+
except Exception: # noqa: BLE001
|
|
116
|
+
return None
|
|
117
|
+
return name or None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _ts(text: Any) -> float | None:
|
|
121
|
+
try:
|
|
122
|
+
return datetime.fromisoformat(str(text).replace("Z", "+00:00")).timestamp()
|
|
123
|
+
except ValueError:
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _schedule_id(block: Any) -> str | None:
|
|
128
|
+
"""The schedule a run belongs to: from the `schedule` block of `run_started` (TCK-B24), or a bare id."""
|
|
129
|
+
if isinstance(block, dict):
|
|
130
|
+
return str(block["schedule_id"]) if block.get("schedule_id") else None
|
|
131
|
+
return str(block) if block else None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def schedule_report(home: Path | None = None) -> dict[str, Any]:
|
|
135
|
+
"""`report --by schedule` (TCK-B24): per schedule its fires, outcomes, cost, skipped and missed counts, read from the
|
|
136
|
+
fire logs (`ended` rows carry each run's cost), and the totals of those figures. Read-only."""
|
|
137
|
+
from tempergraph.schedule import store
|
|
138
|
+
|
|
139
|
+
groups: dict[str, dict[str, Any]] = {}
|
|
140
|
+
for entry in store.list_entries(home):
|
|
141
|
+
sid = str(entry["schedule_id"])
|
|
142
|
+
log = store.read_log(sid, home)
|
|
143
|
+
ended = {str(e["fire_id"]): e for e in log if e.get("kind") == "ended"}
|
|
144
|
+
started = [e for e in log if e.get("kind") == "started"]
|
|
145
|
+
cost = [float((ended[str(e["fire_id"])].get("cost") or {}).get("estimated") or 0.0)
|
|
146
|
+
for e in started if str(e.get("fire_id")) in ended]
|
|
147
|
+
groups[sid] = {"fires": len(started), "ended": len(ended),
|
|
148
|
+
"outcomes": dict(sorted(_count(str(e.get("outcome")) for e in ended.values()).items())),
|
|
149
|
+
"exits": dict(sorted(_count(str(e.get("exit")) for e in ended.values()).items())),
|
|
150
|
+
"estimated_usd": round(sum(cost), 6),
|
|
151
|
+
"incomplete": any((e.get("cost") or {}).get("incomplete") for e in ended.values()),
|
|
152
|
+
"skipped": sum(1 for e in log if e.get("kind") == "skipped"),
|
|
153
|
+
"missed": sum(1 for e in log if e.get("kind") == "missed"),
|
|
154
|
+
"refused": sum(1 for e in log if e.get("kind") == "refused")}
|
|
155
|
+
keys = ("fires", "ended", "estimated_usd", "skipped", "missed", "refused")
|
|
156
|
+
total = {k: round(sum(g[k] for g in groups.values()), 6) for k in keys}
|
|
157
|
+
total["incomplete"] = any(g["incomplete"] for g in groups.values())
|
|
158
|
+
return {"schema_version": 1, "by": "schedule", "groups": groups, "totals": total}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def run_row(log: Path, recs: Iterable[dict[str, Any]], segment: int | None = None) -> dict[str, Any] | None:
|
|
162
|
+
"""The `run` row of one segment of a thread, from its run log (CST-B9, OBS-B15); numbers and names only."""
|
|
163
|
+
root, workflow, task = _parts(log)
|
|
164
|
+
started: dict[str, Any] | None = None
|
|
165
|
+
exit_: dict[str, Any] | None = None
|
|
166
|
+
executors: set[str] = set()
|
|
167
|
+
models: set[str] = set()
|
|
168
|
+
units: set[str] = set()
|
|
169
|
+
repeats: dict[str, int] = defaultdict(int)
|
|
170
|
+
verdicts: dict[str, int] = defaultdict(int)
|
|
171
|
+
tokens: dict[str, int | None] = dict.fromkeys(TOKENS)
|
|
172
|
+
rep = est = 0.0
|
|
173
|
+
n = n_rep = n_est = unmeasured = 0
|
|
174
|
+
agent_s = 0.0
|
|
175
|
+
wait_s = 0.0
|
|
176
|
+
attempts: dict[str, int] = defaultdict(int)
|
|
177
|
+
sup: dict[str, Any] | None = None
|
|
178
|
+
for r in recs:
|
|
179
|
+
if segment is not None and r.get("segment") != segment:
|
|
180
|
+
continue
|
|
181
|
+
kind = r.get("kind")
|
|
182
|
+
if kind == "run_started":
|
|
183
|
+
started = r
|
|
184
|
+
elif kind == "run_exit":
|
|
185
|
+
exit_ = r
|
|
186
|
+
elif kind == "unit_entered" and r.get("unit"):
|
|
187
|
+
units.add(str(r["unit"]))
|
|
188
|
+
if int(r.get("visit") or 1) > 1:
|
|
189
|
+
repeats[str(r.get("entered_from") or "revisit").split(":", 1)[0]] += 1
|
|
190
|
+
elif kind == "attempt_start" and r.get("session_kind") in ("step", "retry") and r.get("unit"):
|
|
191
|
+
attempts[str(r["unit"])] += 1
|
|
192
|
+
if r.get("session_kind") == "retry":
|
|
193
|
+
repeats["retry"] += 1
|
|
194
|
+
elif kind == "agent_run":
|
|
195
|
+
n += 1
|
|
196
|
+
if r.get("executor"):
|
|
197
|
+
executors.add(str(r["executor"]))
|
|
198
|
+
u = r.get("usage") or {}
|
|
199
|
+
for m in (u.get("by_model") or {}):
|
|
200
|
+
models.add(str(m))
|
|
201
|
+
for t in TOKENS:
|
|
202
|
+
v = u.get(t)
|
|
203
|
+
if isinstance(v, int):
|
|
204
|
+
tokens[t] = (tokens[t] or 0) + v
|
|
205
|
+
rc, ec = u.get("reported_cost_usd"), u.get("estimated_cost_usd")
|
|
206
|
+
if isinstance(rc, int | float):
|
|
207
|
+
rep, n_rep = rep + rc, n_rep + 1
|
|
208
|
+
if isinstance(ec, int | float):
|
|
209
|
+
est, n_est = est + ec, n_est + 1
|
|
210
|
+
if not isinstance(rc, int | float) and not isinstance(ec, int | float):
|
|
211
|
+
unmeasured += 1
|
|
212
|
+
if isinstance(r.get("duration_s"), int | float):
|
|
213
|
+
agent_s += float(r["duration_s"])
|
|
214
|
+
elif kind == "gate" and r.get("verdict"):
|
|
215
|
+
verdicts[str(r["verdict"])] += 1
|
|
216
|
+
elif kind == "supervision":
|
|
217
|
+
sup = r
|
|
218
|
+
elif kind == "human" and isinstance(r.get("wait_s"), int | float):
|
|
219
|
+
wait_s += float(r["wait_s"])
|
|
220
|
+
if exit_ is None:
|
|
221
|
+
return None
|
|
222
|
+
t0, t1 = _ts((started or {}).get("ts")), _ts(exit_.get("ts"))
|
|
223
|
+
home = home_path()
|
|
224
|
+
completeness = "incomplete" if unmeasured else "complete" if n_rep == n else "estimated"
|
|
225
|
+
return {
|
|
226
|
+
"row_id": str(uuid.uuid4()), "kind": "run", "schema_version": 1,
|
|
227
|
+
"machine_id": _machine(home).get("machine_id"), "user": _git_user(root),
|
|
228
|
+
"repo": root.parent.name, "state_root": str(root), "workflow": workflow,
|
|
229
|
+
"workflow_version": (started or {}).get("workflow_version"), "thread_id": f"{workflow}/{task}",
|
|
230
|
+
"segment": exit_.get("segment"), "alias": (started or {}).get("alias"), "label": (started or {}).get("label"),
|
|
231
|
+
"origin": (started or {}).get("origin"), "parent": (started or {}).get("parent"),
|
|
232
|
+
"schedule_id": _schedule_id((started or {}).get("schedule")), "ticket": task,
|
|
233
|
+
"executors": sorted(executors), "models": sorted(models),
|
|
234
|
+
"exit_code": exit_.get("exit_code"), "reason": exit_.get("reason"), "units_run": len(units),
|
|
235
|
+
"repeats": dict(repeats), "gate_verdicts": dict(verdicts), "escapes": None, "tokens": tokens,
|
|
236
|
+
"sessions": n, "reported_sessions": n_rep, "estimated_sessions": n_est, "unmeasured_sessions": unmeasured,
|
|
237
|
+
"reported_cost_usd": round(rep, 6) if n_rep else None, "estimated_cost_usd": round(est, 6) if n_est else None,
|
|
238
|
+
"completeness": completeness, "wall_s": round(t1 - t0, 3) if t0 is not None and t1 is not None else None,
|
|
239
|
+
"agent_s": round(agent_s, 3) if agent_s else None, "person_wait_s": round(wait_s, 3) if wait_s else None,
|
|
240
|
+
# copied from the segment's supervision record, the builder the ledger row uses too (SUP-AC2)
|
|
241
|
+
**_supervision_fields(sup),
|
|
242
|
+
"ended_at": exit_.get("ts"),
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def session_rows(log: Path, recs: Iterable[dict[str, Any]], run: dict[str, Any]) -> list[dict[str, Any]]:
|
|
247
|
+
"""The `session` rows of one segment, one per `agent_run` (CST-B9): numbers and engine words only."""
|
|
248
|
+
out = []
|
|
249
|
+
for r in recs:
|
|
250
|
+
if r.get("kind") != "agent_run" or r.get("segment") != run.get("segment"):
|
|
251
|
+
continue
|
|
252
|
+
u = r.get("usage") or {}
|
|
253
|
+
models = sorted((u.get("by_model") or {}).keys())
|
|
254
|
+
outcome = "ok" if r.get("ok") else "timed_out" if r.get("timed_out") else "stalled" if r.get("stalled") \
|
|
255
|
+
else "infra" if r.get("infra_cause") else "failed"
|
|
256
|
+
out.append({"row_id": str(uuid.uuid4()), "kind": "session", "schema_version": 1,
|
|
257
|
+
"machine_id": run.get("machine_id"), "thread_id": run.get("thread_id"),
|
|
258
|
+
"state_root": run.get("state_root"), "workflow": run.get("workflow"),
|
|
259
|
+
"workflow_version": run.get("workflow_version"), "segment": run.get("segment"),
|
|
260
|
+
"unit": r.get("unit"), "session_kind": r.get("session_kind") or "step",
|
|
261
|
+
"executor": r.get("executor"), "model": models[0] if len(models) == 1 else None,
|
|
262
|
+
"tokens": {t: u.get(t) for t in TOKENS}, "reported_cost_usd": u.get("reported_cost_usd"),
|
|
263
|
+
"estimated_cost_usd": u.get("estimated_cost_usd"), "duration_s": r.get("duration_s"),
|
|
264
|
+
"slow_host": bool(r.get("slow_host")), "outcome": outcome, "tool_calls": len(r.get("tools") or []),
|
|
265
|
+
"ended_at": r.get("ts")})
|
|
266
|
+
return out
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _supervision_fields(sup: dict[str, Any] | None) -> dict[str, Any]:
|
|
270
|
+
if sup is None:
|
|
271
|
+
return dict.fromkeys(("touches_undesigned", "touches_by_decider", "agent_own_rescues", "level", "level_by",
|
|
272
|
+
"callers_unknown"))
|
|
273
|
+
by: dict[str, int] = defaultdict(int)
|
|
274
|
+
for cls in ("rescue", "steer"):
|
|
275
|
+
for d, n in ((sup.get("touches") or {}).get(cls) or {}).items():
|
|
276
|
+
if isinstance(n, int) and n:
|
|
277
|
+
by[d] += n
|
|
278
|
+
return {"touches_undesigned": sup.get("undesigned"), "touches_by_decider": dict(sorted(by.items())),
|
|
279
|
+
"agent_own_rescues": sup.get("agent_own_rescues"), "level": sup.get("level"),
|
|
280
|
+
"level_by": sup.get("level_by"), "callers_unknown": sup.get("callers_unknown")}
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def stats_path(home: Path, month: str) -> Path:
|
|
284
|
+
return home / "stats" / f"{month}.jsonl"
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def append_stats_row(path: Path, row: dict[str, Any]) -> None:
|
|
288
|
+
"""Append `row` to the stats file `path` under the lock beside it (`<month>.lock`).
|
|
289
|
+
|
|
290
|
+
The writers of the stats files and `stats forget` take this one lock, so a row appended while the verb replaces
|
|
291
|
+
the file is not lost (CST-B23). A writer that does not get the lock within :data:`INDEX_LOCK_S` appends anyway,
|
|
292
|
+
so a run's row is never dropped; such a writer is not protected from a rewrite."""
|
|
293
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
294
|
+
with _locked(path):
|
|
295
|
+
append_jsonl(path, row)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def on_run_started(log: Path) -> None:
|
|
299
|
+
"""Called by the run log's writer after `run_started`: the machine index (CST-B8); best effort."""
|
|
300
|
+
try:
|
|
301
|
+
touch_index(_parts(log)[0])
|
|
302
|
+
except Exception: # noqa: BLE001 - C2, LOS-B6
|
|
303
|
+
import logging
|
|
304
|
+
|
|
305
|
+
logging.getLogger("tempergraph.index").warning("machine index not updated")
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def on_run_exit(log: Path, segment: int | None) -> None:
|
|
309
|
+
"""Called by the run log's writer after `run_exit`: the stats row and the outbox rows; best effort (OVR-B4)."""
|
|
310
|
+
try:
|
|
311
|
+
from tempergraph.run.events import records
|
|
312
|
+
|
|
313
|
+
row = run_row(log, records(log), segment)
|
|
314
|
+
if row is None:
|
|
315
|
+
return
|
|
316
|
+
home = ensure_home()
|
|
317
|
+
month = str(row["ended_at"] or now_iso())[:7]
|
|
318
|
+
append_stats_row(stats_path(home, month), row)
|
|
319
|
+
sessions = session_rows(log, records(log), row)
|
|
320
|
+
for srow in sessions:
|
|
321
|
+
append_stats_row(home / "stats" / "sessions" / f"{month}.jsonl", srow)
|
|
322
|
+
from tempergraph.observe import sinks, supervision_cost
|
|
323
|
+
|
|
324
|
+
with contextlib.suppress(Exception): # SCO-B15: the next writing process closes what has ended
|
|
325
|
+
supervision_cost.close(home)
|
|
326
|
+
if sinks.enqueue(home, row, log) + sinks.enqueue_sessions(home, sessions, log, month):
|
|
327
|
+
sinks.start_flusher(home)
|
|
328
|
+
except Exception: # noqa: BLE001
|
|
329
|
+
import logging
|
|
330
|
+
|
|
331
|
+
logging.getLogger("tempergraph.stats").warning("stats row not written")
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
# -- readers ---------------------------------------------------------------------------------------------------
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
SAME = ("kind", "machine_id", "workflow", "segment", "exit_code", "ended_at") # equal in a row's local and sink form
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def read_rows(paths: Iterable[Path], conflicts: list[str] | None = None) -> tuple[list[dict[str, Any]], int]:
|
|
341
|
+
"""Rows from JSON-lines files, de-duplicated by `row_id` (CST-AC3); a newer major schema is skipped. A
|
|
342
|
+
repeated `row_id` whose content differs (a copied `machine.json` or stats file) is kept twice and its id
|
|
343
|
+
added to `conflicts` (CST-B10, CST-B14, CST-B8)."""
|
|
344
|
+
seen: dict[str, tuple[Any, ...]] = {}
|
|
345
|
+
out: list[dict[str, Any]] = []
|
|
346
|
+
unknown = 0
|
|
347
|
+
for p in paths:
|
|
348
|
+
try:
|
|
349
|
+
lines = p.read_text(encoding="utf-8").splitlines()
|
|
350
|
+
except OSError:
|
|
351
|
+
continue
|
|
352
|
+
for ln in lines:
|
|
353
|
+
try:
|
|
354
|
+
r = json.loads(ln)
|
|
355
|
+
except ValueError:
|
|
356
|
+
continue
|
|
357
|
+
if not isinstance(r, dict):
|
|
358
|
+
continue
|
|
359
|
+
if int(r.get("schema_version") or 1) > 1:
|
|
360
|
+
unknown += 1
|
|
361
|
+
continue
|
|
362
|
+
rid = str(r.get("row_id") or "")
|
|
363
|
+
same = tuple(r.get(k) for k in SAME)
|
|
364
|
+
if rid and rid in seen:
|
|
365
|
+
if seen[rid] == same:
|
|
366
|
+
continue
|
|
367
|
+
if conflicts is not None and rid not in conflicts:
|
|
368
|
+
conflicts.append(rid)
|
|
369
|
+
seen.setdefault(rid, same)
|
|
370
|
+
out.append(r)
|
|
371
|
+
return out, unknown
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _key(r: dict[str, Any], by: str) -> str:
|
|
375
|
+
if by == "version":
|
|
376
|
+
return f"{r.get('workflow')}@{r.get('workflow_version') or '?'}"
|
|
377
|
+
if by == "exit":
|
|
378
|
+
return str(r.get("exit_code"))
|
|
379
|
+
if by == "month":
|
|
380
|
+
return str(r.get("ended_at") or "")[:7]
|
|
381
|
+
if by == "executor":
|
|
382
|
+
return ",".join(r.get("executors") or []) or "none"
|
|
383
|
+
if by == "model":
|
|
384
|
+
return ",".join(r.get("models") or []) or "not recorded"
|
|
385
|
+
if by == "machine":
|
|
386
|
+
mid = str(r.get("machine_id") or "?") # two machines may share a label (a host name); never one key
|
|
387
|
+
return f"{r['machine_label']} ({mid[:8]})" if r.get("machine_label") else mid
|
|
388
|
+
if by == "schedule":
|
|
389
|
+
return str(r.get("schedule_id") or "none")
|
|
390
|
+
if by == "decider":
|
|
391
|
+
return ",".join(sorted((r.get("touches_by_decider") or {}).keys())) or "none"
|
|
392
|
+
if by == "repo":
|
|
393
|
+
return str(r.get("repo_id") or r.get("repo") or "none")
|
|
394
|
+
field = {"user": "user", "workflow": "workflow", "ticket": "ticket", "parent": "parent",
|
|
395
|
+
"level": "level", "host": "host"}[by]
|
|
396
|
+
return str(r.get(field) or "none")
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def totals(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
|
400
|
+
"""Run count, thread count, and reported and estimated cost apart with the completeness flag (CST-B14, CST-B15, CST-B16)."""
|
|
401
|
+
rep = [r["reported_cost_usd"] for r in rows if isinstance(r.get("reported_cost_usd"), int | float)]
|
|
402
|
+
est = [r["estimated_cost_usd"] for r in rows if isinstance(r.get("estimated_cost_usd"), int | float)]
|
|
403
|
+
incomplete = any(r.get("completeness") == "incomplete" for r in rows)
|
|
404
|
+
estimated = any(r.get("completeness") == "estimated" for r in rows)
|
|
405
|
+
return {"runs": len(rows), "threads": len({r.get("thread_id") or r.get("thread_hash") for r in rows}),
|
|
406
|
+
"reported_usd": round(sum(rep), 6) if rep else None, "estimated_usd": round(sum(est), 6) if est else None,
|
|
407
|
+
"completeness": "incomplete" if incomplete else "estimated" if estimated else "complete",
|
|
408
|
+
"lower_bound": incomplete,
|
|
409
|
+
"exits": dict(sorted(_count(str(r.get("exit_code")) for r in rows).items()))}
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _count(xs: Iterable[str]) -> dict[str, int]:
|
|
413
|
+
out: dict[str, int] = defaultdict(int)
|
|
414
|
+
for x in xs:
|
|
415
|
+
out[x] += 1
|
|
416
|
+
return out
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def projection(rows: list[dict[str, Any]], by_version: bool = False) -> list[dict[str, Any]]:
|
|
420
|
+
"""Median and 90th percentile of estimated cost per finished run, per workflow (CST-B14, CST-B15, CST-B16); `thin` under 5."""
|
|
421
|
+
per: dict[str, dict[str, float]] = defaultdict(dict)
|
|
422
|
+
finished: set[str] = set()
|
|
423
|
+
for r in rows:
|
|
424
|
+
tid = str(r.get("thread_id") or r.get("thread_hash"))
|
|
425
|
+
key = f"{r.get('workflow')}@{r.get('workflow_version') or '?'}" if by_version else str(r.get("workflow"))
|
|
426
|
+
cost = r.get("estimated_cost_usd") if isinstance(r.get("estimated_cost_usd"), int | float) \
|
|
427
|
+
else r.get("reported_cost_usd")
|
|
428
|
+
if isinstance(cost, int | float):
|
|
429
|
+
per[key][tid] = per[key].get(tid, 0.0) + float(cost)
|
|
430
|
+
if r.get("exit_code") == 0:
|
|
431
|
+
finished.add(tid)
|
|
432
|
+
out = []
|
|
433
|
+
for key, threads in sorted(per.items()):
|
|
434
|
+
costs = sorted(c for t, c in threads.items() if t in finished)
|
|
435
|
+
if not costs:
|
|
436
|
+
continue
|
|
437
|
+
p90 = costs[min(len(costs) - 1, max(0, round(0.9 * len(costs) + 0.5) - 1))]
|
|
438
|
+
out.append({"workflow": key, "runs": len(costs), "median_usd": round(statistics.median(costs), 6),
|
|
439
|
+
"p90_usd": round(p90, 6), "thin": len(costs) < 5})
|
|
440
|
+
return out
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def month_now() -> str:
|
|
444
|
+
return datetime.now(UTC).strftime("%Y-%m")
|