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.
Files changed (232) hide show
  1. tempergraph/__init__.py +8 -0
  2. tempergraph/__main__.py +5 -0
  3. tempergraph/api.py +428 -0
  4. tempergraph/audit/__init__.py +305 -0
  5. tempergraph/audit/catalog.py +342 -0
  6. tempergraph/audit/definition.py +387 -0
  7. tempergraph/audit/history.py +414 -0
  8. tempergraph/audit/history_rules.py +268 -0
  9. tempergraph/audit/history_rules_more.py +244 -0
  10. tempergraph/audit/host.py +270 -0
  11. tempergraph/audit/owned.py +96 -0
  12. tempergraph/audit/prompts.py +89 -0
  13. tempergraph/audit/report.py +248 -0
  14. tempergraph/audit/revisit.py +220 -0
  15. tempergraph/audit/surface.py +224 -0
  16. tempergraph/audit/text_health.py +176 -0
  17. tempergraph/audit/tools.py +391 -0
  18. tempergraph/author/__init__.py +2 -0
  19. tempergraph/author/blueprint.py +346 -0
  20. tempergraph/author/compare.py +122 -0
  21. tempergraph/author/criteria_lint.py +200 -0
  22. tempergraph/author/draw.py +112 -0
  23. tempergraph/author/inventory.py +210 -0
  24. tempergraph/author/literals.py +138 -0
  25. tempergraph/author/scaffold.py +568 -0
  26. tempergraph/author/session.py +439 -0
  27. tempergraph/author/trial.py +391 -0
  28. tempergraph/author/verify.py +353 -0
  29. tempergraph/builtin/__init__.py +1 -0
  30. tempergraph/builtin/upgrade.py +288 -0
  31. tempergraph/catalog.py +134 -0
  32. tempergraph/check_helpers.py +99 -0
  33. tempergraph/cli/__init__.py +1 -0
  34. tempergraph/cli/audit.py +190 -0
  35. tempergraph/cli/author.py +361 -0
  36. tempergraph/cli/improve.py +564 -0
  37. tempergraph/cli/improve_review.py +111 -0
  38. tempergraph/cli/install.py +35 -0
  39. tempergraph/cli/main.py +1261 -0
  40. tempergraph/cli/observe_cli.py +544 -0
  41. tempergraph/cli/outcome.py +77 -0
  42. tempergraph/cli/schedule_cli.py +1090 -0
  43. tempergraph/cli/upgrade.py +126 -0
  44. tempergraph/cli/workflows.py +96 -0
  45. tempergraph/compiler/__init__.py +6 -0
  46. tempergraph/compiler/graph.py +305 -0
  47. tempergraph/compiler/state.py +229 -0
  48. tempergraph/constants.py +72 -0
  49. tempergraph/contracts.py +1025 -0
  50. tempergraph/data/executor_compat.json +11 -0
  51. tempergraph/data/promotion.json +35 -0
  52. tempergraph/data/release.json +20 -0
  53. tempergraph/detach.py +65 -0
  54. tempergraph/docs.py +90 -0
  55. tempergraph/durability/__init__.py +2 -0
  56. tempergraph/durability/alias.py +66 -0
  57. tempergraph/durability/carry.py +591 -0
  58. tempergraph/durability/checkpoint.py +179 -0
  59. tempergraph/durability/control.py +109 -0
  60. tempergraph/durability/engine_file.py +301 -0
  61. tempergraph/durability/lock.py +138 -0
  62. tempergraph/durability/status.py +390 -0
  63. tempergraph/engine_identity.py +42 -0
  64. tempergraph/executor_compat.py +56 -0
  65. tempergraph/executors/__init__.py +4 -0
  66. tempergraph/executors/binding.py +91 -0
  67. tempergraph/executors/capabilities.py +95 -0
  68. tempergraph/executors/claude.py +603 -0
  69. tempergraph/executors/launcher.py +394 -0
  70. tempergraph/executors/mcpconfig.py +156 -0
  71. tempergraph/executors/mcpproxy.py +216 -0
  72. tempergraph/executors/preflight.py +196 -0
  73. tempergraph/executors/registry.py +71 -0
  74. tempergraph/executors/scripted.py +18 -0
  75. tempergraph/executors/session.py +107 -0
  76. tempergraph/executors/standins.py +118 -0
  77. tempergraph/executors/summary.py +110 -0
  78. tempergraph/executors/viewcatalog.py +27 -0
  79. tempergraph/git.py +403 -0
  80. tempergraph/identity.py +65 -0
  81. tempergraph/improve/__init__.py +5 -0
  82. tempergraph/improve/analysis.py +437 -0
  83. tempergraph/improve/artifact.py +477 -0
  84. tempergraph/improve/autonomy.py +192 -0
  85. tempergraph/improve/bindings.py +191 -0
  86. tempergraph/improve/calibration.py +1016 -0
  87. tempergraph/improve/causes.py +416 -0
  88. tempergraph/improve/child.py +651 -0
  89. tempergraph/improve/codehost.py +520 -0
  90. tempergraph/improve/digest.py +472 -0
  91. tempergraph/improve/escape.py +100 -0
  92. tempergraph/improve/filing.py +1047 -0
  93. tempergraph/improve/harvest.py +158 -0
  94. tempergraph/improve/issue_context.py +192 -0
  95. tempergraph/improve/lenses.py +204 -0
  96. tempergraph/improve/lessons.py +233 -0
  97. tempergraph/improve/loop_report.py +138 -0
  98. tempergraph/improve/loop_summary.py +85 -0
  99. tempergraph/improve/lost.py +119 -0
  100. tempergraph/improve/measure.py +121 -0
  101. tempergraph/improve/params.py +98 -0
  102. tempergraph/improve/pause_facts.py +134 -0
  103. tempergraph/improve/pr_later.py +186 -0
  104. tempergraph/improve/prebinding.py +130 -0
  105. tempergraph/improve/promotion.py +413 -0
  106. tempergraph/improve/proposals.py +934 -0
  107. tempergraph/improve/record.py +322 -0
  108. tempergraph/improve/release.py +89 -0
  109. tempergraph/improve/reliability.py +457 -0
  110. tempergraph/improve/repeat.py +115 -0
  111. tempergraph/improve/review.py +910 -0
  112. tempergraph/improve/suites.py +586 -0
  113. tempergraph/improve/trials.py +525 -0
  114. tempergraph/install/__init__.py +11 -0
  115. tempergraph/install/bootstrap.py +133 -0
  116. tempergraph/install/environment.py +173 -0
  117. tempergraph/install/launch.py +37 -0
  118. tempergraph/install/python.py +53 -0
  119. tempergraph/install/reconcile.py +52 -0
  120. tempergraph/install/selfcheck.py +29 -0
  121. tempergraph/install/shim.py +81 -0
  122. tempergraph/install/update.py +400 -0
  123. tempergraph/model/__init__.py +0 -0
  124. tempergraph/model/diagram.py +185 -0
  125. tempergraph/model/flow.py +324 -0
  126. tempergraph/model/prompt_lint.py +203 -0
  127. tempergraph/model/retire.py +52 -0
  128. tempergraph/model/subworkflow.py +274 -0
  129. tempergraph/model/text.py +67 -0
  130. tempergraph/model/validate.py +1158 -0
  131. tempergraph/observe/__init__.py +1 -0
  132. tempergraph/observe/attention.py +196 -0
  133. tempergraph/observe/detail.py +773 -0
  134. tempergraph/observe/forget.py +138 -0
  135. tempergraph/observe/hooks.py +272 -0
  136. tempergraph/observe/labels.py +95 -0
  137. tempergraph/observe/overlay.py +46 -0
  138. tempergraph/observe/report.py +402 -0
  139. tempergraph/observe/risk_report.py +110 -0
  140. tempergraph/observe/rows.py +444 -0
  141. tempergraph/observe/sinks.py +793 -0
  142. tempergraph/observe/supervision_cost.py +797 -0
  143. tempergraph/observe/supervision_report.py +295 -0
  144. tempergraph/observe/switch_report.py +140 -0
  145. tempergraph/package/__init__.py +2 -0
  146. tempergraph/package/change_report.py +116 -0
  147. tempergraph/package/changelog.py +263 -0
  148. tempergraph/package/docs_check.py +115 -0
  149. tempergraph/package/importer.py +90 -0
  150. tempergraph/package/inventory.py +111 -0
  151. tempergraph/package/loader.py +250 -0
  152. tempergraph/package/manifest.py +256 -0
  153. tempergraph/package/readiness.py +124 -0
  154. tempergraph/package/registry.py +383 -0
  155. tempergraph/package/rules.py +128 -0
  156. tempergraph/package/scan.py +65 -0
  157. tempergraph/package/selftest.py +348 -0
  158. tempergraph/package/stamp.py +213 -0
  159. tempergraph/package/transforms.py +481 -0
  160. tempergraph/package/upgrade.py +625 -0
  161. tempergraph/provenance.py +183 -0
  162. tempergraph/py.typed +0 -0
  163. tempergraph/release.py +17 -0
  164. tempergraph/render/__init__.py +0 -0
  165. tempergraph/render/output.py +72 -0
  166. tempergraph/render/prompt.py +166 -0
  167. tempergraph/render/template.py +86 -0
  168. tempergraph/run/__init__.py +2 -0
  169. tempergraph/run/asking.py +233 -0
  170. tempergraph/run/audit.py +63 -0
  171. tempergraph/run/check_worker.py +167 -0
  172. tempergraph/run/checks.py +517 -0
  173. tempergraph/run/commands.py +210 -0
  174. tempergraph/run/complexity.py +268 -0
  175. tempergraph/run/contest.py +76 -0
  176. tempergraph/run/council.py +368 -0
  177. tempergraph/run/council_run.py +527 -0
  178. tempergraph/run/events.py +279 -0
  179. tempergraph/run/finalize.py +132 -0
  180. tempergraph/run/gate.py +747 -0
  181. tempergraph/run/guard.py +89 -0
  182. tempergraph/run/judging.py +357 -0
  183. tempergraph/run/ladder.py +230 -0
  184. tempergraph/run/log.py +600 -0
  185. tempergraph/run/mapping.py +183 -0
  186. tempergraph/run/nodes.py +2304 -0
  187. tempergraph/run/outcome.py +255 -0
  188. tempergraph/run/outcome_record.py +292 -0
  189. tempergraph/run/outcome_trust.py +99 -0
  190. tempergraph/run/rerun.py +351 -0
  191. tempergraph/run/reserve.py +85 -0
  192. tempergraph/run/resources.py +76 -0
  193. tempergraph/run/risk.py +231 -0
  194. tempergraph/run/runner.py +1579 -0
  195. tempergraph/run/scriptcache.py +178 -0
  196. tempergraph/run/selfcheck.py +105 -0
  197. tempergraph/run/session_record.py +72 -0
  198. tempergraph/run/subrun.py +278 -0
  199. tempergraph/run/supervision.py +125 -0
  200. tempergraph/run/tool_access.py +101 -0
  201. tempergraph/schedule/__init__.py +25 -0
  202. tempergraph/schedule/credentials.py +167 -0
  203. tempergraph/schedule/echo.py +169 -0
  204. tempergraph/schedule/exact.py +275 -0
  205. tempergraph/schedule/export.py +164 -0
  206. tempergraph/schedule/launch.py +89 -0
  207. tempergraph/schedule/ledger.py +133 -0
  208. tempergraph/schedule/loop.py +176 -0
  209. tempergraph/schedule/model.py +440 -0
  210. tempergraph/schedule/policies.py +414 -0
  211. tempergraph/schedule/store.py +150 -0
  212. tempergraph/schedule/tick.py +377 -0
  213. tempergraph/schedule/token.py +81 -0
  214. tempergraph/schedule/triggers.py +210 -0
  215. tempergraph/schedule/words.py +423 -0
  216. tempergraph/security/__init__.py +0 -0
  217. tempergraph/security/launch.py +25 -0
  218. tempergraph/security/scrub.py +58 -0
  219. tempergraph/settings.py +950 -0
  220. tempergraph/store/__init__.py +0 -0
  221. tempergraph/store/codelog.py +73 -0
  222. tempergraph/store/layout.py +198 -0
  223. tempergraph/store/logs.py +325 -0
  224. tempergraph/store/manifest.py +99 -0
  225. tempergraph/store/migrate.py +188 -0
  226. tempergraph/workspace.py +874 -0
  227. tempergraph-0.7.1.dist-info/METADATA +70 -0
  228. tempergraph-0.7.1.dist-info/RECORD +232 -0
  229. tempergraph-0.7.1.dist-info/WHEEL +5 -0
  230. tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
  231. tempergraph-0.7.1.dist-info/top_level.txt +2 -0
  232. tempergraph_pytest_plugin.py +64 -0
@@ -0,0 +1,179 @@
1
+ """The per-workflow SQLite checkpoint and thread classification (DUR-B9, DUR-B11, DUR-B3, DUR-B4).
2
+
3
+ Writers open the store with a 60 s busy wait and retry creating an empty store for 30 s. Observers open
4
+ it read-only and create nothing: with no write-ahead log present (no writer has it open) the file is
5
+ opened ``immutable``, else ``mode=ro``, which touches only the live writer's shared-memory index.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sqlite3
11
+ import time
12
+ from collections.abc import Iterator
13
+ from contextlib import contextmanager
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from langgraph.checkpoint.sqlite import SqliteSaver
19
+
20
+ from tempergraph.compiler.graph import CompiledWorkflow, compile_workflow
21
+ from tempergraph.compiler.state import RunState
22
+ from tempergraph.contracts import ThreadState, WorkflowSpec
23
+ from tempergraph.model import flow
24
+
25
+ BUSY_TIMEOUT_S = 60.0
26
+ CREATE_RETRY_S = 30.0
27
+
28
+
29
+ def open_saver(path: Path) -> SqliteSaver:
30
+ """A writer's saver; the folder is owner-only and the file 0600."""
31
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
32
+ deadline = time.monotonic() + CREATE_RETRY_S
33
+ while True:
34
+ try:
35
+ conn = sqlite3.connect(str(path), timeout=BUSY_TIMEOUT_S, check_same_thread=False)
36
+ saver = SqliteSaver(conn)
37
+ saver.setup()
38
+ path.chmod(0o600)
39
+ return saver
40
+ except sqlite3.OperationalError:
41
+ if time.monotonic() > deadline:
42
+ raise
43
+ time.sleep(0.2)
44
+
45
+
46
+ @contextmanager
47
+ def open_readonly(path: Path) -> Iterator[SqliteSaver | None]:
48
+ """An observer's saver, or None when no store exists. Creates no file (DUR-B4)."""
49
+ if not path.exists():
50
+ yield None
51
+ return
52
+ wal = path.with_name(path.name + "-wal")
53
+ mode = "mode=ro" if wal.exists() else "mode=ro&immutable=1"
54
+ conn = sqlite3.connect(f"file:{path}?{mode}", uri=True, timeout=BUSY_TIMEOUT_S, check_same_thread=False)
55
+ try:
56
+ saver = SqliteSaver(conn)
57
+ saver.is_setup = True # never run the writer's setup script on a read-only store
58
+ yield saver
59
+ finally:
60
+ conn.close()
61
+
62
+
63
+ def thread_ids(saver: SqliteSaver) -> list[str]:
64
+ try:
65
+ rows = saver.conn.execute("SELECT DISTINCT thread_id FROM checkpoints ORDER BY thread_id").fetchall()
66
+ except sqlite3.OperationalError:
67
+ return []
68
+ return [r[0] for r in rows]
69
+
70
+
71
+ class _NoNodes:
72
+ """Node bodies for an observer's graph: reading state never runs a node."""
73
+
74
+ def _never(self, *_: Any) -> dict[str, Any]:
75
+ raise RuntimeError("an observer's graph runs no node")
76
+
77
+ step = judge = gate = human = _never
78
+
79
+ def finalizer(self, state: RunState) -> dict[str, Any]:
80
+ return self._never(state)
81
+
82
+
83
+ def observer_graph(spec: WorkflowSpec, saver: SqliteSaver) -> CompiledWorkflow:
84
+ return compile_workflow(spec, _NoNodes(), saver)
85
+
86
+
87
+ @dataclass(frozen=True, kw_only=True)
88
+ class Snapshot:
89
+ """What classification needs from one thread's latest checkpoint."""
90
+
91
+ exists: bool
92
+ next: tuple[str, ...] = ()
93
+ interrupts: tuple[tuple[str, Any], ...] = () # (node, payload)
94
+ values: dict[str, Any] = field(default_factory=dict)
95
+ interrupt_ids: dict[str, str] = field(default_factory=dict) # interrupt id -> unit, for a resume by unit
96
+
97
+
98
+ def _gate_node(task: str, payload: Any) -> str:
99
+ """The node a pause belongs to. A pause raised inside a sub-workflow's child (SWF-B2) is raised from the sub-workflow
100
+ unit's step node, a subgraph of it; its payload names the child's unit as `<unit>/<child unit>`, and the pause is that
101
+ unit's gate, so it reads as `<unit>/<child unit>.human` like a pause of the parent's own. A pause of one item of a
102
+ concurrent map is raised from the map's item node; its payload names the item's slot, and the pause is that slot's
103
+ gate, `<unit>.<item id>.human` (MAP-B6)."""
104
+ unit = str(payload.get("unit") or "") if isinstance(payload, dict) else ""
105
+ if isinstance(payload, dict) and payload.get("slot") and task.endswith(".item_human"):
106
+ return f"{payload['slot']}.human"
107
+ return f"{unit}.human" if task.endswith(".step") and "/" in unit else task
108
+
109
+
110
+ def snapshot(cw: CompiledWorkflow, thread_id: str) -> Snapshot:
111
+ try:
112
+ st = cw.graph.get_state(cw.config(thread_id))
113
+ except sqlite3.OperationalError:
114
+ return Snapshot(exists=False)
115
+ if not st.values:
116
+ return Snapshot(exists=False)
117
+ ints = tuple((_gate_node(t.name, i.value), i.value) for t in st.tasks for i in t.interrupts)
118
+ ids = {str(getattr(i, "id", "")): _gate_node(t.name, i.value).rsplit(".", 1)[0] for t in st.tasks
119
+ for i in t.interrupts}
120
+ return Snapshot(exists=True, next=tuple(st.next), interrupts=ints, values=dict(st.values), interrupt_ids=ids)
121
+
122
+
123
+ def classify_snapshot(snap: Snapshot, lock_held: bool) -> ThreadState:
124
+ """DUR-B9: a held lock reads `running` over any checkpoint state (ADR `sqlite-checkpointer`)."""
125
+ if lock_held:
126
+ return ThreadState.RUNNING
127
+ if not snap.exists:
128
+ return ThreadState.NONE
129
+ if snap.interrupts:
130
+ return ThreadState.PAUSED
131
+ if snap.next:
132
+ return ThreadState.UNFINISHED
133
+ if snap.values.get("finalized"):
134
+ return ThreadState.FINISHED
135
+ return ThreadState.STOPPED
136
+
137
+
138
+ def _reached_by_goto(cw: CompiledWorkflow, node: str) -> bool:
139
+ """`node` is a node of a concurrent map that an item reaches or returns to: an item node, which an item is sent to,
140
+ or the map's own step node, which an item goes back to when it has passed, waits for a person or has stopped the
141
+ map (MAP-B9). Nothing in the checkpoint but the pending task itself says that such a node runs next."""
142
+ unit = node.rpartition(".")[0]
143
+ if not flow.concurrent_map(cw.spec, unit):
144
+ return False
145
+ return node == flow.step_node(unit) or node in {flow.item_node(unit, k) for k in flow.ITEM_KINDS}
146
+
147
+
148
+ def update_values(cw: CompiledWorkflow, config: Any, update: Any) -> bool:
149
+ """A state write outside any node. False when the write cannot be made without losing what is pending; the caller
150
+ then hands it to the first node that runs. That is so when several tasks are pending (of several nodes, or of one
151
+ node sent several times, as the items of a concurrent map are) and the write cannot be attributed, and when one
152
+ is pending at a node of a concurrent map that an item reaches or returns to (one item's pause, even alone, or the
153
+ map's step after a stop inside the map): the checkpoint the write makes keeps only what the graph's edges give,
154
+ and no edge leads there, so the thread would be left with nothing pending (MAP-B6, RCT-B11)."""
155
+ from langgraph.errors import InvalidUpdateError
156
+
157
+ try:
158
+ tasks = cw.graph.get_state(config).tasks
159
+ if len(tasks) > 1 or any(_reached_by_goto(cw, t.name) for t in tasks):
160
+ return False
161
+ cw.graph.update_state(config, update)
162
+ except InvalidUpdateError:
163
+ return False
164
+ return True
165
+
166
+
167
+ def resume_input(value: Any) -> Any:
168
+ """The graph input that answers a pending interrupt; keeps LangGraph inside durability (ADR `the-engine-is-a-src-layout-python-package-inside-its-plugin`)."""
169
+ from langgraph.types import Command
170
+
171
+ return Command(resume=value)
172
+
173
+
174
+ def thread_values(checkpoint: Path, spec: WorkflowSpec, thread_id: str) -> dict[str, Any]:
175
+ """One thread's state values, read-only; empty when there is no store or no such thread."""
176
+ with open_readonly(checkpoint) as saver:
177
+ if saver is None:
178
+ return {}
179
+ return dict(snapshot(observer_graph(spec, saver), thread_id).values or {})
@@ -0,0 +1,109 @@
1
+ """Run control: the stop request file (RCT-B6, RCT-B7, RCT-B3, RCT-B8, RCT-B9, RCT-B10).
2
+
3
+ The `stop` verb writes `runs/<workflow>/<task_id>/control/stop.json`; the engine holding the thread's
4
+ lock picks it up between records and at least once a second while a session runs, removes it and acts.
5
+ A file, not a signal: it carries a mode and is safe after process-id reuse (ADR `stop-verb-as-the-only-observer-control`).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import threading
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Any, Literal
15
+
16
+ from tempergraph.docs import write_json
17
+ from tempergraph.durability.lock import is_held
18
+ from tempergraph.executors.launcher import StopRequest
19
+ from tempergraph.store.layout import lock_path, now_iso, run_dir
20
+
21
+ StopMode = Literal["drain", "now"]
22
+ POLL_S = 1.0
23
+
24
+
25
+ class NotLive(Exception):
26
+ """RCT-B3: the thread's lock is not held; nothing was written."""
27
+
28
+
29
+ def stop_file(state_root: Path, workflow: str, task_id: str) -> Path:
30
+ return run_dir(state_root, workflow, task_id) / "control" / "stop.json"
31
+
32
+
33
+ def request_stop(state_root: Path, workflow: str, task_id: str, mode: StopMode = "drain",
34
+ caller: dict[str, Any] | None = None) -> StopMode:
35
+ """Write (or strengthen) a stop request for a live thread; returns the mode now on file."""
36
+ if not is_held(lock_path(state_root, workflow, task_id)):
37
+ raise NotLive(f"{workflow}/{task_id} is not running")
38
+ path = stop_file(state_root, workflow, task_id)
39
+ current = _read(path)
40
+ if current is not None and current[0] == "now":
41
+ return "now" # the stronger mode wins (RCT-B8, RCT-B9, RCT-B10)
42
+ write_json(path, {"schema_version": 1, "mode": mode, "requested_at": now_iso(), "caller": caller or {}})
43
+ return mode
44
+
45
+
46
+ def _read(path: Path) -> tuple[StopMode, dict[str, Any]] | None:
47
+ if not path.exists():
48
+ return None
49
+ try:
50
+ data = json.loads(path.read_text(encoding="utf-8"))
51
+ mode = data.get("mode")
52
+ return ("now" if mode == "now" else "drain"), data
53
+ except (OSError, ValueError, AttributeError):
54
+ return "drain", {"unparsable": True} # a request that does not parse is a drain, recorded
55
+
56
+
57
+ @dataclass(frozen=True, kw_only=True)
58
+ class TakenStop:
59
+ mode: StopMode
60
+ caller: dict[str, Any]
61
+ unparsable: bool = False
62
+ stale: bool = False
63
+
64
+
65
+ def take_stop(state_root: Path, workflow: str, task_id: str, *, stale: bool = False) -> TakenStop | None:
66
+ """Read and remove a pending request. ``stale``: called by a resume for a request nobody acted on."""
67
+ path = stop_file(state_root, workflow, task_id)
68
+ got = _read(path)
69
+ if got is None:
70
+ return None
71
+ path.unlink(missing_ok=True)
72
+ mode, data = got
73
+ return TakenStop(mode=mode, caller=dict(data.get("caller") or {}), unparsable=bool(data.get("unparsable")),
74
+ stale=stale)
75
+
76
+
77
+ class StopWatcher:
78
+ """Polls the request file while a run holds its lock; ``now`` fires the launcher's stop contract.
79
+
80
+ ``drain`` is only remembered: the run stops at its next boundary (RCT-B1)."""
81
+
82
+ def __init__(self, state_root: Path, workflow: str, task_id: str, session_stop: StopRequest,
83
+ poll_s: float = POLL_S) -> None:
84
+ self.args = (state_root, workflow, task_id)
85
+ self.session_stop = session_stop
86
+ self.poll_s = poll_s
87
+ self.taken: TakenStop | None = None
88
+ self._done = threading.Event()
89
+ self._thread = threading.Thread(target=self._loop, name="stop-watcher", daemon=True)
90
+
91
+ def check(self) -> TakenStop | None:
92
+ got = take_stop(*self.args)
93
+ if got is not None and (self.taken is None or got.mode == "now"):
94
+ self.taken = got
95
+ if self.taken is not None and self.taken.mode == "now":
96
+ self.session_stop.request("stop")
97
+ return self.taken
98
+
99
+ def _loop(self) -> None:
100
+ while not self._done.wait(self.poll_s):
101
+ self.check()
102
+
103
+ def __enter__(self) -> StopWatcher:
104
+ self._thread.start()
105
+ return self
106
+
107
+ def __exit__(self, *exc: object) -> None:
108
+ self._done.set()
109
+ self._thread.join(timeout=self.poll_s * 2)
@@ -0,0 +1,301 @@
1
+ """What a thread records about engines and workflow versions, and what happens to it at its next resume
2
+ (MIG-B8, MIG-B12, MIG-B13, MIG-B14, MIG-B15). The rule: move at the resume boundary, pin only on a break (ADR `threads-move-to-the-new-engine-at-resume-unless-a-release-pins-them`).
3
+
4
+ `engine.json` sits beside the thread's run log. The decisions here are pure functions over that document, the
5
+ release record and the kept engines, so every row of MIG's tables is a test without a second engine installed.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import functools
12
+ import hashlib
13
+ import json
14
+ import sys
15
+ from collections.abc import Mapping, Sequence
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from tempergraph.constants import ENGINE_VERSION
20
+ from tempergraph.contracts import WorkflowSpec
21
+ from tempergraph.docs import write_json
22
+ from tempergraph.store.layout import now_iso, run_dir
23
+
24
+ FILE = "engine.json"
25
+ HISTORY_KEPT = 50
26
+
27
+
28
+ def path(root: Path, workflow: str, task_id: str) -> Path:
29
+ return run_dir(root, workflow, task_id) / FILE
30
+
31
+
32
+ def read(root: Path, workflow: str, task_id: str) -> dict[str, Any]:
33
+ """A thread from before this record reads as started on an unknown engine, not pinned (MIG-B16, MIG-B12, MIG-B10, MIG-B15)."""
34
+ try:
35
+ doc = json.loads(path(root, workflow, task_id).read_text(encoding="utf-8"))
36
+ except (OSError, ValueError):
37
+ return {}
38
+ return doc if isinstance(doc, dict) else {}
39
+
40
+
41
+ def this_engine() -> dict[str, Any]:
42
+ """The engine this process runs on: its version, its environment folder when it is a managed one, its build
43
+ (the source digest) and the program that runs it (DUR-B11), so two copies of one version are told apart."""
44
+ env = Path(sys.prefix)
45
+ managed = env.parent.name == "engines"
46
+ return {"engine_version": ENGINE_VERSION, "engine": env.name if managed else None,
47
+ "engine_digest": _build(env.name if managed else None), "program": _program()}
48
+
49
+
50
+ @functools.lru_cache(maxsize=1)
51
+ def _build(managed: str | None) -> str | None:
52
+ """A managed engine's digest is the end of its folder name; an engine run from its source tree hashes that
53
+ tree (VER-B7); None when neither is known."""
54
+ if managed:
55
+ return managed.rsplit("-", 1)[-1]
56
+ from tempergraph.install.environment import source_digest, staged_engine
57
+
58
+ src = staged_engine()
59
+ try:
60
+ return source_digest(src)[:12] if src is not None else None
61
+ except OSError:
62
+ return None
63
+
64
+
65
+ def _program() -> str | None:
66
+ """The path of the program that started this process (local only, like `log_path`)."""
67
+ arg = sys.argv[0] if sys.argv and sys.argv[0] else ""
68
+ p = Path(arg)
69
+ return str(p.resolve()) if arg and p.exists() else (sys.executable or None)
70
+
71
+
72
+ def checkpoint_format() -> int:
73
+ from tempergraph.release import release
74
+
75
+ return int(release().get("checkpoint_format") or 1)
76
+
77
+
78
+ def unit_digests(spec: WorkflowSpec) -> dict[str, dict[str, Any]]:
79
+ """Per unit: its kind, the keys it produces and a digest of everything declared on it."""
80
+ from tempergraph.package.inventory import canonical
81
+
82
+ out: dict[str, dict[str, Any]] = {}
83
+ for name, u in spec.units.items():
84
+ body = json.dumps(canonical(u), sort_keys=True, separators=(",", ":"), default=str)
85
+ produces = sorted((u.step.produces if u.step else {}) or {})
86
+ out[name] = {"kind": str(u.kind), "digest": hashlib.sha256(body.encode()).hexdigest()[:16],
87
+ "produces": produces}
88
+ return out
89
+
90
+
91
+ def last(doc: Mapping[str, Any]) -> dict[str, Any]:
92
+ hist = doc.get("history") or []
93
+ return dict(hist[-1]) if hist and isinstance(hist[-1], dict) else {}
94
+
95
+
96
+ UNKNOWN = {"engine_version": None, "engine": "unknown"}
97
+
98
+
99
+ def record(root: Path, spec: WorkflowSpec, task_id: str, *, content_version: str, shape_digest: str,
100
+ resumed: bool = False, children: Mapping[str, Mapping[str, Any]] | None = None) -> dict[str, Any] | None:
101
+ """One history entry for this process. Returns `moved_from` (the engine and workflow version of the
102
+ previous process) when either differs from this one's, else None. A resumed thread with no engine file
103
+ was started by a release before this file existed (MIG-B16, MIG-B12, MIG-B10, MIG-B15): `started_on` is unknown, never this engine,
104
+ and `moved_from` says so. `children` is each sub-workflow unit's child as this process runs it: its workflow, its
105
+ content version and its unit digests (SWF-B8), read back by the resume check (SWF-B3)."""
106
+ doc = read(root, spec.name, task_id)
107
+ eng = this_engine()
108
+ prev = last(doc)
109
+ legacy = resumed and not doc.get("history")
110
+ entry = {**eng, "workflow_version": content_version, "shape_digest": shape_digest,
111
+ "checkpoint_format": int(prev.get("checkpoint_format") or checkpoint_format()), "units": unit_digests(spec),
112
+ **({"children": {u: dict(c) for u, c in children.items()}} if children else {}), "started_at": now_iso()}
113
+ hist = [*(doc.get("history") or []), entry][-HISTORY_KEPT:]
114
+ for old in hist[:-1]: # only the latest entry needs the per-unit digests
115
+ old.pop("units", None)
116
+ old.pop("children", None)
117
+ started = doc.get("started_on") or (dict(UNKNOWN) if legacy else eng if not prev else None)
118
+ new = {"schema_version": 1, "started_on": started,
119
+ "last_on": eng, "pinned": doc.get("pinned"), "history": hist}
120
+ write_json(path(root, spec.name, task_id), new)
121
+ if legacy:
122
+ return {"engine_version": "unknown", "workflow_version": None}
123
+ moved = prev and (prev.get("engine_version") != eng["engine_version"]
124
+ or prev.get("workflow_version") != content_version)
125
+ return {"engine_version": prev.get("engine_version"), "workflow_version": prev.get("workflow_version")} \
126
+ if moved else None
127
+
128
+
129
+ def pin(root: Path, workflow: str, task_id: str, engine: str, reason: str) -> dict[str, Any]:
130
+ doc = read(root, workflow, task_id)
131
+ doc = {"schema_version": 1, **doc, "pinned": {"engine": engine, "reason": reason, "since": now_iso()}}
132
+ write_json(path(root, workflow, task_id), doc)
133
+ return doc
134
+
135
+
136
+ def unpin(root: Path, workflow: str, task_id: str) -> None:
137
+ doc = read(root, workflow, task_id)
138
+ if doc.get("pinned"):
139
+ write_json(path(root, workflow, task_id), {**doc, "pinned": None})
140
+
141
+
142
+ def decide(doc: Mapping[str, Any], *, resumes: Sequence[int], kept: Mapping[str, Sequence[int]],
143
+ current: str | None = None) -> tuple[str, str | None]:
144
+ """MIG-B12, MIG-B13, MIG-B14: `("dispatch", engine)` for a pinned thread, `("move", None)` when this engine resumes the
145
+ thread's checkpoint format, `("pin", engine)` to the newest kept engine that does, else
146
+ `("refuse", message)`. `kept` maps each kept engine folder to the formats it resumes."""
147
+ pinned = doc.get("pinned")
148
+ if isinstance(pinned, Mapping) and pinned.get("engine"):
149
+ return ("move", None) if pinned["engine"] == current else ("dispatch", str(pinned["engine"]))
150
+ fmt = int(last(doc).get("checkpoint_format") or 1)
151
+ if fmt in [int(f) for f in resumes]:
152
+ return "move", None
153
+ able = sorted((e for e, formats in kept.items() if fmt in [int(f) for f in formats] and e != current),
154
+ key=_folder_key)
155
+ if able:
156
+ return "pin", able[-1]
157
+ return "refuse", (f"this thread's checkpoint format {fmt} is resumed by no installed engine; install an "
158
+ f"engine release that resumes format {fmt} beside this one, then resume")
159
+
160
+
161
+ def _folder_key(name: str) -> tuple[int, ...]:
162
+ return tuple(int(p) if p.isdigit() else 0 for p in name.split("-", 1)[0].split("."))
163
+
164
+
165
+ def kept_engines(home: Path) -> dict[str, list[int]]:
166
+ """Every complete engine environment and the checkpoint formats its release resumes."""
167
+ out: dict[str, list[int]] = {}
168
+ eng = home / "engines"
169
+ for env in sorted(p for p in eng.iterdir() if (p / ".complete").is_file()) if eng.is_dir() else []:
170
+ try:
171
+ rel = json.loads((env / "release.json").read_text(encoding="utf-8"))
172
+ except (OSError, ValueError):
173
+ rel = {}
174
+ out[env.name] = [int(f) for f in (rel.get("resumes_checkpoint_formats") or [1])]
175
+ return out
176
+
177
+
178
+ def thread_format(root: Path, workflow: str, task_id: str) -> int:
179
+ """The checkpoint format the thread was last written in; this engine's own for a new or unrecorded one."""
180
+ return int(last(read(root, workflow, task_id)).get("checkpoint_format") or checkpoint_format())
181
+
182
+
183
+ def checkpoint_of(root: Path, workflow: str, task_id: str) -> Path:
184
+ from tempergraph.store.layout import checkpoint_path
185
+
186
+ return checkpoint_path(root, workflow, thread_format(root, workflow, task_id))
187
+
188
+
189
+ def resumes() -> list[int]:
190
+ from tempergraph.release import release
191
+
192
+ return [int(f) for f in release().get("resumes_checkpoint_formats") or [1]]
193
+
194
+
195
+ def at_resume(root: Path, workflow: str, task_id: str, home: Path | None = None, *, write: bool = True
196
+ ) -> tuple[str, str | None]:
197
+ """MIG-B12, MIG-B13, MIG-B14 for this process: `("move", None)`, `("dispatch", engine folder)` or `("refuse", message)`.
198
+ A format break writes the pin first; a refusal writes nothing."""
199
+ from tempergraph.store.layout import home_path
200
+
201
+ home = home or home_path()
202
+ doc = read(root, workflow, task_id)
203
+ if doc and not doc.get("history"):
204
+ doc = {**doc, "history": [{"checkpoint_format": 1}]}
205
+ current = this_engine()["engine"]
206
+ action, detail = decide(doc or {"history": [{"checkpoint_format": checkpoint_format()}]},
207
+ resumes=resumes(), kept=kept_engines(home), current=current)
208
+ if action == "pin":
209
+ if write:
210
+ pin(root, workflow, task_id, str(detail), "checkpoint_format")
211
+ action = "dispatch"
212
+ if action == "dispatch" and not (home / "engines" / str(detail) / ".complete").is_file():
213
+ return "refuse", (f"this thread is pinned to engine {detail}, which is no longer installed; run "
214
+ f"`tempergraph update` from a plugin copy of that version to install it beside the "
215
+ "current one, then resume")
216
+ return action, detail
217
+
218
+
219
+ def try_unpin(root: Path, workflow: str, task_id: str) -> str | None:
220
+ """`resume --unpin`: clear the pin when this engine resumes the thread's format. This release ships no
221
+ checkpoint converter, so any other pin stays and the reason is returned."""
222
+ doc = read(root, workflow, task_id)
223
+ if not doc.get("pinned"):
224
+ return None
225
+ fmt = int(last(doc).get("checkpoint_format") or 1)
226
+ if fmt not in resumes():
227
+ return (f"this engine does not resume checkpoint format {fmt} and ships no converter for it; the "
228
+ f"thread stays pinned to {doc['pinned'].get('engine')}")
229
+ unpin(root, workflow, task_id)
230
+ return None
231
+
232
+
233
+ # -- a workflow changed under a thread (MIG-B15) -----------------------------------------------------------------
234
+
235
+
236
+ def _reads(spec: WorkflowSpec, unit: str) -> set[str]:
237
+ """The artifact keys a unit's prompt and judge read."""
238
+ from tempergraph.model.text import TextUnreadable, load_text
239
+ from tempergraph.render.template import TemplateError, fields
240
+
241
+ u = spec.units[unit]
242
+ out: set[str] = set()
243
+ if u.step is not None:
244
+ with contextlib.suppress(TextUnreadable, TemplateError):
245
+ out |= set(fields(load_text(spec, u.step.prompt)))
246
+ if u.gate.judge is not None:
247
+ out |= set(u.gate.judge.references or ())
248
+ return out
249
+
250
+
251
+ def breaks(prev: Mapping[str, Any], spec: WorkflowSpec, values: Mapping[str, Any], pending: Sequence[str]
252
+ ) -> list[str]:
253
+ """The four tests of MIG-B15 against the units of the previous process (`prev` is its history entry).
254
+ An empty list means the thread may resume on the new content."""
255
+ from tempergraph.model import flow
256
+
257
+ old = prev.get("units") or {}
258
+ out: list[str] = []
259
+ order = [n for n in flow.effective_order(spec) if n in spec.units]
260
+ pending_set = set(pending)
261
+ # Units ahead of the earliest pending unit in the order were cleared by a trip back (BUD-B4);
262
+ # they are not completed: they will run again before any reader of their keys.
263
+ pending_positions = [order.index(u) for u in pending if u in order]
264
+ earliest_pending = min(pending_positions) if pending_positions else len(order)
265
+ for unit in pending: # 1 the pending unit keeps its name and kind
266
+ was = old.get(unit) or {}
267
+ if unit not in spec.units:
268
+ out.append(f"the pending unit {unit!r} no longer exists")
269
+ elif was and was.get("kind") != str(spec.units[unit].kind):
270
+ out.append(f"the pending unit {unit!r} changed kind from {was.get('kind')} to {spec.units[unit].kind}")
271
+ done = [u for u in (values.get("attempts") or {}) if u not in pending_set]
272
+ for unit in done: # 2 every completed unit still exists
273
+ if unit in old and unit not in spec.units:
274
+ out.append(f"the completed unit {unit!r} no longer exists, so a trip back cannot find it")
275
+ recorded = {u: set((values.get("artifacts") or {}).get(u) or {}) | set((values.get("values") or {}).get(u) or {})
276
+ for u in done}
277
+ later = [u for u in order if u not in done]
278
+ needed = set().union(*(_reads(spec, u) for u in later)) if later else set()
279
+ for unit in done: # 3 a key a pending or later unit reads from a completed unit is recorded
280
+ if unit not in spec.units or spec.units[unit].step is None:
281
+ continue
282
+ # A unit whose artifacts were cleared by a trip back (BUD-B4) has no recorded keys; it is not
283
+ # completed — it runs again before any reader — so its missing keys are not a break (MIG-B15).
284
+ unit_pos = order.index(unit) if unit in order else -1
285
+ if unit_pos >= earliest_pending and not recorded.get(unit):
286
+ continue
287
+ for key in sorted(set(spec.units[unit].step.produces or {}) & needed): # type: ignore[union-attr]
288
+ if key not in recorded.get(unit, set()):
289
+ out.append(f"{unit!r} now produces {key!r}, which a later unit reads and this thread never recorded")
290
+ inputs = (values.get("request") or {}).get("inputs") or {}
291
+ for p in spec.input.parameters: # 4 every input parameter the new version requires has a value
292
+ if p.name not in inputs:
293
+ out.append(f"the input parameter {p.name!r} has no value in this thread")
294
+ return out
295
+
296
+
297
+ def changed_units(prev: Mapping[str, Any], spec: WorkflowSpec) -> list[str]:
298
+ """The units of the previous process whose prompts, gates or limits changed since."""
299
+ old = prev.get("units") or {}
300
+ now = unit_digests(spec)
301
+ return sorted(u for u, d in now.items() if u in old and old[u].get("digest") != d["digest"])