@tedbrain/vlink 0.0.0-dpv2.pdkadapt.plugin.0.1.3.r2 → 0.0.0-dpv2.pdkadapt.plugin.0.1.5.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.3.r2"}
1
+ {"name": "@tedbrain/vlink", "private": false, "version": "0.0.0-dpv2.pdkadapt.plugin.0.1.5.r2"}
@@ -62,14 +62,16 @@ def save_session(root,envelope,origin):
62
62
  return metadata
63
63
 
64
64
 
65
- def ensure_session(root,origin,exchange,force=False):
65
+ def ensure_session(root,origin,exchange,force=False,allow_account_change=False):
66
66
  token=root/'credentials/token';metadata=root/'credentials/session.json'
67
- if token.is_file() and not force:
68
- if not metadata.is_file():return None # Existing releases renew on a real 401.
67
+ previous=None
68
+ if token.is_file() and metadata.is_file():
69
69
  try:session=loads(metadata.read_bytes())
70
70
  except (OSError,ContractError):raise ContractError('DPV2 session metadata unreadable; use cli.sh login --stdin') from None
71
- if session.get('origin')!=origin:raise ContractError('DPV2 session origin differs; login explicitly for the selected origin')
72
- if session.get('expires_at',0)>time.time()+30:return session
71
+ previous=session.get('subject')
72
+ if session.get('origin')!=origin and not allow_account_change:raise ContractError('DPV2 session origin differs; login explicitly for the selected origin')
73
+ if not force and session.get('expires_at',0)>time.time()+30:return session
74
+ elif token.is_file() and not force:return None # Existing releases renew on a real 401.
73
75
  parsed=urlsplit(origin)
74
76
  official=origin in ('https://tedbrain.com','https://www.tedbrain.com')
