@tedbrain/vlink 0.0.0-dpv2.pdkadapt.plugin.0.1.5.r2 → 0.0.0-dpv2.pdkadapt.plugin.0.1.7.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/package.json CHANGED
@@ -1 +1 @@
1
- {"name": "@tedbrain/vlink", "private": false, "version": "0.0.0-dpv2.pdkadapt.plugin.0.1.5.r2"}
1
+ {"name": "@tedbrain/vlink", "private": false, "version": "0.0.0-dpv2.pdkadapt.plugin.0.1.7.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:
@@ -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=2):
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>=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()
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
- db.execute('UPDATE jobs SET state=?,updated=? WHERE id=?',('RUNNING',time.time(),row['id']))
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,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())
@@ -27,6 +27,7 @@ class Worker:
27
27
  self.stations=Workstations(self.state/'workstations.sqlite3')
28
28
  self.root=self.state/'executions';self.root.mkdir(parents=True,exist_ok=True,mode=0o700)
29
29
  self.version=config['worker_version']
30
+ self._started=time.time();self._tick_failures=0
30
31
 
31
32
  def path(self, row):
32
33
  return self.root/row['id']/row['attempt']
@@ -44,12 +45,25 @@ class Worker:
44
45
  # the attempt still reaches a terminal state (I01814).
45
46
  pass
46
47
  if process.is_file() and live(loads(process.read_bytes())):
48
+ record=loads(process.read_bytes())
47
49
  if row['state']=='CANCELLING':
48
50
  # Cooperative cancellation only fires between synchronous
49
51
  # engine operations; a long EDA call never reaches those
50
52
  # checks, so the supervisor escalates after the grace (I01769).
51
- self._escalate_cancel(row,loads(process.read_bytes()))
53
+ self._escalate_cancel(row,record)
54
+ return
55
+ if row['state'] in ('RUNNING','UNKNOWN'):
56
+ # A live engine whose heartbeat lease expired is hung, not
57
+ # slow: the engine renews at every tool boundary and every
58
+ # progress checkpoint, so silence beyond the lease means the
59
+ # interpreter stopped making progress (I01900).
60
+ self._enforce_lease(row,record)
52
61
  return
62
+ if process.is_file():
63
+ # The engine process is provably gone (live() already treats a
64
+ # zombie as dead): collect the child so no defunct entry lingers
65
+ # in the supervisor's process table misdirecting triage (I01903).
66
+ self._reap(loads(process.read_bytes()))
53
67
  if row['state']=='CANCELLING':
54
68
  # The engine died on its own while a cancel was pending. Cancel was
55
69
  # explicitly requested and the dispatch source is verified gone, so
@@ -89,8 +103,13 @@ class Worker:
89
103
  result=loads(raw)
90
104
  if (result.get('job_id'),result.get('attempt'),result.get('version'))!=(row['id'],row['attempt'],row['version']):
91
105
  raise ContractError('worker receipt identity mismatch')
106
+ # ``reaped`` marks the worker's own local-termination receipts, which
107
+ # carry ``remote_stop_confirmed=False`` but must still reach a terminal
108
+ # state (CANCELLED/FAILED) so the execution budget frees (I01912).
109
+ # Engine receipts never carry the field, so a confirmed remote stop
110
+ # keeps coming only from the engine (I01719 fail-closed).
92
111
  self.jobs.complete(row['id'],row['attempt'],result['result'],stopped=result['remote_stop_confirmed'] is True,
93
- checkpoint_schema=result.get('checkpoint_schema'))
112
+ checkpoint_schema=result.get('checkpoint_schema'),reaped=bool(result.get('reaped')))
94
113
  atomic(observed,canonical({'sha256':digest}))
95
114
  return True
96
115
 
@@ -99,11 +118,17 @@ class Worker:
99
118
 
100
119
  ``jobs.cancel`` timestamps the state change in ``updated``; the engine
101
120
  keeps its cooperative window until then. SIGTERM, then SIGKILL the
