feat: require native EDIF geometry in engineering identity
This commit is contained in:
1 parent
63f3417f19
commit
89500cbb5f
2 files changed
+94
-5
No files matched your search
@@ -17,17 +17,18 @@ from .scoped_manifest import ManifestScope, build_manifest, hash_file
|
||||
POLICY = 'mentor795-native-content-v1'
|
||||
COVERAGE = {'logical_connectivity_and_properties': 'native hierarchy/flat ASCII and CSV',
|
||||
'physical_design_and_primary_assets': 'raw SHA256',
|
||||
'schematic_graphical_geometry': 'unproven', 'production_acceptance': False}
|
||||
'schematic_graphical_geometry': 'native EDIF schematic', 'production_acceptance': False}
|
||||
EXPORTER_PROOF = {
|
||||
'icdb2ascii.exe': 'e37c87356eaf57c0b97e4183458bc8c5eb6eb0ac497cc7ad40dcd585d8cd213b',
|
||||
'icdb2csv.exe': '22059f4a432e8eabf30a5326ebcbd463ed6fa6495af21d7aad5ab5d2f892f255',
|
||||
'edifExporter.exe': '8b5f9682007da5b759e7b2f0fa9720f6771b2efb9a546636b270a58e1268a80e',
|
||||
}
|
||||
INF_HEADER = (b'Design Name\tSystem Name\tSystem Version\tSystem_Date\tCompany_Name\tDepartment_Name'
|
||||
b'\tAddress\tAddress1\tCity\tState_Province\tCountry\tZip\tPhone\tPhone_Ext\tFax\tFax_Ext')
|
||||
CSV_SUFFIXES = ('', '.esf', '.inf', '.npr', '.ppn', '.ppr', '.prm', '.prt', '.pth',
|
||||
'.sht', '.spn', '.spr', '.sym', '.thn')
|
||||
_retained_exports = []
|
||||
_OWNER_NAMES = frozenset({'icdb2ascii.exe', 'icdb2csv.exe', 'icdbnetserver.exe',
|
||||
_OWNER_NAMES = frozenset({'icdb2ascii.exe', 'icdb2csv.exe', 'edifexporter.exe', 'icdbnetserver.exe',
|
||||
'icdbnetlauncher.exe', 'icdbservermanager.exe', 'icdbservermonitor.exe'})
|
||||
|
||||
|
||||
@@ -81,6 +82,61 @@ def normalize_inf(data):
|
||||
return lines[0]+b'\t'.join(values)+ending
|
||||
|
||||
|
||||
def normalize_edif(data, top):
|
||||
"""Bounded structural parse; replace only root/status/written/timestamp."""
|
||||
from datetime import datetime
|
||||
if not data or len(data) > 64*1024*1024:
|
||||
raise ValueError('EDIF report is empty or exceeds the supported parsing limit.')
|
||||
token_pattern = re.compile(rb'\s+|[()]|"(?:[^"\\]|\\.)*"|[^\s()"]+')
|
||||
stack, roots, nodes = [], [], []
|
||||
position = 0
|
||||
for match in token_pattern.finditer(data):
|
||||
if match.start() != position: raise ValueError('Malformed EDIF token.')
|
||||
position = match.end(); token = match.group()
|
||||
if token.isspace(): continue
|
||||
if token == b'(':
|
||||
node = {'start': match.start(), 'items': []}
|
||||
if stack: stack[-1]['items'].append(node)
|
||||
else: roots.append(node)
|
||||
nodes.append(node); stack.append(node)
|
||||
if len(stack) > 256 or len(nodes) > 1000000:
|
||||
raise ValueError('EDIF exceeds supported structural limits.')
|
||||
elif token == b')':
|
||||
if not stack: raise ValueError('Unbalanced EDIF report.')
|
||||
node = stack.pop(); node['end'] = match.end()
|
||||
if not node['items'] or not isinstance(node['items'][0], bytes):
|
||||
raise ValueError('EDIF node has no keyword.')
|
||||
else:
|
||||
if not stack: raise ValueError('Unexpected EDIF content outside the root.')
|
||||
stack[-1]['items'].append(token)
|
||||
if position != len(data) or stack or len(roots) != 1 or roots[0]['items'][0] != b'edif':
|
||||
raise ValueError('Unbalanced or unsupported EDIF root.')
|
||||
def children(node, tag):
|
||||
return [n for n in node['items'] if isinstance(n, dict) and n['items'][0] == tag]
|
||||
def one(node, tag):
|
||||
matches = children(node, tag)
|
||||
if len(matches) != 1: raise ValueError(f'EDIF requires one {tag!r} node in the expected context.')
|
||||
return matches[0]
|
||||
root = roots[0]
|
||||
if one(root, b'edifVersion')['items'] != [b'edifVersion', b'2', b'0', b'0']:
|
||||
raise ValueError('Unsupported EDIF version.')
|
||||
written = one(one(root, b'status'), b'written')
|
||||
if one(written, b'program')['items'][1] != b'"DxDesigner Edif Exporter"':
|
||||
raise ValueError('Unrecognized native EDIF exporter.')
|
||||
stamp = one(written, b'timestamp')
|
||||
values = stamp['items'][1:]
|
||||
if len(values) != 6 or any(not isinstance(v, bytes) or not v.isdigit() for v in values):
|
||||
raise ValueError('Malformed EDIF header timestamp.')
|
||||
datetime(*(int(v) for v in values))
|
||||
design = one(root, b'design')
|
||||
if one(design, b'cellRef')['items'][1] != top.encode('mbcs'):
|
||||
raise ValueError('EDIF top design differs from the requested RootBlock.')
|
||||
if (not any(n['items'] == [b'viewType', b'SCHEMATIC'] for n in nodes)
|
||||
or any(not any(n['items'][0] == tag for n in nodes) for tag in (b'page', b'figure', b'pt'))):
|
||||
raise ValueError('EDIF schematic drawing is absent or unsupported.')
|
||||
return data[:stamp['start']]+b'(timestamp <EXPORT_TIME>)'+data[stamp['end']:]
|
||||
|
||||
|
||||
def csv_identity(root):
|
||||
from .scoped_manifest import scan_tree
|
||||
root = Path(root)
|
||||
@@ -160,7 +216,7 @@ def asset_identity(source, expected_library):
|
||||
|
||||
def check_exporters(mentor_home):
|
||||
for name, expected in EXPORTER_PROOF.items():
|
||||
path = Path(mentor_home)/'iCDB/win32/bin'/name
|
||||
path = Path(mentor_home)/('wv/win32/bin' if name == 'edifExporter.exe' else 'iCDB/win32/bin')/name
|
||||
if not path.is_file() or hash_file(path) != expected:
|
||||
raise ValueError(f'Native identity exporter is not the proven EE7.9.5 binary: {path}')
|
||||
|
||||
@@ -177,6 +233,11 @@ def validate_export_output(kind, code, report, log):
|
||||
if 'iCDB to CSV complete' not in [line.strip() for line in text.splitlines()]:
|
||||
raise ValueError('Native CSV export lacks its completion marker.')
|
||||
csv_identity(report)
|
||||
elif kind == 'edif':
|
||||
if (not Path(report).is_file() or not Path(report).stat().st_size
|
||||
or 'Done' not in [line.strip() for line in text.splitlines()]
|
||||
or f'Dumping edif file {report} ...' not in text):
|
||||
raise ValueError('Native EDIF export lacks a complete nonempty drawing report.')
|
||||
else:
|
||||
raise ValueError('Unsupported native export kind.')
|
||||
|
||||
@@ -217,6 +278,9 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
|
||||
return {'success': False, 'safe_to_continue': False, 'detail': 'An existing iCDB owner prevents isolated identity export.'}
|
||||
if not _database_released(project.parent):
|
||||
return {'success': False, 'safe_to_continue': False, 'detail': 'Analysis copy has unreleased native addresses or DB handles.'}
|
||||
from .backup_recovery import _project_text
|
||||
_, _, top = source_project(project)
|
||||
database = (project.parent/re.findall(r'^KEY iCDBDir "([^"\r\n]+)"', _project_text(project), re.M)[0]).resolve()
|
||||
commands = [
|
||||
('ascii', [str(Path(mentor_home)/'iCDB/win32/bin/icdb2ascii.exe'),
|
||||
f'-project={project}', f'-file={root/"design.rpt"}', f'-clog={root/"ascii.log"}',
|
||||
@@ -224,6 +288,9 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
|
||||
('csv', [str(Path(mentor_home)/'iCDB/win32/bin/icdb2csv.exe'),
|
||||
f'-project={project}', '-snap=DxD', '-file=identity', f'-output={root/"tables"}',
|
||||
f'-clog={root/"csv.log"}', '-properties', '-nostrip'], root/'tables', root/'csv.log'),
|
||||
('edif', [str(Path(mentor_home)/'wv/win32/bin/edifExporter.exe'), '-schematic',
|
||||
'-icdb', str(database), '-isnap', 'DxD', '-top', top, '-o', str(root/'design.edf')],
|
||||
root/'design.edf', root/'edif-stdout.txt'),
|
||||
]
|
||||
for kind, command, report, log in commands:
|
||||
process = None
|
||||
@@ -272,7 +339,7 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
|
||||
else:
|
||||
for handle in handles.values(): handle.Close()
|
||||
_write_json(root/(kind+'-process.json'), record)
|
||||
return {'success': True, 'safe_to_continue': True, 'detail': 'Both native exports completed and released.'}
|
||||
return {'success': True, 'safe_to_continue': True, 'detail': 'All three native exports completed and released.'}
|
||||
|
||||
|
||||
def capture_identity(source, evidence_root, *, expected_library, owner_library, mentor_home,
|
||||
@@ -317,9 +384,11 @@ def capture_identity(source, evidence_root, *, expected_library, owner_library,
|
||||
else:
|
||||
ascii_bytes = normalize_ascii((root/'design.rpt').read_bytes(), top)
|
||||
csv = csv_identity(root/'tables')
|
||||
edif_bytes = normalize_edif((root/'design.edf').read_bytes(), top)
|
||||
if build_manifest(source.parent) != original:
|
||||
raise ValueError('Identity input changed while exporting its disposable copy.')
|
||||
fingerprint = {**assets, 'coverage': COVERAGE, 'ascii_sha256': _digest(ascii_bytes), 'csv': csv}
|
||||
fingerprint = {**assets, 'coverage': COVERAGE, 'ascii_sha256': _digest(ascii_bytes),
|
||||
'csv': csv, 'edif_sha256': _digest(edif_bytes)}
|
||||
outcome = IdentityOutcome(fingerprint, True, 'Native logical exports and primary assets captured.', root)
|
||||
except Exception as error:
|
||||
outcome = IdentityOutcome(None, owner_safe, str(error), root)
|
||||
|
||||
@@ -98,6 +98,7 @@ def test_capture_only_exports_fresh_copy_and_leaves_source_unchanged(project, tm
|
||||
assert clone.parent == root/'project' and clone != source
|
||||
(clone.parent/'database/icdb.dat').write_bytes(b'export changed disposable copy')
|
||||
(root/'design.rpt').write_bytes(ascii_report())
|
||||
(root/'design.edf').write_bytes(edif_report())
|
||||
return {'success': True, 'safe_to_continue': True, 'detail': ''}
|
||||
monkeypatch.setattr(identity, '_run_exports', exports)
|
||||
monkeypatch.setattr(identity, 'csv_identity', lambda _: {'work/identity': 'csv proof'})
|
||||
@@ -150,3 +151,22 @@ def test_export_timeout_retains_process_without_kill(project, tmp_path, monkeypa
|
||||
assert len(identity._retained_exports) == 1
|
||||
assert seen[0][-5:] == ['-f', '-h', '-c', '-t', '-nostrip']
|
||||
assert (root/'ascii-process.json').is_file()
|
||||
|
||||
|
||||
def edif_report(timestamp=b'2026 11 3 11 40 56'):
|
||||
return (b'(edif DxD (edifVersion 2 0 0) (status (written (timestamp '+timestamp+b')'
|
||||
b' (program "DxDesigner Edif Exporter"))) (library Board1 (cell Top'
|
||||
b' (view SCHEMATIC_VIEW (viewType SCHEMATIC) (page sheet1 (figure LINE (pt 1 2)))'
|
||||
b' (property timestamp (string "2026 11 3 11 40 56")))))'
|
||||
b' (design Board1 (cellRef Top (libraryRef Board1))))')
|
||||
|
||||
|
||||
def test_edif_only_normalizes_root_written_timestamp_preserving_geometry_and_properties():
|
||||
from cbb_refresh_verify.native_engineering_identity import normalize_edif
|
||||
first = edif_report()
|
||||
assert normalize_edif(first, 'Top') == normalize_edif(edif_report(b'2026 11 3 11 40 59'), 'Top')
|
||||
assert normalize_edif(first, 'Top') != normalize_edif(first.replace(b'(pt 1 2)', b'(pt 1 3)'), 'Top')
|
||||
assert normalize_edif(first, 'Top') != normalize_edif(first.replace(b'"2026 11 3 11 40 56"', b'"changed"'), 'Top')
|
||||
for bad in [first[:-1], first.replace(b'(edifVersion 2 0 0)', b'(edifVersion 1 0 0)'),
|
||||
first.replace(b'(cellRef Top', b'(cellRef Other'), first.replace(b'(pt 1 2)', b'')]:
|
||||
with pytest.raises(ValueError): normalize_edif(bad, 'Top')
|
||||
Reference in new issue
Block a user