casino / validate.py
Rikardnilsson's picture
Fix OCEL object attribute history consistency
cc8d681 verified
Raw History Blame Contribute Delete
11.6 kB
#!/usr/bin/env python3
"""Validate JSON/SQLite OCEL object-attribute histories fail-closed."""
from __future__ import annotations
import argparse
import json
import sqlite3
from pathlib import Path
from typing import Any
CHECK_NAME = "ocel_json_sqlite_object_attribute_histories"
SQL_TYPES = {
"string": "TEXT",
"time": "TIMESTAMP",
"integer": "INTEGER",
"float": "REAL",
"boolean": "BOOLEAN",
}
PYTHON_TYPES = {
"string": str,
"time": str,
"integer": int,
"float": float,
"boolean": bool,
}
class HistoryValidationError(ValueError):
"""Raised when JSON and SQLite object histories are not exactly equal."""
def quote_identifier(value: str) -> str:
return '"' + value.replace('"', '""') + '"'
def same_value(left: Any, right: Any) -> bool:
"""Compare values without treating JSON booleans as integers."""
return type(left) is type(right) and left == right
def record_value(history: dict[tuple[str, str, str], Any], object_id: str,
name: str, timestamp: str, value: Any, source: str) -> None:
key = (object_id, name, timestamp)
if key in history and not same_value(history[key], value):
raise HistoryValidationError(
f"{source}: conflicting values for object={object_id!r}, "
f"attribute={name!r}, time={timestamp!r}: "
f"{history[key]!r} versus {value!r}"
)
history[key] = value
def read_json_history(log_path: Path) -> tuple[
dict[tuple[str, str, str], Any], dict[str, str],
dict[str, dict[str, str]], dict[str, int]
]:
log = json.loads(log_path.read_text(encoding="utf-8"))
declarations = {
row["name"]: {attr["name"]: attr["type"] for attr in row["attributes"]}
for row in log["objectTypes"]
}
identities: dict[str, str] = {}
history: dict[tuple[str, str, str], Any] = {}
raw_rows = 0
boolean_values = 0
game_round_status_values = 0
for obj in log["objects"]:
object_id = obj["id"]
object_type = obj["type"]
if object_id in identities:
raise HistoryValidationError(f"JSON: duplicate object id {object_id!r}")
identities[object_id] = object_type
if object_type not in declarations:
raise HistoryValidationError(f"JSON: undeclared object type {object_type!r}")
for attr in obj["attributes"]:
raw_rows += 1
name, timestamp, value = attr["name"], attr["time"], attr["value"]
declared = declarations[object_type].get(name)
if declared is None:
raise HistoryValidationError(
f"JSON: undeclared attribute {object_type}.{name} on {object_id!r}"
)
if declared not in PYTHON_TYPES or type(value) is not PYTHON_TYPES[declared]:
raise HistoryValidationError(
f"JSON: {object_id!r}.{name} at {timestamp} must be {declared}; "
f"got {type(value).__name__} value {value!r}"
)
record_value(history, object_id, name, timestamp, value, "JSON")
if declared == "boolean":
boolean_values += 1
if object_type == "game_round" and name == "status":
game_round_status_values += 1
metrics = {
"objects": len(identities),
"json_attribute_rows": raw_rows,
"json_history_values": len(history),
"boolean_values": boolean_values,
"game_round_status_values": game_round_status_values,
}
return history, identities, declarations, metrics
def checked_sqlite_value(object_id: str, name: str, timestamp: str,
declared: str, value: Any) -> Any:
if value is None:
return None
if declared == "boolean":
if type(value) is not int or value not in (0, 1):
raise HistoryValidationError(
f"SQLite: {object_id!r}.{name} at {timestamp} must be BOOLEAN 0/1; "
f"got {type(value).__name__} value {value!r}"
)
return bool(value)
expected = PYTHON_TYPES[declared]
if type(value) is not expected:
raise HistoryValidationError(
f"SQLite: {object_id!r}.{name} at {timestamp} must be {declared}; "
f"got {type(value).__name__} value {value!r}"
)
return value
def read_sqlite_history(sqlite_path: Path, declarations: dict[str, dict[str, str]]) -> tuple[
dict[tuple[str, str, str], Any], dict[str, str], dict[str, int]
]:
connection = sqlite3.connect(sqlite_path)
history: dict[tuple[str, str, str], Any] = {}
try:
identities = dict(connection.execute("SELECT ocel_id, ocel_type FROM object"))
type_maps = dict(connection.execute("SELECT ocel_type, ocel_type_map FROM object_map_type"))
snapshot_rows = 0
raw_history_values = 0
for object_type, attributes in declarations.items():
if object_type not in type_maps:
raise HistoryValidationError(f"SQLite: missing object type {object_type!r}")
table = "object_" + type_maps[object_type]
quoted_table = quote_identifier(table)
column_info = connection.execute(f"PRAGMA table_info({quoted_table})").fetchall()
sql_columns = {row[1]: (row[2] or "").upper() for row in column_info}
required = {"ocel_id", "ocel_time", "ocel_changed_field", *attributes}
if not required.issubset(sql_columns):
raise HistoryValidationError(
f"SQLite: {table} lacks columns {sorted(required - set(sql_columns))}"
)
for name, declared in attributes.items():
expected_sql = SQL_TYPES[declared]
if sql_columns[name] != expected_sql:
raise HistoryValidationError(
f"SQLite: {table}.{name} must be {expected_sql}; got {sql_columns[name]!r}"
)
names = list(attributes)
selected = ["ocel_id", "ocel_time", "ocel_changed_field", *names]
columns_sql = ", ".join(quote_identifier(name) for name in selected)
rows = connection.execute(
f"SELECT {columns_sql} FROM {quoted_table} "
"ORDER BY ocel_id, ocel_time, rowid"
)
previous: dict[str, dict[str, Any]] = {}
for row in rows:
snapshot_rows += 1
object_id, timestamp, changed_field = row[:3]
current = {
name: checked_sqlite_value(object_id, name, timestamp, attributes[name], value)
for name, value in zip(names, row[3:])
}
if object_id not in previous:
changed = [name for name in names if current[name] is not None]
elif changed_field is not None:
if changed_field not in attributes:
raise HistoryValidationError(
f"SQLite: {table} has unknown changed field {changed_field!r}"
)
changed = [changed_field]
else:
changed = [
name for name in names
if not same_value(current[name], previous[object_id][name])
]
if not changed:
raise HistoryValidationError(
f"SQLite: {table} has a no-op snapshot for {object_id!r} at "
f"{timestamp}; its attribute history cannot be reconstructed"
)
for name in changed:
value = current[name]
if value is None:
raise HistoryValidationError(
f"SQLite: null history value for {object_id!r}.{name} at {timestamp}"
)
record_value(history, object_id, name, timestamp, value, "SQLite")
raw_history_values += 1
previous[object_id] = current
metrics = {
"sqlite_snapshot_rows": snapshot_rows,
"sqlite_history_values": len(history),
"sqlite_decoded_values": raw_history_values,
}
return history, identities, metrics
finally:
connection.close()
def validate_object_attribute_histories(log_path: Path, sqlite_path: Path) -> dict[str, int]:
json_history, json_identities, declarations, metrics = read_json_history(log_path)
sqlite_history, sqlite_identities, sqlite_metrics = read_sqlite_history(sqlite_path, declarations)
metrics.update(sqlite_metrics)
if json_identities != sqlite_identities:
missing = sorted(set(json_identities) - set(sqlite_identities))[:10]
extra = sorted(set(sqlite_identities) - set(json_identities))[:10]
wrong_type = sorted(
object_id for object_id in set(json_identities) & set(sqlite_identities)
if json_identities[object_id] != sqlite_identities[object_id]
)[:10]
raise HistoryValidationError(
f"Object identity mismatch; missing={missing}, extra={extra}, wrong_type={wrong_type}"
)
json_keys = set(json_history)
sqlite_keys = set(sqlite_history)
if json_keys != sqlite_keys:
missing = sorted(json_keys - sqlite_keys)[:10]
extra = sorted(sqlite_keys - json_keys)[:10]
raise HistoryValidationError(
f"Attribute-history keys differ; missing_from_sqlite={missing}, extra_in_sqlite={extra}"
)
differences = [
(key, json_history[key], sqlite_history[key])
for key in sorted(json_keys)
if not same_value(json_history[key], sqlite_history[key])
]
if differences:
raise HistoryValidationError(f"Attribute-history values differ: {differences[:10]}")
if metrics["json_history_values"] != metrics["sqlite_history_values"]:
raise HistoryValidationError("Attribute-history counts differ after comparison")
return metrics
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("dataset", type=Path)
args = parser.parse_args()
root = args.dataset
report_path = root / "validation_report.json"
report = json.loads(report_path.read_text(encoding="utf-8"))
try:
metrics = validate_object_attribute_histories(
root / "ocel" / "askersund_casno_ocel20.json",
root / "ocel" / "askersund_casno_ocel20.sqlite",
)
except Exception as error:
report["status"] = "FAIL"
report.setdefault("checks", {})[CHECK_NAME] = False
report["object_attribute_history"] = {
"error": f"{type(error).__name__}: {error}"
}
report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
print(json.dumps({"status": "FAIL", "check": CHECK_NAME, "error": str(error)}, indent=2))
raise SystemExit(1)
report.setdefault("checks", {})[CHECK_NAME] = True
report["status"] = "PASS" if all(report["checks"].values()) else "FAIL"
report["object_attribute_history"] = metrics
report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
print(json.dumps({"status": report["status"], "check": CHECK_NAME, "metrics": metrics}, indent=2))
if report["status"] != "PASS":
raise SystemExit(1)
if __name__ == "__main__":
main()