|
|
@@ -4,11 +4,13 @@
|
|
|
from __future__ import annotations
|
|
|
|
|
|
import argparse
|
|
|
+import ast
|
|
|
import hashlib
|
|
|
import json
|
|
|
import os
|
|
|
import re
|
|
|
import signal
|
|
|
+import shutil
|
|
|
import subprocess
|
|
|
import sys
|
|
|
import tempfile
|
|
|
@@ -102,7 +104,8 @@ def cmd_test(args: argparse.Namespace) -> int:
|
|
|
unit_pass=unit_code==0 and unit_count>0 and unit_errors==0 and unit_skipped==0
|
|
|
receipt['unit']={'command':command,'exit_code':unit_code,'tests':unit_count,'skipped':unit_skipped,'status':'PASS' if unit_pass else 'FAIL','log':str(log_path),'log_sha256':hashlib.sha256(log_path.read_bytes()).hexdigest()}
|
|
|
print('Unit tests: '+('PASS' if unit_pass else 'FAIL')+'; '+str(log_path),flush=True)
|
|
|
- rtl_code=cmd_diagnose(argparse.Namespace(target='all' if len(products)==2 else products[0],run_root=out/'rtl',timeout=args.timeout))
|
|
|
+ rtl_code=cmd_diagnose(argparse.Namespace(target='all' if len(products)==2 else products[0],run_root=out/'rtl',
|
|
|
+ timeout=args.timeout,reuse_rtl=getattr(args,'reuse_rtl',None)))
|
|
|
receipt['rtl_result']=str(out/'rtl/RESULT.json');receipt['complete']=True
|
|
|
receipt['status']='PASS' if unit_pass and rtl_code==0 else 'FAIL'
|
|
|
receipt_path.write_text(json.dumps(receipt,indent=2)+'\n')
|
|
|
@@ -116,6 +119,140 @@ def cmd_package(args: argparse.Namespace) -> int:
|
|
|
return package_main(args.package_args)
|
|
|
|
|
|
|
|
|
+def _file_hash(path):
|
|
|
+ with Path(path).open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()
|
|
|
+
|
|
|
+def _json_hash(value):
|
|
|
+ return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':')).encode()).hexdigest()
|
|
|
+
|
|
|
+def _generator_dependencies():
|
|
|
+ pending=['tools/generate_target.py','tools/generate_6400_manual.py','tools/generate_mrdimm_params.py',
|
|
|
+ 'tools/generate_mrdimm_adc.py','tools/target_registry.py','tools/fw_targets.py']
|
|
|
+ found=set()
|
|
|
+ while pending:
|
|
|
+ name=pending.pop()
|
|
|
+ if name in found:continue
|
|
|
+ found.add(name)
|
|
|
+ for node in ast.walk(ast.parse((ROOT/name).read_text(encoding='utf-8-sig'))):
|
|
|
+ modules=[a.name for a in node.names] if isinstance(node,ast.Import) else (
|
|
|
+ [node.module,*[node.module+'.'+a.name for a in node.names]] if isinstance(node,ast.ImportFrom) and node.module else [])
|
|
|
+ for module in modules:
|
|
|
+ path=module.replace('.','/')+'.py'
|
|
|
+ if module.startswith('tools.') and (ROOT/path).is_file():pending.append(path)
|
|
|
+ return found
|
|
|
+
|
|
|
+def rtl_plan(products,tests,tools):
|
|
|
+ registry=load_registry(ROOT)
|
|
|
+ inputs={};steps=[]
|
|
|
+ generator_files=_generator_dependencies()
|
|
|
+ for product in products:
|
|
|
+ manifest_path='products/'+product+'/source-closure.json'
|
|
|
+ manifest=json.loads((ROOT/manifest_path).read_text(encoding='utf-8'))
|
|
|
+ sources=manifest['sources']
|
|
|
+ target=next(row for row in registry['targets'].values() if row['project_id']==product)
|
|
|
+ paths=set(sources)|generator_files|{manifest_path,'tools/fw_cli.py','projects/registry.json'}
|
|
|
+ paths.update(p.relative_to(ROOT).as_posix() for p in (ROOT/'contracts').glob('*') if p.suffix in ('.json','.yaml'))
|
|
|
+ for key in ('project_config','adc','sdc'):
|
|
|
+ if target.get(key):paths.add(target[key])
|
|
|
+ projects=[target['project_config']];seen_projects=set()
|
|
|
+ while projects:
|
|
|
+ name=projects.pop()
|
|
|
+ if name in seen_projects:continue
|
|
|
+ seen_projects.add(name);paths.add(name)
|
|
|
+ configuration=json.loads((ROOT/name).read_text(encoding='utf-8'))
|
|
|
+ if configuration.get('inherits'):projects.append(configuration['inherits'])
|
|
|
+ for key in ('board_evidence','constraints','source_closure'):
|
|
|
+ value=configuration.get(key)
|
|
|
+ if isinstance(value,str) and (ROOT/value).is_file():paths.add(value)
|
|
|
+ if product=='mrdimm-chamber':paths.add('config/pin_inventory.prod2u_door_temp_v1_2.json')
|
|
|
+ paths.update('tests/sim/'+name+'.v' for name in tests[product])
|
|
|
+ if product=='6400-front-rear':paths.add('src/modules/double_bank_target_store.v')
|
|
|
+ pending=list(paths)
|
|
|
+ while pending:
|
|
|
+ name=pending.pop()
|
|
|
+ if Path(name).suffix not in ('.v','.sv','.vh'):continue
|
|
|
+ for include in re.findall(chr(96)+r'include\s+"([^"]+)"',(ROOT/name).read_text(encoding='utf-8')):
|
|
|
+ path=include if (ROOT/include).is_file() else (Path(name).parent/include).as_posix()
|
|
|
+ if path not in paths:paths.add(path);pending.append(path)
|
|
|
+ inputs[product]={name:_file_hash(ROOT/name) for name in sorted(paths)}
|
|
|
+ source_args=[name for name in sources if name.endswith('.v')]
|
|
|
+ for top,behavior in [(manifest['top_module'],False),*((name,True) for name in tests[product])]:
|
|
|
+ if not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*',top):raise ValueError('invalid regression top')
|
|
|
+ binary='{run_root}/'+top+'.vvp'
|
|
|
+ command=['iverilog','-g2012','-Wall','-I.','-B',tools['iverilog']['library_root'],'-s',top,'-o',binary,*source_args]
|
|
|
+ if behavior:
|
|
|
+ command.append('tests/sim/'+top+'.v')
|
|
|
+ if top=='prod2u_6400_uart_e2e_tb':command.append('src/modules/double_bank_target_store.v')
|
|
|
+ steps.append({'name':top+'-compile','command':command,'marker':None,'binary':top+'.vvp'})
|
|
|
+ if behavior:steps.append({'name':top,'command':['vvp',binary,'+ARTIFACT_DIR={run_root}'],'marker':top+' PASS','binary':None})
|
|
|
+ if len({x['name'] for x in steps})!=len(steps):raise ValueError('duplicate regression output names')
|
|
|
+ return {'schema':'prod2u-rtl-input-closure-v1','inputs':inputs,'tools':tools,
|
|
|
+ 'test_configuration':{p:tests[p] for p in products},'steps':steps}
|
|
|
+
|
|
|
+def _render_command(step,run_root):
|
|
|
+ return [arg.replace('{run_root}',str(run_root)) for arg in step['command']]
|
|
|
+
|
|
|
+def validate_rtl_cache(path,plan):
|
|
|
+ path=Path(path).resolve();receipt_bytes=path.read_bytes();cached=json.loads(receipt_bytes)
|
|
|
+ if cached.get('schema')!='prod2u-rtl-regression-v2' or cached.get('status')!='PASS' or cached.get('complete') is not True:
|
|
|
+ raise ValueError('RTL_REUSE_REJECTED: only complete v2 PASS receipts can be reused')
|
|
|
+ key=_json_hash(plan)
|
|
|
+ if cached.get('cache_key')!=key or cached.get('plan')!=plan:
|
|
|
+ raise ValueError('RTL_REUSE_REJECTED: input/tool/command closure differs')
|
|
|
+ if not plan['steps'] or cached.get('inputs')!=plan['inputs']:
|
|
|
+ raise ValueError('RTL_REUSE_REJECTED: empty or inconsistent input evidence')
|
|
|
+ origin=cached.get('source',{})
|
|
|
+ if any(not re.fullmatch('[0-9a-f]{40}',str(origin.get(k,''))) or origin.get(k)!=cached.get(k) for k in ('commit','tree')):
|
|
|
+ raise ValueError('RTL_REUSE_REJECTED: source identity missing or inconsistent')
|
|
|
+ rows=cached.get('results',[])
|
|
|
+ if len(rows)!=len(plan['steps']) or cached.get('expected_check_count')!=len(rows):
|
|
|
+ raise ValueError('RTL_REUSE_REJECTED: missing checks')
|
|
|
+ native_root=cached.get('native_run_root')
|
|
|
+ if not native_root or not Path(native_root).is_absolute():raise ValueError('RTL_REUSE_REJECTED: native command root missing')
|
|
|
+ copies={}
|
|
|
+ for expected,row in zip(plan['steps'],rows):
|
|
|
+ command=_render_command(expected,native_root)
|
|
|
+ name=expected['name']+'.log'
|
|
|
+ if (row.get('name')!=expected['name'] or row.get('command')!=command or row.get('required_marker')!=expected['marker']
|
|
|
+ or row.get('status')!='PASS' or row.get('exit_code')!=0 or row.get('log')!=name):
|
|
|
+ raise ValueError('RTL_REUSE_REJECTED: result/command mismatch')
|
|
|
+ data=(path.parent/name).read_bytes()
|
|
|
+ if hashlib.sha256(data).hexdigest()!=row.get('log_sha256'):raise ValueError('RTL_REUSE_REJECTED: log hash mismatch')
|
|
|
+ text=data.decode('utf-8',errors='replace')
|
|
|
+ lines=text.splitlines()
|
|
|
+ if not lines or json.loads(lines[0])!=command or (expected['marker'] and expected['marker'] not in text):
|
|
|
+ raise ValueError('RTL_REUSE_REJECTED: native log/marker mismatch')
|
|
|
+ copies[name]=data
|
|
|
+ artifacts=cached.get('artifacts',{})
|
|
|
+ required={step['binary'] for step in plan['steps'] if step['binary']}
|
|
|
+ if not required<=set(artifacts):raise ValueError('RTL_REUSE_REJECTED: compiled binaries missing')
|
|
|
+ for name,expected_hash in artifacts.items():
|
|
|
+ if not re.fullmatch(r'[A-Za-z0-9_.-]+\.(vvp|hex)',name):
|
|
|
+ raise ValueError('RTL_REUSE_REJECTED: invalid artifact name')
|
|
|
+ data=(path.parent/name).read_bytes()
|
|
|
+ if not data or hashlib.sha256(data).hexdigest()!=expected_hash:raise ValueError('RTL_REUSE_REJECTED: artifact hash mismatch')
|
|
|
+ copies[name]=data
|
|
|
+ return cached,copies,receipt_bytes
|
|
|
+
|
|
|
+def _rtl_tools():
|
|
|
+ result={}
|
|
|
+ driver=Path(shutil.which('iverilog') or '')
|
|
|
+ requested=os.environ.get('PROD2U_IVERILOG_LIBDIR')
|
|
|
+ candidates=[Path(requested)] if requested else [driver.parent.parent/'lib/ivl',*sorted(Path('/usr/lib').glob('*/ivl'))]
|
|
|
+ library=next((p.resolve() for p in candidates if (p/'ivl').is_file() and (p/'ivlpp').is_file()),None)
|
|
|
+ if library is None:raise ValueError('Icarus backend directory unavailable; set PROD2U_IVERILOG_LIBDIR')
|
|
|
+ for tool in ('iverilog','vvp'):
|
|
|
+ path=Path(shutil.which(tool) or '')
|
|
|
+ if not path.is_file():raise ValueError('RTL tool missing: '+tool)
|
|
|
+ version=subprocess.check_output([tool,*(['-B',str(library)] if tool=='iverilog' else []),'-V'],stderr=subprocess.STDOUT)
|
|
|
+ result[tool]={'path':str(path.resolve()),'sha256':_file_hash(path),'version':version.decode(errors='replace').splitlines()[0],
|
|
|
+ 'version_output_sha256':hashlib.sha256(version).hexdigest()}
|
|
|
+ result['iverilog']['library_root']=str(library)
|
|
|
+ result['iverilog']['library_files']={p.relative_to(library).as_posix():_file_hash(p) for p in sorted(library.rglob('*')) if p.is_file()}
|
|
|
+ import yaml
|
|
|
+ result['python']=sys.version;result['PyYAML']=yaml.__version__
|
|
|
+ return result
|
|
|
+
|
|
|
def cmd_diagnose(args: argparse.Namespace) -> int:
|
|
|
"""Bounded migrated RTL checks; explicitly not the full Quick/Full gate."""
|
|
|
if sys.platform != "linux":
|
|
|
@@ -123,7 +260,6 @@ def cmd_diagnose(args: argparse.Namespace) -> int:
|
|
|
out = args.run_root.resolve()
|
|
|
if out == ROOT or ROOT in out.parents:
|
|
|
return _die("--run-root must be outside the source checkout")
|
|
|
- out.mkdir(parents=True, exist_ok=False)
|
|
|
products = ("6400-front-rear", "mrdimm-chamber") if args.target == "all" else (args.target,)
|
|
|
test_manifest_path=ROOT/'config/current-product-tests.json'
|
|
|
test_manifest=json.loads(test_manifest_path.read_text(encoding='utf-8'))
|
|
|
@@ -132,15 +268,30 @@ def cmd_diagnose(args: argparse.Namespace) -> int:
|
|
|
tests={name:entry['testbenches'] for name,entry in test_manifest['targets'].items()}
|
|
|
if any(not tests[p] for p in products):
|
|
|
return _die('empty current product test set')
|
|
|
- receipt = {"scope": "migration-diagnostic-only", "run_id": out.name,
|
|
|
- "hardware": "NOT_RUN", "results": [], "inputs": {}, "status": "RUNNING", "complete": False,
|
|
|
- "expected_check_count": sum(1 + 2 * len(tests[p]) for p in products)}
|
|
|
+ for product in products:_generate_one(product,check=True)
|
|
|
+ plan=rtl_plan(products,tests,_rtl_tools())
|
|
|
identity=source_identity(ROOT)
|
|
|
+ reuse=getattr(args,'reuse_rtl',None)
|
|
|
+ if reuse:
|
|
|
+ cached,copies,receipt_bytes=validate_rtl_cache(reuse,plan)
|
|
|
+ out.mkdir(parents=True,exist_ok=False)
|
|
|
+ for name,data in copies.items():(out/name).write_bytes(data)
|
|
|
+ receipt={**cached,'run_id':out.name,'source':identity,'commit':identity['commit'],'tree':identity['tree'],
|
|
|
+ 'execution':'reused','reuse':{'receipt':str(Path(reuse).resolve()),'sha256':hashlib.sha256(receipt_bytes).hexdigest(),
|
|
|
+ 'source':cached['source'],'scope':'copied verified native evidence; no RTL command rerun'}}
|
|
|
+ (out/'REUSED-RECEIPT.json').write_bytes(receipt_bytes)
|
|
|
+ (out/'RESULT.json').write_text(json.dumps(receipt,indent=2)+'\n',encoding='utf-8')
|
|
|
+ print('RTL evidence reused after exact closure/log/artifact checks: '+str(reuse),flush=True)
|
|
|
+ return 0
|
|
|
+ out.mkdir(parents=True,exist_ok=False)
|
|
|
+ receipt = {"schema":"prod2u-rtl-regression-v2","scope": "migration-diagnostic-only", "run_id": out.name,
|
|
|
+ "hardware": "NOT_RUN", "results": [], "inputs": {}, "status": "RUNNING", "complete": False,
|
|
|
+ "expected_check_count":len(plan['steps']),"plan":plan,"cache_key":_json_hash(plan),
|
|
|
+ "native_run_root":str(out),"execution":"fresh"}
|
|
|
receipt['commit']=identity['commit'];receipt['tree']=identity['tree'];receipt['source']=identity
|
|
|
- for tool, flag in (("iverilog", "-V"), ("vvp", "-V")):
|
|
|
- receipt[tool] = subprocess.check_output([tool, flag], stderr=subprocess.STDOUT, text=True).splitlines()[0]
|
|
|
+ for tool in ('iverilog','vvp'):receipt[tool]=plan['tools'][tool]['version']
|
|
|
|
|
|
- def execute(name: str, command: list[str], marker: str | None = None) -> bool:
|
|
|
+ def execute(name: str, command: list[str], marker: str | None = None,binary=None) -> bool:
|
|
|
log_path = out / (name + ".log")
|
|
|
with log_path.open("w", encoding="utf-8") as log:
|
|
|
log.write(json.dumps(command) + "\n"); log.flush()
|
|
|
@@ -150,7 +301,7 @@ def cmd_diagnose(args: argparse.Namespace) -> int:
|
|
|
except subprocess.TimeoutExpired:
|
|
|
os.killpg(process.pid, signal.SIGKILL); process.wait(); code = 124
|
|
|
observed = log_path.read_text(errors="replace")
|
|
|
- passed = code == 0 and (marker is None or marker in observed)
|
|
|
+ passed = code == 0 and (marker is None or marker in observed) and (not binary or ((out/binary).is_file() and (out/binary).stat().st_size>0))
|
|
|
receipt["results"].append({"name": name, "command": command, "exit_code": code,
|
|
|
"status": "PASS" if passed else "FAIL", "required_marker": marker,
|
|
|
"log": log_path.name, "log_sha256": hashlib.sha256(log_path.read_bytes()).hexdigest()})
|
|
|
@@ -160,34 +311,15 @@ def cmd_diagnose(args: argparse.Namespace) -> int:
|
|
|
print(f"{name}: {'PASS' if passed else 'FAIL'}", flush=True)
|
|
|
return passed
|
|
|
|
|
|
- for product in products:
|
|
|
- manifest_path = ROOT / "products" / product / "source-closure.json"
|
|
|
- manifest = json.loads(manifest_path.read_text())
|
|
|
- sources = manifest["sources"]
|
|
|
- benches = tests[product]
|
|
|
- contract_paths = ["contracts/6400-manual.yaml"] if product == "6400-front-rear" else ["contracts/mrdimm-wire.yaml", "projects/mrdimm-chamber/project.json"]
|
|
|
- input_paths = set(sources + contract_paths + [f"tests/sim/{test}.v" for test in benches])
|
|
|
- input_paths.add(manifest_path.relative_to(ROOT).as_posix())
|
|
|
- # Include transitive generated headers imported by the mailbox.
|
|
|
- input_paths.update(p.relative_to(ROOT).as_posix() for p in (ROOT / "generated").rglob("*.vh"))
|
|
|
- input_paths.add("tools/fw_cli.py")
|
|
|
- input_paths.add("config/current-product-tests.json")
|
|
|
- input_paths.update(p.relative_to(ROOT).as_posix() for p in (ROOT / "tests/sim").glob("*.vh"))
|
|
|
- if product == "6400-front-rear":
|
|
|
- input_paths.add("src/modules/double_bank_target_store.v")
|
|
|
- receipt["inputs"][product] = {p: hashlib.sha256((ROOT / p).read_bytes()).hexdigest() for p in sorted(input_paths)}
|
|
|
- source_args = [p for p in sources if p.endswith(".v")]
|
|
|
- for top, behavior in [(manifest["top_module"], False), *((test, True) for test in benches)]:
|
|
|
- binary = out / (top + ".vvp")
|
|
|
- argv = ["iverilog", "-g2012", "-Wall", "-I.", "-s", top, "-o", str(binary), *source_args]
|
|
|
- if behavior:
|
|
|
- argv.append(f"tests/sim/{top}.v")
|
|
|
- if top == "prod2u_6400_uart_e2e_tb":
|
|
|
- argv.append("src/modules/double_bank_target_store.v")
|
|
|
- if execute(top + "-compile", argv) and behavior:
|
|
|
- execute(top, ["vvp", str(binary), "+ARTIFACT_DIR=" + str(out)], top + " PASS")
|
|
|
+ receipt['inputs']=plan['inputs']
|
|
|
+ compile_pass={}
|
|
|
+ for step in plan['steps']:
|
|
|
+ if step['binary']:
|
|
|
+ compile_pass[step['name'].removesuffix('-compile')]=execute(step['name'],_render_command(step,out),None,step['binary'])
|
|
|
+ elif compile_pass.get(step['name']):
|
|
|
+ execute(step['name'],_render_command(step,out),step['marker'])
|
|
|
receipt["complete"] = True
|
|
|
- receipt["artifacts"] = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in out.glob("*.hex")}
|
|
|
+ receipt["artifacts"] = {p.name: _file_hash(p) for p in out.iterdir() if p.suffix in (".hex",".vvp")}
|
|
|
receipt["status"] = "PASS" if len(receipt["results"]) == receipt["expected_check_count"] and all(
|
|
|
item["status"] == "PASS" for item in receipt["results"]) else "FAIL"
|
|
|
(out / "RESULT.json").write_text(json.dumps(receipt, indent=2) + "\n")
|
|
|
@@ -205,10 +337,12 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
tes.add_argument("target")
|
|
|
tes.add_argument("--run-root",type=Path)
|
|
|
tes.add_argument("--timeout",type=int,default=180)
|
|
|
+ tes.add_argument("--reuse-rtl",type=Path,help="reuse only matching complete RTL evidence; Python tests still run")
|
|
|
diag = sub.add_parser("diagnose", help="bounded migration tests; not Full acceptance")
|
|
|
diag.add_argument("target", choices=("all", "6400-front-rear", "mrdimm-chamber"))
|
|
|
diag.add_argument("--run-root", type=Path, required=True)
|
|
|
diag.add_argument("--timeout", type=int, default=60)
|
|
|
+ diag.add_argument("--reuse-rtl",type=Path,help="verified v2 RTL receipt; mismatches reject instead of silently rerunning")
|
|
|
bld = sub.add_parser("build")
|
|
|
bld.add_argument("target")
|
|
|
bld.add_argument("--run-root",type=Path)
|