recording.py
1"""Ordered ordinary JSON experiment stream, written only by output stage."""23from __future__ import annotations45from typing import Any, Dict67from sim_platform.domain.json_values import copy_json8from sim_platform.domain.models import ContractError91011class ExperimentLog:12 """Numbered JSON records of one run, written in order by the output thread.1314 Assembly creates it with a log-file adapter (AgentLogFile from the persistence15 package, not yet typed) and writes the header at once. The 'end' message writes16 the trailer; close() closes the adapter.1718 Args:19 adapter: Append-only JSON writer with ``path``, ``append(value)`` and ``close()``.20 run_id: Run recorded in the header.21 """2223 def __init__(self, adapter: Any, run_id: str) -> None:24 self.adapter, self.path = adapter, adapter.path25 self.number, self.ended = 0, False26 adapter.append(dict(header=dict(run_id=run_id)))2728 def __call__(self, message: Dict[str, Any]) -> None:29 if self.ended:30 raise ContractError('experiment log already ended')31 self.number += 132 self.adapter.append(dict(record=dict(index=self.number, **copy_json(message))))33 if message['kind'] == 'end':34 self.adapter.append(dict(end=dict(records=self.number, status=message['status'])))35 self.ended = True3637 def close(self) -> None:38 self.adapter.close()