|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from datetime import datetime |
| 4 | +import json |
| 5 | +from pathlib import Path |
| 6 | +from typing import Any |
| 7 | + |
| 8 | + |
| 9 | +def _is_iso_timestamp(value: str) -> bool: |
| 10 | + try: |
| 11 | + datetime.fromisoformat(value) |
| 12 | + except ValueError: |
| 13 | + return False |
| 14 | + return True |
| 15 | + |
| 16 | + |
| 17 | +def _ensure_dict(value: Any, context: str) -> tuple[dict[str, Any] | None, list[str]]: |
| 18 | + if isinstance(value, dict): |
| 19 | + return value, [] |
| 20 | + return None, [f"{context} must be a JSON object."] |
| 21 | + |
| 22 | + |
| 23 | +def _load_json_file(path: Path) -> tuple[dict[str, Any] | None, list[str]]: |
| 24 | + try: |
| 25 | + with path.open("r", encoding="utf-8") as handle: |
| 26 | + data = json.load(handle) |
| 27 | + except FileNotFoundError: |
| 28 | + return None, [f"Missing file: {path}"] |
| 29 | + except json.JSONDecodeError as exc: |
| 30 | + return None, [f"Invalid JSON in {path}: {exc}"] |
| 31 | + return _ensure_dict(data, str(path)) |
| 32 | + |
| 33 | + |
| 34 | +def validate_run_metadata(metadata: dict[str, Any]) -> list[str]: |
| 35 | + errors: list[str] = [] |
| 36 | + |
| 37 | + required_string_fields = ( |
| 38 | + "run_id", |
| 39 | + "protocol", |
| 40 | + "preset", |
| 41 | + "mouse_id", |
| 42 | + "project", |
| 43 | + "started_at", |
| 44 | + "git_branch", |
| 45 | + "git_commit", |
| 46 | + "run_mode", |
| 47 | + ) |
| 48 | + for field in required_string_fields: |
| 49 | + value = metadata.get(field) |
| 50 | + if not isinstance(value, str) or not value: |
| 51 | + errors.append(f"run_metadata.{field} must be a non-empty string.") |
| 52 | + |
| 53 | + if "git_tag" not in metadata: |
| 54 | + errors.append("run_metadata.git_tag is required (string or null).") |
| 55 | + else: |
| 56 | + git_tag = metadata.get("git_tag") |
| 57 | + if git_tag is not None and not isinstance(git_tag, str): |
| 58 | + errors.append("run_metadata.git_tag must be a string or null.") |
| 59 | + |
| 60 | + git_dirty = metadata.get("git_dirty") |
| 61 | + if not isinstance(git_dirty, bool): |
| 62 | + errors.append("run_metadata.git_dirty must be boolean.") |
| 63 | + |
| 64 | + run_mode = metadata.get("run_mode") |
| 65 | + if run_mode not in {"debug", "production"}: |
| 66 | + errors.append("run_metadata.run_mode must be one of: debug, production.") |
| 67 | + |
| 68 | + schema_version = metadata.get("schema_version") |
| 69 | + if not isinstance(schema_version, int) or schema_version < 1: |
| 70 | + errors.append("run_metadata.schema_version must be an integer >= 1.") |
| 71 | + |
| 72 | + started_at = metadata.get("started_at") |
| 73 | + if isinstance(started_at, str) and not _is_iso_timestamp(started_at): |
| 74 | + errors.append("run_metadata.started_at must be an ISO-8601 timestamp.") |
| 75 | + |
| 76 | + return errors |
| 77 | + |
| 78 | + |
| 79 | +def validate_event_record(record: dict[str, Any], line_number: int) -> list[str]: |
| 80 | + errors: list[str] = [] |
| 81 | + |
| 82 | + timestamp = record.get("timestamp") |
| 83 | + if not isinstance(timestamp, str) or not timestamp: |
| 84 | + errors.append(f"events.jsonl line {line_number}: timestamp must be a non-empty string.") |
| 85 | + elif not _is_iso_timestamp(timestamp): |
| 86 | + errors.append(f"events.jsonl line {line_number}: timestamp must be ISO-8601.") |
| 87 | + |
| 88 | + event_type = record.get("event_type") |
| 89 | + if not isinstance(event_type, str) or not event_type: |
| 90 | + errors.append(f"events.jsonl line {line_number}: event_type must be a non-empty string.") |
| 91 | + |
| 92 | + payload = record.get("payload") |
| 93 | + if not isinstance(payload, dict): |
| 94 | + errors.append(f"events.jsonl line {line_number}: payload must be a JSON object.") |
| 95 | + |
| 96 | + return errors |
| 97 | + |
| 98 | + |
| 99 | +def validate_result_payload(result: dict[str, Any]) -> list[str]: |
| 100 | + errors: list[str] = [] |
| 101 | + |
| 102 | + protocol = result.get("protocol") |
| 103 | + if not isinstance(protocol, str) or not protocol: |
| 104 | + errors.append("result.protocol must be a non-empty string.") |
| 105 | + |
| 106 | + preset = result.get("preset") |
| 107 | + if not isinstance(preset, str) or not preset: |
| 108 | + errors.append("result.preset must be a non-empty string.") |
| 109 | + |
| 110 | + total_trials = result.get("total_trials") |
| 111 | + if not isinstance(total_trials, int) or total_trials < 0: |
| 112 | + errors.append("result.total_trials must be an integer >= 0.") |
| 113 | + |
| 114 | + outcomes = result.get("outcomes") |
| 115 | + if not isinstance(outcomes, list) or any(not isinstance(item, str) for item in outcomes): |
| 116 | + errors.append("result.outcomes must be a list of strings.") |
| 117 | + |
| 118 | + outcome_counts = result.get("outcome_counts") |
| 119 | + if not isinstance(outcome_counts, dict): |
| 120 | + errors.append("result.outcome_counts must be a JSON object.") |
| 121 | + else: |
| 122 | + for key, value in outcome_counts.items(): |
| 123 | + if not isinstance(key, str): |
| 124 | + errors.append("result.outcome_counts keys must be strings.") |
| 125 | + if not isinstance(value, int) or value < 0: |
| 126 | + errors.append("result.outcome_counts values must be integers >= 0.") |
| 127 | + |
| 128 | + if isinstance(total_trials, int) and isinstance(outcomes, list): |
| 129 | + if len(outcomes) != total_trials: |
| 130 | + errors.append( |
| 131 | + f"result.total_trials ({total_trials}) must equal len(result.outcomes) ({len(outcomes)})." |
| 132 | + ) |
| 133 | + |
| 134 | + if isinstance(total_trials, int) and isinstance(outcome_counts, dict): |
| 135 | + count_sum = sum(value for value in outcome_counts.values() if isinstance(value, int)) |
| 136 | + if count_sum != total_trials: |
| 137 | + errors.append( |
| 138 | + f"result.total_trials ({total_trials}) must equal sum(result.outcome_counts.values()) " |
| 139 | + f"({count_sum})." |
| 140 | + ) |
| 141 | + |
| 142 | + return errors |
| 143 | + |
| 144 | + |
| 145 | +def validate_run_directory(run_dir: Path) -> list[str]: |
| 146 | + errors: list[str] = [] |
| 147 | + if not run_dir.exists(): |
| 148 | + return [f"Run directory does not exist: {run_dir}"] |
| 149 | + if not run_dir.is_dir(): |
| 150 | + return [f"Run path is not a directory: {run_dir}"] |
| 151 | + |
| 152 | + metadata_path = run_dir / "run_metadata.json" |
| 153 | + events_path = run_dir / "events.jsonl" |
| 154 | + result_path = run_dir / "result.json" |
| 155 | + |
| 156 | + metadata, metadata_errors = _load_json_file(metadata_path) |
| 157 | + errors.extend(metadata_errors) |
| 158 | + result, result_errors = _load_json_file(result_path) |
| 159 | + errors.extend(result_errors) |
| 160 | + |
| 161 | + if metadata is not None: |
| 162 | + errors.extend(validate_run_metadata(metadata)) |
| 163 | + run_id = metadata.get("run_id") |
| 164 | + if isinstance(run_id, str) and run_id and run_id != run_dir.name: |
| 165 | + errors.append(f"run_metadata.run_id ({run_id}) must match run directory name ({run_dir.name}).") |
| 166 | + |
| 167 | + if result is not None: |
| 168 | + errors.extend(validate_result_payload(result)) |
| 169 | + |
| 170 | + if metadata is not None and result is not None: |
| 171 | + metadata_protocol = metadata.get("protocol") |
| 172 | + result_protocol = result.get("protocol") |
| 173 | + if metadata_protocol != result_protocol: |
| 174 | + errors.append("run_metadata.protocol must match result.protocol.") |
| 175 | + |
| 176 | + metadata_preset = metadata.get("preset") |
| 177 | + result_preset = result.get("preset") |
| 178 | + if metadata_preset != result_preset: |
| 179 | + errors.append("run_metadata.preset must match result.preset.") |
| 180 | + |
| 181 | + if not events_path.exists(): |
| 182 | + errors.append(f"Missing file: {events_path}") |
| 183 | + else: |
| 184 | + line_count = 0 |
| 185 | + parsed_event_count = 0 |
| 186 | + with events_path.open("r", encoding="utf-8") as handle: |
| 187 | + for line_count, raw_line in enumerate(handle, start=1): |
| 188 | + line = raw_line.strip() |
| 189 | + if not line: |
| 190 | + continue |
| 191 | + try: |
| 192 | + record = json.loads(line) |
| 193 | + except json.JSONDecodeError as exc: |
| 194 | + errors.append(f"events.jsonl line {line_count}: invalid JSON ({exc}).") |
| 195 | + continue |
| 196 | + record_dict, record_errors = _ensure_dict(record, f"events.jsonl line {line_count}") |
| 197 | + if record_dict is None: |
| 198 | + errors.extend(record_errors) |
| 199 | + continue |
| 200 | + errors.extend(validate_event_record(record_dict, line_count)) |
| 201 | + parsed_event_count += 1 |
| 202 | + if line_count == 0: |
| 203 | + errors.append("events.jsonl must contain at least one event record.") |
| 204 | + elif parsed_event_count == 0: |
| 205 | + errors.append("events.jsonl must contain at least one non-empty event record.") |
| 206 | + |
| 207 | + return errors |
0 commit comments