test_remote_job.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. from argparse import Namespace
  2. import subprocess
  3. import json
  4. import os
  5. import sys
  6. import pytest
  7. from tools import remote_job as job
  8. @pytest.mark.parametrize('action,expected', [('quick','diagnose'),('td','build')])
  9. def test_firmware_alias_runs_canonical_entry_with_run_directory(tmp_path,action,expected):
  10. source=tmp_path/'source space';(source/'tools').mkdir(parents=True)
  11. (source/'tools/__init__.py').write_text('')
  12. (source/'tools/fw_cli.py').write_text('import json\ndef main(args):\n print(json.dumps(args)); return 7\n')
  13. a=Namespace(action=action,command=[],target='mrdimm-chamber')
  14. job.prepare_alias(a)
  15. run_root=tmp_path/'run space \u6d4b\u8bd5 $()'
  16. p=subprocess.run([sys.executable,*a.command[1:]],cwd=source,env=dict(os.environ,PROD2U_RUN_DIR=str(run_root)),capture_output=True,text=True)
  17. assert p.returncode==7
  18. command=json.loads(p.stdout)
  19. assert command[:4]==[expected,'mrdimm-chamber','--run-root',str(run_root/'native')]
  20. assert a.task==action and a.action=='submit'
  21. def test_full_alias_requires_explicit_suite_and_keeps_command():
  22. a=Namespace(action='full',command=[])
  23. with pytest.raises(ValueError,match='explicit suite'):job.prepare_alias(a)
  24. a.command=['python3','suite with spaces.py','--seed','17']
  25. job.prepare_alias(a)
  26. assert a.action=='submit' and a.task=='full' and a.command[1]=='suite with spaces.py'
  27. def test_exact_snapshot_is_self_contained_and_reuse_preserves_changes(tmp_path):
  28. source=tmp_path/'repo';source.mkdir()
  29. def git(*args):
  30. return subprocess.check_output(['git','-C',str(source),*args],text=True).strip()
  31. git('init','-q');git('config','user.name','Fixture');git('config','user.email','fixture@example.invalid')
  32. (source/'file').write_text('first');git('add','file');git('commit','-qm','first')
  33. commit=git('rev-parse','HEAD');destination=tmp_path/'snapshot \u6d4b\u8bd5 space'
  34. first=job.snapshot(str(source),str(destination),commit)
  35. assert job.snapshot(str(source),str(destination),commit)==first
  36. assert not (destination/'.git/objects/info/alternates').exists()
  37. assert subprocess.run(['git','-C',str(destination),'symbolic-ref','-q','HEAD'],capture_output=True).returncode==1
  38. (destination/'unknown').write_text('preserve')
  39. with pytest.raises(ValueError,match='clean'):job.snapshot(str(source),str(destination),commit)
  40. assert (destination/'unknown').read_text()=='preserve'
  41. with pytest.raises(ValueError,match='full 40'):job.snapshot(str(source),str(tmp_path/'short'),commit[:8])
  42. assert not (tmp_path/'short').exists()
  43. (source/'file').write_text('second');git('commit','-qam','second')
  44. other=tmp_path/'different'
  45. job.snapshot(str(source),str(other),git('rev-parse','HEAD'))
  46. with pytest.raises(ValueError,match='different commit'):job.snapshot(str(source),str(other),commit)
  47. assert (other/'file').read_text()=='second'
  48. def test_high_level_ssh_forwards_action_without_local_execution(monkeypatch,capsys):
  49. import shlex
  50. calls=[]
  51. def run(command,**kwargs):
  52. calls.append(command)
  53. return subprocess.CompletedProcess(command,0,b'{"status":"running"}\n',b'')
  54. monkeypatch.setattr(job.subprocess,'run',run)
  55. assert job.main(['--ssh-runner','/snapshot \u4e2d\u6587/tools/remote_job.py','container-status'])==0
  56. assert shlex.split(calls[0][-1])==['python3','/snapshot \u4e2d\u6587/tools/remote_job.py','container-status']
  57. @pytest.mark.parametrize('action', ['doctor','container-up','container-stop','container-down','container-recreate','container-status'])
  58. def test_lifecycle_alias_uses_existing_controller_and_returns_failure(monkeypatch,action):
  59. real_path=job.Path
  60. class OutsideContainer:
  61. def exists(self):return False
  62. monkeypatch.setattr(job,'Path',lambda p: OutsideContainer() if str(p)=='/run/.containerenv' else real_path(p))
  63. monkeypatch.setattr(job.sys,'platform','linux')
  64. monkeypatch.setattr(job.os,'geteuid',lambda:0)
  65. seen=[]
  66. monkeypatch.setattr(job,'container_main',lambda args:seen.append(args) or 7)
  67. assert job.main([action,'--container','prod2u-test','--workspace','/exact source'])==7
  68. assert seen==[['--name','prod2u-test','--workspace','/exact source',action.removeprefix('container-')]]
  69. def test_sync_uses_local_source_and_process_scoped_lan_ssh(monkeypatch):
  70. before=os.environ.get('GIT_SSH_COMMAND');seen=[]
  71. def run(command,**kwargs):
  72. seen.append((command,kwargs));return subprocess.CompletedProcess(command,9)
  73. monkeypatch.setattr(job.subprocess,'run',run)
  74. assert job.main(['sync'])==9
  75. assert seen[0][0]==['git','-C',str(job.ROOT),'push','lan','HEAD']
  76. assert 'StrictHostKeyChecking=no' in seen[0][1]['env']['GIT_SSH_COMMAND']
  77. assert os.environ.get('GIT_SSH_COMMAND')==before
  78. def args(tmp_path):
  79. return Namespace(run_root=tmp_path,run_id='fixture',workspace=str(tmp_path),
  80. snapshot_id='snapshot',target='mrdimm-chamber',task='smoke',
  81. toolchain_id='test-image',container='prod2u-dev',heavy=False,
  82. command=['python3','-c','print("literal $() quoted")'])
  83. def test_duplicate_submit_starts_one_unit_and_conflict_does_not_overwrite(tmp_path,monkeypatch):
  84. a=args(tmp_path)
  85. monkeypatch.setattr(job,'source_binding',lambda p:{'workspace':str(p),'commit':'a'*40,'tree':'b'*40})
  86. monkeypatch.setattr(job,'boot_id',lambda:'boot')
  87. calls=[]
  88. def run(command,**kw):
  89. calls.append(command)
  90. return subprocess.CompletedProcess(command,0,'active\n' if command[0]=='systemctl' else '','')
  91. monkeypatch.setattr(job.subprocess,'run',run)
  92. first=job.submit(a);second=job.submit(a)
  93. assert first['identity']==second['identity']
  94. assert sum(x[0]=='systemd-run' for x in calls)==1
  95. assert first['spec']['command']==a.command
  96. original=(tmp_path/'fixture/SPEC.json').read_bytes()
  97. a.command=['false']
  98. with pytest.raises(ValueError,match='RUN_ID_CONFLICT'):job.submit(a)
  99. assert (tmp_path/'fixture/SPEC.json').read_bytes()==original
  100. assert sum(x[0]=='systemd-run' for x in calls)==1
  101. def test_empty_command_never_creates_run(tmp_path):
  102. a=args(tmp_path);a.command=[]
  103. with pytest.raises(ValueError,match='nonempty'):job.submit(a)
  104. assert not (tmp_path/'fixture').exists()
  105. @pytest.mark.parametrize('name',['../escape','/absolute','x/y','','.','..','bad name'])
  106. def test_invalid_run_paths_are_rejected(tmp_path,name):
  107. with pytest.raises(ValueError):job.job_dir(tmp_path,name)
  108. def test_boot_change_marks_interrupted_without_pid_or_unit_lookup(tmp_path,monkeypatch):
  109. folder=tmp_path/'run';folder.mkdir()
  110. job.save_status(folder,{'status':'RUNNING','boot_id':'previous-boot','unit':'old','process':{'pid':1}})
  111. monkeypatch.setattr(job,'boot_id',lambda:'new-boot')
  112. monkeypatch.setattr(job.subprocess,'run',lambda *a,**kw:pytest.fail('old unit must not be consulted after reboot'))
  113. result=job.refresh(folder)
  114. assert result['status']=='INTERRUPTED' and result['exit_code'] is None
  115. assert job.read(folder/'RESULT.json')['status']=='INTERRUPTED'
  116. def test_live_cgroup_is_not_declared_stopped_when_supervisor_unit_is_missing(tmp_path,monkeypatch):
  117. folder=tmp_path/'run';folder.mkdir()
  118. job.save_status(folder,{'status':'RUNNING','boot_id':'boot','unit':'old','job_cgroup':'/owned'})
  119. monkeypatch.setattr(job,'boot_id',lambda:'boot')
  120. monkeypatch.setattr(job,'populated',lambda path:True)
  121. monkeypatch.setattr(job.subprocess,'run',lambda *a,**kw:pytest.fail('live group is authoritative'))
  122. assert job.refresh(folder)['status']=='RUNNING'
  123. def test_transient_unit_query_failure_is_not_terminal(tmp_path,monkeypatch):
  124. folder=tmp_path/'run';folder.mkdir()
  125. job.save_status(folder,{'status':'QUEUED','boot_id':'boot','unit':'unit'})
  126. monkeypatch.setattr(job,'boot_id',lambda:'boot')
  127. monkeypatch.setattr(job.subprocess,'run',lambda *a,**kw:subprocess.CompletedProcess(a,1,'','bus unavailable'))
  128. with pytest.raises(RuntimeError,match='cannot inspect'):job.refresh(folder)
  129. assert job.read(folder/'RUN-STATUS.json')['status']=='QUEUED'
  130. assert not (folder/'RESULT.json').exists()
  131. def test_cancel_kills_only_bound_cgroup_and_rejects_stale_boot(tmp_path,monkeypatch):
  132. monkeypatch.setattr(job,'CGROOT',tmp_path);monkeypatch.setattr(job,'boot_id',lambda:'boot')
  133. state={'boot_id':'boot','identity':'a'*64,'container_cgroup':'/container',
  134. 'job_cgroup':'/container/prod2u-job-'+('a'*24)}
  135. path=tmp_path/state['job_cgroup'].lstrip('/');path.mkdir(parents=True)
  136. kill=path/'cgroup.kill';kill.write_text('0')
  137. job.kill_job_group(state);assert kill.read_text()=='1'
  138. kill.write_text('0');state['boot_id']='old'
  139. with pytest.raises(RuntimeError,match='stale'):job.kill_job_group(state)
  140. assert kill.read_text()=='0'
  141. def test_failed_command_cannot_be_reported_as_pass(tmp_path):
  142. folder=tmp_path/'run';folder.mkdir()
  143. job.save_status(folder,{'status':'RUNNING'})
  144. (folder/'stdout.log').write_text('native failure')
  145. assert job.finish(folder,7,None)==1
  146. result=job.read(folder/'RESULT.json')
  147. assert result['status']=='FAIL' and result['exit_code']==7
  148. assert result['artifacts'][0]['path']=='stdout.log'
  149. def test_cancel_before_heavy_lock_stops_only_its_unit(tmp_path,monkeypatch):
  150. folder=tmp_path/'queued';folder.mkdir()
  151. job.save_status(folder,{'status':'QUEUED','phase':'submit','boot_id':'boot','unit':job.unit_name(folder)})
  152. monkeypatch.setattr(job,'boot_id',lambda:'boot')
  153. calls=[]
  154. monkeypatch.setattr(job.subprocess,'run',lambda args,**kw:calls.append(args))
  155. result=job.cancel(folder)
  156. assert result['status']=='CANCELLED' and result['exit_code']==130
  157. assert calls==[['systemctl','stop',job.unit_name(folder)]]
  158. assert not (folder/'GO').exists()
  159. @pytest.mark.parametrize('status,phase',[('PASS','finished'),('RUNNING','command'),('QUEUED','container_start')])
  160. def test_repeated_worker_does_not_execute_again(tmp_path,monkeypatch,status,phase):
  161. folder=tmp_path/'worker';folder.mkdir()
  162. job.atomic(folder/'SPEC.json',{})
  163. job.save_status(folder,{'status':status,'phase':phase})
  164. monkeypatch.setattr(job.signal,'signal',lambda *args:None)
  165. assert job.launch_locked(folder,None)==0
  166. assert not (folder/'stdout.log').exists() and not (folder/'GO').exists()
  167. def test_failure_bundle_contains_native_result_and_small_wave_but_indexes_large_wave(tmp_path):
  168. import json,zipfile,hashlib
  169. folder=tmp_path/'run';folder.mkdir();(folder/'native').mkdir()
  170. job.save_status(folder,{'status':'RUNNING','run_id':'run'})
  171. (folder/'stderr.log').write_text('native failure')
  172. (folder/'native/RESULT.json').write_text('{"status":"FAIL","seed":42}')
  173. (folder/'native/window.vcd').write_bytes(b'$timescale 1ns $end\n#10\n')
  174. (folder/'native/full.fst').write_bytes(b'x'*(job.SMALL_WAVE_LIMIT+1))
  175. (folder/'native/output.bit').write_bytes(b'not a diagnostic')
  176. assert job.finish(folder,7,'native failed')==1
  177. state=job.read(folder/'RESULT.json');bundle=folder/state['failure_bundle']['path']
  178. assert hashlib.sha256(bundle.read_bytes()).hexdigest()==state['failure_bundle']['sha256']
  179. with zipfile.ZipFile(bundle) as archive:
  180. index=json.loads(archive.read('FAILURE-INDEX.json'))
  181. assert index['job_status']=='FAIL' and index['exit_code']==7
  182. assert archive.read('files/native/RESULT.json')==b'{"status":"FAIL","seed":42}'
  183. assert 'files/native/window.vcd' in archive.namelist()
  184. assert not any(name.endswith('full.fst') for name in archive.namelist())
  185. rows={x['path']:x for x in index['artifacts']}
  186. assert rows['native/full.fst']['disposition']=='remote_large_waveform'
  187. assert rows['native/output.bit']['disposition']=='remote_non_diagnostic_artifact'
  188. before=bundle.read_bytes()
  189. assert job.finish(folder,0,None)==1 and bundle.read_bytes()==before
  190. def test_bounded_diagnostics_label_tail_instead_of_claiming_complete_log(tmp_path,monkeypatch):
  191. import json,zipfile
  192. monkeypatch.setattr(job,'DIAGNOSTIC_LIMIT',32)
  193. folder=tmp_path/'run';folder.mkdir();(folder/'stderr.log').write_bytes(bytes(range(100)))
  194. job.save_status(folder,{'status':'FAIL','exit_code':7})
  195. with zipfile.ZipFile(folder/job.BUNDLE_NAME) as archive:
  196. index=json.loads(archive.read('FAILURE-INDEX.json'))
  197. row=index['artifacts'][0]
  198. assert row['disposition']=='tail_only' and row['included_bytes']==32
  199. assert archive.read(row['member'])==bytes(range(68,100))
  200. def test_diagnostic_error_does_not_mask_command_failure_or_overwrite_file(tmp_path):
  201. folder=tmp_path/'run';folder.mkdir();(folder/job.BUNDLE_NAME).write_bytes(b'preserve')
  202. job.save_status(folder,{'status':'FAIL','exit_code':7})
  203. state=job.read(folder/'RESULT.json')
  204. assert state['status']=='FAIL' and state['exit_code']==7
  205. assert 'failure_bundle_error' in state and 'failure_bundle' not in state
  206. assert (folder/job.BUNDLE_NAME).read_bytes()==b'preserve'
  207. def test_fetch_failure_keeps_remote_job_status_and_binds_archive_hash(tmp_path,monkeypatch):
  208. from tools import remote_transfer
  209. calls=[]
  210. def download(remote,source,destination,sha):
  211. calls.append((source,sha))
  212. destination.parent.mkdir(parents=True,exist_ok=True);destination.write_bytes(b'zip')
  213. return {'status':'PASS','destination':str(destination),'size':3,'sha256':sha,
  214. 'transferred_chunks':[0],'reused_chunks':[],'scope':'file byte integrity'}
  215. monkeypatch.setattr(remote_transfer,'download',download)
  216. state={'run_id':'failure','status':'FAIL','exit_code':7,
  217. 'failure_bundle':{'path':job.BUNDLE_NAME,'size':3,'sha256':'a'*64}}
  218. result=job.fetch_failure(state,'/data/prod2u/source/tools/remote_job.py','/data/prod2u/runs',tmp_path)
  219. assert result['status']=='PASS' and state['status']=='FAIL' and state['exit_code']==7
  220. assert calls==[('/data/prod2u/runs/failure/'+job.BUNDLE_NAME,'a'*64)]
  221. assert (tmp_path/'run-failure/TRANSFER-RECEIPT.json').is_file()
  222. def test_fetch_error_is_reported_separately_from_remote_failure(monkeypatch,capsys):
  223. import json
  224. state={'run_id':'failed','status':'FAIL','exit_code':7}
  225. monkeypatch.setattr(job.subprocess,'run',lambda *a,**kw:subprocess.CompletedProcess(a,0,json.dumps(state).encode(),b''))
  226. monkeypatch.setattr(job,'fetch_failure',lambda *a:(_ for _ in ()).throw(RuntimeError('download unavailable')))
  227. assert job.main(['--ssh-runner','/data/prod2u/source/tools/remote_job.py','status','failed'])==3
  228. result=json.loads(capsys.readouterr().out)
  229. assert result['status']=='FAIL' and result['exit_code']==7 and result['failure_download']['status']=='FAIL'