@tedbrain/vlink 0.0.0-dpv2.pdkadapt.plugin.0.1.1.r1

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.
@@ -0,0 +1,400 @@
1
+ """Install immutable npm components and atomically select a plugin release.
2
+
3
+ This module runs under the verified bootstrap Python, never the user's Python.
4
+ The public channel can move, but a running command captures one exact selection.
5
+ """
6
+ import base64
7
+ from contextlib import contextmanager
8
+ import hashlib
9
+ import http.client
10
+ import json
11
+ import os
12
+ from pathlib import Path, PurePosixPath
13
+ import platform
14
+ import re
15
+ import shutil
16
+ import ssl
17
+ import stat
18
+ import sys
19
+ import tarfile
20
+ import tempfile
21
+ import time
22
+ import urllib.error
23
+ import urllib.parse
24
+ import urllib.request
25
+
26
+ MAX_MANIFEST = 4 * 1024 * 1024
27
+ MAX_ARCHIVE = 1024 * 1024 * 1024
28
+ MAX_UNPACKED = 4 * MAX_ARCHIVE
29
+ ID = re.compile(r"[a-z][a-z0-9-]{0,63}\Z")
30
+ SHA = re.compile(r"[a-f0-9]{64}\Z")
31
+ TARGETS = {"linux-x64", "darwin-x64", "darwin-arm64", "win32-x64"}
32
+ VLINK_DPV2_VERSION = re.compile(r'0\.0\.0-dpv2\.pdkadapt\.(?:plugin|executor-linux-x64|(?:python|vlink|bootstrap)-(?:linux-x64|darwin-x64|darwin-arm64|win32-x64))\.[0-9]+\.[0-9]+\.[0-9]+(?:-[a-zA-Z0-9.-]+)?\.r[1-9][0-9]*')
33
+
34
+
35
+ def package_identity(package, version):
36
+ return isinstance(package,str) and isinstance(version,str) and bool(
37
+ re.fullmatch(r'@tedbrain/dpv2-[a-z0-9-]+',package) or
38
+ (package=='@tedbrain/vlink' and VLINK_DPV2_VERSION.fullmatch(version)))
39
+
40
+
41
+ class ContractError(ValueError):
42
+ pass
43
+
44
+
45
+ class Unavailable(OSError):
46
+ """Only transient retrieval failures permit a verified local fallback."""
47
+
48
+
49
+ def loads(data):
50
+ def unique(pairs):
51
+ result = {}
52
+ for key, value in pairs:
53
+ if key in result:
54
+ raise ContractError("duplicate JSON key")
55
+ result[key] = value
56
+ return result
57
+ try:
58
+ return json.loads(data, object_pairs_hook=unique,
59
+ parse_constant=lambda _: (_ for _ in ()).throw(ContractError("non-finite JSON")))
60
+ except (ValueError, UnicodeError) as error:
61
+ raise ContractError("invalid JSON document") from error
62
+
63
+
64
+ def canonical(value):
65
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
66
+
67
+
68
+ def digest(value):
69
+ return hashlib.sha256(canonical(value)).hexdigest()
70
+
71
+
72
+ def host_target():
73
+ system = {"Linux": "linux", "Darwin": "darwin", "Windows": "win32"}.get(platform.system())
74
+ arch = {"x86_64": "x64", "AMD64": "x64", "arm64": "arm64", "aarch64": "arm64"}.get(platform.machine())
75
+ target = f"{system}-{arch}"
76
+ if target not in TARGETS:
77
+ raise ContractError("unsupported client target")
78
+ if system == "linux" and platform.libc_ver()[0] != "glibc":
79
+ raise ContractError("Linux glibc runtime required")
80
+ return target
81
+
82
+
83
+ def relative(value):
84
+ if not isinstance(value, str) or not value or "\\" in value or ":" in value or "\x00" in value:
85
+ raise ContractError("invalid relative path")
86
+ path = PurePosixPath(value)
87
+ if path.is_absolute() or any(p in ("", ".", "..") for p in value.split("/")):
88
+ raise ContractError("unsafe relative path")
89
+ # A single portable inventory must not alias device names or trim on Windows.
90
+ reserved = {'CON', 'PRN', 'AUX', 'NUL', *('COM'+str(n) for n in range(1,10)),
91
+ *('LPT'+str(n) for n in range(1,10))}
92
+ if any(part.endswith((' ', '.')) or part.split('.')[0].upper() in reserved
93
+ or any(ord(char)<32 or char in '<>"|?*' for char in part)
94
+ for part in value.split('/')):
95
+ raise ContractError("nonportable relative path")
96
+ return value
97
+
98
+
99
+ def endpoint(value, *, registry=False, local_registry=None):
100
+ if not isinstance(value, str):
101
+ raise ContractError("URL must be a string")
102
+ parsed = urllib.parse.urlsplit(value)
103
+ if parsed.username or parsed.password or parsed.fragment or not parsed.hostname:
104
+ raise ContractError("URL contains credentials/fragment or lacks a host")
105
+ origin = f"{parsed.scheme}://{parsed.netloc}"
106
+ if registry:
107
+ if local_registry:
108
+ local = urllib.parse.urlsplit(local_registry)
109
+ if local.scheme != "http" or local.hostname != "127.0.0.1" or not local.port:
110
+ raise ContractError("explicit numeric loopback registry required")
111
+ if origin != f"http://{local.netloc}":
112
+ raise ContractError("archive escapes test registry")
113
+ elif parsed.scheme != "https" or parsed.hostname != "registry.npmjs.org" or parsed.port not in (None, 443):
114
+ raise ContractError("client archives must come directly from npm registry")
115
+ if parsed.query:
116
+ raise ContractError("npm archive URL must be immutable and query-free")
117
+ elif parsed.scheme != "https" and not (local_registry and parsed.scheme == "http" and parsed.hostname == "127.0.0.1"):
118
+ raise ContractError("HTTPS metadata required")
119
+ return value
120
+
121
+
122
+ class NoRedirect(urllib.request.HTTPRedirectHandler):
123
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
124
+ return None
125
+
126
+
127
+ def tls_context():
128
+ # Standalone interpreters cannot rely on their producer's absolute CA
129
+ # path. The CA inventory travels inside the verified Python component.
130
+ executable=Path(sys.executable).resolve()
131
+ for root in (executable.parent,executable.parent.parent):
132
+ bundle=root/'ssl/cacert.pem'
133
+ if bundle.is_file():return ssl.create_default_context(cafile=str(bundle))
134
+ return ssl.create_default_context()
135
+
136
+
137
+ def retrieve(url, target, limit, *, local_registry=None, archive=False):
138
+ endpoint(url, registry=archive, local_registry=local_registry)
139
+ opener = urllib.request.build_opener(NoRedirect(),urllib.request.HTTPSHandler(context=tls_context()))
140
+ try:
141
+ with opener.open(url, timeout=30) as response:
142
+ if response.status != 200:
143
+ raise ContractError("unexpected download response")
144
+ length = response.headers.get("Content-Length")
145
+ if length is not None and int(length) > limit:
146
+ raise ContractError("download exceeds declared limit")
147
+ count = 0
148
+ while True:
149
+ chunk = response.read(min(65536, limit + 1 - count))
150
+ if not chunk:
151
+ break
152
+ count += len(chunk)
153
+ if count > limit:
154
+ raise ContractError("download exceeds declared limit")
155
+ target.write(chunk)
156
+ if length is not None and count != int(length):
157
+ raise Unavailable("download was interrupted")
158
+ except urllib.error.HTTPError as error:
159
+ if error.code in (408, 429, 500, 502, 503, 504):
160
+ raise Unavailable("download temporarily unavailable") from None
161
+ raise ContractError("download rejected; no cache downgrade") from None
162
+ except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.IncompleteRead) as error:
163
+ if isinstance(getattr(error, 'reason', None), ssl.SSLError):
164
+ raise ContractError('TLS verification failed; no cache downgrade') from None
165
+ raise Unavailable("download temporarily unavailable") from None
166
+
167
+
168
+ def manifest(value, plugin, target, local_registry=None):
169
+ if not isinstance(value, dict) or set(value) != {"schema", "plugin", "version", "target", "components", "entrypoints"}:
170
+ raise ContractError("strict plugin release schema required")
171
+ if value["schema"] != 1 or value["plugin"] != plugin or not ID.fullmatch(plugin) or value["target"] != target or target not in TARGETS:
172
+ raise ContractError("plugin release identity/target mismatch")
173
+ if not isinstance(value["version"], str) or not re.fullmatch(r"\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?", value["version"]):
174
+ raise ContractError("plugin semver required")
175
+ components = value["components"]
176
+ if not isinstance(components, dict) or not 1 <= len(components) <= 16:
177
+ raise ContractError("bounded component set required")
178
+ for name, item in components.items():
179
+ if not ID.fullmatch(name) or not isinstance(item, dict) or set(item) != {"version", "package", "url", "sha256", "integrity", "size", "files"}:
180
+ raise ContractError("invalid component descriptor")
181
+ if not isinstance(item["version"], str) or not re.fullmatch(r"\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?", item["version"]):
182
+ raise ContractError("component semver required")
183
+ if not package_identity(item["package"],item["version"]):
184
+ raise ContractError("DPV2 npm package identity required")
185
+ endpoint(item["url"], registry=True, local_registry=local_registry)
186
+ if not isinstance(item["sha256"], str) or not SHA.fullmatch(item["sha256"]) or type(item["size"]) is not int or not 0 < item["size"] <= MAX_ARCHIVE:
187
+ raise ContractError("bounded archive identity required")
188
+ try:
189
+ if not isinstance(item['integrity'], str):
190
+ raise ValueError()
191
+ sri = base64.b64decode(item["integrity"][7:], validate=True)
192
+ if not item["integrity"].startswith("sha512-") or len(sri) != 64:
193
+ raise ValueError()
194
+ except (ValueError, TypeError):
195
+ raise ContractError("npm SHA512 integrity required") from None
196
+ files = item["files"]
197
+ if not isinstance(files, dict) or not 1 <= len(files) <= 100000 or "package.json" not in files:
198
+ raise ContractError("complete npm file inventory required")
199
+ total = 0
200
+ folded = set()
201
+ for path, expected in files.items():
202
+ relative(path)
203
+ if path.casefold() in folded:
204
+ raise ContractError("case-colliding archive paths")
205
+ folded.add(path.casefold())
206
+ if not isinstance(expected, dict) or set(expected) != {"sha256", "size", "executable"} or not isinstance(expected['sha256'], str) or not SHA.fullmatch(expected["sha256"]) or type(expected["size"]) is not int or expected["size"] < 0 or type(expected["executable"]) is not bool:
207
+ raise ContractError("invalid file identity")
208
+ total += expected["size"]
209
+ if total > MAX_UNPACKED:
210
+ raise ContractError("component unpacked size exceeds limit")
211
+ entries = value["entrypoints"]
212
+ if not isinstance(entries, dict) or set(entries) != {"cli", "vlink", "python"}:
213
+ raise ContractError("cli, vlink and python entrypoints required")
214
+ for entry in entries.values():
215
+ if not isinstance(entry, dict) or set(entry) != {"component", "path"} or not isinstance(entry['component'], str) or entry["component"] not in components or relative(entry["path"]) not in components[entry["component"]]["files"]:
216
+ raise ContractError("entrypoint not present in release files")
217
+ return value
218
+
219
+
220
+ @contextmanager
221
+ def locked(root):
222
+ root.mkdir(parents=True, exist_ok=True, mode=0o700)
223
+ lock = root / ".install.lock"
224
+ if lock.is_symlink():
225
+ raise ContractError("symlink install lock refused")
226
+ with lock.open("a+b") as stream:
227
+ if os.name == "nt":
228
+ import msvcrt
229
+ if stream.tell() == 0:
230
+ stream.write(b"0"); stream.flush()
231
+ stream.seek(0)
232
+ deadline = time.monotonic() + 60
233
+ while True:
234
+ try:
235
+ msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
236
+ break
237
+ except OSError:
238
+ if time.monotonic() >= deadline:
239
+ raise Unavailable("installer busy") from None
240
+ time.sleep(0.1)
241
+ else:
242
+ import fcntl
243
+ fcntl.flock(stream, fcntl.LOCK_EX)
244
+ try:
245
+ yield
246
+ finally:
247
+ stream.seek(0)
248
+ if os.name == "nt":
249
+ msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
250
+ else:
251
+ fcntl.flock(stream, fcntl.LOCK_UN)
252
+
253
+
254
+ def atomic(path, data):
255
+ descriptor, temp = tempfile.mkstemp(prefix=".new-", dir=path.parent)
256
+ try:
257
+ with os.fdopen(descriptor, "wb") as stream:
258
+ stream.write(data); stream.flush(); os.fsync(stream.fileno())
259
+ os.replace(temp, path)
260
+ finally:
261
+ if os.path.exists(temp):
262
+ os.unlink(temp)
263
+
264
+
265
+ def hash_file(path, algorithm="sha256"):
266
+ value = hashlib.new(algorithm)
267
+ with path.open("rb") as stream:
268
+ for chunk in iter(lambda: stream.read(65536), b""):
269
+ value.update(chunk)
270
+ return value.digest()
271
+
272
+
273
+ def verify_tree(directory, component):
274
+ if directory.is_symlink() or not directory.is_dir():
275
+ raise ContractError("immutable component unavailable")
276
+ observed = set()
277
+ for path in directory.rglob("*"):
278
+ if path.is_symlink():
279
+ raise ContractError("symlink inside installed component")
280
+ if path.is_dir():
281
+ continue
282
+ key = path.relative_to(directory).as_posix()
283
+ expected = component["files"].get(key)
284
+ if not expected or not path.is_file() or path.stat().st_size != expected["size"] or hash_file(path).hex() != expected["sha256"]:
285
+ raise ContractError("installed component changed")
286
+ if os.name != "nt" and bool(path.stat().st_mode & stat.S_IXUSR) != expected["executable"]:
287
+ raise ContractError("installed component mode changed")
288
+ observed.add(key)
289
+ if observed != set(component["files"]):
290
+ raise ContractError("installed component incomplete")
291
+ package = loads((directory / "package.json").read_bytes())
292
+ if package.get("name") != component["package"] or package.get("version") != component["version"]:
293
+ raise ContractError("npm package identity mismatch")
294
+
295
+
296
+ class Installer:
297
+ def __init__(self, root, plugin="pdkadapt", target=None, local_registry=None):
298
+ self.root = Path(root).absolute()
299
+ if self.root.is_symlink():
300
+ raise ContractError("plugin root must not be a symlink")
301
+ self.plugin = plugin
302
+ self.target = target or host_target()
303
+ self.local_registry = local_registry
304
+
305
+ def component_path(self, component):
306
+ return self.root / "components" / component["sha256"]
307
+
308
+ def install_component(self, component):
309
+ destination = self.component_path(component)
310
+ if destination.exists() or destination.is_symlink():
311
+ verify_tree(destination, component)
312
+ return False
313
+ parent = self.root / "components"
314
+ parent.mkdir(exist_ok=True)
315
+ if parent.is_symlink():
316
+ raise ContractError("component directory symlink refused")
317
+ with tempfile.TemporaryDirectory(prefix=".stage-", dir=parent) as temp:
318
+ stage = Path(temp)
319
+ archive = stage / "archive.tgz"
320
+ with archive.open("wb") as stream:
321
+ retrieve(component["url"], stream, component["size"], local_registry=self.local_registry, archive=True)
322
+ if archive.stat().st_size != component["size"] or hash_file(archive).hex() != component["sha256"] or "sha512-" + base64.b64encode(hash_file(archive, "sha512")).decode() != component["integrity"]:
323
+ raise ContractError("npm archive integrity mismatch")
324
+ unpacked = stage / "unpacked"
325
+ unpacked.mkdir()
326
+ seen = set()
327
+ with tarfile.open(archive, "r:gz") as tar:
328
+ for member in tar:
329
+ name = member.name.rstrip("/")
330
+ if member.isdir() and name == "package":
331
+ continue
332
+ if not name.startswith("package/"):
333
+ raise ContractError("npm archive must have package/ root")
334
+ path = relative(name[len("package/"):])
335
+ if member.isdir():
336
+ continue
337
+ expected = component["files"].get(path)
338
+ if not member.isfile() or path in seen or not expected or member.size != expected["size"]:
339
+ raise ContractError("archive file inventory mismatch")
340
+ seen.add(path)
341
+ output = unpacked / path
342
+ output.parent.mkdir(parents=True, exist_ok=True)
343
+ with tar.extractfile(member) as source, output.open("xb") as target:
344
+ shutil.copyfileobj(source, target, 65536)
345
+ output.chmod(0o700 if expected["executable"] else 0o600)
346
+ verify_tree(unpacked, component)
347
+ os.replace(unpacked, destination)
348
+ return True
349
+
350
+ def read_meta(self):
351
+ path = self.root / "meta.json"
352
+ if path.is_symlink() or not path.is_file() or path.stat().st_size > MAX_MANIFEST:
353
+ raise ContractError("no complete locally verified plugin installation")
354
+ meta = loads(path.read_bytes())
355
+ if set(meta) != {"schema", "selection_sha256", "release"} or meta["schema"] != 1:
356
+ raise ContractError("invalid local plugin metadata")
357
+ release = manifest(meta["release"], self.plugin, self.target, self.local_registry)
358
+ if digest(release) != meta["selection_sha256"]:
359
+ raise ContractError("local plugin selection changed")
360
+ return meta
361
+
362
+ def cached(self):
363
+ meta = self.read_meta()
364
+ for component in meta["release"]["components"].values():
365
+ verify_tree(self.component_path(component), component)
366
+ return meta
367
+
368
+ def sync(self, version_url):
369
+ import io
370
+ with locked(self.root):
371
+ body = io.BytesIO()
372
+ try:
373
+ retrieve(version_url, body, MAX_MANIFEST, local_registry=self.local_registry)
374
+ except Unavailable:
375
+ return {"meta": self.cached(), "downloaded": [], "warning": "UPDATE_UNAVAILABLE_USING_VERIFIED_CACHE"}
376
+ release = manifest(loads(body.getvalue()), self.plugin, self.target, self.local_registry)
377
+ previous = None
378
+ if (self.root / "meta.json").exists():
379
+ previous = self.read_meta()
380
+ if previous:
381
+ # A component update may change the graph independently, but the
382
+ # same component version must never be silently republished.
383
+ for name, component in release["components"].items():
384
+ old = previous["release"]["components"].get(name)
385
+ if old and old["version"] == component["version"] and old != component:
386
+ raise ContractError("same component version changed identity")
387
+ downloaded = []
388
+ for name, component in release["components"].items():
389
+ if self.install_component(component):
390
+ downloaded.append(name)
391
+ meta = {"schema": 1, "selection_sha256": digest(release), "release": release}
392
+ # Never replace or remove an old component: in-flight processes keep it.
393
+ if previous != meta:
394
+ atomic(self.root / "meta.json", canonical(meta))
395
+ return {"meta": meta, "downloaded": downloaded, "warning": None}
396
+
397
+ def entries(self, meta):
398
+ release = meta["release"]
399
+ return {name: self.component_path(release["components"][entry["component"]]) / entry["path"]
400
+ for name, entry in release["entrypoints"].items()}
@@ -0,0 +1,199 @@
1
+ """Durable DPV2 job state; API restarts never replay an execution attempt."""
2
+ from contextlib import contextmanager
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ import re
7
+ import secrets
8
+ import sqlite3
9
+ import time
10
+ from .installer import canonical, ContractError
11
+
12
+
13
+ class Conflict(ContractError):
14
+ pass
15
+
16
+
17
+ class NotFound(ContractError):
18
+ pass
19
+
20
+
21
+ class Jobs:
22
+ def __init__(self, path):
23
+ self.path = Path(path)
24
+ self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
25
+ if self.path.is_symlink():
26
+ raise ContractError('job database cannot be a symlink')
27
+ with self.connection() as db:
28
+ db.executescript('''
29
+ CREATE TABLE IF NOT EXISTS jobs (
30
+ id TEXT PRIMARY KEY, subject TEXT NOT NULL, workstation TEXT NOT NULL,
31
+ request TEXT NOT NULL, state TEXT NOT NULL, attempt TEXT NOT NULL,
32
+ version TEXT NOT NULL, result TEXT, checkpoint_schema TEXT, stopped INTEGER NOT NULL DEFAULT 0,
33
+ created REAL NOT NULL, updated REAL NOT NULL);
34
+ CREATE TABLE IF NOT EXISTS attempts (
35
+ id TEXT PRIMARY KEY, job TEXT NOT NULL, version TEXT NOT NULL,
36
+ request TEXT NOT NULL, state TEXT NOT NULL, result TEXT, created REAL NOT NULL);
37
+ CREATE TABLE IF NOT EXISTS requests (
38
+ subject TEXT NOT NULL, key TEXT NOT NULL, digest TEXT NOT NULL,
39
+ job TEXT NOT NULL, attempt TEXT NOT NULL, PRIMARY KEY(subject,key));
40
+ CREATE TABLE IF NOT EXISTS events (
41
+ seq INTEGER PRIMARY KEY AUTOINCREMENT, job TEXT NOT NULL, attempt TEXT NOT NULL,
42
+ body TEXT NOT NULL, created REAL NOT NULL);
43
+ CREATE INDEX IF NOT EXISTS events_job ON events(job,seq);
44
+ ''')
45
+ self.path.chmod(0o600)
46
+
47
+ @contextmanager
48
+ def connection(self):
49
+ db=sqlite3.connect(self.path,timeout=30)
50
+ db.row_factory=sqlite3.Row
51
+ db.execute('PRAGMA journal_mode=WAL')
52
+ db.execute('PRAGMA synchronous=FULL')
53
+ try:
54
+ yield db
55
+ db.commit()
56
+ except BaseException:
57
+ db.rollback();raise
58
+ finally:db.close()
59
+
60
+ @staticmethod
61
+ def event(db,job,attempt,body):
62
+ encoded=canonical(body).decode()
63
+ if len(encoded)>65536:raise ContractError('event too large')
64
+ db.execute('INSERT INTO events(job,attempt,body,created) VALUES(?,?,?,?)',(job,attempt,encoded,time.time()))
65
+
66
+ @staticmethod
67
+ def public(row):
68
+ return {'job_id':row['id'],'run_id':row['id'],'workstation_id':row['workstation'],
69
+ 'job_status':row['state'],'attempt':row['attempt'],'plugin_version':row['version'],
70
+ 'result':json.loads(row['result']) if row['result'] else None,
71
+ 'remote_stop_confirmed':bool(row['stopped'])}
72
+
73
+ def get(self,subject,job):
74
+ with self.connection() as db:
75
+ row=db.execute('SELECT * FROM jobs WHERE id=? AND subject=?',(job,subject)).fetchone()
76
+ if row is None:raise NotFound('job not found')
77
+ value=self.public(row)
78
+ value['attempts']=[{'id':a['id'],'version':a['version'],'state':a['state']} for a in db.execute('SELECT * FROM attempts WHERE job=? ORDER BY created',(job,))]
79
+ return value
80
+
81
+ def submit(self,subject,workstation,request,key,version,*,resume=None,compatible=()):
82
+ if not re.fullmatch(r'[A-Za-z0-9._-]{1,128}',key or ''):
83
+ raise ContractError('Idempotency-Key required')
84
+ fingerprint=hashlib.sha256(canonical({'workstation':workstation,'request':request,'resume':resume})).hexdigest()
85
+ with self.connection() as db:
86
+ db.execute('BEGIN IMMEDIATE')
87
+ known=db.execute('SELECT * FROM requests WHERE subject=? AND key=?',(subject,key)).fetchone()
88
+ if known:
89
+ if known['digest']!=fingerprint:raise Conflict('idempotency key was used for a different request')
90
+ row=db.execute('SELECT * FROM jobs WHERE id=?',(known['job'],)).fetchone()
91
+ result=self.public(row);result.update(replayed=True,submission_attempt=known['attempt'])
92
+ return result
93
+ if resume:
94
+ old=db.execute('SELECT * FROM jobs WHERE id=? AND subject=?',(resume,subject)).fetchone()
95
+ if old is None:raise NotFound('job not found')
96
+ if old['state'] not in ('FAILED','CANCELLED','WAITING_INPUT') or not old['stopped']:
97
+ raise Conflict('previous execution is not confirmed stopped')
98
+ if old['checkpoint_schema'] not in compatible:
99
+ raise Conflict('checkpoint is incompatible with selected plugin version')
100
+ if old['workstation']!=workstation:raise Conflict('resume cannot silently change workstation')
101
+ previous=json.loads(old['request'])
102
+ for field in ('vendor_dir','alias','foundry','arch','cells','mode'):
103
+ if previous.get(field,'')!=request.get(field,''):
104
+ raise Conflict('resume cannot change original '+field)
105
+ job=resume
106
+ else:job=secrets.token_hex(16)
107
+ attempt=secrets.token_hex(16);now=time.time();encoded=canonical(request).decode()
108
+ db.execute('INSERT INTO attempts(id,job,version,request,state,created) VALUES(?,?,?,?,?,?)',
109
+ (attempt,job,version,encoded,'ACCEPTED',now))
110
+ if resume:
111
+ db.execute('UPDATE jobs SET request=?,state=?,attempt=?,version=?,result=NULL,stopped=0,updated=? WHERE id=?',
112
+ (encoded,'ACCEPTED',attempt,version,now,job))
113
+ else:
114
+ db.execute('INSERT INTO jobs(id,subject,workstation,request,state,attempt,version,created,updated) VALUES(?,?,?,?,?,?,?,?,?)',
115
+ (job,subject,workstation,encoded,'ACCEPTED',attempt,version,now,now))
116
+ db.execute('INSERT INTO requests VALUES(?,?,?,?,?)',(subject,key,fingerprint,job,attempt))
117
+ self.event(db,job,attempt,{'event':'accepted','plugin_version':version})
118
+ return dict(self.public(db.execute('SELECT * FROM jobs WHERE id=?',(job,)).fetchone()),replayed=False,submission_attempt=attempt)
119
+
120
+ def claim(self,version,*,max_active=2):
121
+ if type(max_active) is not int or not 1<=max_active<=16:
122
+ raise ContractError('bounded worker concurrency required')
123
+ with self.connection() as db:
124
+ 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
+ active=db.execute("SELECT COUNT(*) FROM jobs WHERE state IN ('RUNNING','CANCELLING','UNKNOWN')").fetchone()[0]
128
+ if active>=max_active:return None
129
+ row=db.execute("SELECT * FROM jobs AS queued WHERE state=? AND version=? AND NOT EXISTS (SELECT 1 FROM jobs AS active WHERE active.workstation=queued.workstation AND active.state IN ('RUNNING','CANCELLING','UNKNOWN')) ORDER BY created LIMIT 1",('ACCEPTED',version)).fetchone()
130
+ if row is None:return None
131
+ db.execute('UPDATE jobs SET state=?,updated=? WHERE id=?',('RUNNING',time.time(),row['id']))
132
+ db.execute('UPDATE attempts SET state=? WHERE id=?',('RUNNING',row['attempt']))
133
+ self.event(db,row['id'],row['attempt'],{'event':'running'})
134
+ return dict(row)
135
+
136
+ def cancel(self,subject,job,key):
137
+ if not re.fullmatch(r'[A-Za-z0-9._-]{1,128}',key or ''):
138
+ raise ContractError('Idempotency-Key required')
139
+ fingerprint=hashlib.sha256(canonical({'action':'cancel','job':job})).hexdigest()
140
+ with self.connection() as db:
141
+ db.execute('BEGIN IMMEDIATE')
142
+ row=db.execute('SELECT * FROM jobs WHERE id=? AND subject=?',(job,subject)).fetchone()
143
+ if row is None:raise NotFound('job not found')
144
+ known=db.execute('SELECT * FROM requests WHERE subject=? AND key=?',(subject,key)).fetchone()
145
+ if known:
146
+ if known['digest']!=fingerprint:raise Conflict('idempotency key was used for a different request')
147
+ # A delayed cancellation retry must never cancel a newer resume attempt.
148
+ return dict(self.public(row),replayed=True,submission_attempt=known['attempt'])
149
+ db.execute('INSERT INTO requests VALUES(?,?,?,?,?)',(subject,key,fingerprint,job,row['attempt']))
150
+ if row['state'] not in ('ACCEPTED','RUNNING','CANCELLING','UNKNOWN'):
151
+ return self.public(row)
152
+ # An unclaimed queued attempt has no remote execution to stop.
153
+ stopped=row['state']=='ACCEPTED';state='CANCELLED' if stopped else 'CANCELLING'
154
+ db.execute('UPDATE jobs SET state=?,stopped=?,updated=? WHERE id=?',(state,int(stopped),time.time(),job))
155
+ db.execute('UPDATE attempts SET state=? WHERE id=?',(state,row['attempt']))
156
+ self.event(db,job,row['attempt'],{'event':'cancel_requested','remote_stop_confirmed':stopped})
157
+ return self.public(db.execute('SELECT * FROM jobs WHERE id=?',(job,)).fetchone())
158
+
159
+ def append(self,job,attempt,event):
160
+ with self.connection() as db:
161
+ db.execute('BEGIN IMMEDIATE')
162
+ current=db.execute('SELECT attempt FROM jobs WHERE id=?',(job,)).fetchone()
163
+ if current is None or current['attempt']!=attempt:raise Conflict('stale attempt')
164
+ self.event(db,job,attempt,event)
165
+
166
+ def complete(self,job,attempt,result,*,stopped,checkpoint_schema=None):
167
+ # Process exit alone cannot establish that remote EDA stopped.
168
+ delivery=result.get('delivery')
169
+ success=(result.get('ok') is True and result.get('job_status')=='COMPLETED'
170
+ and isinstance(delivery,dict) and delivery.get('status')=='INSTALLED'
171
+ and type(delivery.get('files')) is int and delivery['files']>0
172
+ and type(delivery.get('total_size')) is int and delivery['total_size']>0
173
+ and isinstance(delivery.get('tree_sha256'),str)
174
+ and re.fullmatch('[a-f0-9]{64}',delivery['tree_sha256']) is not None)
175
+ with self.connection() as db:
176
+ db.execute('BEGIN IMMEDIATE')
177
+ row=db.execute('SELECT * FROM jobs WHERE id=?',(job,)).fetchone()
178
+ if row is None or row['attempt']!=attempt or row['state'] not in ('RUNNING','CANCELLING','UNKNOWN'):
179
+ raise Conflict('stale or terminal execution attempt')
180
+ state=('SUCCEEDED' if success else 'CANCELLED' if row['state']=='CANCELLING' else
181
+ 'WAITING_INPUT' if result.get('job_status')=='WAITING_FOR_DECISION' else 'FAILED') if stopped else 'UNKNOWN'
182
+ encoded=canonical(result).decode()
183
+ db.execute('UPDATE jobs SET state=?,result=?,stopped=?,checkpoint_schema=?,updated=? WHERE id=?',
184
+ (state,encoded,int(stopped),checkpoint_schema,time.time(),job))
185
+ db.execute('UPDATE attempts SET state=?,result=? WHERE id=?',(state,encoded,attempt))
186
+ self.event(db,job,attempt,{'event':'terminal','job_status':state,'remote_stop_confirmed':bool(stopped)})
187
+
188
+ def events(self,subject,job,after=0):
189
+ self.get(subject,job)
190
+ if type(after) is not int or after<0:raise ContractError('invalid event cursor')
191
+ with self.connection() as db:
192
+ return [{'seq':r['seq'],'attempt':r['attempt'],'event':json.loads(r['body'])} for r in
193
+ db.execute('SELECT * FROM events WHERE job=? AND seq>? ORDER BY seq LIMIT 200',(job,after))]
194
+
195
+ def lookup(self,subject,key):
196
+ with self.connection() as db:
197
+ row=db.execute('SELECT job,attempt FROM requests WHERE subject=? AND key=?',(subject,key)).fetchone()
198
+ if row is None:raise NotFound('request not found')
199
+ return dict(self.get(subject,row['job']),submission_attempt=row['attempt'])