75
77
  loopback=(os.environ.get('DPV2_TEST_LOOPBACK')=='1' and parsed.scheme=='http' and
@@ -85,4 +87,6 @@ def ensure_session(root,origin,exchange,force=False):
85
87
  if envelope.get('outcome')=='response' and status in (401,403):
86
88
  raise ContractError('Saved V1 vlink credential rejected; use cli.sh login --stdin')
87
89
  raise ContractError('DPV2 login service unavailable; retry authentication later; business request was not replayed')
90
+ if previous and not allow_account_change and envelope.get('body',{}).get('subject')!=previous:
91
+ raise ContractError('Saved V1 account differs from the DPV2 session; run cli.sh login explicitly to switch accounts; original request was not retried')
88
92
  return save_session(root,envelope,origin)
@@ -169,7 +169,7 @@ def main(argv=None):
169
169
  if not a.stdin:
170
170
  from .auth import saved_credential
171
171
  if saved_credential() is not None:
172
- session=ensure_session(root,origin,lambda credential:exchange_session(root,credential),force=True)
172
+ session=ensure_session(root,origin,lambda credential:exchange_session(root,credential),force=True,allow_account_change=True)
173
173
  print(json.dumps(dict(session,ok=True,reused_v1=True)));return 0
174
174
  if not sys.stdin.isatty():raise ContractError('login required: no saved V1 vlink credential; use login --stdin')
175
175
  credential=sys.stdin.readline().strip() if a.stdin else getpass.getpass('TedBrain invitation code: ')
@@ -163,7 +163,7 @@ class Jobs:
163
163
  if current is None or current['attempt']!=attempt:raise Conflict('stale attempt')
164
164
  self.event(db,job,attempt,event)
165
165
 
166
- def complete(self,job,attempt,result,*,stopped,checkpoint_schema=None):
166
+ def complete(self,job,attempt,result,*,stopped,checkpoint_schema=None,reaped=False):
167
167
  # Process exit alone cannot establish that remote EDA stopped.
168
168
  delivery=result.get('delivery')
169
169
  success=(result.get('ok') is True and result.get('job_status')=='COMPLETED'
@@ -177,8 +177,13 @@ class Jobs:
177
177
  row=db.execute('SELECT * FROM jobs WHERE id=?',(job,)).fetchone()
178
178
  if row is None or row['attempt']!=attempt or row['state'] not in ('RUNNING','CANCELLING','UNKNOWN'):
179
179
  raise Conflict('stale or terminal execution attempt')
180
+ # ``stopped`` stays the only path that claims a confirmed remote
181
+ # stop. A reaped dead attempt must still reach a terminal state so
182
+ # the execution budget frees: a pending cancel ends CANCELLED, a
183
+ # grace-expired UNKNOWN outcome ends FAILED (I01814).
180
184
  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'
185
+ 'WAITING_INPUT' if result.get('job_status')=='WAITING_FOR_DECISION' else 'FAILED'
186
+ ) if stopped else ('CANCELLED' if row['state']=='CANCELLING' else 'FAILED' if reaped else 'UNKNOWN')
182
187
  encoded=canonical(result).decode()
183
188
  db.execute('UPDATE jobs SET state=?,result=?,stopped=?,checkpoint_schema=?,updated=? WHERE id=?',
184
189
  (state,encoded,int(stopped),checkpoint_schema,time.time(),job))
@@ -14,7 +14,7 @@ import subprocess
14
14
  import sys
15
15
  import time
16
16
  from .installer import ContractError, atomic, canonical, loads
17
- from .jobs import Jobs
17
+ from .jobs import Conflict, Jobs
18
18
  from .workstations import Workstations
19
19
  from .executor import live
20
20
 
@@ -34,17 +34,15 @@ class Worker:
34
34
  def reconcile(self, row):
35
35
  directory=self.path(row);receipt=directory/'result.json';process=directory/'process.json'
36
36
  if receipt.is_file():
37
- if receipt.is_symlink() or receipt.stat().st_size>1048576:raise ContractError('invalid worker receipt')
38
- raw=receipt.read_bytes();digest=hashlib.sha256(raw).hexdigest()
39
- observed=directory/'observed-result.json'
40
- if observed.is_file() and loads(observed.read_bytes()).get('sha256')==digest:return
41
- result=loads(raw)
42
- if (result.get('job_id'),result.get('attempt'),result.get('version'))!=(row['id'],row['attempt'],row['version']):
43
- raise ContractError('worker receipt identity mismatch')
44
- self.jobs.complete(row['id'],row['attempt'],result['result'],stopped=result['remote_stop_confirmed'] is True,
45
- checkpoint_schema=result.get('checkpoint_schema'))
46
- atomic(observed,canonical({'sha256':digest}))
47
- return
37
+ try:
38
+ if self._consume_receipt(row,directory,receipt):return
39
+ except Conflict:
40
+ # Another observation already drove this attempt terminal.
41
+ return
42
+ except (ContractError,ValueError):
43
+ # Poisoned receipt: fall through to the dead-attempt paths so
44
+ # the attempt still reaches a terminal state (I01814).
45
+ pass
48
46
  if process.is_file() and live(loads(process.read_bytes())):
49
47
  if row['state']=='CANCELLING':
50
48
  # Cooperative cancellation only fires between synchronous
@@ -52,9 +50,49 @@ class Worker:
52
50
  # checks, so the supervisor escalates after the grace (I01769).
53
51
  self._escalate_cancel(row,loads(process.read_bytes()))
54
52
  return
55
- if row['state']!='UNKNOWN':
56
- self.jobs.complete(row['id'],row['attempt'],{'ok':False,'job_status':'UNKNOWN',
57
- 'error':{'code':'WORKER_OUTCOME_UNKNOWN','message':'Execution receipt unavailable; reconcile the original attempt'}},stopped=False)
53
+ if row['state']=='CANCELLING':
54
+ # The engine died on its own while a cancel was pending. Cancel was
55
+ # explicitly requested and the dispatch source is verified gone, so
56
+ # the attempt must reach its terminal state instead of flipping
57
+ # back to UNKNOWN and leaking the execution budget (I01814). The
58
+ # remote EDA tree cannot be observed, so the stop stays unconfirmed
59
+ # and this attempt can never be resumed.
60
+ self.jobs.complete(row['id'],row['attempt'],{'ok':False,'job_status':'CANCELLED',
61
+ 'error':{'code':'WORKER_CANCEL_REAPED','message':'Cancelled attempt reaped: the execution process is gone and the receipt was never delivered; remote stop could not be observed'}},
62
+ stopped=False)
63
+ return
64
+ if row['state']=='UNKNOWN':
65
+ # The first dead-attempt observation keeps the verdict UNKNOWN for
66
+ # one grace window in case a receipt still lands. After the grace
67
+ # the attempt is reaped into a terminal FAILED state so the
68
+ # execution budget frees; the stop remains unconfirmed (I01814).
69
+ grace=float(self.config.get('reap_grace_seconds',600))
70
+ if time.time()-float(row['updated'] or 0)<grace:return
71
+ self.jobs.complete(row['id'],row['attempt'],{'ok':False,'job_status':'FAILED',
72
+ 'error':{'code':'WORKER_OUTCOME_REAPED','message':'Attempt reaped after the outcome-unknown grace: the execution process is gone and the receipt was never delivered; remote stop could not be observed'}},
73
+ stopped=False,reaped=True)
74
+ return
75
+ self.jobs.complete(row['id'],row['attempt'],{'ok':False,'job_status':'UNKNOWN',
76
+ 'error':{'code':'WORKER_OUTCOME_UNKNOWN','message':'Execution receipt unavailable; reconcile the original attempt'}},stopped=False)
77
+
78
+ def _consume_receipt(self,row,directory,receipt):
79
+ """Complete the attempt from its receipt; True when reconcile is done.
80
+
81
+ An unreadable or identity-mismatched receipt raises: the caller falls
82
+ through to the dead-attempt paths, so a poisoned receipt can never
83
+ wedge the attempt out of the execution budget forever (I01814).
84
+ """
85
+ if receipt.is_symlink() or receipt.stat().st_size>1048576:raise ContractError('invalid worker receipt')
86
+ raw=receipt.read_bytes();digest=hashlib.sha256(raw).hexdigest()
87
+ observed=directory/'observed-result.json'
88
+ if observed.is_file() and loads(observed.read_bytes()).get('sha256')==digest:return False
89
+ result=loads(raw)
90
+ if (result.get('job_id'),result.get('attempt'),result.get('version'))!=(row['id'],row['attempt'],row['version']):
91
+ raise ContractError('worker receipt identity mismatch')
92
+ self.jobs.complete(row['id'],row['attempt'],result['result'],stopped=result['remote_stop_confirmed'] is True,
93
+ checkpoint_schema=result.get('checkpoint_schema'))
94
+ atomic(observed,canonical({'sha256':digest}))
95
+ return True
58
96
 
59
97
  def _escalate_cancel(self,row,process_row):
60
98
  """Terminate a CANCELLING engine group once the grace elapses.
@@ -116,8 +154,16 @@ class Worker:
116
154
 
117
155
  def tick(self):
118
156
  with self.jobs.connection() as db:
119
- active=[dict(row) for row in db.execute("SELECT * FROM jobs WHERE version=? AND state IN ('RUNNING','CANCELLING','UNKNOWN')",(self.version,))]
120
- for row in active:self.reconcile(row)
157
+ # Reconciliation spans every version: the execution budget counts
158
+ # RUNNING/CANCELLING/UNKNOWN across versions, so a supervisor may
159
+ # never skip dead attempts of versions it no longer claims
160
+ # (I01814). Live attempts are untouched: reconcile returns early
161
+ # on a live process, and a per-row guard keeps one poisoned
162
+ # attempt from killing the supervisor loop.
163
+ active=[dict(row) for row in db.execute("SELECT * FROM jobs WHERE state IN ('RUNNING','CANCELLING','UNKNOWN')")]
164
+ for row in active:
165
+ try:self.reconcile(row)
166
+ except (ContractError,Conflict,ValueError):pass
121
167
  row=self.jobs.claim(self.version,max_active=self.config.get('max_active_jobs',2))
122
168
  if row is not None:
123
169
  try:self.launch(row)