"""Convert bounded native observations into portable, byte-bound analysis files. No selection is performed here: native snapshots were taken before turnover. """ import copy import gzip import hashlib import json import math import struct import uuid from pathlib import Path MAX_ANALYSIS_BYTES = 256 * 1024 * 1024 METRIC_NAMES = ('total_score','total_speed','total_abs_steering','total_actual_distance', 'total_drifting_amount','total_momentum_change_frequency','total_throttle_change_frequency', 'total_braking_frequency','total_distance_from_wall','total_distance_from_center', 'network_novelty','collision_count','best_lap_performance','total_racing_line_efficiency') AVERAGE = set(METRIC_NAMES[:10]) AVERAGE_ONLY = {'total_abs_steering','total_momentum_change_frequency','total_throttle_change_frequency', 'total_braking_frequency','total_distance_from_wall','total_distance_from_center'} CHANNELS = [{'metric':metric,'type':kind} for metric in METRIC_NAMES for kind in ('default','average') if not (kind=='default' and metric in AVERAGE_ONLY) and not (kind=='average' and metric not in AVERAGE)] ROLES = ('fitness','fastest_lap','clean_laps') def encoded(value): return json.dumps(value,allow_nan=False,separators=(',',':')).encode() def bounded_read(path,limit=MAX_ANALYSIS_BYTES): path=Path(path) if path.is_symlink() or not path.is_file() or path.stat().st_size>limit: raise ValueError('Invalid or oversized native analysis file') with path.open('rb') as stream:data=stream.read(limit+1) if len(data)>limit:raise ValueError('Native analysis exceeds complete artifact limit') return data def parsed(data): return json.loads(data,parse_constant=lambda _: (_ for _ in ()).throw(ValueError('Nonfinite native analysis'))) def parameter_hash(network): params=[] for matrix,bias in zip(network['weights'],network['biases']): params.extend(value for row in matrix for value in row) params.extend(bias) return hashlib.sha256(b''.join(struct.pack('expected:raise ValueError('Extra native observations') row=checked_row(parsed(line),(count-1)//population+1,(count-1)%population) if row['candidate_id'] in selected_ids: if row!=selected_ids[row['candidate_id']]:raise ValueError('Winner observation not in descriptor stream') seen_selected.add(row['candidate_id']) if config['mode']=='evaluate':evaluation_row=row if count!=expected or native.get('rows')!=count or set(selected_ids)!=seen_selected: raise ValueError('Incomplete native analysis') files={'descriptors.jsonl':descriptors} conditions={'track_sha256':hashlib.sha256(track_bytes).hexdigest(), 'network_sha256':hashlib.sha256(network_bytes).hexdigest(),'vehicle_type':template['Type'], 'requested_ticks':config['ticks'],'control_hz':config['control_hz'], 'collision':config['collision'],'idle':config['idle'],'math_profile':'proton','clean_min_laps':config['clean_min_laps']} winners={} for role,row in winner_rows.items(): metadata={'status':'unavailable','reason':('frozen_evaluation_does_not_select_winners' if config['mode']=='evaluate' else 'no_completed_lap' if role=='fastest_lap' else 'no_eligible_clean_laps'), 'candidate_id':None,'generation':None,'car':None,'selection_fitness':None, 'best_lap_seconds':None,'forward_laps':None,'physical_contacts':None,'collision_updates':None, 'total_actual_distance':None,'artifact':None} if row is not None: if config['mode']!='train':raise ValueError('Frozen evaluation selected a winner') objective=row['objectives'];lap=objective['best_lap_seconds'] if role=='fitness' and row['generation']!=generations:raise ValueError('Fitness winner is not final population') if role!='fitness' and (lap is None or lap<=0 or objective['forward_laps']<1):raise ValueError('Winner did not complete a lap') if role=='clean_laps' and (objective['forward_laps']MAX_ANALYSIS_BYTES:raise ValueError('Complete analysis exceeds 256 MiB; no truncation') return files,summary,evaluation