@tedbrain/vlink 0.0.0-dpv2.pdkadapt.plugin.0.1.7.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/handoff.py +188 -0
- package/tedbrain_plugin_runtime/rungc.py +176 -0
- package/tedbrain_plugin_runtime/worker.py +21 -0
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"}
|
|
@@ -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
|
|
@@ -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())
|
|
@@ -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:
|
|
@@ -111,6 +112,9 @@ class Worker:
|
|
|
111
112
|
self.jobs.complete(row['id'],row['attempt'],result['result'],stopped=result['remote_stop_confirmed'] is True,
|
|
112
113
|
checkpoint_schema=result.get('checkpoint_schema'),reaped=bool(result.get('reaped')))
|
|
113
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')))
|
|
114
118
|
return True
|
|
115
119
|
|
|
116
120
|
def _escalate_cancel(self,row,process_row):
|
|
@@ -242,6 +246,20 @@ class Worker:
|
|
|
242
246
|
'last_error':None if error is None else '%s: %s'%(type(error).__name__,error)}))
|
|
243
247
|
except (OSError,ValueError):pass
|
|
244
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
|
|
262
|
+
|
|
245
263
|
def launch(self, row):
|
|
246
264
|
directory=self.path(row)
|
|
247
265
|
# Exclusive creation is a second guard after the DB claim. Existing
|
|
@@ -310,6 +328,9 @@ class Worker:
|
|
|
310
328
|
def main(argv=None):
|
|
311
329
|
parser=argparse.ArgumentParser();parser.add_argument('--config',type=Path,required=True);parser.add_argument('--once',action='store_true')
|
|
312
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()
|
|
313
334
|
lock=worker.state/('worker-'+worker.version+'.lock')
|
|
314
335
|
with lock.open('a') as stream:
|
|
315
336
|
fcntl.flock(stream,fcntl.LOCK_EX|fcntl.LOCK_NB)
|