Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
79 changes: 79 additions & 0 deletions core/janus/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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()
Expand Down Expand Up @@ -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"),
Expand Down
231 changes: 231 additions & 0 deletions core/janus/memory/snapshot_archive.py
Original file line number Diff line number Diff line change
@@ -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)}
4 changes: 2 additions & 2 deletions docs/BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down
9 changes: 9 additions & 0 deletions docs/DATA_MODEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,15 @@ version. Predictions reference an artifact through the existing `model_version`
column using the `version@<artifact_id[:12]>` 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:
Expand Down
Loading
Loading