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,793 @@
|
|
|
1
|
+
"""Sinks for run rows and heartbeats (CST-B10, CST-B12, CST-B13, CST-B11), the fleet copy at home, and the readers (CST-B14, CST-B15, CST-B16).
|
|
2
|
+
|
|
3
|
+
Nothing leaves the machine unless the operator lists a sink in `config/sinks.json` of the home folder or the
|
|
4
|
+
state root (CST-B1). A run's exit appends a *reference* to its local stats row to each sink's outbox; the
|
|
5
|
+
flusher builds the sink row from that local row with the sink's key, appends it to this machine's folder in
|
|
6
|
+
the sink, and only then drops the reference, so an outbox never holds names or text (CST-B5) and a row may
|
|
7
|
+
arrive twice (readers de-duplicate by `row_id`). Every flush also syncs the fleet copy under
|
|
8
|
+
`~/.tempergraph/fleet/<sink>/`, which `stats` reads with no sink access at query time (CST-B7).
|
|
9
|
+
|
|
10
|
+
The flusher is detached by default, so a slow share never delays a run's exit; `TEMPERGRAPH_FLUSHER=inline`
|
|
11
|
+
flushes in the exiting process and `off` leaves the outbox for `stats flush`.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import contextlib
|
|
17
|
+
import hashlib
|
|
18
|
+
import hmac
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import secrets
|
|
23
|
+
import sys
|
|
24
|
+
import time
|
|
25
|
+
from collections import defaultdict
|
|
26
|
+
from collections.abc import Iterable
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from datetime import datetime
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any
|
|
31
|
+
|
|
32
|
+
from tempergraph.observe.rows import _locked, read_index, read_rows, totals
|
|
33
|
+
from tempergraph.store.layout import now_iso
|
|
34
|
+
|
|
35
|
+
SINKS_FILE = "sinks.json"
|
|
36
|
+
ROW_KINDS = ("run", "heartbeat", "supervision", "session")
|
|
37
|
+
DEFAULT_KINDS = ("run", "heartbeat", "supervision") # `session` rows are opt-in (CST-B9)
|
|
38
|
+
SLUG = re.compile(r"^[a-z0-9-]{1,40}$")
|
|
39
|
+
WORD = re.compile(r"^[a-z0-9_:-]{1,40}$")
|
|
40
|
+
STALE_S = 300
|
|
41
|
+
FAILING_WARN_S = 7 * 86_400
|
|
42
|
+
HEARTBEAT_S = 60.0
|
|
43
|
+
ROLLUP_BY = ("machine", "user", "repo", "workflow", "executor", "model")
|
|
44
|
+
# Fields copied as they are from a local `run` row: numbers, booleans and engine words only (CST-B9).
|
|
45
|
+
COPY = ("row_id", "kind", "schema_version", "machine_id", "workflow", "workflow_version", "segment", "executors",
|
|
46
|
+
"models", "exit_code", "reason", "units_run", "repeats", "gate_verdicts", "escapes", "tokens", "sessions",
|
|
47
|
+
"reported_sessions", "estimated_sessions", "unmeasured_sessions", "reported_cost_usd", "estimated_cost_usd",
|
|
48
|
+
"completeness", "wall_s", "agent_s", "person_wait_s", "touches_undesigned", "touches_by_decider",
|
|
49
|
+
"agent_own_rescues", "level", "level_by", "callers_unknown", "ended_at")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class SinkConfigError(ValueError):
|
|
53
|
+
"""A `sinks.json` the engine refuses (CST-B10, CST-B14, CST-B8): exit 2 from the `stats` verbs."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True, kw_only=True)
|
|
57
|
+
class Sink:
|
|
58
|
+
name: str
|
|
59
|
+
kind: str
|
|
60
|
+
path: Path
|
|
61
|
+
include: tuple[str, ...] = DEFAULT_KINDS
|
|
62
|
+
user: str = "hash"
|
|
63
|
+
repo: str = "hash"
|
|
64
|
+
tickets: bool = False
|
|
65
|
+
|
|
66
|
+
def takes(self, kind: str) -> bool:
|
|
67
|
+
return kind in self.include
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# -- configuration ---------------------------------------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _file(folder: Path) -> list[dict[str, Any]]:
|
|
74
|
+
p = folder / "config" / SINKS_FILE
|
|
75
|
+
if not p.exists():
|
|
76
|
+
return []
|
|
77
|
+
try:
|
|
78
|
+
doc = json.loads(p.read_text(encoding="utf-8"))
|
|
79
|
+
except (OSError, ValueError) as exc:
|
|
80
|
+
raise SinkConfigError(f"{p}: not readable JSON ({type(exc).__name__})") from exc
|
|
81
|
+
entries = doc.get("sinks") if isinstance(doc, dict) else None
|
|
82
|
+
if not isinstance(entries, list):
|
|
83
|
+
raise SinkConfigError(f"{p}: needs a `sinks` list")
|
|
84
|
+
names = [str(e.get("name")) for e in entries if isinstance(e, dict)]
|
|
85
|
+
dup = sorted({n for n in names if names.count(n) > 1})
|
|
86
|
+
if dup:
|
|
87
|
+
raise SinkConfigError(f"{p}: two sinks named {dup[0]!r}")
|
|
88
|
+
return [dict(e, _file=str(p)) for e in entries if isinstance(e, dict)]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _sink(e: dict[str, Any]) -> Sink:
|
|
92
|
+
where = e.get("_file")
|
|
93
|
+
name, kind = str(e.get("name") or ""), str(e.get("kind") or "directory")
|
|
94
|
+
if not SLUG.match(name):
|
|
95
|
+
raise SinkConfigError(f"{where}: sink name {name!r} must match [a-z0-9-]{{1,40}}")
|
|
96
|
+
if kind == "otlp":
|
|
97
|
+
raise SinkConfigError(f"{where}: sink {name!r}: the otlp kind is designed but not in this release (TEL)")
|
|
98
|
+
if kind != "directory" or not e.get("path"):
|
|
99
|
+
raise SinkConfigError(f"{where}: sink {name!r} needs kind `directory` and a `path`")
|
|
100
|
+
include = tuple(e.get("include") or DEFAULT_KINDS)
|
|
101
|
+
bad = [k for k in include if k not in ROW_KINDS]
|
|
102
|
+
user, repo = str(e.get("user") or "hash"), str(e.get("repo") or "hash")
|
|
103
|
+
if bad or user not in ("name", "hash", "none") or repo not in ("name", "hash"):
|
|
104
|
+
raise SinkConfigError(f"{where}: sink {name!r}: include, user or repo has a value it does not take")
|
|
105
|
+
return Sink(name=name, kind=kind, path=Path(str(e["path"])).expanduser(), include=include, user=user,
|
|
106
|
+
repo=repo, tickets=e.get("tickets") is True)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def load(home: Path, state_root: Path | None = None) -> list[Sink]:
|
|
110
|
+
"""The sinks in force: the home folder's list, a state root's entries replacing those of the same name."""
|
|
111
|
+
merged: dict[str, dict[str, Any]] = {}
|
|
112
|
+
for folder in (home, state_root):
|
|
113
|
+
if folder is not None:
|
|
114
|
+
for e in _file(folder):
|
|
115
|
+
merged[str(e.get("name"))] = e
|
|
116
|
+
return [_sink(e) for e in merged.values()]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def find(home: Path, name: str, state_root: Path | None = None) -> Sink | None:
|
|
120
|
+
return next((s for s in load(home, state_root) if s.name == name), None)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# -- identity (CST-B11) ---------------------------------------------------------------------------------------
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def sink_key(sink: Sink) -> bytes | None:
|
|
127
|
+
"""The sink's shared key from `<path>/sink.json`, made by the first machine that writes; None if unreachable."""
|
|
128
|
+
if not sink.path.is_dir():
|
|
129
|
+
return None
|
|
130
|
+
p = sink.path / "sink.json"
|
|
131
|
+
for _ in range(2):
|
|
132
|
+
try:
|
|
133
|
+
return bytes.fromhex(str(json.loads(p.read_text(encoding="utf-8"))["key"]))
|
|
134
|
+
except FileNotFoundError:
|
|
135
|
+
pass
|
|
136
|
+
except (OSError, ValueError, KeyError):
|
|
137
|
+
return None
|
|
138
|
+
try:
|
|
139
|
+
fd = os.open(p, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
140
|
+
except FileExistsError:
|
|
141
|
+
time.sleep(0.05)
|
|
142
|
+
continue
|
|
143
|
+
except OSError:
|
|
144
|
+
return None
|
|
145
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
146
|
+
json.dump({"schema_version": 1, "key": secrets.token_hex(32), "created_at": now_iso()}, fh)
|
|
147
|
+
return None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def digest(key: bytes, text: str) -> str:
|
|
151
|
+
return hmac.new(key, text.encode("utf-8"), hashlib.sha256).hexdigest()[:32]
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def normalize_origin(url: str) -> str:
|
|
155
|
+
"""`git@host:o/r.git`, `https://u:p@host/o/r` → `host/o/r`: no scheme, credentials or `.git`."""
|
|
156
|
+
u = url.strip()
|
|
157
|
+
u = re.sub(r"^[a-z+]+://", "", u)
|
|
158
|
+
u = re.sub(r"^[^@/]*@", "", u)
|
|
159
|
+
u = u.replace(":", "/", 1) if re.match(r"^[^/]+:[^/]", u) else u
|
|
160
|
+
u = re.sub(r"\.git/?$", "", u).rstrip("/")
|
|
161
|
+
host, _, rest = u.partition("/")
|
|
162
|
+
return f"{host.lower()}/{rest}" if rest else host.lower()
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _git(repo_dir: Path, *args: str) -> str:
|
|
166
|
+
from tempergraph import git
|
|
167
|
+
|
|
168
|
+
if not repo_dir.is_dir():
|
|
169
|
+
return ""
|
|
170
|
+
try:
|
|
171
|
+
return git.git(list(args), repo_dir, check=False).strip()
|
|
172
|
+
except git.GitError:
|
|
173
|
+
return ""
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@dataclass
|
|
177
|
+
class _Who:
|
|
178
|
+
"""The git facts one state root's rows are hashed from; read once per flush."""
|
|
179
|
+
|
|
180
|
+
origin: str
|
|
181
|
+
folder: str
|
|
182
|
+
email: str
|
|
183
|
+
name: str
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
_WHO: dict[str, _Who] = {}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _who(state_root: str | None) -> _Who:
|
|
190
|
+
key = str(state_root or "")
|
|
191
|
+
if key not in _WHO:
|
|
192
|
+
repo_dir = Path(key).parent if key else Path.cwd()
|
|
193
|
+
origin = _git(repo_dir, "remote", "get-url", "origin")
|
|
194
|
+
_WHO[key] = _Who(origin=normalize_origin(origin) if origin else "", folder=repo_dir.name,
|
|
195
|
+
email=_git(repo_dir, "config", "user.email"), name=_git(repo_dir, "config", "user.name"))
|
|
196
|
+
return _WHO[key]
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _repo_id(sink: Sink, key: bytes, who: _Who) -> str | None:
|
|
200
|
+
if sink.repo == "name":
|
|
201
|
+
return who.folder or None
|
|
202
|
+
return digest(key, who.origin or f"folder:{who.folder}")
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def sink_row(row: dict[str, Any], sink: Sink, key: bytes) -> dict[str, Any]:
|
|
206
|
+
"""The row a sink receives from a local `run` row: hashed names, no free text (CST-B11, CST-B5)."""
|
|
207
|
+
who = _who(row.get("state_root"))
|
|
208
|
+
out = {k: row.get(k) for k in COPY}
|
|
209
|
+
out["thread_hash"] = digest(key, str(row.get("thread_id")))
|
|
210
|
+
out["repo_id"] = _repo_id(sink, key, who)
|
|
211
|
+
out["user"] = (digest(key, who.email) if who.email else None) if sink.user == "hash" \
|
|
212
|
+
else (row.get("user") or who.name or None) if sink.user == "name" else None
|
|
213
|
+
out["ticket"] = row.get("ticket") if sink.tickets else None
|
|
214
|
+
alias = row.get("alias")
|
|
215
|
+
out["alias"] = alias if isinstance(alias, str) and SLUG.match(alias) else None
|
|
216
|
+
origin = row.get("origin")
|
|
217
|
+
out["origin"] = origin if isinstance(origin, str) and WORD.match(origin) else None
|
|
218
|
+
for f in ("parent", "schedule_id"): # TCK-B24: a scheduled run's `origin` goes as a word, its schedule id as an HMAC
|
|
219
|
+
out[f] = digest(key, str(row[f])) if row.get(f) else None
|
|
220
|
+
return out
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
# -- writing into the sink -------------------------------------------------------------------------------------
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _machine(home: Path) -> dict[str, Any]:
|
|
227
|
+
try:
|
|
228
|
+
return dict(json.loads((home / "machine.json").read_text(encoding="utf-8")))
|
|
229
|
+
except (OSError, ValueError):
|
|
230
|
+
return {}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _replace(path: Path, data: Any) -> None:
|
|
234
|
+
"""Atomic replace with the share's own permissions, so every machine can read it."""
|
|
235
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
236
|
+
tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
|
|
237
|
+
tmp.write_text(json.dumps(data, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
238
|
+
os.replace(tmp, path)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _append(path: Path, row: dict[str, Any]) -> None:
|
|
242
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
243
|
+
with open(path, "a", encoding="utf-8") as fh:
|
|
244
|
+
fh.write(json.dumps(row, ensure_ascii=False) + "\n")
|
|
245
|
+
fh.flush()
|
|
246
|
+
os.fsync(fh.fileno())
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _machine_dir(sink: Sink, home: Path) -> Path:
|
|
250
|
+
from tempergraph.constants import ENGINE_VERSION
|
|
251
|
+
from tempergraph.store.layout import ensure_home
|
|
252
|
+
|
|
253
|
+
me = _machine(ensure_home(home)) # machine.json exists before this machine writes anywhere
|
|
254
|
+
folder = sink.path / "machines" / str(me.get("machine_id") or "unknown")
|
|
255
|
+
if not (folder / "machine.json").exists():
|
|
256
|
+
_replace(folder / "machine.json", {"schema_version": 1, "machine_id": me.get("machine_id"),
|
|
257
|
+
"label": me.get("label"), "engine_version": ENGINE_VERSION,
|
|
258
|
+
"first_seen": now_iso()})
|
|
259
|
+
return folder
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
# -- outbox and flush ------------------------------------------------------------------------------------------
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def outbox(home: Path, name: str) -> Path:
|
|
266
|
+
return home / "outbox" / f"{name}.jsonl"
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def enqueue(home: Path, row: dict[str, Any], log: Path) -> int:
|
|
270
|
+
"""At `run_exit`: a reference to the local row in each sink's outbox; returns how many sinks took it."""
|
|
271
|
+
from tempergraph.docs import append_jsonl
|
|
272
|
+
|
|
273
|
+
root = log.parents[3]
|
|
274
|
+
try:
|
|
275
|
+
sinks = [s for s in load(home, root) if s.takes("run")]
|
|
276
|
+
except SinkConfigError:
|
|
277
|
+
import logging
|
|
278
|
+
|
|
279
|
+
logging.getLogger("tempergraph.sinks").warning("sinks.json refused; no row queued")
|
|
280
|
+
return 0
|
|
281
|
+
month = str(row.get("ended_at") or now_iso())[:7]
|
|
282
|
+
for s in sinks:
|
|
283
|
+
append_jsonl(outbox(home, s.name), {"row_id": row["row_id"], "kind": "run", "month": month,
|
|
284
|
+
"state_root": str(root)})
|
|
285
|
+
return len(sinks)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def enqueue_sessions(home: Path, sessions: list[dict[str, Any]], log: Path, month: str) -> int:
|
|
289
|
+
"""References to the segment's `session` rows for each sink that opted into them."""
|
|
290
|
+
from tempergraph.docs import append_jsonl
|
|
291
|
+
|
|
292
|
+
if not sessions:
|
|
293
|
+
return 0
|
|
294
|
+
root = log.parents[3]
|
|
295
|
+
try:
|
|
296
|
+
takers = [s for s in load(home, root) if s.takes("session")]
|
|
297
|
+
except SinkConfigError:
|
|
298
|
+
return 0
|
|
299
|
+
for s in takers:
|
|
300
|
+
for r in sessions:
|
|
301
|
+
append_jsonl(outbox(home, s.name), {"row_id": r["row_id"], "kind": "session", "month": month,
|
|
302
|
+
"state_root": str(root)})
|
|
303
|
+
return len(takers)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def session_row(row: dict[str, Any], key: bytes) -> dict[str, Any]:
|
|
307
|
+
"""The `session` row a sink receives: the thread hashed, no text (CST-B9, CST-B11)."""
|
|
308
|
+
out = {k: row.get(k) for k in ("row_id", "kind", "schema_version", "machine_id", "workflow", "workflow_version",
|
|
309
|
+
"segment", "unit", "session_kind", "executor", "model", "tokens",
|
|
310
|
+
"reported_cost_usd", "estimated_cost_usd", "duration_s", "slow_host", "outcome",
|
|
311
|
+
"tool_calls", "ended_at")}
|
|
312
|
+
out["thread_hash"] = digest(key, str(row.get("thread_id")))
|
|
313
|
+
return out
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def start_flusher(home: Path) -> None:
|
|
317
|
+
mode = os.environ.get("TEMPERGRAPH_FLUSHER", "detached")
|
|
318
|
+
if mode == "off":
|
|
319
|
+
return
|
|
320
|
+
if mode == "inline":
|
|
321
|
+
flush(home)
|
|
322
|
+
return
|
|
323
|
+
from tempergraph import detach
|
|
324
|
+
|
|
325
|
+
detach.start("tempergraph.observe.sinks", ("flush",), home)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _local_rows(home: Path, month: str, cache: dict[str, dict[str, dict[str, Any]]]) -> dict[str, dict[str, Any]]:
|
|
329
|
+
if month not in cache:
|
|
330
|
+
found, _ = read_rows([home / "stats" / f"{month}.jsonl"])
|
|
331
|
+
cache[month] = {str(r.get("row_id")): r for r in found}
|
|
332
|
+
return cache[month]
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _kept_rows(home: Path, kind: str, month: str, cache: dict[str, dict[str, dict[str, Any]]]
|
|
336
|
+
) -> dict[str, dict[str, Any]]:
|
|
337
|
+
k = f"{kind}:{month}"
|
|
338
|
+
if k not in cache:
|
|
339
|
+
path = home / "supervision" / "rows" if kind == "supervision" else home / "stats" / "sessions"
|
|
340
|
+
cache[k] = {str(r.get("row_id")): r for r in _read_jsonl(path / f"{month}.jsonl")}
|
|
341
|
+
return cache[k]
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def supervision_row(row: dict[str, Any], key: bytes) -> dict[str, Any]:
|
|
345
|
+
"""The `supervision` row a sink receives (CST-B9, SCO-B17): figures and hashed ids only."""
|
|
346
|
+
out = {k: row.get(k) for k in ("row_id", "kind", "schema_version", "workflow", "closed_at", "marginal", "turn",
|
|
347
|
+
"completeness")}
|
|
348
|
+
out["machine_id"] = row.get("machine_id")
|
|
349
|
+
out["thread_hash"] = digest(key, str(row.get("thread_id")))
|
|
350
|
+
out["sessions"] = [{"host": s.get("host"), "session_hash": digest(key, str(s.get("session_hash"))),
|
|
351
|
+
"reported_cost_usd": s.get("reported_cost_usd")} for s in row.get("sessions") or []]
|
|
352
|
+
return out
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _read_jsonl(path: Path) -> list[dict[str, Any]]:
|
|
356
|
+
try:
|
|
357
|
+
lines = path.read_text(encoding="utf-8").splitlines()
|
|
358
|
+
except OSError:
|
|
359
|
+
return []
|
|
360
|
+
out = []
|
|
361
|
+
for ln in lines:
|
|
362
|
+
with contextlib.suppress(ValueError):
|
|
363
|
+
r = json.loads(ln)
|
|
364
|
+
if isinstance(r, dict):
|
|
365
|
+
out.append(r)
|
|
366
|
+
return out
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _flush_one(home: Path, name: str, box: Path) -> dict[str, Any]:
|
|
370
|
+
state_file = box.with_suffix(".state.json")
|
|
371
|
+
result: dict[str, Any] = {"name": name, "delivered": 0, "kept": 0, "error": None}
|
|
372
|
+
with _locked(box, wait_s=0.5) as got:
|
|
373
|
+
if not got:
|
|
374
|
+
result["error"] = "another flush holds the outbox"
|
|
375
|
+
return result
|
|
376
|
+
entries = _read_jsonl(box)
|
|
377
|
+
cache: dict[str, dict[str, dict[str, Any]]] = {}
|
|
378
|
+
done = 0
|
|
379
|
+
for e in entries:
|
|
380
|
+
root = e.get("state_root")
|
|
381
|
+
try:
|
|
382
|
+
sink = find(home, name, Path(root) if root else None)
|
|
383
|
+
except SinkConfigError as exc:
|
|
384
|
+
result["error"] = str(exc)
|
|
385
|
+
break
|
|
386
|
+
if sink is None:
|
|
387
|
+
result["error"] = "no longer configured"
|
|
388
|
+
break
|
|
389
|
+
kind = str(e.get("kind")) if e.get("kind") in ("supervision", "session") else "run"
|
|
390
|
+
rows = _local_rows(home, str(e.get("month")), cache) if kind == "run" else \
|
|
391
|
+
_kept_rows(home, kind, str(e.get("month")), cache)
|
|
392
|
+
local = rows.get(str(e.get("row_id")))
|
|
393
|
+
if local is None: # the local row is gone; nothing to send
|
|
394
|
+
done += 1
|
|
395
|
+
continue
|
|
396
|
+
key = sink_key(sink)
|
|
397
|
+
if key is None:
|
|
398
|
+
result["error"] = "unreachable"
|
|
399
|
+
break
|
|
400
|
+
try:
|
|
401
|
+
folder = _machine_dir(sink, home)
|
|
402
|
+
if kind == "run":
|
|
403
|
+
_append(folder / "runs" / f"{e.get('month')}.jsonl", sink_row(local, sink, key))
|
|
404
|
+
elif kind == "supervision":
|
|
405
|
+
_append(folder / "supervision" / f"{e.get('month')}.jsonl", supervision_row(local, key))
|
|
406
|
+
else:
|
|
407
|
+
_append(folder / "sessions" / f"{e.get('month')}.jsonl", session_row(local, key))
|
|
408
|
+
except OSError as exc:
|
|
409
|
+
result["error"] = f"write failed ({type(exc).__name__})"
|
|
410
|
+
break
|
|
411
|
+
done += 1
|
|
412
|
+
result["delivered"] += 1
|
|
413
|
+
rest = entries[done:]
|
|
414
|
+
if rest:
|
|
415
|
+
tmp = box.with_name(f".{box.name}.tmp")
|
|
416
|
+
tmp.write_text("".join(json.dumps(r) + "\n" for r in rest), encoding="utf-8")
|
|
417
|
+
os.replace(tmp, box)
|
|
418
|
+
else:
|
|
419
|
+
box.unlink(missing_ok=True)
|
|
420
|
+
result["kept"] = len(rest)
|
|
421
|
+
from tempergraph.docs import write_json
|
|
422
|
+
|
|
423
|
+
if result["error"] and result["error"] != "another flush holds the outbox":
|
|
424
|
+
prev = _read_state(state_file)
|
|
425
|
+
write_json(state_file, {"schema_version": 1, "first_failure_at": prev.get("first_failure_at") or now_iso(),
|
|
426
|
+
"last_error": result["error"], "last_try_at": now_iso()})
|
|
427
|
+
elif not result["error"]:
|
|
428
|
+
state_file.unlink(missing_ok=True)
|
|
429
|
+
return result
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _read_state(path: Path) -> dict[str, Any]:
|
|
433
|
+
try:
|
|
434
|
+
return dict(json.loads(path.read_text(encoding="utf-8")))
|
|
435
|
+
except (OSError, ValueError):
|
|
436
|
+
return {}
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def flush(home: Path, state_root: Path | None = None) -> dict[str, Any]:
|
|
440
|
+
"""`stats flush` and the detached flusher: deliver every outbox, in order, then sync (CST-B10, CST-B12, CST-B13)."""
|
|
441
|
+
results = []
|
|
442
|
+
names = sorted(p.stem for p in (home / "outbox").glob("*.jsonl")) if (home / "outbox").is_dir() else []
|
|
443
|
+
for name in names:
|
|
444
|
+
results.append(_flush_one(home, name, outbox(home, name)))
|
|
445
|
+
with contextlib.suppress(SinkConfigError):
|
|
446
|
+
write_heartbeats(home, state_root)
|
|
447
|
+
synced = sync(home, state_root)
|
|
448
|
+
return {"schema_version": 1, "sinks": results, "synced": synced["sinks"]}
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def warnings(home: Path, now: float | None = None) -> list[str]:
|
|
452
|
+
"""One line per sink failing for 7 days or more (CST-B10, CST-B12, CST-B13), for `status`."""
|
|
453
|
+
now = time.time() if now is None else now
|
|
454
|
+
out = []
|
|
455
|
+
folder = home / "outbox"
|
|
456
|
+
for p in sorted(folder.glob("*.state.json")) if folder.is_dir() else []:
|
|
457
|
+
st = _read_state(p)
|
|
458
|
+
since = _ts(st.get("first_failure_at"))
|
|
459
|
+
if since is not None and now - since >= FAILING_WARN_S:
|
|
460
|
+
name = p.name.removesuffix(".state.json")
|
|
461
|
+
out.append(f"sink {name} has failed since {st.get('first_failure_at')}: {st.get('last_error')}; "
|
|
462
|
+
f"its rows wait in the outbox (`tempergraph stats flush`)")
|
|
463
|
+
return out
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _ts(text: Any) -> float | None:
|
|
467
|
+
try:
|
|
468
|
+
return datetime.fromisoformat(str(text).replace("Z", "+00:00")).timestamp()
|
|
469
|
+
except ValueError:
|
|
470
|
+
return None
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
# -- heartbeat (CST-B9) --------------------------------------------------------------------------------------
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _live_threads(home: Path, now: float) -> list[dict[str, Any]]:
|
|
477
|
+
"""Threads on this machine that run now or wait on a person, from the indexed state roots; read-only."""
|
|
478
|
+
from tempergraph.durability.lock import is_held
|
|
479
|
+
from tempergraph.run.events import records
|
|
480
|
+
from tempergraph.store.layout import lock_path
|
|
481
|
+
|
|
482
|
+
out = []
|
|
483
|
+
for entry in read_index(home):
|
|
484
|
+
root = Path(str(entry.get("path")))
|
|
485
|
+
runs = root / "runs"
|
|
486
|
+
if not runs.is_dir():
|
|
487
|
+
continue
|
|
488
|
+
for folder in sorted(p for p in runs.glob("*/*") if p.is_dir()):
|
|
489
|
+
wf, task = folder.parent.name, folder.name
|
|
490
|
+
held = is_held(lock_path(root, wf, task))
|
|
491
|
+
if not held and _read_state(folder / "exit.json").get("exit_code") != 3:
|
|
492
|
+
continue
|
|
493
|
+
unit = attempt = alias = None
|
|
494
|
+
est = 0.0
|
|
495
|
+
pause_ts = None
|
|
496
|
+
exit_code: Any = None
|
|
497
|
+
measured = False
|
|
498
|
+
for r in records(folder / "run.jsonl"):
|
|
499
|
+
k = r.get("kind")
|
|
500
|
+
if k == "run_started":
|
|
501
|
+
alias, est, pause_ts, exit_code, measured = r.get("alias"), 0.0, None, None, False
|
|
502
|
+
elif k == "run_exit": # written while the lock is still held
|
|
503
|
+
exit_code = r.get("exit_code")
|
|
504
|
+
elif k == "unit_entered":
|
|
505
|
+
unit = r.get("unit")
|
|
506
|
+
elif k == "attempt_start":
|
|
507
|
+
attempt = r.get("attempt")
|
|
508
|
+
elif k == "agent_run":
|
|
509
|
+
v = (r.get("usage") or {}).get("estimated_cost_usd")
|
|
510
|
+
if isinstance(v, int | float):
|
|
511
|
+
est, measured = est + float(v), True
|
|
512
|
+
elif k == "pause":
|
|
513
|
+
pause_ts = _ts(r.get("ts"))
|
|
514
|
+
running = held and exit_code is None
|
|
515
|
+
paused = exit_code == 3
|
|
516
|
+
if not (running or paused):
|
|
517
|
+
continue
|
|
518
|
+
out.append({"thread_id": f"{wf}/{task}", "state_root": str(root), "workflow": wf, "alias": alias,
|
|
519
|
+
"state": "running" if running else "paused", "unit": unit, "attempt": attempt,
|
|
520
|
+
"estimated_cost_usd": round(est, 6) if measured else None, # never 0 when unmeasured
|
|
521
|
+
"waiting_for_person_s": round(now - pause_ts, 1) if paused and pause_ts else None,
|
|
522
|
+
"waiting_on": "person" if paused else None})
|
|
523
|
+
return out
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def heartbeat(home: Path, sink: Sink, key: bytes, now: float | None = None) -> dict[str, Any]:
|
|
527
|
+
now = time.time() if now is None else now
|
|
528
|
+
me = _machine(home)
|
|
529
|
+
threads = []
|
|
530
|
+
for t in _live_threads(home, now):
|
|
531
|
+
who = _who(t["state_root"])
|
|
532
|
+
alias = t.get("alias")
|
|
533
|
+
threads.append({"thread_hash": digest(key, t["thread_id"]), "repo_id": _repo_id(sink, key, who),
|
|
534
|
+
"workflow": t["workflow"], "alias": alias if isinstance(alias, str) and SLUG.match(alias)
|
|
535
|
+
else None, **{k: t[k] for k in ("state", "unit", "attempt", "estimated_cost_usd",
|
|
536
|
+
"waiting_for_person_s", "waiting_on")}})
|
|
537
|
+
return {"schema_version": 1, "kind": "heartbeat", "machine_id": me.get("machine_id"), "label": me.get("label"),
|
|
538
|
+
"at": now_iso(), "threads": threads}
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def write_heartbeats(home: Path, state_root: Path | None = None) -> int:
|
|
542
|
+
"""Replaces this machine's `heartbeat.json` in every reachable sink that takes heartbeats; best effort."""
|
|
543
|
+
n = 0
|
|
544
|
+
for s in load(home, state_root):
|
|
545
|
+
if not s.takes("heartbeat"):
|
|
546
|
+
continue
|
|
547
|
+
key = sink_key(s)
|
|
548
|
+
if key is None:
|
|
549
|
+
continue
|
|
550
|
+
with contextlib.suppress(OSError):
|
|
551
|
+
_replace(_machine_dir(s, home) / "heartbeat.json", heartbeat(home, s, key))
|
|
552
|
+
n += 1
|
|
553
|
+
return n
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
_LAST_BEAT: dict[str, float] = {}
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def on_record(log: Path, kind: str) -> None:
|
|
560
|
+
"""Called by the run log's writer: a heartbeat at most every 60 s while the run lives, and at its ends."""
|
|
561
|
+
home_s = os.environ.get("TEMPERGRAPH_HOME", "")
|
|
562
|
+
now = time.monotonic()
|
|
563
|
+
if kind not in ("run_started", "run_exit", "pause") and now - _LAST_BEAT.get(home_s, -1e9) < HEARTBEAT_S:
|
|
564
|
+
return
|
|
565
|
+
_LAST_BEAT[home_s] = now
|
|
566
|
+
from tempergraph.store.layout import home_path
|
|
567
|
+
|
|
568
|
+
with contextlib.suppress(Exception):
|
|
569
|
+
home, root = home_path(), log.parents[3]
|
|
570
|
+
if (home / "config" / SINKS_FILE).exists() or (root / "config" / SINKS_FILE).exists():
|
|
571
|
+
write_heartbeats(home, root)
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
# -- sync and the fleet copy (CST-B10, CST-B12, CST-B13, LOS-B10, LOS-B11) --------------------------------------------------------------
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def _copy_new_bytes(src: Path, dst: Path, offset: int) -> int:
|
|
578
|
+
"""Appends `src`'s whole lines past `offset` to `dst`; returns the new offset. A shorter source starts over."""
|
|
579
|
+
size = src.stat().st_size
|
|
580
|
+
if size < offset:
|
|
581
|
+
offset = 0
|
|
582
|
+
dst.unlink(missing_ok=True)
|
|
583
|
+
if size == offset:
|
|
584
|
+
return offset
|
|
585
|
+
with open(src, "rb") as fh:
|
|
586
|
+
fh.seek(offset)
|
|
587
|
+
data = fh.read(size - offset)
|
|
588
|
+
cut = data.rfind(b"\n") + 1
|
|
589
|
+
if cut:
|
|
590
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
591
|
+
with open(dst, "ab") as out:
|
|
592
|
+
out.write(data[:cut])
|
|
593
|
+
return offset + cut
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def _sync_one(home: Path, sink: Sink) -> dict[str, Any]:
|
|
597
|
+
from tempergraph.docs import write_json
|
|
598
|
+
|
|
599
|
+
dst = home / "fleet" / sink.name
|
|
600
|
+
state = _read_state(dst / "synced.json")
|
|
601
|
+
offsets: dict[str, int] = dict(state.get("offsets") or {})
|
|
602
|
+
machines: dict[str, Any] = dict(state.get("machines") or {})
|
|
603
|
+
src = sink.path / "machines"
|
|
604
|
+
if not src.is_dir():
|
|
605
|
+
return {"name": sink.name, "reachable": False, "synced_at": state.get("synced_at")}
|
|
606
|
+
now = now_iso()
|
|
607
|
+
for mdir in sorted(p for p in src.iterdir() if p.is_dir()):
|
|
608
|
+
mid = mdir.name
|
|
609
|
+
rows = 0
|
|
610
|
+
for f in sorted(mdir.rglob("*.jsonl")):
|
|
611
|
+
rel = str(f.relative_to(src))
|
|
612
|
+
with contextlib.suppress(OSError):
|
|
613
|
+
offsets[rel] = _copy_new_bytes(f, dst / "machines" / rel, int(offsets.get(rel) or 0))
|
|
614
|
+
rows += len(_read_jsonl(dst / "machines" / rel)) if "runs" in f.parts else 0
|
|
615
|
+
for whole in ("machine.json", "heartbeat.json"):
|
|
616
|
+
with contextlib.suppress(OSError, ValueError):
|
|
617
|
+
_replace(dst / "machines" / mid / whole, json.loads((mdir / whole).read_text(encoding="utf-8")))
|
|
618
|
+
label = _read_state(dst / "machines" / mid / "machine.json").get("label")
|
|
619
|
+
machines[mid] = {"label": label, "synced_at": now, "rows": rows}
|
|
620
|
+
me = str(_machine(home).get("machine_id") or "unknown")
|
|
621
|
+
key = sink_key(sink)
|
|
622
|
+
pending: list[dict[str, Any]] = []
|
|
623
|
+
if key is not None: # this machine's rows still in the outbox (CST-B10, CST-B12, CST-B13 "adds this machine's own rows")
|
|
624
|
+
cache: dict[str, dict[str, dict[str, Any]]] = {}
|
|
625
|
+
for e in _read_jsonl(outbox(home, sink.name)):
|
|
626
|
+
local = _local_rows(home, str(e.get("month")), cache).get(str(e.get("row_id")))
|
|
627
|
+
if local is not None:
|
|
628
|
+
pending.append(sink_row(local, sink, key))
|
|
629
|
+
pend = dst / "machines" / me / "pending.jsonl"
|
|
630
|
+
if pending:
|
|
631
|
+
pend.parent.mkdir(parents=True, exist_ok=True)
|
|
632
|
+
pend.write_text("".join(json.dumps(r) + "\n" for r in pending), encoding="utf-8")
|
|
633
|
+
else:
|
|
634
|
+
pend.unlink(missing_ok=True)
|
|
635
|
+
_rollup(dst)
|
|
636
|
+
write_json(dst / "synced.json", {"schema_version": 1, "synced_at": now, "machines": machines,
|
|
637
|
+
"offsets": offsets})
|
|
638
|
+
return {"name": sink.name, "reachable": True, "synced_at": now, "machines": len(machines)}
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def _fleet_paths(dst: Path) -> list[Path]:
|
|
642
|
+
m = dst / "machines"
|
|
643
|
+
return sorted(m.glob("*/runs/*.jsonl")) + sorted(m.glob("*/pending.jsonl")) if m.is_dir() else []
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def _rollup(dst: Path) -> None:
|
|
647
|
+
from tempergraph.docs import write_json
|
|
648
|
+
from tempergraph.observe.rows import _key
|
|
649
|
+
|
|
650
|
+
found, _ = read_rows(_fleet_paths(dst))
|
|
651
|
+
_labels(found, _machine_labels([dst / "machines"]))
|
|
652
|
+
per_month: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
|
653
|
+
for r in found:
|
|
654
|
+
per_month[str(r.get("ended_at") or "")[:7] or "unknown"].append(r)
|
|
655
|
+
for month, rs in per_month.items():
|
|
656
|
+
doc: dict[str, Any] = {"schema_version": 1, "month": month, "totals": totals(rs), "by": {}}
|
|
657
|
+
for by in ROLLUP_BY:
|
|
658
|
+
groups: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
|
659
|
+
for r in rs:
|
|
660
|
+
groups[_key(r, by)].append(r)
|
|
661
|
+
doc["by"][by] = {k: totals(v) for k, v in sorted(groups.items())}
|
|
662
|
+
write_json(dst / "rollup" / f"{month}.json", doc)
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def sync(home: Path, state_root: Path | None = None) -> dict[str, Any]:
|
|
666
|
+
"""`stats sync`: pull every directory sink into the fleet copy; writes the fleet copy only (CST-B14, CST-B15, CST-B16)."""
|
|
667
|
+
return {"schema_version": 1, "sinks": [_sync_one(home, s) for s in load(home, state_root)]}
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
# -- readers (CST-B14, CST-B15, CST-B16) ----------------------------------------------------------------------------------------
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def _machine_labels(folders: Iterable[Path]) -> dict[str, str]:
|
|
674
|
+
out: dict[str, str] = {}
|
|
675
|
+
for f in folders:
|
|
676
|
+
for m in sorted(f.glob("*/machine.json")) if f.is_dir() else []:
|
|
677
|
+
label = _read_state(m).get("label")
|
|
678
|
+
if label:
|
|
679
|
+
out[m.parent.name] = str(label)
|
|
680
|
+
return out
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def _labels(rows: list[dict[str, Any]], labels: dict[str, str]) -> None:
|
|
684
|
+
for r in rows:
|
|
685
|
+
mid = str(r.get("machine_id") or "")
|
|
686
|
+
if mid in labels and not r.get("machine_label"):
|
|
687
|
+
r["machine_label"] = labels[mid]
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
def _month_ok(row: dict[str, Any], month: str | None, since: str | None) -> bool:
|
|
691
|
+
ended = str(row.get("ended_at") or "")
|
|
692
|
+
if month:
|
|
693
|
+
return ended[:7] == month
|
|
694
|
+
if since:
|
|
695
|
+
return ended[:10] >= since
|
|
696
|
+
return True
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def _ago(at: Any, now: float) -> float | None:
|
|
700
|
+
t = _ts(at)
|
|
701
|
+
return round(now - t, 1) if t is not None else None
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
def rows_for(home: Path, source: str | None, local: bool, month: str | None, since: str | None,
|
|
705
|
+
state_root: Path | None = None, conflicts: list[str] | None = None
|
|
706
|
+
) -> tuple[list[dict[str, Any]], int, dict[str, Any] | None]:
|
|
707
|
+
"""Rows for `stats`: the home folder (this machine plus each sink's fleet copy), `--local`, or `--source`."""
|
|
708
|
+
now = time.time()
|
|
709
|
+
local_paths = sorted((home / "stats").glob("*.jsonl")) if (home / "stats").is_dir() else []
|
|
710
|
+
me = _machine(home)
|
|
711
|
+
labels = {str(me.get("machine_id")): str(me.get("label"))} if me.get("label") else {}
|
|
712
|
+
synced: dict[str, Any] | None = None
|
|
713
|
+
if local:
|
|
714
|
+
paths = local_paths
|
|
715
|
+
elif source:
|
|
716
|
+
sink = find(home, source, state_root)
|
|
717
|
+
if sink is None:
|
|
718
|
+
raise SinkConfigError(f"no sink named {source!r} is configured")
|
|
719
|
+
paths = sorted((sink.path / "machines").glob("*/runs/*.jsonl"))
|
|
720
|
+
labels.update(_machine_labels([sink.path / "machines"]))
|
|
721
|
+
else:
|
|
722
|
+
paths, synced = [], {}
|
|
723
|
+
for s in load(home, state_root):
|
|
724
|
+
dst = home / "fleet" / s.name
|
|
725
|
+
paths += _fleet_paths(dst)
|
|
726
|
+
labels.update(_machine_labels([dst / "machines"]))
|
|
727
|
+
st = _read_state(dst / "synced.json")
|
|
728
|
+
if st:
|
|
729
|
+
synced[s.name] = {"synced_at": st.get("synced_at"), "machines": {
|
|
730
|
+
mid: {**m, "ago_s": _ago(m.get("synced_at"), now)} for mid, m in (st.get("machines") or {}).items()}}
|
|
731
|
+
paths += local_paths # after the fleet copy, so a delivered row reads as the sink holds it
|
|
732
|
+
synced = synced or None
|
|
733
|
+
if month:
|
|
734
|
+
paths = [p for p in paths if p.stem in (month, "pending")]
|
|
735
|
+
found, unknown = read_rows(paths, conflicts)
|
|
736
|
+
found = [r for r in found if _month_ok(r, month, since)]
|
|
737
|
+
_labels(found, labels)
|
|
738
|
+
return found, unknown, synced
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
def live(home: Path, source: str | None, state_root: Path | None = None) -> dict[str, Any]:
|
|
742
|
+
"""`stats --live`: heartbeats of every machine, a beat older than 5 minutes that lists a running thread
|
|
743
|
+
marked `stale`; this machine's own threads are read fresh. Read-only."""
|
|
744
|
+
now = time.time()
|
|
745
|
+
me = str(_machine(home).get("machine_id") or "")
|
|
746
|
+
beats: dict[str, dict[str, Any]] = {}
|
|
747
|
+
if source:
|
|
748
|
+
sink = find(home, source, state_root)
|
|
749
|
+
if sink is None:
|
|
750
|
+
raise SinkConfigError(f"no sink named {source!r} is configured")
|
|
751
|
+
folders = [sink.path / "machines"]
|
|
752
|
+
else:
|
|
753
|
+
folders = [home / "fleet" / s.name / "machines" for s in load(home, state_root)]
|
|
754
|
+
for f in folders:
|
|
755
|
+
for p in sorted(f.glob("*/heartbeat.json")) if f.is_dir() else []:
|
|
756
|
+
b = _read_state(p)
|
|
757
|
+
mid = str(b.get("machine_id") or p.parent.name)
|
|
758
|
+
if mid not in beats or str(b.get("at")) > str(beats[mid].get("at")):
|
|
759
|
+
beats[mid] = b
|
|
760
|
+
if not source:
|
|
761
|
+
own = _live_threads(home, now)
|
|
762
|
+
beats[me] = {"machine_id": me, "label": _machine(home).get("label"), "at": now_iso(), "threads": [
|
|
763
|
+
{k: t[k] for k in ("workflow", "alias", "state", "unit", "attempt", "estimated_cost_usd",
|
|
764
|
+
"waiting_for_person_s", "waiting_on")} | {"thread_id": t["thread_id"]} for t in own]}
|
|
765
|
+
machines, runs = [], []
|
|
766
|
+
for mid, b in sorted(beats.items()):
|
|
767
|
+
age = _ago(b.get("at"), now)
|
|
768
|
+
threads = list(b.get("threads") or [])
|
|
769
|
+
stale = bool(age is not None and age > STALE_S and any(t.get("state") == "running" for t in threads))
|
|
770
|
+
machines.append({"machine_id": mid, "label": b.get("label"), "at": b.get("at"), "age_s": age,
|
|
771
|
+
"stale": stale, "this_machine": mid == me})
|
|
772
|
+
for t in threads:
|
|
773
|
+
wait = t.get("waiting_for_person_s")
|
|
774
|
+
if isinstance(wait, int | float) and t.get("state") == "paused" and age is not None and mid != me:
|
|
775
|
+
wait = round(wait + age, 1) # the wait has gone on since the beat was written
|
|
776
|
+
runs.append({**t, "waiting_for_person_s": wait, "machine_id": mid, "label": b.get("label"),
|
|
777
|
+
"stale": stale})
|
|
778
|
+
return {"schema_version": 1, "source": source or "home", "machines": machines, "runs": runs}
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def main(argv: list[str] | None = None) -> int:
|
|
782
|
+
"""`python -m tempergraph.observe.sinks flush`: the detached flusher."""
|
|
783
|
+
from tempergraph.store.layout import home_path
|
|
784
|
+
|
|
785
|
+
args = sys.argv[1:] if argv is None else argv
|
|
786
|
+
if args[:1] == ["flush"]:
|
|
787
|
+
with contextlib.suppress(Exception):
|
|
788
|
+
flush(home_path())
|
|
789
|
+
return 0
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
if __name__ == "__main__":
|
|
793
|
+
raise SystemExit(main())
|