endomorphosis's picture
Publish screened CVEfixes source spans from all three pinned shards
e134a8d verified
Raw History Blame Contribute Delete
20.5 kB
#!/usr/bin/env python3
"""Offline materialized-release integrity check (stdlib + PyArrow; no project imports).
Reconstructs normalized source rows and native CIDs, binds the original scan
receipts, and checks lossless spans. It does not rerun the native scanner,
execute source content, prove semantics, or establish repository licensing.
"""
import argparse
import base64
from collections import Counter, defaultdict
from decimal import Decimal
import hashlib
import json
from pathlib import Path, PurePosixPath
import re
import sys
import unicodedata
from urllib.parse import urlsplit
import pyarrow.parquet as pq
BODY = ('cve_description', 'cwe_description', 'commit_message', 'diff_with_context', 'vulnerable_code', 'fixed_code')
PROSE = set(BODY[:3])
RECORD_KEYS = set('source_cid row_index split component_id repository_family cve_id commit_hash file_paths_json origin_json row_template_json scan_json raw_description_container_sha256'.split())
SOURCE_KEYS = set('source_field_id source_cid field field_index split text text_sha256 description_language raw_description_container_sha256'.split())
SPAN_KEYS = set('schema policy_id source_cid field field_index raw_body_sha256 text normalized_text start_char end_char start_byte end_byte span_id span_text_sha256 kind status candidate_eligible word_count char_count exceeds_candidate_limit reasons requires_file_context complete_compilation_unit source_semantics_verified truncated source_field_id split'.split())
SPLITS = ('train', 'validation', 'test')
def check(ok, message):
if not ok:
raise ValueError(message)
def wire(value, ascii=False):
return json.dumps(value, sort_keys=True, ensure_ascii=ascii, separators=(',', ':'), allow_nan=False)
def sha(value):
return hashlib.sha256(value).hexdigest()
def file_sha(path):
value = hashlib.sha256()
with path.open('rb') as stream:
for block in iter(lambda: stream.read(4 * 1024 * 1024), b''):
value.update(block)
return value.hexdigest()
def decode(value):
result = json.loads(value)
check(wire(result) == value, 'noncanonical JSON column')
return result
def native(value):
"""Fixed ir-canonical-json-v1 profile with default ordered collections."""
if value is None or type(value) is bool:
return json.dumps(value)
if type(value) is str:
return json.dumps(unicodedata.normalize('NFC', value), ensure_ascii=False)
if type(value) is int:
return str(value)
if type(value) is float:
number = Decimal(repr(value))
check(number.is_finite(), 'nonfinite native number')
result = format(number, 'f')
return '0' if number.is_zero() else result.rstrip('0').rstrip('.') if '.' in result else result
if type(value) is list:
return '[' + ','.join(native(item) for item in value) + ']'
check(type(value) is dict and all(type(k) is str for k in value), 'unsupported native value')
normalized = {unicodedata.normalize('NFC', key): item for key, item in value.items()}
check(len(normalized) == len(value), 'NFC key collision')
return '{' + ','.join(native(key) + ':' + native(normalized[key]) for key in sorted(normalized)) + '}'
def row_cid(row):
envelope = {'canonicalization': 'ir-canonical-json-v1', 'collection_semantics': {},
'domain': 'cvefixes-security-ir/pinned-source-row', 'identity_profile': 'ir-canonical-identity-v1',
'payload': {'dataset_id': 'hitoshura25/cvefixes', 'row': row,
'source_revision': 'd4f5c4ea65329d9ccbb8a3b3149e5d06eda5edb2'},
'schema_version': 'cvefixes-pinned-source-row/v1'}
raw = bytes.fromhex('01551220') + hashlib.sha256(native(envelope).encode()).digest()
return 'b' + base64.b32encode(raw).decode().rstrip('=').lower()
def family(url):
parsed = urlsplit(url)
return parsed.netloc.casefold() + '/' + parsed.path.strip('/').removesuffix('.git').casefold()
def has_text(value):
return type(value) is str or type(value) is list and any(has_text(x) for x in value) or type(value) is dict and any(has_text(x) for x in value.values())
def verify(root):
root = Path(root).resolve()
manifest = json.loads((root / 'manifest.json').read_text())
check(manifest['schema'] == 'cvefixes-public-source-span-release/v1', 'release schema differs')
entries = {entry['path']: entry for entry in manifest['files']}
check(len(entries) == len(manifest['files']), 'duplicate listed path')
actual = set()
for path in root.rglob('*'):
check(not path.is_symlink(), 'materialized release required')
if path.is_file(): actual.add(path.relative_to(root).as_posix())
check(actual - {'manifest.json', '.gitattributes'} == set(entries), 'file allowlist differs')
tables = {name: [] for name in ('records', 'sources', 'spans', 'exclusions')}
schemas = {}
for name, entry in entries.items():
path = PurePosixPath(name)
check(not path.is_absolute() and '..' not in path.parts and path.as_posix() == name and '\\' not in name, 'unsafe release path')
check((root / name).stat().st_size == entry['size_bytes'] and file_sha(root / name) == entry['sha256'], 'file digest/size differs')
if not name.endswith('.parquet'): continue
match = re.fullmatch(r'data/(records|sources|spans|exclusions)/(train|validation|test)/part-[0-9]{6}\.parquet', name)
check(match is not None, 'unexpected Parquet path')
table_name, split = match.groups()
check(entry['table'] == table_name and entry['split'] == split, 'shard metadata differs')
table = pq.ParquetFile(root / name).read()
check(table.num_rows == entry['rows'] and 0 < table.num_rows <= 4096, 'shard row bound differs')
if table_name in schemas: check(schemas[table_name].equals(table.schema, check_metadata=False), 'inconsistent table schema')
schemas[table_name] = table.schema
rows = table.to_pylist()
check(all(row.get('split', 'train') == split for row in rows), 'row split differs from file')
tables[table_name].extend(rows)
screening = json.loads((root / 'screening-report.json').read_text())
check(screening['source_repo'] == 'Publicus/cvefixes-security-ir-graphrag' and screening['source_revision'] == '6fd5918bed34f8851430e74a149502587a953fe2', 'source pin differs')
check(screening['counts']['rows_considered'] == 12987 and screening['export_profile'] == 'cvefixes-screened-source-spans/v1', 'screening scope differs')
check(screening['native_digest_only_public_profile_used_for_body_publication'] is False and screening['benchmark_decontamination_complete'] is False, 'publication/decontamination claims differ')
sources, records, used, offsets, candidate_groups = {}, {}, set(), {}, defaultdict(set)
for source in tables['sources']:
check(set(source) == SOURCE_KEYS and source['source_field_id'] not in sources, 'source field schema/identity differs')
check(source['field'] in BODY and type(source['field_index']) is int and source['field_index'] >= 0 and source['text'], 'invalid source field')
check(sha(source['text'].encode()) == source['text_sha256'], 'source body digest differs')
identity = {'schema': 'cvefixes-source-field/v1', **{key: source[key] for key in ('source_cid', 'field', 'field_index', 'text_sha256')}}
check(source['source_field_id'] == 'sha256:' + sha(wire(identity).encode()), 'source field ID differs')
sources[source['source_field_id']] = source
fences = defaultdict(list); presence = {key: Counter() for key in BODY}
row_indexes = set()
for record in tables['records']:
check(set(record) == RECORD_KEYS and record['source_cid'] not in records and record['row_index'] not in row_indexes, 'duplicate/invalid source record')
row, origin, scan = (decode(record[key]) for key in ('row_template_json', 'origin_json', 'scan_json'))
def resolve(value, field, index=0, language=None):
if value is None or value == '': return value
check(type(value) is dict and set(value) == {'source_field_id'}, 'unreferenced raw body in row template')
key = value['source_field_id']; check(key in sources and key not in used, 'missing/reused body reference')
source = sources[key]; used.add(key)
check((source['source_cid'], source['field'], source['field_index'], source['split'], source['description_language']) == (record['source_cid'], field, index, record['split'], language), 'source reference binding differs')
check(source['raw_description_container_sha256'] == (record['raw_description_container_sha256'] if field == 'cve_description' else None), 'description container binding differs')
return source['text']
for field in BODY:
if field == 'cve_description':
for index, description in enumerate(row[field]): description['value'] = resolve(description['value'], field, index, description['lang'])
else: row[field] = resolve(row[field], field)
presence[field]['null' if row[field] is None else 'empty' if not row[field] else 'nonempty'] += 1
check(row_cid(row) == record['source_cid'], 'native canonical source CID differs')
check(scan['findings'] == [] and scan['record_sha256'] == sha(wire(row, ascii=True).encode()) and scan['policy_sha256'] == screening['native_scan_policy_sha256'], 'zero-finding scan receipt binding differs')
check(scan['fields_scanned'] == sorted(key for key, value in row.items() if has_text(value)), 'native scan field coverage differs')
check(row['row_index'] == record['row_index'] == origin['source_row_index'] and origin['source_status'] == 'admitted' and origin['security_ir_source_cid'] == record['source_cid'], 'parent row routing differs')
pin = screening['source_shards'][record['row_index'] // 4329]
check(origin['source_shard_row_index'] == record['row_index'] % 4329 and origin['source_shard_path'] == pin['source_path'] and origin['source_shard_cid'] == pin['content_id'] and origin['relative_path'] == pin['release_path'], 'parent shard routing differs')
check(row['cve_id'] == record['cve_id'] and row['hash'] == record['commit_hash'] and decode(record['file_paths_json']) == row['file_paths'] and record['repository_family'] == family(row['repo_url']), 'record metadata differs')
check(record['repository_family'] != 'github.com/bottlepy/bottle', 'known benchmark family was retained')
for key, value in [('repository', record['repository_family']), ('cve', row['cve_id']), ('commit', row['hash'])] + [('body', sha(row[field].encode())) for field in BODY[-2:] if row[field]]:
if value: fences[(key, value)].append(record['source_cid'])
records[record['source_cid']] = record; row_indexes.add(record['row_index'])
check(used == set(sources), 'unreferenced source fields published')
parents = {key: key for key in records}
def find(key):
while parents[key] != key: parents[key] = parents[parents[key]]; key = parents[key]
return key
for group in fences.values():
for key in group[1:]: parents[find(key)] = find(group[0])
components = defaultdict(list)
for key in records: components[find(key)].append(key)
for group in components.values():
group.sort(); component_id = 'sha256:' + sha(wire(group).encode())
bucket = int.from_bytes(hashlib.sha256(('cvefixes-source-span-development/v1\n' + group[0]).encode()).digest()[:8], 'big') % 100
split = 'train' if bucket < 80 else 'validation' if bucket < 90 else 'test'
check(all(records[key]['component_id'] == component_id and records[key]['split'] == split for key in group), 'grouped component/split assignment differs')
span_ids, statuses, chars, bytes_count = set(), Counter(), 0, 0
for span in tables['spans']:
check(set(span) == SPAN_KEYS and span['span_id'] not in span_ids and span['source_field_id'] in sources, 'span schema/identity differs')
span_ids.add(span['span_id']); source = sources[span['source_field_id']]; text = span['text']
check((span['source_cid'], span['field'], span['field_index'], span['raw_body_sha256'], span['split']) == (source['source_cid'], source['field'], source['field_index'], source['text_sha256'], source['split']), 'span parent differs')
start, byte_start = offsets.get(span['source_field_id'], (0, 0)); raw = text.encode()
check(span['start_char'] == start and span['start_byte'] == byte_start and span['end_char'] == start + len(text) and span['end_byte'] == byte_start + len(raw) and text and source['text'][start:span['end_char']] == text, 'span gap/overlap or Unicode/UTF-8 selector differs')
offsets[span['source_field_id']] = (span['end_char'], span['end_byte'])
identity = {key: span[key] for key in ('schema', 'policy_id', 'source_cid', 'field', 'field_index', 'raw_body_sha256')}
identity['selector'] = {key: span[key] for key in ('start_char', 'end_char', 'start_byte', 'end_byte')}
check(span['schema'] == 'security-ir-source-span/v1' and span['policy_id'] == 'cvefixes-security-source-spans/v1' and span['span_id'] == 'sha256:' + sha(wire(identity).encode()) and span['span_text_sha256'] == sha(raw), 'span canonical identity differs')
exceeds = len(text.split()) > 48 or len(text) > 4096
check(span['normalized_text'] == re.sub(r'\s+', ' ', text).strip() and span['word_count'] == len(text.split()) and span['char_count'] == len(text) and span['exceeds_candidate_limit'] == exceeds, 'span auxiliary text/count differs')
check(span['requires_file_context'] == (span['field'] not in PROSE) and all(span[k] is False for k in ('complete_compilation_unit', 'source_semantics_verified', 'truncated')), 'span context/authority claims differ')
if not text.strip(): expected, reasons = 'excluded_whitespace', ['whitespace_only']; check(span['kind'] == 'whitespace', 'whitespace kind differs')
elif span['field'] in PROSE:
expected = 'oversize' if exceeds else 'candidate'; reasons = (['prose_word_limit'] if len(text.split()) > 48 else []) + (['prose_character_limit'] if len(text) > 4096 else [])
check(span['kind'] == 'prose_sentence', 'prose kind differs')
else:
expected, reasons = 'context_required', ['requires_file_context']
check(span['kind'] in ({'code_context'} if span['field'] in BODY[-2:] else {'diff_context', 'diff_hunk'}), 'code/diff kind differs')
if expected == 'candidate':
candidate_groups[span['normalized_text'].casefold()].add(span['split'])
check(span['status'] in {'candidate', 'excluded_cross_partition_duplicate'}, 'candidate disposition differs')
reasons = [] if span['status'] == 'candidate' else ['cross_partition_duplicate']
else: check(span['status'] == expected, 'span disposition differs')
check(span['reasons'] == reasons and span['candidate_eligible'] == (span['status'] == 'candidate'), 'span reason/eligibility differs')
statuses[span['status']] += 1; chars += len(text); bytes_count += len(raw)
for source_id, source in sources.items(): check(offsets.get(source_id) == (len(source['text']), len(source['text'].encode())), 'source reconstruction incomplete')
for span in tables['spans']:
if span['status'] in {'candidate', 'excluded_cross_partition_duplicate'}: check(span['candidate_eligible'] == (len(candidate_groups[span['normalized_text'].casefold()]) == 1), 'cross-partition duplicate fence differs')
excluded_indexes, reasons = set(), Counter()
for row in tables['exclusions']:
check(set(row) == {'row_index', 'source_cid', 'reasons'} and type(row['row_index']) is int and row['row_index'] not in excluded_indexes and row['source_cid'] not in records and type(row['reasons']) is list and row['reasons'], 'exclusion leaked extra fields or duplicates retained row')
check(set(row['reasons']) <= set(screening['exclusion_reason_counts']), 'unrecognized exclusion reason')
excluded_indexes.add(row['row_index']); reasons.update(row['reasons'])
check(not row_indexes & excluded_indexes and row_indexes | excluded_indexes == set(range(12987)), 'original row accounting incomplete')
check(len(records) == screening['counts']['retained_rows'] and len(excluded_indexes) == screening['counts']['excluded_rows'] and dict(reasons) == screening['exclusion_reason_counts'], 'screening omission counts differ')
counts = {'original_rows_considered': 12987, 'retained_records': len(records), 'excluded_records': len(excluded_indexes),
'source_fields': len(sources), 'spans': len(span_ids), 'eligible_candidates': statuses['candidate']}
check(manifest['counts'] == counts and counts == {'original_rows_considered': 12987, 'retained_records': 9402,
'excluded_records': 3585, 'source_fields': 52243, 'spans': 197031, 'eligible_candidates': 42588}, 'complete release counts differ')
coverage = manifest['coverage']; source_chars = sum(len(s['text']) for s in sources.values()); source_bytes = sum(len(s['text'].encode()) for s in sources.values())
check(coverage['source_characters'] == coverage['represented_characters'] == chars == source_chars == 169398242
and coverage['source_utf8_bytes'] == coverage['represented_utf8_bytes'] == bytes_count == source_bytes == 169810611
and coverage['omitted_retained_source_characters'] == coverage['omitted_retained_source_bytes'] == 0, 'complete source coverage differs')
check(manifest['span_status_counts'] == dict(statuses) and manifest['span_kind_counts'] == dict(Counter(s['kind'] for s in tables['spans']))
and manifest['span_reason_counts'] == dict(Counter(reason for s in tables['spans'] for reason in s['reasons']))
and manifest['exclusion_reason_counts'] == dict(reasons), 'status/reason counts differ')
check(manifest['source_field_counts'] == dict(Counter(s['field'] for s in sources.values()))
and manifest['body_field_row_presence_counts'] == {k: dict(v) for k, v in presence.items()}, 'field/presence counts differ')
check(manifest['source_field_coverage'] == {field: {'characters': sum(len(s['text']) for s in sources.values() if s['field'] == field),
'utf8_bytes': sum(len(s['text'].encode()) for s in sources.values() if s['field'] == field)} for field in BODY}, 'field coverage differs')
check(manifest['split_counts'] == {name: {split: sum(r['split'] == split for r in tables[name]) for split in SPLITS}
for name in ('records', 'sources', 'spans')}, 'partition counts differ')
check(manifest['screening_report_sha256'] == file_sha(root / 'screening-report.json')
and manifest['source'] == {'repo_id': screening['source_repo'], 'revision': screening['source_revision'],
'manifest_sha256': screening['source_manifest_sha256'], 'original_row_index_sha256': screening['source_index_sha256'],
'original_shards': screening['source_shards'], 'upstream_license_provenance': screening['source_license_provenance']}, 'source provenance differs')
check(manifest['gold_formal_target_count'] == manifest['provider_calls'] == 0 and all(manifest[k] is False for k in
('formal_targets_generated', 'proof_authority', 'execution_authority', 'source_content_executed',
'native_digest_only_public_profile_used_for_body_publication', 'benchmark_decontamination_complete')), 'unsupported release authority claim')
return {'schema': 'cvefixes-span-release-verification/v1', 'status': 'passed', 'manifest_sha256': file_sha(root / 'manifest.json'),
'records': len(records), 'sources': len(sources), 'spans': len(span_ids), 'exclusions': len(excluded_indexes), 'span_status_counts': dict(statuses),
'represented_characters': chars, 'represented_utf8_bytes': bytes_count, 'native_parent_cids_reconstructed': True,
'zero_finding_scan_receipts_bound_to_rows': True, 'native_scanner_reexecuted': False, 'source_content_executed': False, 'network_calls': 0}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('release_root', type=Path)
try: print(wire(verify(parser.parse_args().release_root)))
except Exception as error: print(wire({'status': 'failed', 'error_type': type(error).__name__, 'message': str(error)}), file=sys.stderr); raise SystemExit(1)