diff --git a/README.md b/README.md index d9c5f70..88f9a1e 100644 --- a/README.md +++ b/README.md @@ -137,6 +137,7 @@ No performance claims yet. The scaffold proves the invariants: | BeliefBench runner and baselines | `tests/test_beliefbench.py` | | GDELT and RSS map to observations | `tests/test_gdelt.py`, `tests/test_rss.py` | | Retries, dead letters, and replay | `tests/test_scheduler.py` | +| Snapshot archives are tamper-evident and replay identical features | `tests/test_snapshot_archive.py` | | Quality checks catch duplicate, future, and stale data | `tests/test_quality.py` | | Predictions are immutable and settle once | `tests/test_ledger.py` | | RSI stays bounded; MACD / Bollinger / OBV behave | `tests/test_indicators.py` | diff --git a/core/janus/cli.py b/core/janus/cli.py index 78a8f5a..69201c1 100644 --- a/core/janus/cli.py +++ b/core/janus/cli.py @@ -19,6 +19,7 @@ ModelRegistry, ) from .memory.migrations import apply_migrations, current_version +from .memory.snapshot_archive import export_snapshot, import_snapshot, verify_snapshot from .memory.models import ObservationKind from .memory.store import JanusStore @@ -29,9 +30,11 @@ config_app = typer.Typer(help="Inspect and validate local configuration.") schema_app = typer.Typer(help="Export and verify the domain contract schema.") model_app = typer.Typer(help="Inspect content-addressed model artifacts.") +archive_app = typer.Typer(help="Export, import, and verify as-of snapshot archives.") app.add_typer(config_app, name="config") app.add_typer(schema_app, name="schema") app.add_typer(model_app, name="model") +app.add_typer(archive_app, name="archive") @app.command() @@ -159,6 +162,82 @@ def schema_check( raise typer.Exit(code=1) +@archive_app.command("export") +def archive_export( + out: Path = typer.Option(..., "--out", help="Archive directory"), + as_of: str = typer.Option(..., "--as-of", help="Snapshot as-of timestamp"), + db: Optional[str] = typer.Option(None, "--db", help="SQLite path"), + no_parquet: bool = typer.Option(False, "--no-parquet", help="Skip Parquet files"), + as_json: bool = typer.Option(False, "--json", help="Emit manifest JSON"), +) -> None: + """Write a hash-manifested as-of snapshot archive.""" + + try: + stamp = datetime.fromisoformat(as_of) + except ValueError as exc: + raise typer.BadParameter("use an ISO timestamp") from exc + if stamp.tzinfo is None: + stamp = stamp.replace(tzinfo=timezone.utc) + settings = load_settings() + try: + manifest = export_snapshot( + JanusStore(db or settings.database), + out, + as_of=stamp, + parquet=not no_parquet, + ) + except ValueError as exc: + raise typer.BadParameter(str(exc)) from exc + if as_json: + typer.echo(json.dumps(manifest, indent=2, sort_keys=True)) + else: + typer.echo( + f"wrote {out} observations={manifest['counts']['observations']} " + f"features={manifest['counts']['features']} " + f"hash={manifest['snapshot_hash'][:12]}" + ) + + +@archive_app.command("verify") +def archive_verify( + directory: Path = typer.Argument(..., help="Archive directory"), + as_json: bool = typer.Option(False, "--json", help="Emit JSON"), +) -> None: + """Verify an archive manifest and every referenced file.""" + + result = verify_snapshot(directory) + if as_json: + typer.echo(json.dumps(result.to_dict(), indent=2, sort_keys=True)) + elif result.ok: + typer.echo(f"ok snapshot={result.snapshot_hash[:12]}") + else: + for error in result.errors: + typer.echo(error, err=True) + if not result.ok: + raise typer.Exit(code=1) + + +@archive_app.command("import") +def archive_import( + directory: Path = typer.Argument(..., help="Archive directory"), + db: Optional[str] = typer.Option(None, "--db", help="SQLite path"), + skip_verify: bool = typer.Option(False, "--skip-verify", help="Skip manifest checks"), +) -> None: + """Import a verified archive into a store.""" + + settings = load_settings() + try: + counts = import_snapshot( + JanusStore(db or settings.database), directory, verify=not skip_verify + ) + except ValueError as exc: + typer.echo(str(exc), err=True) + raise typer.Exit(code=1) from exc + typer.echo( + f"imported observations={counts['observations']} features={counts['features']}" + ) + + @app.command() def migrate( db: Optional[str] = typer.Option(None, "--db", help="SQLite path"), diff --git a/core/janus/memory/snapshot_archive.py b/core/janus/memory/snapshot_archive.py new file mode 100644 index 0000000..b0524db --- /dev/null +++ b/core/janus/memory/snapshot_archive.py @@ -0,0 +1,231 @@ +from __future__ import annotations + +import hashlib +import json +from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Sequence + +from .. import __version__ +from ..contracts import SCHEMA_VERSION +from .models import Observation +from .store import JanusStore + +ARCHIVE_VERSION = "snapshot-v1" + + +@dataclass(frozen=True) +class SnapshotVerification: + ok: bool + errors: tuple[str, ...] + snapshot_hash: str + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +def _digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _write_json(path: Path, payload: Any) -> None: + path.write_text( + json.dumps(payload, indent=2, sort_keys=True, default=str) + "\n", + encoding="utf-8", + ) + + +def _as_of_stamp(as_of: datetime) -> str: + if as_of.tzinfo is None or as_of.tzinfo.utcoffset(as_of) is None: + raise ValueError("as_of must be timezone-aware") + return as_of.astimezone(timezone.utc).isoformat() + + +def _observation_rows(store: JanusStore, as_of: datetime) -> list[dict[str, Any]]: + entities = [ + str(row["entity_id"]) + for row in store.connection.execute( + "SELECT DISTINCT entity_id FROM observation ORDER BY entity_id" + ).fetchall() + ] + rows: list[dict[str, Any]] = [] + for entity_id in entities: + for observation in store.query_observations_as_of( + entity_id, as_of, mode="published" + ): + rows.append(observation.model_dump(mode="json")) + return sorted(rows, key=lambda item: (item["entity_id"], item["published_at"], item["id"])) + + +def _feature_rows(store: JanusStore, as_of: datetime) -> list[dict[str, Any]]: + stamp = as_of.astimezone(timezone.utc).isoformat() + rows = store.connection.execute( + """ + SELECT entity_id, as_of, name, version, value, features_hash, source_hash, + computed_at + FROM feature_value + WHERE as_of <= ? + ORDER BY entity_id, as_of, name, version + """, + (stamp,), + ).fetchall() + return [ + { + "entity_id": row["entity_id"], + "as_of": row["as_of"], + "name": row["name"], + "version": row["version"], + "value": json.loads(row["value"]), + "features_hash": row["features_hash"], + "source_hash": row["source_hash"], + "computed_at": row["computed_at"], + } + for row in rows + ] + + +def _write_frame(path: Path, rows: Sequence[dict[str, Any]]) -> bool: + try: + import pandas as pd + except ImportError: # pragma: no cover - optional dependency + return False + try: + pd.DataFrame(list(rows)).to_parquet(path, index=False) + except (ImportError, ValueError, ModuleNotFoundError): + return False + return True + + +def export_snapshot( + store: JanusStore, + out_dir: Path, + *, + as_of: datetime, + parquet: bool = True, +) -> dict[str, Any]: + """Write a hash-manifested as-of snapshot archive.""" + + target = Path(out_dir) + target.mkdir(parents=True, exist_ok=True) + observations = _observation_rows(store, as_of) + features = _feature_rows(store, as_of) + _write_json(target / "observations.json", observations) + _write_json(target / "features.json", features) + + files: dict[str, dict[str, Any]] = {} + for name, rows in (("observations.json", observations), ("features.json", features)): + path = target / name + files[name] = {"sha256": _digest(path), "bytes": path.stat().st_size, "rows": len(rows)} + if parquet: + for name, rows in (("observations.parquet", observations), ("features.parquet", features)): + path = target / name + if _write_frame(path, rows): + files[name] = { + "sha256": _digest(path), + "bytes": path.stat().st_size, + "rows": len(rows), + } + + lineage = { + "archive_version": ARCHIVE_VERSION, + "code_version": __version__, + "schema_version": SCHEMA_VERSION, + "store": str(store.path), + "as_of": _as_of_stamp(as_of), + } + counts = {"observations": len(observations), "features": len(features)} + content = { + "archive_version": ARCHIVE_VERSION, + "as_of": _as_of_stamp(as_of), + "lineage": lineage, + "counts": counts, + "files": files, + } + snapshot_hash = hashlib.sha256( + json.dumps(content, sort_keys=True, separators=(",", ":"), default=str).encode("utf-8") + ).hexdigest() + manifest = {**content, "snapshot_hash": snapshot_hash} + _write_json(target / "manifest.json", manifest) + return manifest + + +def verify_snapshot(in_dir: Path) -> SnapshotVerification: + target = Path(in_dir) + manifest_path = target / "manifest.json" + if not manifest_path.exists(): + return SnapshotVerification(False, ("missing manifest.json",), "") + try: + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + except json.JSONDecodeError as exc: + return SnapshotVerification(False, (f"invalid manifest: {exc}",), "") + errors: list[str] = [] + files = manifest.get("files", {}) + for name, meta in files.items(): + path = target / name + if not path.exists(): + errors.append(f"missing file: {name}") + continue + if _digest(path) != meta.get("sha256"): + errors.append(f"hash mismatch: {name}") + if meta.get("rows") is not None: + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except json.JSONDecodeError: + if name.endswith(".json"): + errors.append(f"invalid json: {name}") + continue + if isinstance(payload, list) and len(payload) != meta["rows"]: + errors.append(f"row count mismatch: {name}") + content = { + key: manifest[key] + for key in ("archive_version", "as_of", "lineage", "counts", "files") + if key in manifest + } + expected = hashlib.sha256( + json.dumps(content, sort_keys=True, separators=(",", ":"), default=str).encode("utf-8") + ).hexdigest() + if expected != manifest.get("snapshot_hash"): + errors.append("snapshot hash mismatch") + return SnapshotVerification( + ok=not errors, + errors=tuple(errors), + snapshot_hash=str(manifest.get("snapshot_hash", "")), + ) + + +def import_snapshot( + store: JanusStore, + in_dir: Path, + *, + verify: bool = True, +) -> dict[str, int]: + target = Path(in_dir) + if verify: + result = verify_snapshot(target) + if not result.ok: + raise ValueError("snapshot verification failed: " + "; ".join(result.errors)) + observations = json.loads((target / "observations.json").read_text(encoding="utf-8")) + features = json.loads((target / "features.json").read_text(encoding="utf-8")) + for row in observations: + store.insert_observation(Observation.model_validate(row)) + with store.connection: + for row in features: + store.connection.execute( + """ + INSERT OR REPLACE INTO feature_value + (entity_id, as_of, name, version, value, features_hash, source_hash, computed_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + row["entity_id"], + row["as_of"], + row["name"], + row["version"], + json.dumps(row["value"], sort_keys=True, default=str), + row["features_hash"], + row["source_hash"], + row["computed_at"], + ), + ) + return {"observations": len(observations), "features": len(features)} diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md index f27cbdb..ea994d3 100644 --- a/docs/BACKLOG.md +++ b/docs/BACKLOG.md @@ -7,7 +7,7 @@ criteria. ## How to read this -**Current status (2026-11-24):** JAN-001, JAN-002, JAN-003, JAN-005, JAN-007, +**Current status (2026-11-24):** JAN-001, JAN-002, JAN-003, JAN-005, JAN-007, JAN-021, JAN-008, JAN-009, JAN-010, JAN-015, JAN-016, JAN-019, JAN-023, JAN-024, JAN-025, JAN-027, JAN-028, JAN-031 (tracker #39 / JAN-074), JAN-033, JAN-034, JAN-035, JAN-037, JAN-040, JAN-041, @@ -25,7 +25,7 @@ DSH UI wiring and cron are deferred to v0.2. See `schemas/janus.schema.json`, `tests/test_debrief.py`, `tests/test_persona_weighting.py`, `tests/test_mcp_service.py`, `tests/test_beliefbench.py`, `tests/test_gdelt.py`, `tests/test_rss.py`, `tests/test_scheduler.py`, -`tests/test_quality.py`, and `tests/test_copy.py`. +`tests/test_quality.py`, `tests/test_snapshot_archive.py`, and `tests/test_copy.py`. - **Milestones** are delivery windows, not promises: M0 foundation, M1 data and memory, M2 analysis, M3 forecast and review, M4 interface, M5 evaluation and diff --git a/docs/DATA_MODEL.md b/docs/DATA_MODEL.md index 6a81ef4..09fae9e 100644 --- a/docs/DATA_MODEL.md +++ b/docs/DATA_MODEL.md @@ -76,6 +76,15 @@ version. Predictions reference an artifact through the existing `model_version` column using the `version@` convention; no table or migration is added. See `docs/FORECASTING.md` for replay rules. +## Snapshot archives + +`core/janus/memory/snapshot_archive.py` exports an as-of freeze as +`manifest.json` plus `observations.json` and `features.json` (and Parquet when +an optional writer is available). The manifest records row counts, per-file +SHA-256 hashes, lineage, and a content hash. `verify_snapshot` detects tampering +or missing files before `import_snapshot` writes into a fresh store. The CLI +exposes `janus archive export/verify/import`. + ## As-of semantics There are two questions, and two modes: diff --git a/tests/test_snapshot_archive.py b/tests/test_snapshot_archive.py new file mode 100644 index 0000000..1710f53 --- /dev/null +++ b/tests/test_snapshot_archive.py @@ -0,0 +1,150 @@ +from __future__ import annotations + +import json +from datetime import datetime, timezone + +import pytest + +from janus.analysis.feature_store import FeatureStore +from janus.memory.models import Observation, ObservationKind +from janus.memory.snapshot_archive import ( + export_snapshot, + import_snapshot, + verify_snapshot, +) +from janus.memory.store import JanusStore + + +def _seed() -> JanusStore: + store = JanusStore(":memory:") + as_of = datetime(2026, 1, 2, tzinfo=timezone.utc) + for index in range(2): + store.insert_observation( + Observation( + id=f"news-{index}", + entity_id="ACME", + kind=ObservationKind.news, + source="rss", + published_at=as_of, + value={"title": f"story {index}"}, + raw_hash=f"hash-{index}", + ) + ) + store.insert_observation( + Observation( + id="future", + entity_id="ACME", + kind=ObservationKind.news, + source="rss", + published_at=datetime(2026, 3, 1, tzinfo=timezone.utc), + value={"title": "future"}, + raw_hash="future", + ) + ) + FeatureStore(store).materialize( + "ACME", + as_of, + {"close": 101.5, "rsi_14": 61.0, "feature_version": "v1"}, + source_hash="source-1", + ) + return store + + +def test_export_manifest_and_verify(tmp_path) -> None: + store = _seed() + as_of = datetime(2026, 1, 3, tzinfo=timezone.utc) + manifest = export_snapshot(store, tmp_path / "snap", as_of=as_of) + + assert manifest["counts"] == {"observations": 2, "features": 2} + assert manifest["lineage"]["as_of"].startswith("2026-01-03") + assert "observations.json" in manifest["files"] + assert "features.json" in manifest["files"] + assert verify_snapshot(tmp_path / "snap").ok is True + + observations = json.loads((tmp_path / "snap" / "observations.json").read_text()) + assert {row["id"] for row in observations} == {"news-0", "news-1"} + + +def test_tampering_is_detected(tmp_path) -> None: + store = _seed() + export_snapshot(store, tmp_path / "snap", as_of=datetime(2026, 1, 3, tzinfo=timezone.utc)) + path = tmp_path / "snap" / "observations.json" + path.write_text(path.read_text() + " ") + + result = verify_snapshot(tmp_path / "snap") + assert result.ok is False + assert any("hash mismatch" in error for error in result.errors) + with pytest.raises(ValueError, match="verification failed"): + import_snapshot(JanusStore(":memory:"), tmp_path / "snap") + + +def test_import_round_trips_observations_and_features(tmp_path) -> None: + source = _seed() + as_of = datetime(2026, 1, 2, tzinfo=timezone.utc) + export_snapshot(source, tmp_path / "snap", as_of=as_of) + + target = JanusStore(":memory:") + counts = import_snapshot(target, tmp_path / "snap") + + assert counts == {"observations": 2, "features": 2} + assert target.get_observation("news-0") is not None + assert target.get_observation("future") is None + assert FeatureStore(target).get("ACME", as_of) == FeatureStore(source).get( + "ACME", as_of + ) + original_hash = source.connection.execute( + "SELECT DISTINCT features_hash FROM feature_value" + ).fetchone()[0] + restored_hash = target.connection.execute( + "SELECT DISTINCT features_hash FROM feature_value" + ).fetchone()[0] + assert restored_hash == original_hash + + +def test_missing_manifest_is_explicit(tmp_path) -> None: + result = verify_snapshot(tmp_path / "missing") + assert result.ok is False + assert result.errors == ("missing manifest.json",) + + +def test_archive_cli_export_and_verify(tmp_path, monkeypatch) -> None: + from typer.testing import CliRunner + + from janus.cli import app + + path = tmp_path / "janus.db" + store = JanusStore(path) + as_of = datetime(2026, 1, 2, tzinfo=timezone.utc) + store.insert_observation( + Observation( + id="news", + entity_id="ACME", + kind=ObservationKind.news, + source="rss", + published_at=as_of, + value={"title": "story"}, + raw_hash="hash", + ) + ) + monkeypatch.setenv("JANUS_DB", str(path)) + runner = CliRunner() + + exported = runner.invoke( + app, + [ + "archive", + "export", + "--out", + str(tmp_path / "snap"), + "--as-of", + as_of.isoformat(), + "--no-parquet", + ], + ) + assert exported.exit_code == 0, exported.output + + verified = runner.invoke( + app, ["archive", "verify", str(tmp_path / "snap"), "--json"] + ) + assert verified.exit_code == 0, verified.output + assert json.loads(verified.output)["ok"] is True