102
- whole session group (the engine owns its EDA children), and confirm
103
- death before recording the receipt: the execution tree stopping is
104
- the worker's own observation, never an assumption. A killed engine
105
- leaves no trustworthy checkpoint, so the receipt carries
106
- ``checkpoint_schema=None`` and this attempt cannot be resumed.
121
+ whole session group, and confirm death before recording the receipt:
122
+ the local execution tree stopping is the worker's own observation,
123
+ never an assumption. In the DPV2 topology the engine drives the
124
+ workstation EDA through elink, so this group kill proves only that the
125
+ local engine tree is gone — the remote EDA stop can never be observed
126
+ here, and the receipt records ``remote_stop_confirmed=False`` instead
127
+ of presenting a local kill as a confirmed remote stop (I01912). A
128
+ killed engine leaves no trustworthy checkpoint, so the receipt carries
129
+ ``checkpoint_schema=None`` and this attempt cannot be resumed; the
130
+ ``reaped`` mark keeps it terminal (CANCELLED) despite the unconfirmed
131
+ stop.
107
132
  """
108
133
  grace=float(self.config.get('cancel_grace_seconds',30))
109
134
  if time.time()<row['updated']+grace:return
@@ -119,12 +144,103 @@ class Worker:
119
144
  if live(process_row):
120
145
  # Termination unconfirmed: stay CANCELLING and retry on the next tick.
121
146
  return
147
+ self._reap(process_row)
122
148
  atomic(self.path(row)/'result.json',canonical({
123
149
  'job_id':row['id'],'attempt':row['attempt'],'version':row['version'],
124
150
  'result':{'ok':False,'job_status':'CANCELLED',
125
- 'error':{'code':'WORKER_CANCEL_TERMINATED',
126
- 'message':'Engine process group terminated after the cancellation grace; the local execution tree is confirmed stopped'}},
127
- 'remote_stop_confirmed':True,'checkpoint_schema':None}))
151
+ 'error':{'code':'WORKER_CANCEL_TERMINATED_LOCAL',
152
+ 'message':'Engine process group terminated locally after the cancellation grace; the remote workstation stop was never observed or confirmed'}},
153
+ 'remote_stop_confirmed':False,'reaped':True,'checkpoint_schema':None}))
154
+
155
+ def _lease_budget(self,row):
156
+ """Silence budget after which a live engine counts as hung (I01900).
157
+
158
+ The engine renews the lease at every tool boundary and progress
159
+ checkpoint, so the honest silent window is one remote call. The engine
160
+ reports its own per-call budget with each renewal; the worker never
161
+ enforces less than three times that, so a slow EDA call inside its own
162
+ request timeout can never be mis-read as a hang even when the operator
163
+ tightened ``lease_ttl_seconds``. Older attempts without renewals keep
164
+ the configured default.
165
+ """
166
+ budget=float(self.config.get('lease_ttl_seconds',7200))
167
+ floor=float(row['lease_floor'] or 0)
168
+ return max(budget,3.0*floor) if floor>0 else budget
169
+
170
+ def _enforce_lease(self,row,process_row):
171
+ """Force-reclaim a live engine past its heartbeat lease (I01900).
172
+
173
+ Extends the I01769 escalation to the lease-expiry case: log the
174
+ decision with its numbers, SIGTERM then SIGKILL the whole session
175
+ group, and confirm death before recording the receipt. The engine
176
+ drives the workstation EDA through elink, so the confirmed death is a
177
+ local fact only: the receipt records ``remote_stop_confirmed=False``
178
+ — a hung-engine kill never presents itself as a confirmed remote
179
+ stop (I01912) — and the ``reaped`` mark keeps the attempt terminal
180
+ (FAILED) so the execution budget frees. A killed engine leaves no
181
+ trustworthy checkpoint, so the receipt carries
182
+ ``checkpoint_schema=None`` and this attempt cannot be resumed. If the
183
+ group survives the signals the attempt is left untouched and the next
184
+ tick retries with fresh evidence.
185
+ """
186
+ if row['version']!=self.version:return
187
+ # The heartbeat column is authoritative (seeded at claim, renewed by
188
+ # the engine); only a pre-upgrade row without any lease history falls
189
+ # back to its state-change timestamp.
190
+ heartbeat=float(row['heartbeat'] or 0)
191
+ last=heartbeat if heartbeat>0 else float(row['updated'] or 0)
192
+ budget=self._lease_budget(row)
193
+ silence=time.time()-last
194
+ if silence<=budget:return
195
+ self.jobs.append(row['id'],row['attempt'],
196
+ {'event':'worker_lease_expired','silence':round(silence,3),
197
+ 'budget':budget,'last_activity':last})
198
+ pid=process_row['pid']
199
+ for name,delay in (('SIGTERM',float(self.config.get('cancel_term_seconds',10))),
200
+ ('SIGKILL',5.0)):
201
+ try:os.killpg(pid,getattr(signal,name))
202
+ except ProcessLookupError:break
203
+ deadline=time.time()+delay
204
+ while time.time()<deadline and live(process_row):time.sleep(0.2)
205
+ if not live(process_row):break
206
+ if live(process_row):
207
+ # Termination unconfirmed: stay RUNNING/UNKNOWN and retry on the
208
+ # next tick; the lease keeps expiring so the evidence accumulates.
209
+ return
210
+ self._reap(process_row)
211
+ atomic(self.path(row)/'result.json',canonical({
212
+ 'job_id':row['id'],'attempt':row['attempt'],'version':row['version'],
213
+ 'result':{'ok':False,'job_status':'FAILED',
214
+ 'error':{'code':'WORKER_LEASE_TERMINATED_LOCAL',
215
+ 'message':'Engine process group terminated locally after the heartbeat lease expired; the remote workstation stop was never observed or confirmed'}},
216
+ 'remote_stop_confirmed':False,'reaped':True,'checkpoint_schema':None}))
217
+
218
+ def _reap(self,record):
219
+ """waitpid a confirmed-dead engine child so no defunct survives (I01903).
220
+
221
+ An unreaped engine stays a zombie of this supervisor for its whole
222
+ lifetime, cluttering live-process triage. Only the parent can
223
+ collect: a restarted supervisor inherits no children, and ECHILD
224
+ there is the expected no-op. The verdict always comes from /proc,
225
+ never from waitpid.
226
+ """
227
+ try:os.waitpid(record['pid'],os.WNOHANG)
228
+ except OSError:pass
229
+
230
+ def _publish_health(self,ok,error=None):
231
+ """Best-effort tick health record for the e01 monitor (I01903).
232
+
233
+ Advisory observations only: the jobs database stays the state
234
+ authority and a monitor judges liveness from the ``updated`` age, so
235
+ a dead supervisor surfaces as a stale file, never as a stale OK.
236
+ """
237
+ try:
238
+ atomic(self.state/'worker-health.json',canonical({
239
+ 'schema':1,'worker_version':self.version,'pid':os.getpid(),
240
+ 'started':self._started,'updated':time.time(),'last_tick_ok':bool(ok),
241
+ 'consecutive_failures':self._tick_failures,
242
+ 'last_error':None if error is None else '%s: %s'%(type(error).__name__,error)}))
243
+ except (OSError,ValueError):pass
128
244
 
129
245
  def launch(self, row):
130
246
  directory=self.path(row)
@@ -153,6 +269,18 @@ class Worker:
153
269
  self.jobs.append(row['id'],row['attempt'],{'event':'worker_started','plugin_version':self.version})
154
270
 
155
271
  def tick(self):
272
+ try:result=self._tick()
273
+ except Exception as error:
274
+ # A failing tick must be observable, not a silent dead service:
275
+ # the supervisor keeps looping and the health file carries the
276
+ # failure for the e01 monitor (I01903).
277
+ self._tick_failures+=1
278
+ self._publish_health(ok=False,error=error)
279
+ return False
280
+ self._publish_health(ok=True)
281
+ return result
282
+
283
+ def _tick(self):
156
284
  with self.jobs.connection() as db:
157
285
  # Reconciliation spans every version: the execution budget counts
158
286
  # RUNNING/CANCELLING/UNKNOWN across versions, so a supervisor may
@@ -164,7 +292,11 @@ class Worker:
164
292
  for row in active:
165
293
  try:self.reconcile(row)
166
294
  except (ContractError,Conflict,ValueError):pass
167
- row=self.jobs.claim(self.version,max_active=self.config.get('max_active_jobs',2))
295
+ # I01900 budgets: ``max_active_jobs`` caps one workstation so a single
296
+ # leaked station can no longer block every other workstation; the
297
+ # global fuse moves to ``max_total_jobs``.
298
+ row=self.jobs.claim(self.version,max_active=self.config.get('max_active_jobs',1),
299
+ max_total=self.config.get('max_total_jobs',16))
168
300
  if row is not None:
169
301
  try:self.launch(row)
170
302
  except Exception: