@tedbrain/vlink 0.0.0-dpv2.pdkadapt.plugin.0.1.5.r2 → 0.0.0-dpv2.pdkadapt.plugin.0.1.8.r2
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.
- package/README.md +11 -0
- package/package.json +1 -1
- package/tedbrain_plugin_runtime/engine.py +27 -3
- package/tedbrain_plugin_runtime/handoff.py +188 -0
- package/tedbrain_plugin_runtime/jobs.py +44 -6
- package/tedbrain_plugin_runtime/ops.py +226 -0
- package/tedbrain_plugin_runtime/rungc.py +176 -0
- package/tedbrain_plugin_runtime/supervisor.py +160 -0
- package/tedbrain_plugin_runtime/worker.py +164 -11
package/README.md
CHANGED
|
@@ -28,5 +28,16 @@ PYTHONDONTWRITEBYTECODE=1 TED_EDA_MODE=LOCAL python3 -m pytest tests/test_dpv2*.
|
|
|
28
28
|
- SQLite 保留 job/attempt/幂等键/事件。运行中版本固定;恢复必须确认旧执行停止、检查点兼容且原工艺范围一致。
|
|
29
29
|
- guide.md 和 tedbrain skill 是发布候选文档,不代表其目标公网 URL 已可用。
|
|
30
30
|
|
|
31
|
+
## 服务端工艺通告(I01928)
|
|
32
|
+
|
|
33
|
+
适配成功(作业 SUCCEEDED 且交付为 INSTALLED)后,装到工作站的那棵结果树同时留在 DPV2 的 run store。worker 把它通告到一个只读的清单目录,供其它 DPV2 plugin(TED 作业 runner,I01920)读取。默认关闭;部署配置设置 `pdk_handoff_root` 后启用。
|
|
34
|
+
|
|
35
|
+
- 清单位置:`<pdk_handoff_root>/<subject>/<alias>.json`,原子写入,目录 0700。每个 (subject, alias) 只保留最新一次成功交付。
|
|
36
|
+
- 清单字段:`schema`、`kind=dpv2-pdk-handoff`、`plugin=pdkadapt`、`subject`、`alias`、`run_id`、`attempt`、`workstation_id`、`plugin_version`、`mode`、`cells`、`completion_sha256`、`tree{path,files,total_size,tree_sha256}`、`published_at`。
|
|
37
|
+
- 发布前重新计算结果树摘要,必须与引擎确认的交付一致。不一致或树缺失时写 `<state_root>/handoff-status.json`,不写清单,也不改变作业结果。
|
|
38
|
+
- 触发时机:worker 启动时全量同步一次;每次消费到成功回执后同步该 (subject, alias)。
|
|
39
|
+
- 清单不复制工艺内容,也不构成授权。使用方在使用前必须按同一规则重新校验 `tree_sha256`:按路径排序的 `{name,size,sha256}` 列表(排除根目录的 `.ted-result.json`,遇到符号链接即拒绝),对 `json.dumps(entries, sort_keys=True, separators=(",", ":"))` 的 UTF-8 字节取 SHA-256。
|
|
40
|
+
- 清单只说明服务端留有这棵树,不表示任何工作站当前安装的内容与它一致。
|
|
41
|
+
|
|
31
42
|
公开 runtime、服务器独立部署和真实 full 适配必须另取实际证据。发布授权边界以项目规则为准。
|
|
32
43
|
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name": "@tedbrain/vlink", "private": false, "version": "0.0.0-dpv2.pdkadapt.plugin.0.1.
|
|
1
|
+
{"name": "@tedbrain/vlink", "private": false, "version": "0.0.0-dpv2.pdkadapt.plugin.0.1.8.r2"}
|
|
@@ -6,7 +6,20 @@ from pathlib import Path
|
|
|
6
6
|
import sys
|
|
7
7
|
import traceback
|
|
8
8
|
from .installer import atomic,canonical,loads,ContractError
|
|
9
|
-
from .jobs import Jobs
|
|
9
|
+
from .jobs import Conflict,Jobs
|
|
10
|
+
|
|
11
|
+
# Matches the transport's own DEFAULT_REQUEST_TIMEOUT_SECONDS: a single remote
|
|
12
|
+
# call can never silently outlast its request budget, so the supervisor's
|
|
13
|
+
# lease stays strictly above the longest honest silent window.
|
|
14
|
+
LEASE_FLOOR=600
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def call_floor():
|
|
18
|
+
"""The engine's per-call budget; the supervisor multiplies it for the lease."""
|
|
19
|
+
raw=os.environ.get('TED_ELINK_TIMEOUT','')
|
|
20
|
+
try:floor=int(raw)
|
|
21
|
+
except ValueError:floor=0
|
|
22
|
+
return floor if 0<floor<=24*3600 else LEASE_FLOOR
|
|
10
23
|
|
|
11
24
|
|
|
12
25
|
class Cancelled(Exception):
|
|
@@ -17,6 +30,14 @@ def run(path):
|
|
|
17
30
|
path=Path(path);spec=loads(path.read_bytes());row=spec['job'];config=spec['config'];station=spec['workstation']
|
|
18
31
|
jobs=Jobs(Path(config['state_root'])/'jobs.sqlite3')
|
|
19
32
|
request=loads(row['request']);directory=path.parent
|
|
33
|
+
# I01900 heartbeat lease: the engine renews at every tool boundary and
|
|
34
|
+
# every progress checkpoint. Renewal is best-effort against a supervisor
|
|
35
|
+
# that may have already reaped or cancelled this attempt; losing that race
|
|
36
|
+
# must not mask the original outcome.
|
|
37
|
+
floor=call_floor()
|
|
38
|
+
def beat():
|
|
39
|
+
try:jobs.beat(row['id'],row['attempt'],floor=floor)
|
|
40
|
+
except (Conflict,ContractError):pass
|
|
20
41
|
# Only server-pinned inventories can bind the runtime. Remote home and
|
|
21
42
|
# connection come from the authenticated enrollment, never job parameters.
|
|
22
43
|
executor=config['executor_contracts'][station['release_sha256']]
|
|
@@ -41,8 +62,9 @@ def run(path):
|
|
|
41
62
|
|
|
42
63
|
class Session(PdkAdaptSession):
|
|
43
64
|
def send_tool(self,*args,**kwargs):
|
|
44
|
-
cancelled()
|
|
45
|
-
result=super().send_tool(*args,**kwargs)
|
|
65
|
+
cancelled();beat()
|
|
66
|
+
try:result=super().send_tool(*args,**kwargs)
|
|
67
|
+
finally:beat()
|
|
46
68
|
cancelled()
|
|
47
69
|
return result
|
|
48
70
|
def publish_server_result(self):
|
|
@@ -72,8 +94,10 @@ def run(path):
|
|
|
72
94
|
atomic(pointer,canonical({'path':str(session.root),'attempt':row['attempt']}))
|
|
73
95
|
session.workflow=PdkWorkflow(session,request)
|
|
74
96
|
os.environ['TED_PDK_PROGRESS_FILE']=str(session.root/'extraction-progress.json')
|
|
97
|
+
beat()
|
|
75
98
|
def progress(state):
|
|
76
99
|
jobs.append(row['id'],row['attempt'],{'event':'checkpoint','step':state.step,'phase':state.status})
|
|
100
|
+
beat()
|
|
77
101
|
cancelled()
|
|
78
102
|
result=None;stopped=False
|
|
79
103
|
try:
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Server-side PDK handoff to other DPV2 plugins (I01928, parent I01920).
|
|
2
|
+
|
|
3
|
+
pdkadapt is the only producer of adapted PDK trees. When an attempt ends in a
|
|
4
|
+
confirmed INSTALLED delivery, the tree that was installed on the workstation
|
|
5
|
+
also stays in the DPV2 run store. This module announces that tree in a small
|
|
6
|
+
manifest area that another plugin (the TED job runner) reads. It never opens
|
|
7
|
+
the job database or the run store to consumers and never copies PDK content:
|
|
8
|
+
a manifest names one finished tree by run id and digest, and the consumer must
|
|
9
|
+
verify the digest again before it uses the tree.
|
|
10
|
+
|
|
11
|
+
The feature is off until the deployment sets ``pdk_handoff_root``.
|
|
12
|
+
"""
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
import re
|
|
17
|
+
import time
|
|
18
|
+
|
|
19
|
+
from .installer import ContractError, atomic, canonical, loads
|
|
20
|
+
|
|
21
|
+
SCHEMA = 1
|
|
22
|
+
KIND = "dpv2-pdk-handoff"
|
|
23
|
+
SUBJECT = re.compile(r"tedbrain-(?:user|invite)-[a-f0-9]{24}")
|
|
24
|
+
IDENTIFIER = re.compile(r"[a-f0-9]{32}")
|
|
25
|
+
# Aliases are produced by request_contract: alphanumerics plus ``._-``, never
|
|
26
|
+
# starting with a dot, so a manifest path can never escape its directory.
|
|
27
|
+
ALIAS = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}")
|
|
28
|
+
# Same bounds as ted_eda_tools.pdk.readiness.tree_receipt.
|
|
29
|
+
MAX_FILE_BYTES = 16 * 1024 * 1024
|
|
30
|
+
MAX_TOTAL_BYTES = 128 * 1024 * 1024
|
|
31
|
+
MAX_ENTRIES = 50000
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def root(config):
|
|
35
|
+
"""The handoff directory, or None when the deployment did not enable it."""
|
|
36
|
+
value = config.get("pdk_handoff_root")
|
|
37
|
+
return Path(value).absolute() if value else None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def tree_path(state_root, subject, workstation, run_id, alias):
|
|
41
|
+
"""Location of the retained tree in the DPV2 run store (the engine's layout)."""
|
|
42
|
+
for name, value, pattern in (
|
|
43
|
+
("subject", subject, SUBJECT),
|
|
44
|
+
("workstation", workstation, IDENTIFIER),
|
|
45
|
+
("run_id", run_id, IDENTIFIER),
|
|
46
|
+
("alias", alias, ALIAS),
|
|
47
|
+
):
|
|
48
|
+
if not isinstance(value, str) or not pattern.fullmatch(value):
|
|
49
|
+
raise ContractError("unsafe " + name)
|
|
50
|
+
return (
|
|
51
|
+
Path(state_root).absolute() / "engine" / "dpv2" / "clients" / subject
|
|
52
|
+
/ "machines" / workstation / "runs" / run_id / "pdks" / alias
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _file_digest(path):
|
|
57
|
+
value = hashlib.sha256()
|
|
58
|
+
with path.open("rb") as stream:
|
|
59
|
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
|
60
|
+
value.update(chunk)
|
|
61
|
+
return value.hexdigest()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def tree_receipt(tree):
|
|
65
|
+
"""The engine's delivery digest: sorted entries of relative name, size and file digest.
|
|
66
|
+
|
|
67
|
+
The archive marker ``.ted-result.json`` belongs to the installed copy only
|
|
68
|
+
and is excluded exactly as in the engine's own receipt.
|
|
69
|
+
"""
|
|
70
|
+
tree = Path(tree)
|
|
71
|
+
if tree.is_symlink() or not tree.is_dir():
|
|
72
|
+
raise ContractError("retained adapted tree is missing")
|
|
73
|
+
entries = []
|
|
74
|
+
total = 0
|
|
75
|
+
for path in sorted(tree.rglob("*")):
|
|
76
|
+
if path.is_symlink():
|
|
77
|
+
raise ContractError("retained adapted tree contains a symlink")
|
|
78
|
+
if path.name == ".ted-result.json" and path.parent == tree:
|
|
79
|
+
continue
|
|
80
|
+
if path.is_file():
|
|
81
|
+
size = path.stat().st_size
|
|
82
|
+
total += size
|
|
83
|
+
if size > MAX_FILE_BYTES or total > MAX_TOTAL_BYTES or len(entries) >= MAX_ENTRIES:
|
|
84
|
+
raise ContractError("retained adapted tree exceeds handoff limits")
|
|
85
|
+
entries.append({"name": path.relative_to(tree).as_posix(), "size": size, "sha256": _file_digest(path)})
|
|
86
|
+
if not entries:
|
|
87
|
+
raise ContractError("retained adapted tree is empty")
|
|
88
|
+
payload = json.dumps(entries, sort_keys=True, separators=(",", ":")).encode()
|
|
89
|
+
return {"files": len(entries), "total_size": total, "tree_sha256": hashlib.sha256(payload).hexdigest()}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def delivery_of(row):
|
|
93
|
+
"""The confirmed delivery of a SUCCEEDED job row, or None."""
|
|
94
|
+
if row["state"] != "SUCCEEDED" or not row["result"]:
|
|
95
|
+
return None
|
|
96
|
+
delivery = (json.loads(row["result"]) or {}).get("delivery")
|
|
97
|
+
if not isinstance(delivery, dict) or delivery.get("status") != "INSTALLED":
|
|
98
|
+
return None
|
|
99
|
+
return delivery
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def manifest(row, state_root):
|
|
103
|
+
"""The handoff manifest for one SUCCEEDED job, or None when it has no delivery.
|
|
104
|
+
|
|
105
|
+
The retained tree is hashed again and must equal the delivery that the
|
|
106
|
+
engine confirmed; a tree that drifted is refused, not announced.
|
|
107
|
+
"""
|
|
108
|
+
delivery = delivery_of(row)
|
|
109
|
+
if delivery is None:
|
|
110
|
+
return None
|
|
111
|
+
request = json.loads(row["request"])
|
|
112
|
+
alias = request.get("alias")
|
|
113
|
+
if delivery.get("alias") != alias:
|
|
114
|
+
raise ContractError("delivery alias differs from the request")
|
|
115
|
+
tree = tree_path(state_root, row["subject"], row["workstation"], row["id"], alias)
|
|
116
|
+
receipt = tree_receipt(tree)
|
|
117
|
+
for key in ("files", "total_size", "tree_sha256"):
|
|
118
|
+
if receipt[key] != delivery.get(key):
|
|
119
|
+
raise ContractError("retained tree differs from the confirmed delivery")
|
|
120
|
+
return {
|
|
121
|
+
"schema": SCHEMA, "kind": KIND, "plugin": "pdkadapt",
|
|
122
|
+
"subject": row["subject"], "alias": alias,
|
|
123
|
+
"run_id": row["id"], "attempt": row["attempt"], "workstation_id": row["workstation"],
|
|
124
|
+
"plugin_version": row["version"], "mode": request.get("mode", ""), "cells": request.get("cells", ""),
|
|
125
|
+
"completion_sha256": delivery.get("completion_sha256"),
|
|
126
|
+
"tree": dict(receipt, path=str(tree)), "published_at": time.time(),
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def target(handoff, subject, alias):
|
|
131
|
+
"""Where the manifest of one (subject, alias) pair lives."""
|
|
132
|
+
for value, pattern in ((subject, SUBJECT), (alias, ALIAS)):
|
|
133
|
+
if not isinstance(value, str) or not pattern.fullmatch(value):
|
|
134
|
+
raise ContractError("unsafe handoff path")
|
|
135
|
+
return Path(handoff) / subject / (alias + ".json")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def stored(path):
|
|
139
|
+
"""The manifest already stored at ``path``, or None."""
|
|
140
|
+
if path.is_symlink() or not path.is_file():
|
|
141
|
+
return None
|
|
142
|
+
value = loads(path.read_bytes())
|
|
143
|
+
if isinstance(value, dict) and value.get("kind") == KIND and value.get("schema") == SCHEMA:
|
|
144
|
+
return value
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def sync(config, jobs, *, only=None):
|
|
149
|
+
"""Announce the newest confirmed delivery of each (subject, alias) pair.
|
|
150
|
+
|
|
151
|
+
``only`` limits the pass to one pair after a completion. A manifest whose
|
|
152
|
+
run id and digest already equal the job row is left untouched, so a
|
|
153
|
+
restart only hashes trees that changed. Failures are reported, never
|
|
154
|
+
raised: announcing a delivery must not change the outcome of an adaptation.
|
|
155
|
+
"""
|
|
156
|
+
report = {"enabled": False, "published": [], "unchanged": 0, "failed": []}
|
|
157
|
+
handoff = root(config)
|
|
158
|
+
if handoff is None:
|
|
159
|
+
return report
|
|
160
|
+
report["enabled"] = True
|
|
161
|
+
with jobs.connection() as db:
|
|
162
|
+
rows = db.execute("SELECT * FROM jobs WHERE state='SUCCEEDED' ORDER BY updated DESC, id").fetchall()
|
|
163
|
+
newest = {}
|
|
164
|
+
for row in rows:
|
|
165
|
+
delivery = delivery_of(row)
|
|
166
|
+
if delivery is None:
|
|
167
|
+
continue
|
|
168
|
+
pair = (row["subject"], json.loads(row["request"]).get("alias"))
|
|
169
|
+
if only is not None and pair != only:
|
|
170
|
+
continue
|
|
171
|
+
newest.setdefault(pair, (row, delivery))
|
|
172
|
+
for (subject, alias), (row, delivery) in sorted(newest.items()):
|
|
173
|
+
try:
|
|
174
|
+
path = target(handoff, subject, alias)
|
|
175
|
+
previous = stored(path)
|
|
176
|
+
if previous is not None and previous.get("run_id") == row["id"] \
|
|
177
|
+
and (previous.get("tree") or {}).get("tree_sha256") == delivery.get("tree_sha256"):
|
|
178
|
+
report["unchanged"] += 1
|
|
179
|
+
continue
|
|
180
|
+
value = manifest(row, config["state_root"])
|
|
181
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
182
|
+
atomic(path, canonical(value))
|
|
183
|
+
report["published"].append({"subject": subject, "alias": alias, "run_id": row["id"],
|
|
184
|
+
"tree_sha256": value["tree"]["tree_sha256"]})
|
|
185
|
+
except (ContractError, ValueError, TypeError, KeyError, OSError) as error:
|
|
186
|
+
report["failed"].append({"subject": subject, "alias": alias, "run_id": row["id"],
|
|
187
|
+
"error": "%s: %s" % (type(error).__name__, error)})
|
|
188
|
+
return report
|
|
@@ -42,6 +42,16 @@ class Jobs:
|
|
|
42
42
|
body TEXT NOT NULL, created REAL NOT NULL);
|
|
43
43
|
CREATE INDEX IF NOT EXISTS events_job ON events(job,seq);
|
|
44
44
|
''')
|
|
45
|
+
# I01900 heartbeat lease columns. Databases written by older
|
|
46
|
+
# releases upgrade in place: the base schema above is unchanged
|
|
47
|
+
# and the lease columns are appended with defaults, so a
|
|
48
|
+
# pre-I01900 worker and a post-I01900 worker can both keep
|
|
49
|
+
# reading the same file.
|
|
50
|
+
columns={row[1] for row in db.execute('PRAGMA table_info(jobs)')}
|
|
51
|
+
if 'heartbeat' not in columns:
|
|
52
|
+
db.execute('ALTER TABLE jobs ADD COLUMN heartbeat REAL NOT NULL DEFAULT 0')
|
|
53
|
+
if 'lease_floor' not in columns:
|
|
54
|
+
db.execute('ALTER TABLE jobs ADD COLUMN lease_floor REAL NOT NULL DEFAULT 0')
|
|
45
55
|
self.path.chmod(0o600)
|
|
46
56
|
|
|
47
57
|
@contextmanager
|
|
@@ -117,22 +127,50 @@ class Jobs:
|
|
|
117
127
|
self.event(db,job,attempt,{'event':'accepted','plugin_version':version})
|
|
118
128
|
return dict(self.public(db.execute('SELECT * FROM jobs WHERE id=?',(job,)).fetchone()),replayed=False,submission_attempt=attempt)
|
|
119
129
|
|
|
120
|
-
def claim(self,version,*,max_active=
|
|
130
|
+
def claim(self,version,*,max_active=1,max_total=16):
|
|
131
|
+
"""Claim the oldest queued attempt of ``version`` under I01900 budgets.
|
|
132
|
+
|
|
133
|
+
``max_active`` bounds one workstation: a leaked attempt wedges only its
|
|
134
|
+
own station, never the whole deployment (I01814). ``max_total`` stays a
|
|
135
|
+
small global fuse over RUNNING/CANCELLING/UNKNOWN across every version
|
|
136
|
+
and workstation: neither an upgrade nor a supervisor restart may bypass
|
|
137
|
+
it. Seeding ``heartbeat`` at claim starts the lease window before the
|
|
138
|
+
engine's first renewal.
|
|
139
|
+
"""
|
|
121
140
|
if type(max_active) is not int or not 1<=max_active<=16:
|
|
122
141
|
raise ContractError('bounded worker concurrency required')
|
|
142
|
+
if type(max_total) is not int or not 1<=max_total<=64:
|
|
143
|
+
raise ContractError('bounded global concurrency required')
|
|
123
144
|
with self.connection() as db:
|
|
124
145
|
db.execute('BEGIN IMMEDIATE')
|
|
125
|
-
# Include old versions and unknown outcomes: neither an upgrade
|
|
126
|
-
# nor a supervisor restart may bypass the execution budget.
|
|
127
146
|
active=db.execute("SELECT COUNT(*) FROM jobs WHERE state IN ('RUNNING','CANCELLING','UNKNOWN')").fetchone()[0]
|
|
128
|
-
if active>=
|
|
129
|
-
row=db.execute("SELECT * FROM jobs AS queued WHERE state=? AND version=? AND
|
|
147
|
+
if active>=max_total:return None
|
|
148
|
+
row=db.execute("SELECT * FROM jobs AS queued WHERE state=? AND version=? AND (SELECT COUNT(*) FROM jobs AS active WHERE active.workstation=queued.workstation AND active.state IN ('RUNNING','CANCELLING','UNKNOWN'))<? ORDER BY created LIMIT 1",('ACCEPTED',version,max_active)).fetchone()
|
|
130
149
|
if row is None:return None
|
|
131
|
-
|
|
150
|
+
now=time.time()
|
|
151
|
+
db.execute("UPDATE jobs SET state=?,heartbeat=?,lease_floor=0,updated=? WHERE id=?",('RUNNING',now,now,row['id']))
|
|
132
152
|
db.execute('UPDATE attempts SET state=? WHERE id=?',('RUNNING',row['attempt']))
|
|
133
153
|
self.event(db,row['id'],row['attempt'],{'event':'running'})
|
|
134
154
|
return dict(row)
|
|
135
155
|
|
|
156
|
+
def beat(self,job,attempt,*,floor):
|
|
157
|
+
"""Renew the engine heartbeat lease (I01900).
|
|
158
|
+
|
|
159
|
+
Only the lease columns move: ``updated`` remains the state-change clock
|
|
160
|
+
that the UNKNOWN grace and the cancel escalation measure, so a healthy
|
|
161
|
+
hung-looking-in-DB engine can never extend its own reap grace. A stale
|
|
162
|
+
or terminal attempt refuses the renewal; the engine treats that as its
|
|
163
|
+
signal that the supervisor already reaped this attempt.
|
|
164
|
+
"""
|
|
165
|
+
if type(floor) is not int or not 1<=floor<=24*3600:
|
|
166
|
+
raise ContractError('heartbeat call budget required')
|
|
167
|
+
with self.connection() as db:
|
|
168
|
+
db.execute('BEGIN IMMEDIATE')
|
|
169
|
+
row=db.execute('SELECT attempt,state FROM jobs WHERE id=?',(job,)).fetchone()
|
|
170
|
+
if row is None or row['attempt']!=attempt or row['state'] not in ('RUNNING','CANCELLING','UNKNOWN'):
|
|
171
|
+
raise Conflict('stale attempt')
|
|
172
|
+
db.execute('UPDATE jobs SET heartbeat=?,lease_floor=? WHERE id=?',(time.time(),float(floor),job))
|
|
173
|
+
|
|
136
174
|
def cancel(self,subject,job,key):
|
|
137
175
|
if not re.fullmatch(r'[A-Za-z0-9._-]{1,128}',key or ''):
|
|
138
176
|
raise ContractError('Idempotency-Key required')
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Sanctioned operator face for DPV2 attempt triage and reaping (I01903).
|
|
2
|
+
|
|
3
|
+
The productized I01814 hotfix. ``list`` surveys every non-terminal attempt
|
|
4
|
+
(read-only). ``reap`` shows the same survey and, with ``--apply``, performs
|
|
5
|
+
exactly what the supervisor's own reconcile would do for attempts whose
|
|
6
|
+
engine process is provably dead — never touching a live process, always
|
|
7
|
+
taking a VACUUM INTO backup first and failing closed when the backup is
|
|
8
|
+
refused. ``alerts`` evaluates budget/queue/age/tick-health thresholds as a
|
|
9
|
+
one-shot command for the e01 monitor (exit 1 when any alert fires).
|
|
10
|
+
"""
|
|
11
|
+
import argparse
|
|
12
|
+
import fcntl
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
import secrets
|
|
17
|
+
import sqlite3
|
|
18
|
+
import sys
|
|
19
|
+
import time
|
|
20
|
+
from .installer import ContractError, atomic, canonical, loads
|
|
21
|
+
from .executor import live
|
|
22
|
+
from .worker import Worker
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def resolve(args):
|
|
26
|
+
"""Operator selects the state root via the worker config or directly."""
|
|
27
|
+
if args.config:
|
|
28
|
+
config=loads(args.config.read_bytes())
|
|
29
|
+
if not isinstance(config.get('state_root'),str) or not config['state_root']:
|
|
30
|
+
raise ContractError('config lacks state_root')
|
|
31
|
+
return Path(config['state_root']),config
|
|
32
|
+
if args.state_root:return Path(args.state_root),{}
|
|
33
|
+
raise ContractError('either --config or --state-root is required')
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def open_worker(state_root,config):
|
|
37
|
+
"""Supervisor view of the operator-selected state root.
|
|
38
|
+
|
|
39
|
+
Only the dead-attempt reconcile paths run here and none of them compare
|
|
40
|
+
``worker_version``, so an operator-supplied ``--state-root`` without a
|
|
41
|
+
full worker config is legitimate; the config's own knobs (grace, budget
|
|
42
|
+
caps) are still honored when a worker config file was given.
|
|
43
|
+
"""
|
|
44
|
+
minimal=dict(config)
|
|
45
|
+
minimal['state_root']=str(state_root)
|
|
46
|
+
minimal.setdefault('worker_version','ops')
|
|
47
|
+
return Worker(minimal)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _receipt_state(directory,row):
|
|
51
|
+
receipt=directory/'result.json'
|
|
52
|
+
if not receipt.is_file():return 'none'
|
|
53
|
+
try:
|
|
54
|
+
result=loads(receipt.read_bytes())
|
|
55
|
+
except (ContractError,ValueError):return 'invalid'
|
|
56
|
+
if (result.get('job_id'),result.get('attempt'),result.get('version'))!=(row['id'],row['attempt'],row['version']):
|
|
57
|
+
return 'invalid'
|
|
58
|
+
return 'valid'
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def survey(state_root,config,now=None):
|
|
62
|
+
"""Classify every non-terminal attempt without touching anything.
|
|
63
|
+
|
|
64
|
+
Verdicts mirror the supervisor's reconcile decision for the same facts:
|
|
65
|
+
a live process is always protected, a dead attempt is reaped (CANCELLING
|
|
66
|
+
at once, UNKNOWN after its outcome grace) and a valid receipt is consumed
|
|
67
|
+
before any of that.
|
|
68
|
+
"""
|
|
69
|
+
now=float(now or time.time())
|
|
70
|
+
worker=open_worker(state_root,config)
|
|
71
|
+
grace=float(worker.config.get('reap_grace_seconds',600))
|
|
72
|
+
with worker.jobs.connection() as db:
|
|
73
|
+
active=[dict(row) for row in db.execute("SELECT * FROM jobs WHERE state IN ('RUNNING','CANCELLING','UNKNOWN')")]
|
|
74
|
+
active_total=db.execute("SELECT COUNT(*) FROM jobs WHERE state IN ('RUNNING','CANCELLING','UNKNOWN')").fetchone()[0]
|
|
75
|
+
queued=db.execute("SELECT COUNT(*) FROM jobs WHERE state='ACCEPTED'").fetchone()[0]
|
|
76
|
+
oldest=db.execute("SELECT MIN(created) FROM jobs WHERE state IN ('RUNNING','CANCELLING','UNKNOWN')").fetchone()[0]
|
|
77
|
+
stations={row[0]:row[1] for row in db.execute(
|
|
78
|
+
"SELECT workstation,COUNT(*) FROM jobs WHERE state IN ('RUNNING','CANCELLING','UNKNOWN') GROUP BY workstation")}
|
|
79
|
+
rows=[]
|
|
80
|
+
for row in active:
|
|
81
|
+
directory=worker.path(row)
|
|
82
|
+
receipt=_receipt_state(directory,row)
|
|
83
|
+
process=directory/'process.json'
|
|
84
|
+
record=None
|
|
85
|
+
if process.is_file():
|
|
86
|
+
try:record=loads(process.read_bytes())
|
|
87
|
+
except (ContractError,ValueError):record=None
|
|
88
|
+
process_state='missing' if record is None else ('live' if live(record) else 'dead')
|
|
89
|
+
verdict,action='unknown-verdict','observe'
|
|
90
|
+
if process_state=='live':verdict,action='live-protected','observe'
|
|
91
|
+
elif receipt=='valid':verdict,action='receipt-pending','consume-receipt'
|
|
92
|
+
elif row['state']=='CANCELLING':verdict,action='cancel-reap','reap-cancelled'
|
|
93
|
+
elif row['state']=='UNKNOWN':
|
|
94
|
+
if now-float(row['updated'] or 0)<grace:verdict,action='outcome-grace-waiting','observe'
|
|
95
|
+
else:verdict,action='outcome-reap','reap-failed'
|
|
96
|
+
rows.append({'job_id':row['id'],'attempt':row['attempt'],'state':row['state'],
|
|
97
|
+
'version':row['version'],'age':round(now-float(row['created'] or 0),3),
|
|
98
|
+
'workstation':row['workstation'],'process':process_state,'receipt':receipt,
|
|
99
|
+
'verdict':verdict,'action':action,'reapable':action.startswith('reap-')})
|
|
100
|
+
return {'schema':1,'state_root':str(state_root),'now':now,'grace_seconds':grace,
|
|
101
|
+
'budget':{'active_total':active_total,'queued':queued,
|
|
102
|
+
'max_total':int(worker.config.get('max_total_jobs',16)),
|
|
103
|
+
'per_workstation':stations},
|
|
104
|
+
'oldest_active_age':round(now-float(oldest),3) if oldest is not None else None,
|
|
105
|
+
'attempts':rows}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _backup(database,target):
|
|
109
|
+
"""VACUUM INTO snapshot; a refused backup aborts the apply fail-closed."""
|
|
110
|
+
backup=target/('jobs.sqlite3.bak-ops-%d-%d-%s'%(int(time.time()),os.getpid(),secrets.token_hex(4)))
|
|
111
|
+
db=sqlite3.connect(database,timeout=30)
|
|
112
|
+
try:db.execute('VACUUM INTO ?',(str(backup),))
|
|
113
|
+
finally:db.close()
|
|
114
|
+
return backup
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def reap(state_root,config,apply=False):
|
|
118
|
+
"""Report dead attempts, or reap them under the supervisor's semantics.
|
|
119
|
+
|
|
120
|
+
Without ``--apply`` this is the survey, untouched state. With ``--apply``
|
|
121
|
+
the exclusive ops lock and the VACUUM INTO backup are taken first, then
|
|
122
|
+
``Worker.reconcile`` runs for every row the survey marked reapable — the
|
|
123
|
+
same delivered code path the supervisor itself would run on its next
|
|
124
|
+
tick, so a row that turned live between survey and apply is still never
|
|
125
|
+
signalled.
|
|
126
|
+
"""
|
|
127
|
+
report=survey(state_root,config)
|
|
128
|
+
if not apply:return dict(report,applied=False)
|
|
129
|
+
target=Path(state_root).absolute()
|
|
130
|
+
database=target/'jobs.sqlite3'
|
|
131
|
+
if not database.is_file():raise ContractError('jobs database missing; refusing to apply')
|
|
132
|
+
worker=open_worker(target,config)
|
|
133
|
+
reapable=[row for row in report['attempts'] if row['reapable']]
|
|
134
|
+
with (target/'.ops-reap.lock').open('a') as stream:
|
|
135
|
+
fcntl.flock(stream,fcntl.LOCK_EX)
|
|
136
|
+
backup=_backup(database,target)
|
|
137
|
+
results=[]
|
|
138
|
+
with worker.jobs.connection() as db:
|
|
139
|
+
full={row['id']:dict(row) for row in
|
|
140
|
+
db.execute("SELECT * FROM jobs WHERE state IN ('RUNNING','CANCELLING','UNKNOWN')")}
|
|
141
|
+
for row in reapable:
|
|
142
|
+
current=full.get(row['job_id'])
|
|
143
|
+
if current is None or current['attempt']!=row['attempt']:
|
|
144
|
+
results.append({'job_id':row['job_id'],'outcome':'stale','detail':'attempt changed under the operator'})
|
|
145
|
+
continue
|
|
146
|
+
try:worker.reconcile(current)
|
|
147
|
+
except (ContractError,ValueError) as error:
|
|
148
|
+
results.append({'job_id':row['job_id'],'attempt':row['attempt'],'outcome':'error','detail':str(error)})
|
|
149
|
+
continue
|
|
150
|
+
with worker.jobs.connection() as db:
|
|
151
|
+
after=db.execute('SELECT state,result FROM jobs WHERE id=?',(row['job_id'],)).fetchone()
|
|
152
|
+
results.append({'job_id':row['job_id'],'attempt':row['attempt'],'from':row['state'],
|
|
153
|
+
'outcome':'reaped','state':after['state'] if after else None})
|
|
154
|
+
return dict(report,applied=True,backup=str(backup),results=results,
|
|
155
|
+
ok=not any(entry.get('outcome')=='error' for entry in results))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def read_health(state_root):
|
|
159
|
+
path=Path(state_root)/'supervisor-health.json'
|
|
160
|
+
if not path.exists():path=Path(state_root)/'worker-health.json'
|
|
161
|
+
if not path.is_file():return None
|
|
162
|
+
try:return loads(path.read_bytes())
|
|
163
|
+
except (ContractError,ValueError):return {'schema':0,'invalid':True}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def alerts(state_root,config,*,max_age,max_queue,budget_fraction,health_ttl,now=None):
|
|
167
|
+
"""Evaluate the four I01903 signals; raw numbers, consumer thresholds."""
|
|
168
|
+
now=float(now or time.time())
|
|
169
|
+
report=survey(state_root,config,now=now)
|
|
170
|
+
found=[]
|
|
171
|
+
budget=report['budget']
|
|
172
|
+
if budget['max_total']>0 and budget['active_total']>=budget['max_total']:
|
|
173
|
+
found.append({'alert':'budget-exhausted','active':budget['active_total'],'max_total':budget['max_total']})
|
|
174
|
+
elif budget['max_total']>0 and budget['active_total']/budget['max_total']>=budget_fraction:
|
|
175
|
+
found.append({'alert':'budget-high','active':budget['active_total'],'max_total':budget['max_total'],
|
|
176
|
+
'fraction':round(budget['active_total']/budget['max_total'],3)})
|
|
177
|
+
if budget['queued']>max_queue:
|
|
178
|
+
found.append({'alert':'queue-deep','queued':budget['queued'],'max_queue':max_queue})
|
|
179
|
+
if report['oldest_active_age'] is not None and report['oldest_active_age']>max_age:
|
|
180
|
+
found.append({'alert':'aged-attempt','oldest_active_age':report['oldest_active_age'],'max_age':max_age})
|
|
181
|
+
health=read_health(state_root)
|
|
182
|
+
if health is None:
|
|
183
|
+
found.append({'alert':'worker-health-missing','state_root':str(state_root)})
|
|
184
|
+
elif health.get('invalid'):
|
|
185
|
+
found.append({'alert':'worker-health-unreadable','state_root':str(state_root)})
|
|
186
|
+
else:
|
|
187
|
+
age=now-float(health.get('updated') or 0)
|
|
188
|
+
if age>health_ttl:
|
|
189
|
+
found.append({'alert':'worker-health-stale','age':round(age,3),'health_ttl':health_ttl,
|
|
190
|
+
'pid':health.get('pid')})
|
|
191
|
+
if not health.get('last_tick_ok',True) or int(health.get('consecutive_failures') or 0)>0:
|
|
192
|
+
found.append({'alert':'worker-tick-failing','consecutive_failures':health.get('consecutive_failures'),
|
|
193
|
+
'last_error':health.get('last_error')})
|
|
194
|
+
return {'schema':1,'state_root':str(state_root),'now':now,'ok':not found,'alerts':found,
|
|
195
|
+
'survey':{key:report[key] for key in ('budget','oldest_active_age','grace_seconds')}}
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def main(argv=None):
|
|
199
|
+
argv=list(sys.argv[1:] if argv is None else argv)
|
|
200
|
+
parser=argparse.ArgumentParser(description='DPV2 pdkadapt operator triage (I01903); read-only unless reap --apply')
|
|
201
|
+
parser.add_argument('--config',type=Path,help='worker/service config JSON containing state_root')
|
|
202
|
+
parser.add_argument('--state-root',type=Path,help='plugin state root (alternative to --config)')
|
|
203
|
+
sub=parser.add_subparsers(dest='command',required=True)
|
|
204
|
+
sub.add_parser('list',help='read-only survey of non-terminal attempts and budget')
|
|
205
|
+
p_reap=sub.add_parser('reap',help='survey dead attempts; --apply reaps with a VACUUM INTO backup')
|
|
206
|
+
p_reap.add_argument('--apply',action='store_true',help='mutate: backup first, then reap provably dead attempts')
|
|
207
|
+
p_alerts=sub.add_parser('alerts',help='evaluate budget/queue/age/tick-health thresholds (exit 1 on alerts)')
|
|
208
|
+
p_alerts.add_argument('--max-age',type=float,default=86400.0)
|
|
209
|
+
p_alerts.add_argument('--max-queue',type=int,default=16)
|
|
210
|
+
p_alerts.add_argument('--budget-fraction',type=float,default=0.9)
|
|
211
|
+
p_alerts.add_argument('--health-ttl',type=float,default=120.0)
|
|
212
|
+
args=parser.parse_args(argv)
|
|
213
|
+
state_root,config=resolve(args)
|
|
214
|
+
if args.command=='list':payload=survey(state_root,config)
|
|
215
|
+
elif args.command=='reap':payload=reap(state_root,config,apply=args.apply)
|
|
216
|
+
else:payload=alerts(state_root,config,max_age=args.max_age,max_queue=args.max_queue,
|
|
217
|
+
budget_fraction=args.budget_fraction,health_ttl=args.health_ttl)
|
|
218
|
+
print(json.dumps(payload,ensure_ascii=False),flush=True)
|
|
219
|
+
return 0 if payload.get('ok',True) else 1
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
if __name__=='__main__':
|
|
223
|
+
try:raise SystemExit(main())
|
|
224
|
+
except (ContractError,sqlite3.Error) as error:
|
|
225
|
+
print(json.dumps({'ok':False,'error':{'code':'OPS_REQUEST_FAILED','message':str(error)}}),file=sys.stderr)
|
|
226
|
+
raise SystemExit(2)
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Terminal-run bulk pruning for the DPV2 engine store (I01939).
|
|
2
|
+
|
|
3
|
+
Finished DPV2 runs keep their full execution scratch forever; on e01 the
|
|
4
|
+
``ted-data`` GDS alone reached ~7.4G in two days. This tool prunes the bulky
|
|
5
|
+
scratch of terminal runs while preserving every contract artifact:
|
|
6
|
+
|
|
7
|
+
kept per run: ``pdks/`` (delivered tree), ``session.json``, ``decision-evidence/``
|
|
8
|
+
and every other file or directory whose name is not on the bulk list.
|
|
9
|
+
pruned per run: ``ted-data/``, ``checkpoints/``, ``incoming/`` and
|
|
10
|
+
``snapshot-step-*/`` directories.
|
|
11
|
+
|
|
12
|
+
Only runs whose job row in ``jobs.sqlite3`` is terminal (SUCCEEDED, FAILED,
|
|
13
|
+
CANCELLED) and whose ``updated`` timestamp is older than the retention window
|
|
14
|
+
are eligible; run directories that do not map to a terminal job are reported
|
|
15
|
+
and never touched. Deletion is explicit (``--execute``); the default is a
|
|
16
|
+
dry-run plan. Every executed deletion is appended to ``rungc-ledger.jsonl``
|
|
17
|
+
next to the engine state.
|
|
18
|
+
"""
|
|
19
|
+
import argparse
|
|
20
|
+
import json
|
|
21
|
+
import re
|
|
22
|
+
import shutil
|
|
23
|
+
import sqlite3
|
|
24
|
+
import sys
|
|
25
|
+
import time
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
|
|
28
|
+
from .handoff import IDENTIFIER, SUBJECT
|
|
29
|
+
|
|
30
|
+
TERMINAL_STATES = frozenset({'SUCCEEDED', 'FAILED', 'CANCELLED'})
|
|
31
|
+
BULK_DIRS = frozenset({'ted-data', 'checkpoints', 'incoming'})
|
|
32
|
+
SNAPSHOT_PREFIX = 'snapshot-step-'
|
|
33
|
+
LEDGER_NAME = 'rungc-ledger.jsonl'
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def bulk_targets(run_dir):
|
|
37
|
+
"""Bulky subpaths of a run directory; symlinks are refused, not followed."""
|
|
38
|
+
targets = []
|
|
39
|
+
for child in sorted(run_dir.iterdir()):
|
|
40
|
+
if child.name in BULK_DIRS or child.name.startswith(SNAPSHOT_PREFIX):
|
|
41
|
+
if child.is_symlink():
|
|
42
|
+
raise ValueError('refusing symlinked bulk path: ' + str(child))
|
|
43
|
+
targets.append(child)
|
|
44
|
+
return targets
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def tree_bytes(path):
|
|
48
|
+
total = 0
|
|
49
|
+
if path.is_file():
|
|
50
|
+
return path.stat().st_size
|
|
51
|
+
for child in path.rglob('*'):
|
|
52
|
+
try:
|
|
53
|
+
if child.is_file() and not child.is_symlink():
|
|
54
|
+
total += child.stat().st_size
|
|
55
|
+
except OSError:
|
|
56
|
+
continue
|
|
57
|
+
return total
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def load_jobs(db_path):
|
|
61
|
+
"""{job_id: (subject, workstation, state, updated)} read from jobs.sqlite3."""
|
|
62
|
+
rows = {}
|
|
63
|
+
with sqlite3.connect('file:' + str(db_path) + '?mode=ro', uri=True) as db:
|
|
64
|
+
db.row_factory = sqlite3.Row
|
|
65
|
+
for row in db.execute(
|
|
66
|
+
'SELECT id,subject,workstation,state,updated FROM jobs'):
|
|
67
|
+
rows[row['id']] = (row['subject'], row['workstation'],
|
|
68
|
+
row['state'], float(row['updated']))
|
|
69
|
+
return rows
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def plan(state_root, retention_days):
|
|
73
|
+
"""(prune, skipped, problems) for the engine store.
|
|
74
|
+
|
|
75
|
+
prune: [(run_dir, [bulk paths], bytes)] — terminal-old runs to prune.
|
|
76
|
+
skipped: [run_dir] — mapped to a live or recent job; never touched.
|
|
77
|
+
problems: [f"{run_dir} ({reason})"] — unmapped rows, path/job mismatches
|
|
78
|
+
and refused bulk paths; reported, never touched.
|
|
79
|
+
"""
|
|
80
|
+
state = Path(state_root)
|
|
81
|
+
engine = state / 'engine' / 'dpv2' / 'clients'
|
|
82
|
+
db_path = state / 'jobs.sqlite3'
|
|
83
|
+
if not engine.is_dir() or not db_path.is_file():
|
|
84
|
+
raise SystemExit('engine store or jobs database missing under ' + str(state))
|
|
85
|
+
cutoff = time.time() - retention_days * 86400
|
|
86
|
+
jobs = load_jobs(db_path)
|
|
87
|
+
prune, skipped, problems = [], [], []
|
|
88
|
+
for subject_dir in sorted(engine.iterdir()):
|
|
89
|
+
if not SUBJECT.fullmatch(subject_dir.name):
|
|
90
|
+
continue
|
|
91
|
+
machines = subject_dir / 'machines'
|
|
92
|
+
if not machines.is_dir():
|
|
93
|
+
continue
|
|
94
|
+
for station_dir in sorted(machines.iterdir()):
|
|
95
|
+
if not IDENTIFIER.fullmatch(station_dir.name):
|
|
96
|
+
continue
|
|
97
|
+
runs_dir = station_dir / 'runs'
|
|
98
|
+
if not runs_dir.is_dir():
|
|
99
|
+
continue
|
|
100
|
+
for run_dir in sorted(runs_dir.iterdir()):
|
|
101
|
+
if not run_dir.is_dir() or run_dir.is_symlink():
|
|
102
|
+
continue
|
|
103
|
+
if not IDENTIFIER.fullmatch(run_dir.name):
|
|
104
|
+
continue
|
|
105
|
+
entry = jobs.get(run_dir.name)
|
|
106
|
+
if entry is None:
|
|
107
|
+
problems.append(f'{run_dir} (no job row)')
|
|
108
|
+
continue
|
|
109
|
+
subject, station, state_name, updated = entry
|
|
110
|
+
if (state_name not in TERMINAL_STATES) or (updated >= cutoff):
|
|
111
|
+
skipped.append(run_dir)
|
|
112
|
+
continue
|
|
113
|
+
expected = (subject_dir.name, station_dir.name)
|
|
114
|
+
if (subject, station) != expected:
|
|
115
|
+
problems.append(f'{run_dir} (path/job mismatch)')
|
|
116
|
+
continue
|
|
117
|
+
try:
|
|
118
|
+
targets = bulk_targets(run_dir)
|
|
119
|
+
except ValueError as error:
|
|
120
|
+
problems.append(f'{run_dir} ({error})')
|
|
121
|
+
continue
|
|
122
|
+
if not targets:
|
|
123
|
+
continue
|
|
124
|
+
freed = sum(tree_bytes(target) for target in targets)
|
|
125
|
+
prune.append((run_dir, targets, freed))
|
|
126
|
+
return prune, skipped, problems
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def execute(state_root, plan):
|
|
130
|
+
"""Delete every bulk target; append one receipt line per run directory."""
|
|
131
|
+
ledger = Path(state_root) / 'engine' / 'dpv2' / LEDGER_NAME
|
|
132
|
+
receipts = []
|
|
133
|
+
for run_dir, targets, freed in plan:
|
|
134
|
+
removed = []
|
|
135
|
+
for target in targets:
|
|
136
|
+
shutil.rmtree(target)
|
|
137
|
+
removed.append({'path': str(target), 'bytes': None})
|
|
138
|
+
receipts.append({'schema': 1, 'kind': 'dpv2-rungc', 'run': str(run_dir),
|
|
139
|
+
'freed_bytes': freed, 'removed': [r['path'] for r in removed],
|
|
140
|
+
'executed_at': time.time()})
|
|
141
|
+
with ledger.open('a') as stream:
|
|
142
|
+
for receipt in receipts:
|
|
143
|
+
stream.write(json.dumps(receipt, sort_keys=True) + '\n')
|
|
144
|
+
return receipts
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def main(argv=None):
|
|
148
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
149
|
+
parser.add_argument('--state-root', required=True, type=Path,
|
|
150
|
+
help='pdkadapt state root (parent of engine/ and jobs.sqlite3)')
|
|
151
|
+
parser.add_argument('--retention-days', type=int, default=14)
|
|
152
|
+
parser.add_argument('--execute', action='store_true',
|
|
153
|
+
help='delete bulk targets; default is a dry-run plan')
|
|
154
|
+
args = parser.parse_args(argv)
|
|
155
|
+
|
|
156
|
+
prune, skipped, problems = plan(args.state_root, args.retention_days)
|
|
157
|
+
total = sum(freed for _, _, freed in prune)
|
|
158
|
+
for run_dir, targets, freed in prune:
|
|
159
|
+
names = ','.join(target.name for target in targets)
|
|
160
|
+
print(f'{run_dir} {freed} bytes [{names}]')
|
|
161
|
+
for path in skipped:
|
|
162
|
+
print('SKIPPED (live or recent): ' + str(path))
|
|
163
|
+
for problem in problems:
|
|
164
|
+
print('PROBLEM (untouched): ' + problem)
|
|
165
|
+
print(f'{len(prune)} runs prunable, {total} bytes; '
|
|
166
|
+
f'{len(skipped)} skipped; {len(problems)} problems')
|
|
167
|
+
if not args.execute:
|
|
168
|
+
print('dry-run; rerun with --execute to delete')
|
|
169
|
+
return 0
|
|
170
|
+
execute(args.state_root, prune)
|
|
171
|
+
print('executed; ledger at ' + str(Path(args.state_root) / 'engine' / 'dpv2' / LEDGER_NAME))
|
|
172
|
+
return 0
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
if __name__ == '__main__':
|
|
176
|
+
sys.exit(main())
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""One current supervisor, with each attempt's original engine/SDK binding.
|
|
2
|
+
|
|
3
|
+
Version locks exclude the historical worker units. Deployment stops only their
|
|
4
|
+
supervisor processes (KillMode=process); this module never signals a process
|
|
5
|
+
merely to take supervision over from an older release.
|
|
6
|
+
"""
|
|
7
|
+
import argparse
|
|
8
|
+
from contextlib import ExitStack
|
|
9
|
+
import fcntl
|
|
10
|
+
import hashlib
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
import re
|
|
14
|
+
import sqlite3
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
from .installer import ContractError, atomic, canonical, loads
|
|
18
|
+
from .worker import Worker
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class VersionWorker(Worker):
|
|
22
|
+
def _enforce_lease(self, row, process_row):
|
|
23
|
+
# Historical engines cannot renew the new lease. Retain their
|
|
24
|
+
# supervision policy while keeping cancellation/dead-process recovery.
|
|
25
|
+
if self.config.get('worker_heartbeat_contract') == 'dpv2-lease-1':
|
|
26
|
+
return super()._enforce_lease(row, process_row)
|
|
27
|
+
|
|
28
|
+
def reconcile(self, row):
|
|
29
|
+
# The dispatcher visits all registered versions. Only the matching
|
|
30
|
+
# version may apply its cancellation/lease policy to this attempt.
|
|
31
|
+
if row['version'] == self.version:
|
|
32
|
+
return super().reconcile(row)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def load_registry(path):
|
|
36
|
+
path = Path(path)
|
|
37
|
+
if path.is_symlink() or not path.is_file() or path.stat().st_size > 1048576:
|
|
38
|
+
raise ContractError('supervisor registry unavailable')
|
|
39
|
+
spec = loads(path.read_bytes())
|
|
40
|
+
if spec.get('schema') != 1 or spec.get('kind') != 'dpv2-supervisor-registry':
|
|
41
|
+
raise ContractError('supervisor registry identity required')
|
|
42
|
+
implementation = Path(__file__).with_name('worker.py')
|
|
43
|
+
if (hashlib.sha256(implementation.read_bytes()).hexdigest() != spec.get('worker_sha256')
|
|
44
|
+
or hashlib.sha256(Path(__file__).read_bytes()).hexdigest() != spec.get('supervisor_sha256')):
|
|
45
|
+
raise ContractError('supervisor implementation differs from approved registry')
|
|
46
|
+
state = Path(spec['state_root'])
|
|
47
|
+
if not state.is_absolute() or '..' in state.parts or state.is_symlink():
|
|
48
|
+
raise ContractError('real absolute supervisor state required')
|
|
49
|
+
if spec.get('health_file') != str(state / 'supervisor-health.json'):
|
|
50
|
+
raise ContractError('supervisor health path differs from state authority')
|
|
51
|
+
limits = spec.get('limits', {})
|
|
52
|
+
per, total = limits.get('per_workstation'), limits.get('global')
|
|
53
|
+
if (type(per) is not int or type(total) is not int or not 1 <= per <= total <= 1024):
|
|
54
|
+
raise ContractError('explicit workstation and global budgets required')
|
|
55
|
+
rows = spec.get('versions')
|
|
56
|
+
if not isinstance(rows, list) or not rows:
|
|
57
|
+
raise ContractError('explicit pinned worker configurations required')
|
|
58
|
+
configs = {}
|
|
59
|
+
for row in rows:
|
|
60
|
+
version = row.get('version', '')
|
|
61
|
+
if not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', version) or version in configs:
|
|
62
|
+
raise ContractError('unique exact worker version required')
|
|
63
|
+
config_path = Path(row['config'])
|
|
64
|
+
if (not config_path.is_absolute() or config_path.is_symlink()
|
|
65
|
+
or not config_path.is_file() or config_path.stat().st_size > 16777216):
|
|
66
|
+
raise ContractError('fixed worker configuration unavailable')
|
|
67
|
+
raw = config_path.read_bytes()
|
|
68
|
+
if hashlib.sha256(raw).hexdigest() != row.get('sha256'):
|
|
69
|
+
raise ContractError('worker configuration changed')
|
|
70
|
+
config = loads(raw)
|
|
71
|
+
if config.get('worker_heartbeat_contract') not in (None, 'dpv2-lease-1'):
|
|
72
|
+
raise ContractError('unknown worker heartbeat contract')
|
|
73
|
+
if config.get('worker_version') != version or Path(config['state_root']) != state:
|
|
74
|
+
raise ContractError('worker version/state differs from registry')
|
|
75
|
+
# Engine executable, SDK, runtime, transport and original configuration
|
|
76
|
+
# remain pinned. Only dispatcher admission budgets are centrally set.
|
|
77
|
+
configs[version] = dict(config, max_active_jobs=per, max_total_jobs=total)
|
|
78
|
+
return spec, configs
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Supervisor:
|
|
82
|
+
def __init__(self, path):
|
|
83
|
+
self.spec, configs = load_registry(path)
|
|
84
|
+
self.state = Path(self.spec['state_root'])
|
|
85
|
+
self.configs = configs
|
|
86
|
+
self.workers = {}
|
|
87
|
+
self.acquired = False
|
|
88
|
+
self.failures = 0
|
|
89
|
+
self.handles = ExitStack()
|
|
90
|
+
|
|
91
|
+
def acquire(self):
|
|
92
|
+
try:
|
|
93
|
+
# Taking every legacy version lock before processing any attempt
|
|
94
|
+
# fails closed if even one historical worker is still running.
|
|
95
|
+
for name in ['supervisor.lock'] + ['worker-' + v + '.lock' for v in sorted(self.configs)]:
|
|
96
|
+
stream = self.handles.enter_context((self.state / name).open('a'))
|
|
97
|
+
fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
98
|
+
self.workers = {version: VersionWorker(config) for version, config in self.configs.items()}
|
|
99
|
+
self.acquired = True
|
|
100
|
+
except BaseException:
|
|
101
|
+
self.close()
|
|
102
|
+
raise
|
|
103
|
+
return self
|
|
104
|
+
|
|
105
|
+
def close(self):
|
|
106
|
+
self.acquired = False
|
|
107
|
+
self.handles.close()
|
|
108
|
+
|
|
109
|
+
def tick(self):
|
|
110
|
+
if not self.acquired:
|
|
111
|
+
raise ContractError('supervisor version locks are not held')
|
|
112
|
+
with sqlite3.connect('file:' + str(self.state / 'jobs.sqlite3') + '?mode=ro', uri=True) as db:
|
|
113
|
+
active = {row[0] for row in db.execute(
|
|
114
|
+
"SELECT DISTINCT version FROM jobs WHERE state IN ('ACCEPTED','RUNNING','CANCELLING','UNKNOWN')")}
|
|
115
|
+
missing = active - set(self.workers)
|
|
116
|
+
if missing:
|
|
117
|
+
raise ContractError('active versions missing pinned supervisor configurations: ' + ','.join(sorted(missing)))
|
|
118
|
+
results, health = {}, {}
|
|
119
|
+
for version, worker in sorted(self.workers.items()):
|
|
120
|
+
started = time.time()
|
|
121
|
+
results[version] = worker.tick()
|
|
122
|
+
try:
|
|
123
|
+
observed = loads((self.state / 'worker-health.json').read_bytes())
|
|
124
|
+
except (OSError, ContractError, ValueError):
|
|
125
|
+
observed = {}
|
|
126
|
+
if (observed.get('pid') != os.getpid() or observed.get('worker_version') != version
|
|
127
|
+
or float(observed.get('updated') or 0) < started):
|
|
128
|
+
observed = {'last_tick_ok': False, 'last_error': 'version health not published by this supervisor'}
|
|
129
|
+
health[version] = observed
|
|
130
|
+
failed = [version for version, value in health.items() if value.get('last_tick_ok') is not True]
|
|
131
|
+
self.failures = self.failures + 1 if failed else 0
|
|
132
|
+
# Preserve every version's verdict. A healthy last version may not
|
|
133
|
+
# overwrite/mask an earlier version's failure in the shared file.
|
|
134
|
+
atomic(self.state / 'supervisor-health.json', canonical({
|
|
135
|
+
'schema': 1, 'kind': 'dpv2-supervisor-health', 'pid': os.getpid(),
|
|
136
|
+
'updated': time.time(), 'worker_sha256': self.spec['worker_sha256'],
|
|
137
|
+
'last_tick_ok': not failed, 'consecutive_failures': self.failures,
|
|
138
|
+
'last_error': 'unhealthy versions: ' + ','.join(failed) if failed else None,
|
|
139
|
+
'versions': health}))
|
|
140
|
+
return results
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def main(argv=None):
|
|
144
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
145
|
+
parser.add_argument('--registry', type=Path, required=True)
|
|
146
|
+
parser.add_argument('--once', action='store_true')
|
|
147
|
+
args = parser.parse_args(argv)
|
|
148
|
+
supervisor = Supervisor(args.registry).acquire()
|
|
149
|
+
try:
|
|
150
|
+
while True:
|
|
151
|
+
supervisor.tick()
|
|
152
|
+
if args.once:
|
|
153
|
+
return 0
|
|
154
|
+
time.sleep(1)
|
|
155
|
+
finally:
|
|
156
|
+
supervisor.close()
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
if __name__ == '__main__':
|
|
160
|
+
raise SystemExit(main())
|
|
@@ -17,6 +17,7 @@ from .installer import ContractError, atomic, canonical, loads
|
|
|
17
17
|
from .jobs import Conflict, Jobs
|
|
18
18
|
from .workstations import Workstations
|
|
19
19
|
from .executor import live
|
|
20
|
+
from .handoff import sync as sync_handoff
|
|
20
21
|
|
|
21
22
|
|
|
22
23
|
class Worker:
|
|
@@ -27,6 +28,7 @@ class Worker:
|
|
|
27
28
|
self.stations=Workstations(self.state/'workstations.sqlite3')
|
|
28
29
|
self.root=self.state/'executions';self.root.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
29
30
|
self.version=config['worker_version']
|
|
31
|
+
self._started=time.time();self._tick_failures=0
|
|
30
32
|
|
|
31
33
|
def path(self, row):
|
|
32
34
|
return self.root/row['id']/row['attempt']
|
|
@@ -44,12 +46,25 @@ class Worker:
|
|
|
44
46
|
# the attempt still reaches a terminal state (I01814).
|
|
45
47
|
pass
|
|
46
48
|
if process.is_file() and live(loads(process.read_bytes())):
|
|
49
|
+
record=loads(process.read_bytes())
|
|
47
50
|
if row['state']=='CANCELLING':
|
|
48
51
|
# Cooperative cancellation only fires between synchronous
|
|
49
52
|
# engine operations; a long EDA call never reaches those
|
|
50
53
|
# checks, so the supervisor escalates after the grace (I01769).
|
|
51
|
-
self._escalate_cancel(row,
|
|
54
|
+
self._escalate_cancel(row,record)
|
|
55
|
+
return
|
|
56
|
+
if row['state'] in ('RUNNING','UNKNOWN'):
|
|
57
|
+
# A live engine whose heartbeat lease expired is hung, not
|
|
58
|
+
# slow: the engine renews at every tool boundary and every
|
|
59
|
+
# progress checkpoint, so silence beyond the lease means the
|
|
60
|
+
# interpreter stopped making progress (I01900).
|
|
61
|
+
self._enforce_lease(row,record)
|
|
52
62
|
return
|
|
63
|
+
if process.is_file():
|
|
64
|
+
# The engine process is provably gone (live() already treats a
|
|
65
|
+
# zombie as dead): collect the child so no defunct entry lingers
|
|
66
|
+
# in the supervisor's process table misdirecting triage (I01903).
|
|
67
|
+
self._reap(loads(process.read_bytes()))
|
|
53
68
|
if row['state']=='CANCELLING':
|
|
54
69
|
# The engine died on its own while a cancel was pending. Cancel was
|
|
55
70
|
# explicitly requested and the dispatch source is verified gone, so
|
|
@@ -89,9 +104,17 @@ class Worker:
|
|
|
89
104
|
result=loads(raw)
|
|
90
105
|
if (result.get('job_id'),result.get('attempt'),result.get('version'))!=(row['id'],row['attempt'],row['version']):
|
|
91
106
|
raise ContractError('worker receipt identity mismatch')
|
|
107
|
+
# ``reaped`` marks the worker's own local-termination receipts, which
|
|
108
|
+
# carry ``remote_stop_confirmed=False`` but must still reach a terminal
|
|
109
|
+
# state (CANCELLED/FAILED) so the execution budget frees (I01912).
|
|
110
|
+
# Engine receipts never carry the field, so a confirmed remote stop
|
|
111
|
+
# keeps coming only from the engine (I01719 fail-closed).
|
|
92
112
|
self.jobs.complete(row['id'],row['attempt'],result['result'],stopped=result['remote_stop_confirmed'] is True,
|
|
93
|
-
checkpoint_schema=result.get('checkpoint_schema'))
|
|
113
|
+
checkpoint_schema=result.get('checkpoint_schema'),reaped=bool(result.get('reaped')))
|
|
94
114
|
atomic(observed,canonical({'sha256':digest}))
|
|
115
|
+
if (result['result'] or {}).get('ok') is True:
|
|
116
|
+
# I01928: a confirmed delivery is announced to other DPV2 plugins.
|
|
117
|
+
self.publish_handoff(only=(row['subject'],json.loads(row['request']).get('alias')))
|
|
95
118
|
return True
|
|
96
119
|
|
|
97
120
|
def _escalate_cancel(self,row,process_row):
|
|
@@ -99,11 +122,17 @@ class Worker:
|
|
|
99
122
|
|
|
100
123
|
``jobs.cancel`` timestamps the state change in ``updated``; the engine
|
|
101
124
|
keeps its cooperative window until then. SIGTERM, then SIGKILL the
|
|
102
|
-
whole session group
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
125
|
+
whole session group, and confirm death before recording the receipt:
|
|
126
|
+
the local execution tree stopping is the worker's own observation,
|
|
127
|
+
never an assumption. In the DPV2 topology the engine drives the
|
|
128
|
+
workstation EDA through elink, so this group kill proves only that the
|
|
129
|
+
local engine tree is gone — the remote EDA stop can never be observed
|
|
130
|
+
here, and the receipt records ``remote_stop_confirmed=False`` instead
|
|
131
|
+
of presenting a local kill as a confirmed remote stop (I01912). A
|
|
132
|
+
killed engine leaves no trustworthy checkpoint, so the receipt carries
|
|
133
|
+
``checkpoint_schema=None`` and this attempt cannot be resumed; the
|
|
134
|
+
``reaped`` mark keeps it terminal (CANCELLED) despite the unconfirmed
|
|
135
|
+
stop.
|
|
107
136
|
"""
|
|
108
137
|
grace=float(self.config.get('cancel_grace_seconds',30))
|
|
109
138
|
if time.time()<row['updated']+grace:return
|
|
@@ -119,12 +148,117 @@ class Worker:
|
|
|
119
148
|
if live(process_row):
|
|
120
149
|
# Termination unconfirmed: stay CANCELLING and retry on the next tick.
|
|
121
150
|
return
|
|
151
|
+
self._reap(process_row)
|
|
122
152
|
atomic(self.path(row)/'result.json',canonical({
|
|
123
153
|
'job_id':row['id'],'attempt':row['attempt'],'version':row['version'],
|
|
124
154
|
'result':{'ok':False,'job_status':'CANCELLED',
|
|
125
|
-
'error':{'code':'
|
|
126
|
-
'message':'Engine process group terminated after the cancellation grace; the
|
|
127
|
-
'remote_stop_confirmed':True,'checkpoint_schema':None}))
|
|
155
|
+
'error':{'code':'WORKER_CANCEL_TERMINATED_LOCAL',
|
|
156
|
+
'message':'Engine process group terminated locally after the cancellation grace; the remote workstation stop was never observed or confirmed'}},
|
|
157
|
+
'remote_stop_confirmed':False,'reaped':True,'checkpoint_schema':None}))
|
|
158
|
+
|
|
159
|
+
def _lease_budget(self,row):
|
|
160
|
+
"""Silence budget after which a live engine counts as hung (I01900).
|
|
161
|
+
|
|
162
|
+
The engine renews the lease at every tool boundary and progress
|
|
163
|
+
checkpoint, so the honest silent window is one remote call. The engine
|
|
164
|
+
reports its own per-call budget with each renewal; the worker never
|
|
165
|
+
enforces less than three times that, so a slow EDA call inside its own
|
|
166
|
+
request timeout can never be mis-read as a hang even when the operator
|
|
167
|
+
tightened ``lease_ttl_seconds``. Older attempts without renewals keep
|
|
168
|
+
the configured default.
|
|
169
|
+
"""
|
|
170
|
+
budget=float(self.config.get('lease_ttl_seconds',7200))
|
|
171
|
+
floor=float(row['lease_floor'] or 0)
|
|
172
|
+
return max(budget,3.0*floor) if floor>0 else budget
|
|
173
|
+
|
|
174
|
+
def _enforce_lease(self,row,process_row):
|
|
175
|
+
"""Force-reclaim a live engine past its heartbeat lease (I01900).
|
|
176
|
+
|
|
177
|
+
Extends the I01769 escalation to the lease-expiry case: log the
|
|
178
|
+
decision with its numbers, SIGTERM then SIGKILL the whole session
|
|
179
|
+
group, and confirm death before recording the receipt. The engine
|
|
180
|
+
drives the workstation EDA through elink, so the confirmed death is a
|
|
181
|
+
local fact only: the receipt records ``remote_stop_confirmed=False``
|
|
182
|
+
— a hung-engine kill never presents itself as a confirmed remote
|
|
183
|
+
stop (I01912) — and the ``reaped`` mark keeps the attempt terminal
|
|
184
|
+
(FAILED) so the execution budget frees. A killed engine leaves no
|
|
185
|
+
trustworthy checkpoint, so the receipt carries
|
|
186
|
+
``checkpoint_schema=None`` and this attempt cannot be resumed. If the
|
|
187
|
+
group survives the signals the attempt is left untouched and the next
|
|
188
|
+
tick retries with fresh evidence.
|
|
189
|
+
"""
|
|
190
|
+
if row['version']!=self.version:return
|
|
191
|
+
# The heartbeat column is authoritative (seeded at claim, renewed by
|
|
192
|
+
# the engine); only a pre-upgrade row without any lease history falls
|
|
193
|
+
# back to its state-change timestamp.
|
|
194
|
+
heartbeat=float(row['heartbeat'] or 0)
|
|
195
|
+
last=heartbeat if heartbeat>0 else float(row['updated'] or 0)
|
|
196
|
+
budget=self._lease_budget(row)
|
|
197
|
+
silence=time.time()-last
|
|
198
|
+
if silence<=budget:return
|
|
199
|
+
self.jobs.append(row['id'],row['attempt'],
|
|
200
|
+
{'event':'worker_lease_expired','silence':round(silence,3),
|
|
201
|
+
'budget':budget,'last_activity':last})
|
|
202
|
+
pid=process_row['pid']
|
|
203
|
+
for name,delay in (('SIGTERM',float(self.config.get('cancel_term_seconds',10))),
|
|
204
|
+
('SIGKILL',5.0)):
|
|
205
|
+
try:os.killpg(pid,getattr(signal,name))
|
|
206
|
+
except ProcessLookupError:break
|
|
207
|
+
deadline=time.time()+delay
|
|
208
|
+
while time.time()<deadline and live(process_row):time.sleep(0.2)
|
|
209
|
+
if not live(process_row):break
|
|
210
|
+
if live(process_row):
|
|
211
|
+
# Termination unconfirmed: stay RUNNING/UNKNOWN and retry on the
|
|
212
|
+
# next tick; the lease keeps expiring so the evidence accumulates.
|
|
213
|
+
return
|
|
214
|
+
self._reap(process_row)
|
|
215
|
+
atomic(self.path(row)/'result.json',canonical({
|
|
216
|
+
'job_id':row['id'],'attempt':row['attempt'],'version':row['version'],
|
|
217
|
+
'result':{'ok':False,'job_status':'FAILED',
|
|
218
|
+
'error':{'code':'WORKER_LEASE_TERMINATED_LOCAL',
|
|
219
|
+
'message':'Engine process group terminated locally after the heartbeat lease expired; the remote workstation stop was never observed or confirmed'}},
|
|
220
|
+
'remote_stop_confirmed':False,'reaped':True,'checkpoint_schema':None}))
|
|
221
|
+
|
|
222
|
+
def _reap(self,record):
|
|
223
|
+
"""waitpid a confirmed-dead engine child so no defunct survives (I01903).
|
|
224
|
+
|
|
225
|
+
An unreaped engine stays a zombie of this supervisor for its whole
|
|
226
|
+
lifetime, cluttering live-process triage. Only the parent can
|
|
227
|
+
collect: a restarted supervisor inherits no children, and ECHILD
|
|
228
|
+
there is the expected no-op. The verdict always comes from /proc,
|
|
229
|
+
never from waitpid.
|
|
230
|
+
"""
|
|
231
|
+
try:os.waitpid(record['pid'],os.WNOHANG)
|
|
232
|
+
except OSError:pass
|
|
233
|
+
|
|
234
|
+
def _publish_health(self,ok,error=None):
|
|
235
|
+
"""Best-effort tick health record for the e01 monitor (I01903).
|
|
236
|
+
|
|
237
|
+
Advisory observations only: the jobs database stays the state
|
|
238
|
+
authority and a monitor judges liveness from the ``updated`` age, so
|
|
239
|
+
a dead supervisor surfaces as a stale file, never as a stale OK.
|
|
240
|
+
"""
|
|
241
|
+
try:
|
|
242
|
+
atomic(self.state/'worker-health.json',canonical({
|
|
243
|
+
'schema':1,'worker_version':self.version,'pid':os.getpid(),
|
|
244
|
+
'started':self._started,'updated':time.time(),'last_tick_ok':bool(ok),
|
|
245
|
+
'consecutive_failures':self._tick_failures,
|
|
246
|
+
'last_error':None if error is None else '%s: %s'%(type(error).__name__,error)}))
|
|
247
|
+
except (OSError,ValueError):pass
|
|
248
|
+
|
|
249
|
+
def publish_handoff(self,only=None):
|
|
250
|
+
"""Announce confirmed PDK deliveries to other DPV2 plugins (I01928).
|
|
251
|
+
|
|
252
|
+
Advisory only: a failed announcement is recorded in
|
|
253
|
+
``handoff-status.json`` and never changes a job outcome.
|
|
254
|
+
"""
|
|
255
|
+
try:report=sync_handoff(self.config,self.jobs,only=only)
|
|
256
|
+
except Exception as error:
|
|
257
|
+
report={'enabled':True,'published':[],'unchanged':0,'failed':[{'error':'%s: %s'%(type(error).__name__,error)}]}
|
|
258
|
+
if report.get('enabled') and (report['published'] or report['failed']):
|
|
259
|
+
try:atomic(self.state/'handoff-status.json',canonical(dict(report,updated=time.time())))
|
|
260
|
+
except (OSError,ValueError):pass
|
|
261
|
+
return report
|
|
128
262
|
|
|
129
263
|
def launch(self, row):
|
|
130
264
|
directory=self.path(row)
|
|
@@ -153,6 +287,18 @@ class Worker:
|
|
|
153
287
|
self.jobs.append(row['id'],row['attempt'],{'event':'worker_started','plugin_version':self.version})
|
|
154
288
|
|
|
155
289
|
def tick(self):
|
|
290
|
+
try:result=self._tick()
|
|
291
|
+
except Exception as error:
|
|
292
|
+
# A failing tick must be observable, not a silent dead service:
|
|
293
|
+
# the supervisor keeps looping and the health file carries the
|
|
294
|
+
# failure for the e01 monitor (I01903).
|
|
295
|
+
self._tick_failures+=1
|
|
296
|
+
self._publish_health(ok=False,error=error)
|
|
297
|
+
return False
|
|
298
|
+
self._publish_health(ok=True)
|
|
299
|
+
return result
|
|
300
|
+
|
|
301
|
+
def _tick(self):
|
|
156
302
|
with self.jobs.connection() as db:
|
|
157
303
|
# Reconciliation spans every version: the execution budget counts
|
|
158
304
|
# RUNNING/CANCELLING/UNKNOWN across versions, so a supervisor may
|
|
@@ -164,7 +310,11 @@ class Worker:
|
|
|
164
310
|
for row in active:
|
|
165
311
|
try:self.reconcile(row)
|
|
166
312
|
except (ContractError,Conflict,ValueError):pass
|
|
167
|
-
|
|
313
|
+
# I01900 budgets: ``max_active_jobs`` caps one workstation so a single
|
|
314
|
+
# leaked station can no longer block every other workstation; the
|
|
315
|
+
# global fuse moves to ``max_total_jobs``.
|
|
316
|
+
row=self.jobs.claim(self.version,max_active=self.config.get('max_active_jobs',1),
|
|
317
|
+
max_total=self.config.get('max_total_jobs',16))
|
|
168
318
|
if row is not None:
|
|
169
319
|
try:self.launch(row)
|
|
170
320
|
except Exception:
|
|
@@ -178,6 +328,9 @@ class Worker:
|
|
|
178
328
|
def main(argv=None):
|
|
179
329
|
parser=argparse.ArgumentParser();parser.add_argument('--config',type=Path,required=True);parser.add_argument('--once',action='store_true')
|
|
180
330
|
args=parser.parse_args(argv);worker=Worker(loads(args.config.read_bytes()))
|
|
331
|
+
# I01928: a restart re-announces deliveries written before the handoff
|
|
332
|
+
# area existed or lost with it. The job database stays the authority.
|
|
333
|
+
worker.publish_handoff()
|
|
181
334
|
lock=worker.state/('worker-'+worker.version+'.lock')
|
|
182
335
|
with lock.open('a') as stream:
|
|
183
336
|
fcntl.flock(stream,fcntl.LOCK_EX|fcntl.LOCK_NB)
|