"""Opt-in onboard JSONL evidence. Disk never runs on the motor worker. RAM is bounded; full files have no duration/size cutoff and are never rotated. Backpressure and I/O failures are explicit, rather than silently losing evidence. """ import base64 import hashlib import json import os import queue import re import threading import time from datetime import datetime, timezone from pathlib import Path class SessionLog: SYNC_INTERVAL = 1.0 MAX_RECORD_BYTES = 8192 MAX_QUEUE_BYTES = 4 * 1024 * 1024 def __init__(self,root): self.root=Path(root)/'Session Logs' self.lock=threading.RLock();self.queue=queue.Queue(maxsize=4096) self.path=None;self.id=None;self.thread=None self.error=None;self.dropped=0;self.written=0;self.closed=True;self.closing=False self.external_ack={} self.queued_bytes=0;self.drop_reasons={} def start(self,identifier,vehicle,create=True,options=None): if not isinstance(identifier,str) or not re.fullmatch(r'[a-f0-9]{32}',identifier):raise ValueError('Invalid capture ID') with self.lock: if self.id==identifier:return # A closed capture can never reopen. if not self.closed:raise ValueError('Finish the current diagnostic session first') label=re.sub(r'[^A-Za-z0-9А-Яа-яЁё_. -]','_',str(vehicle))[:100].strip(' .') or 'Rover' folder=self.root/label if create:folder.mkdir(parents=True,exist_ok=True,mode=0o700) if folder.is_symlink():raise ValueError('Invalid log directory') prior=list(folder.glob('*_'+identifier+'.jsonl')) self.id=identifier;self.external_ack={};self.dropped=self.written=0 self.path=None;self.error=None;self.closed=True;self.closing=False if prior: self.path=prior[0];self.error='CaptureInterrupted' # Inspect only a bounded tail. Never append, repair or scan an hour-long file. with self.path.open('rb') as stream: stream.seek(max(0,self.path.stat().st_size-16384));tail=stream.read(16384) try: end=json.loads(tail.splitlines()[-1]) if tail.endswith(b'\n') else {} if end.get('type')=='session_end': self.written=int(end['written_records']);self.dropped=int(end['dropped_records']);self.error=None except (ValueError,KeyError,IndexError,TypeError):pass return if not create:self.error='CaptureNotFound';return stamp=datetime.now(timezone.utc).strftime('%Y-%m-%d_%H-%M-%S_UTC') self.path=folder/(stamp+'_'+identifier+'.jsonl') fd=os.open(self.path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|getattr(os,'O_NOFOLLOW',0),0o600) self.file=os.fdopen(fd,'wb',buffering=65536) self.error=None;self.closed=False;self.closing=False self.queue=queue.Queue(maxsize=4096) self.queued_bytes=0;self.drop_reasons={} self.file.write((json.dumps({'type':'manifest','schema':'missioncore.rover-session/v1', 'capture_id':identifier,'options':options,'vehicle':str(vehicle)[:128],'started_at':datetime.now(timezone.utc).isoformat(), 'clock_note':'UTC and monotonic clocks are per source; receive order is not synchronized measurement.'},ensure_ascii=False)+'\n').encode()) self.file.flush();os.fsync(self.file.fileno()) self.thread=threading.Thread(target=self._write,daemon=True,name='vesc-session-log');self.thread.start() def append(self,row): with self.lock: if self.closed or self.closing or self.error:return False try:raw=(json.dumps(row,ensure_ascii=False,allow_nan=False,separators=(',',':'))+'\n').encode() except (ValueError,TypeError): self._drop('invalid_record');return False if len(raw)>self.MAX_RECORD_BYTES: self._drop('record_too_large');return False if self.queued_bytes+len(raw)>self.MAX_QUEUE_BYTES or self.queue.full(): self._drop('queue_full');return False try:self.queue.put_nowait(raw) except queue.Full:self._drop('queue_full');return False self.queued_bytes+=len(raw) return True def _drop(self,reason): self.dropped+=1;self.drop_reasons[reason]=self.drop_reasons.get(reason,0)+1 def _write(self): last_sync=time.monotonic();dirty=False try: while True: # Finish is an out-of-band signal, so a full data queue cannot # lose it. Every accepted record drains before the footer. with self.lock: if self.closing and self.queue.empty():break try:row=self.queue.get(timeout=.5) except queue.Empty: if dirty and time.monotonic()-last_sync>=self.SYNC_INTERVAL: self.file.flush();os.fsync(self.file.fileno());last_sync=time.monotonic();dirty=False continue if isinstance(row,threading.Event): self.file.flush();row.set();continue with self.lock:self.queued_bytes-=len(row) self.file.write(row) self.written+=1;dirty=True if time.monotonic()-last_sync>=self.SYNC_INTERVAL: self.file.flush();os.fsync(self.file.fileno());last_sync=time.monotonic();dirty=False self.file.write((json.dumps({'type':'session_end','at_utc':datetime.now(timezone.utc).isoformat(), 'written_records':self.written,'dropped_records':self.dropped,'drop_reasons':self.drop_reasons})+'\n').encode()) self.file.flush();os.fsync(self.file.fileno()) except (OSError,ValueError,TypeError) as error:self.error=type(error).__name__ finally: try:self.file.close() except OSError as error:self.error=type(error).__name__ finally:self.closed=True def finish(self): with self.lock: if self.closed or self.closing:return self.closing=True # Completion is polled. Never hold a request or a motor worker for disk. def external(self,origin,rows): if not isinstance(rows,list) or len(rows)>64:raise ValueError('Invalid external trace') for row in rows: if not isinstance(row,dict) or type(row.get('record_sequence')) is not int:continue seq=row['record_sequence'];previous=self.external_ack.get(origin,0) if seq<=previous:continue if len(json.dumps(row))>8192:continue if seq>previous+1 and origin=='core': if not self.append({'source':'recorder','event':'transport_gap','origin':origin,'after':previous,'before':seq}):break if not self.append(row):break self.external_ack[origin]=seq def status(self): return {'file':str(self.path.relative_to(self.root)) if self.path else None, 'closed':self.closed,'error':self.error,'written':self.written,'dropped':self.dropped, 'external_ack':dict(self.external_ack),'queued_bytes':self.queued_bytes, 'queued_records':self.queue.qsize(),'drop_reasons':dict(self.drop_reasons)} def chunk(self,identifier,offset,total=None,*,limit=4096,snapshot=None): if identifier!=self.id or self.path is None:raise ValueError('Unknown session log') if type(limit) is not int or not 1<=limit<=65536:raise ValueError('Invalid export block size') if type(offset) is not int or offset<0:raise ValueError('Invalid file offset') if self.closing and not self.closed: self.thread.join(1) if not self.closed:raise OSError("Writer is closing") if total is None and not self.closed: flushed=threading.Event() self.queue.put(flushed,timeout=1) if not flushed.wait(1):raise OSError('Writer flush timed out') size=self.path.stat().st_size if total is None:total=size if type(total) is not int or not 0<=offset<=total<=size:raise ValueError('Invalid export snapshot') with self.path.open('rb') as stream: stat=os.fstat(stream.fileno()) prefix=stream.read(min(4096,total)) identity=hashlib.sha256(f'{identifier}:{stat.st_dev}:{stat.st_ino}:{total}:'.encode()+prefix).hexdigest() if snapshot is not None and snapshot!=identity:raise ValueError('Export snapshot changed') stream.seek(offset);raw=stream.read(min(limit,total-offset)) if len(raw)!=min(limit,total-offset):raise OSError('Export snapshot truncated') return {'capture_id':identifier,'offset':offset,'total_bytes':total,'next':offset+len(raw), 'data':base64.b64encode(raw).decode(),'file':self.path.name, 'snapshot':identity,'sha256':hashlib.sha256(raw).hexdigest()}