| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258 |
- from argparse import Namespace
- import subprocess
- import json
- import os
- import sys
- import pytest
- from tools import remote_job as job
- @pytest.mark.parametrize('action,expected', [('quick','diagnose'),('td','build')])
- def test_firmware_alias_runs_canonical_entry_with_run_directory(tmp_path,action,expected):
- source=tmp_path/'source space';(source/'tools').mkdir(parents=True)
- (source/'tools/__init__.py').write_text('')
- (source/'tools/fw_cli.py').write_text('import json\ndef main(args):\n print(json.dumps(args)); return 7\n')
- a=Namespace(action=action,command=[],target='mrdimm-chamber')
- job.prepare_alias(a)
- run_root=tmp_path/'run space \u6d4b\u8bd5 $()'
- 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)
- assert p.returncode==7
- command=json.loads(p.stdout)
- assert command[:4]==[expected,'mrdimm-chamber','--run-root',str(run_root/'native')]
- assert a.task==action and a.action=='submit'
- def test_full_alias_requires_explicit_suite_and_keeps_command():
- a=Namespace(action='full',command=[])
- with pytest.raises(ValueError,match='explicit suite'):job.prepare_alias(a)
- a.command=['python3','suite with spaces.py','--seed','17']
- job.prepare_alias(a)
- assert a.action=='submit' and a.task=='full' and a.command[1]=='suite with spaces.py'
- def test_exact_snapshot_is_self_contained_and_reuse_preserves_changes(tmp_path):
- source=tmp_path/'repo';source.mkdir()
- def git(*args):
- return subprocess.check_output(['git','-C',str(source),*args],text=True).strip()
- git('init','-q');git('config','user.name','Fixture');git('config','user.email','fixture@example.invalid')
- (source/'file').write_text('first');git('add','file');git('commit','-qm','first')
- commit=git('rev-parse','HEAD');destination=tmp_path/'snapshot \u6d4b\u8bd5 space'
- first=job.snapshot(str(source),str(destination),commit)
- assert job.snapshot(str(source),str(destination),commit)==first
- assert not (destination/'.git/objects/info/alternates').exists()
- assert subprocess.run(['git','-C',str(destination),'symbolic-ref','-q','HEAD'],capture_output=True).returncode==1
- (destination/'unknown').write_text('preserve')
- with pytest.raises(ValueError,match='clean'):job.snapshot(str(source),str(destination),commit)
- assert (destination/'unknown').read_text()=='preserve'
- with pytest.raises(ValueError,match='full 40'):job.snapshot(str(source),str(tmp_path/'short'),commit[:8])
- assert not (tmp_path/'short').exists()
- (source/'file').write_text('second');git('commit','-qam','second')
- other=tmp_path/'different'
- job.snapshot(str(source),str(other),git('rev-parse','HEAD'))
- with pytest.raises(ValueError,match='different commit'):job.snapshot(str(source),str(other),commit)
- assert (other/'file').read_text()=='second'
- def test_high_level_ssh_forwards_action_without_local_execution(monkeypatch,capsys):
- import shlex
- calls=[]
- def run(command,**kwargs):
- calls.append(command)
- return subprocess.CompletedProcess(command,0,b'{"status":"running"}\n',b'')
- monkeypatch.setattr(job.subprocess,'run',run)
- assert job.main(['--ssh-runner','/snapshot \u4e2d\u6587/tools/remote_job.py','container-status'])==0
- assert shlex.split(calls[0][-1])==['python3','/snapshot \u4e2d\u6587/tools/remote_job.py','container-status']
- @pytest.mark.parametrize('action', ['doctor','container-up','container-stop','container-down','container-recreate','container-status'])
- def test_lifecycle_alias_uses_existing_controller_and_returns_failure(monkeypatch,action):
- real_path=job.Path
- class OutsideContainer:
- def exists(self):return False
- monkeypatch.setattr(job,'Path',lambda p: OutsideContainer() if str(p)=='/run/.containerenv' else real_path(p))
- monkeypatch.setattr(job.sys,'platform','linux')
- monkeypatch.setattr(job.os,'geteuid',lambda:0)
- seen=[]
- monkeypatch.setattr(job,'container_main',lambda args:seen.append(args) or 7)
- assert job.main([action,'--container','prod2u-test','--workspace','/exact source'])==7
- assert seen==[['--name','prod2u-test','--workspace','/exact source',action.removeprefix('container-')]]
- def test_sync_uses_local_source_and_process_scoped_lan_ssh(monkeypatch):
- before=os.environ.get('GIT_SSH_COMMAND');seen=[]
- def run(command,**kwargs):
- seen.append((command,kwargs));return subprocess.CompletedProcess(command,9)
- monkeypatch.setattr(job.subprocess,'run',run)
- assert job.main(['sync'])==9
- assert seen[0][0]==['git','-C',str(job.ROOT),'push','lan','HEAD']
- assert 'StrictHostKeyChecking=no' in seen[0][1]['env']['GIT_SSH_COMMAND']
- assert os.environ.get('GIT_SSH_COMMAND')==before
- def args(tmp_path):
- return Namespace(run_root=tmp_path,run_id='fixture',workspace=str(tmp_path),
- snapshot_id='snapshot',target='mrdimm-chamber',task='smoke',
- toolchain_id='test-image',container='prod2u-dev',heavy=False,
- command=['python3','-c','print("literal $() quoted")'])
- def test_duplicate_submit_starts_one_unit_and_conflict_does_not_overwrite(tmp_path,monkeypatch):
- a=args(tmp_path)
- monkeypatch.setattr(job,'source_binding',lambda p:{'workspace':str(p),'commit':'a'*40,'tree':'b'*40})
- monkeypatch.setattr(job,'boot_id',lambda:'boot')
- calls=[]
- def run(command,**kw):
- calls.append(command)
- return subprocess.CompletedProcess(command,0,'active\n' if command[0]=='systemctl' else '','')
- monkeypatch.setattr(job.subprocess,'run',run)
- first=job.submit(a);second=job.submit(a)
- assert first['identity']==second['identity']
- assert sum(x[0]=='systemd-run' for x in calls)==1
- assert first['spec']['command']==a.command
- original=(tmp_path/'fixture/SPEC.json').read_bytes()
- a.command=['false']
- with pytest.raises(ValueError,match='RUN_ID_CONFLICT'):job.submit(a)
- assert (tmp_path/'fixture/SPEC.json').read_bytes()==original
- assert sum(x[0]=='systemd-run' for x in calls)==1
- def test_empty_command_never_creates_run(tmp_path):
- a=args(tmp_path);a.command=[]
- with pytest.raises(ValueError,match='nonempty'):job.submit(a)
- assert not (tmp_path/'fixture').exists()
- @pytest.mark.parametrize('name',['../escape','/absolute','x/y','','.','..','bad name'])
- def test_invalid_run_paths_are_rejected(tmp_path,name):
- with pytest.raises(ValueError):job.job_dir(tmp_path,name)
- def test_boot_change_marks_interrupted_without_pid_or_unit_lookup(tmp_path,monkeypatch):
- folder=tmp_path/'run';folder.mkdir()
- job.save_status(folder,{'status':'RUNNING','boot_id':'previous-boot','unit':'old','process':{'pid':1}})
- monkeypatch.setattr(job,'boot_id',lambda:'new-boot')
- monkeypatch.setattr(job.subprocess,'run',lambda *a,**kw:pytest.fail('old unit must not be consulted after reboot'))
- result=job.refresh(folder)
- assert result['status']=='INTERRUPTED' and result['exit_code'] is None
- assert job.read(folder/'RESULT.json')['status']=='INTERRUPTED'
- def test_live_cgroup_is_not_declared_stopped_when_supervisor_unit_is_missing(tmp_path,monkeypatch):
- folder=tmp_path/'run';folder.mkdir()
- job.save_status(folder,{'status':'RUNNING','boot_id':'boot','unit':'old','job_cgroup':'/owned'})
- monkeypatch.setattr(job,'boot_id',lambda:'boot')
- monkeypatch.setattr(job,'populated',lambda path:True)
- monkeypatch.setattr(job.subprocess,'run',lambda *a,**kw:pytest.fail('live group is authoritative'))
- assert job.refresh(folder)['status']=='RUNNING'
- def test_transient_unit_query_failure_is_not_terminal(tmp_path,monkeypatch):
- folder=tmp_path/'run';folder.mkdir()
- job.save_status(folder,{'status':'QUEUED','boot_id':'boot','unit':'unit'})
- monkeypatch.setattr(job,'boot_id',lambda:'boot')
- monkeypatch.setattr(job.subprocess,'run',lambda *a,**kw:subprocess.CompletedProcess(a,1,'','bus unavailable'))
- with pytest.raises(RuntimeError,match='cannot inspect'):job.refresh(folder)
- assert job.read(folder/'RUN-STATUS.json')['status']=='QUEUED'
- assert not (folder/'RESULT.json').exists()
- def test_cancel_kills_only_bound_cgroup_and_rejects_stale_boot(tmp_path,monkeypatch):
- monkeypatch.setattr(job,'CGROOT',tmp_path);monkeypatch.setattr(job,'boot_id',lambda:'boot')
- state={'boot_id':'boot','identity':'a'*64,'container_cgroup':'/container',
- 'job_cgroup':'/container/prod2u-job-'+('a'*24)}
- path=tmp_path/state['job_cgroup'].lstrip('/');path.mkdir(parents=True)
- kill=path/'cgroup.kill';kill.write_text('0')
- job.kill_job_group(state);assert kill.read_text()=='1'
- kill.write_text('0');state['boot_id']='old'
- with pytest.raises(RuntimeError,match='stale'):job.kill_job_group(state)
- assert kill.read_text()=='0'
- def test_failed_command_cannot_be_reported_as_pass(tmp_path):
- folder=tmp_path/'run';folder.mkdir()
- job.save_status(folder,{'status':'RUNNING'})
- (folder/'stdout.log').write_text('native failure')
- assert job.finish(folder,7,None)==1
- result=job.read(folder/'RESULT.json')
- assert result['status']=='FAIL' and result['exit_code']==7
- assert result['artifacts'][0]['path']=='stdout.log'
- def test_cancel_before_heavy_lock_stops_only_its_unit(tmp_path,monkeypatch):
- folder=tmp_path/'queued';folder.mkdir()
- job.save_status(folder,{'status':'QUEUED','phase':'submit','boot_id':'boot','unit':job.unit_name(folder)})
- monkeypatch.setattr(job,'boot_id',lambda:'boot')
- calls=[]
- monkeypatch.setattr(job.subprocess,'run',lambda args,**kw:calls.append(args))
- result=job.cancel(folder)
- assert result['status']=='CANCELLED' and result['exit_code']==130
- assert calls==[['systemctl','stop',job.unit_name(folder)]]
- assert not (folder/'GO').exists()
- @pytest.mark.parametrize('status,phase',[('PASS','finished'),('RUNNING','command'),('QUEUED','container_start')])
- def test_repeated_worker_does_not_execute_again(tmp_path,monkeypatch,status,phase):
- folder=tmp_path/'worker';folder.mkdir()
- job.atomic(folder/'SPEC.json',{})
- job.save_status(folder,{'status':status,'phase':phase})
- monkeypatch.setattr(job.signal,'signal',lambda *args:None)
- assert job.launch_locked(folder,None)==0
- assert not (folder/'stdout.log').exists() and not (folder/'GO').exists()
- def test_failure_bundle_contains_native_result_and_small_wave_but_indexes_large_wave(tmp_path):
- import json,zipfile,hashlib
- folder=tmp_path/'run';folder.mkdir();(folder/'native').mkdir()
- job.save_status(folder,{'status':'RUNNING','run_id':'run'})
- (folder/'stderr.log').write_text('native failure')
- (folder/'native/RESULT.json').write_text('{"status":"FAIL","seed":42}')
- (folder/'native/window.vcd').write_bytes(b'$timescale 1ns $end\n#10\n')
- (folder/'native/full.fst').write_bytes(b'x'*(job.SMALL_WAVE_LIMIT+1))
- (folder/'native/output.bit').write_bytes(b'not a diagnostic')
- assert job.finish(folder,7,'native failed')==1
- state=job.read(folder/'RESULT.json');bundle=folder/state['failure_bundle']['path']
- assert hashlib.sha256(bundle.read_bytes()).hexdigest()==state['failure_bundle']['sha256']
- with zipfile.ZipFile(bundle) as archive:
- index=json.loads(archive.read('FAILURE-INDEX.json'))
- assert index['job_status']=='FAIL' and index['exit_code']==7
- assert archive.read('files/native/RESULT.json')==b'{"status":"FAIL","seed":42}'
- assert 'files/native/window.vcd' in archive.namelist()
- assert not any(name.endswith('full.fst') for name in archive.namelist())
- rows={x['path']:x for x in index['artifacts']}
- assert rows['native/full.fst']['disposition']=='remote_large_waveform'
- assert rows['native/output.bit']['disposition']=='remote_non_diagnostic_artifact'
- before=bundle.read_bytes()
- assert job.finish(folder,0,None)==1 and bundle.read_bytes()==before
- def test_bounded_diagnostics_label_tail_instead_of_claiming_complete_log(tmp_path,monkeypatch):
- import json,zipfile
- monkeypatch.setattr(job,'DIAGNOSTIC_LIMIT',32)
- folder=tmp_path/'run';folder.mkdir();(folder/'stderr.log').write_bytes(bytes(range(100)))
- job.save_status(folder,{'status':'FAIL','exit_code':7})
- with zipfile.ZipFile(folder/job.BUNDLE_NAME) as archive:
- index=json.loads(archive.read('FAILURE-INDEX.json'))
- row=index['artifacts'][0]
- assert row['disposition']=='tail_only' and row['included_bytes']==32
- assert archive.read(row['member'])==bytes(range(68,100))
- def test_diagnostic_error_does_not_mask_command_failure_or_overwrite_file(tmp_path):
- folder=tmp_path/'run';folder.mkdir();(folder/job.BUNDLE_NAME).write_bytes(b'preserve')
- job.save_status(folder,{'status':'FAIL','exit_code':7})
- state=job.read(folder/'RESULT.json')
- assert state['status']=='FAIL' and state['exit_code']==7
- assert 'failure_bundle_error' in state and 'failure_bundle' not in state
- assert (folder/job.BUNDLE_NAME).read_bytes()==b'preserve'
- def test_fetch_failure_keeps_remote_job_status_and_binds_archive_hash(tmp_path,monkeypatch):
- from tools import remote_transfer
- calls=[]
- def download(remote,source,destination,sha):
- calls.append((source,sha))
- destination.parent.mkdir(parents=True,exist_ok=True);destination.write_bytes(b'zip')
- return {'status':'PASS','destination':str(destination),'size':3,'sha256':sha,
- 'transferred_chunks':[0],'reused_chunks':[],'scope':'file byte integrity'}
- monkeypatch.setattr(remote_transfer,'download',download)
- state={'run_id':'failure','status':'FAIL','exit_code':7,
- 'failure_bundle':{'path':job.BUNDLE_NAME,'size':3,'sha256':'a'*64}}
- result=job.fetch_failure(state,'/data/prod2u/source/tools/remote_job.py','/data/prod2u/runs',tmp_path)
- assert result['status']=='PASS' and state['status']=='FAIL' and state['exit_code']==7
- assert calls==[('/data/prod2u/runs/failure/'+job.BUNDLE_NAME,'a'*64)]
- assert (tmp_path/'run-failure/TRANSFER-RECEIPT.json').is_file()
- def test_fetch_error_is_reported_separately_from_remote_failure(monkeypatch,capsys):
- import json
- state={'run_id':'failed','status':'FAIL','exit_code':7}
- monkeypatch.setattr(job.subprocess,'run',lambda *a,**kw:subprocess.CompletedProcess(a,0,json.dumps(state).encode(),b''))
- monkeypatch.setattr(job,'fetch_failure',lambda *a:(_ for _ in ()).throw(RuntimeError('download unavailable')))
- assert job.main(['--ssh-runner','/data/prod2u/source/tools/remote_job.py','status','failed'])==3
- result=json.loads(capsys.readouterr().out)
- assert result['status']=='FAIL' and result['exit_code']==7 and result['failure_download']['status']=='FAIL'
|