diff --git a/README.md b/README.md index d9c5f70..0eeae5c 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` | +| Retention deletes only expired rows; redaction is deep and non-mutating | `tests/test_retention.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..3c1bca3 100644 --- a/core/janus/cli.py +++ b/core/janus/cli.py @@ -19,6 +19,12 @@ ModelRegistry, ) from .memory.migrations import apply_migrations, current_version +from .memory.retention import ( + RetentionPolicy, + RetentionRule, + apply_retention, + export_redacted, +) from .memory.models import ObservationKind from .memory.store import JanusStore @@ -29,9 +35,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.") +retention_app = typer.Typer(help="Apply retention and export redacted data.") app.add_typer(config_app, name="config") app.add_typer(schema_app, name="schema") app.add_typer(model_app, name="model") +app.add_typer(retention_app, name="retention") @app.command() @@ -159,6 +167,83 @@ def schema_check( raise typer.Exit(code=1) +def _retention_rule(value: str) -> RetentionRule: + parts = value.split(":") + if len(parts) != 3: + raise typer.BadParameter("rules use SOURCE:KIND:DAYS, e.g. rss:news:30") + source, kind, days = parts + try: + return RetentionRule(source=source, kind=kind, max_age_days=int(days)) + except ValueError as exc: + raise typer.BadParameter(str(exc)) from exc + + +@retention_app.command("apply") +def retention_apply( + as_of: str = typer.Option(..., "--as-of", help="Retention cutoff timestamp"), + rule: Optional[list[str]] = typer.Option( + None, "--rule", help="SOURCE:KIND:DAYS (repeatable)" + ), + default_days: Optional[int] = typer.Option( + None, "--default-days", help="Fallback max age for unmatched rows" + ), + db: Optional[str] = typer.Option(None, "--db", help="SQLite path"), + dry_run: bool = typer.Option(False, "--dry-run", help="Report without deleting"), + as_json: bool = typer.Option(False, "--json", help="Emit JSON"), +) -> None: + """Delete observations whose retention window has expired.""" + + 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) + policy = RetentionPolicy( + rules=tuple(_retention_rule(item) for item in (rule or [])), + default_max_age_days=default_days, + ) + settings = load_settings() + result = apply_retention( + JanusStore(db or settings.database), + as_of=stamp, + policy=policy, + dry_run=dry_run, + ) + if as_json: + typer.echo(json.dumps(result.to_dict(), indent=2, sort_keys=True)) + else: + typer.echo( + f"scanned={result.scanned} deleted={result.deleted} kept={result.kept}" + ) + + +@retention_app.command("export") +def retention_export( + entity: str = typer.Argument(..., help="Entity id"), + as_of: str = typer.Option(..., "--as-of", help="Point-in-time timestamp"), + out: Path = typer.Option(..., "--out", help="JSONL output path"), + field: Optional[list[str]] = typer.Option( + None, "--field", help="Field name to redact (repeatable)" + ), + db: Optional[str] = typer.Option(None, "--db", help="SQLite path"), +) -> None: + """Export one entity's as-of observations with selected fields redacted.""" + + 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() + rows = JanusStore(db or settings.database).query_observations_as_of( + entity, stamp, mode="published" + ) + target = export_redacted(rows, out, fields=field or []) + typer.echo(f"wrote {len(rows)} redacted observation(s) to {target}") + + @app.command() def migrate( db: Optional[str] = typer.Option(None, "--db", help="SQLite path"), diff --git a/core/janus/memory/retention.py b/core/janus/memory/retention.py new file mode 100644 index 0000000..b36365c --- /dev/null +++ b/core/janus/memory/retention.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +import json +from dataclasses import asdict, dataclass +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any, Iterable, Optional, Sequence + +from .models import Observation +from .store import JanusStore + + +@dataclass(frozen=True) +class RetentionRule: + """One source/kind retention window. ``*`` matches any value.""" + + source: str = "*" + kind: str = "*" + max_age_days: int = 365 + + def __post_init__(self) -> None: + if self.max_age_days < 0: + raise ValueError("max_age_days must be non-negative") + + def matches(self, observation: Observation) -> bool: + source = str(observation.source) + source_base = source.split(":")[0] + source_ok = self.source in {"*", source, source_base} + kind_ok = self.kind in {"*", observation.kind.value} + return source_ok and kind_ok + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +@dataclass(frozen=True) +class RetentionPolicy: + rules: tuple[RetentionRule, ...] = () + default_max_age_days: Optional[int] = None + + def __post_init__(self) -> None: + if self.default_max_age_days is not None and self.default_max_age_days < 0: + raise ValueError("default_max_age_days must be non-negative") + + def max_age_for(self, observation: Observation) -> Optional[int]: + for rule in self.rules: + if rule.matches(observation): + return rule.max_age_days + return self.default_max_age_days + + def expiration(self, observation: Observation) -> Optional[datetime]: + days = self.max_age_for(observation) + if days is None: + return None + return observation.published_at + timedelta(days=days) + + def expired(self, observation: Observation, as_of: datetime) -> bool: + expiration = self.expiration(observation) + return expiration is not None and expiration <= as_of + + def to_dict(self) -> dict[str, Any]: + return { + "rules": [rule.to_dict() for rule in self.rules], + "default_max_age_days": self.default_max_age_days, + } + + @classmethod + def from_dict(cls, payload: dict[str, Any]) -> "RetentionPolicy": + return cls( + rules=tuple(RetentionRule(**item) for item in payload.get("rules", [])), + default_max_age_days=payload.get("default_max_age_days"), + ) + + +@dataclass(frozen=True) +class RetentionResult: + as_of: str + scanned: int + deleted: int + kept: int + by_source: dict[str, int] + deleted_ids: tuple[str, ...] + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +@dataclass(frozen=True) +class RetentionSkip: + observation_id: str + entity_id: str + kind: str + source: str + expiration: Optional[str] + + +def apply_retention( + store: JanusStore, + *, + as_of: datetime, + policy: RetentionPolicy, + dry_run: bool = False, +) -> RetentionResult: + """Delete observations whose policy expiration is at or before ``as_of``.""" + + if as_of.tzinfo is None or as_of.tzinfo.utcoffset(as_of) is None: + raise ValueError("as_of must be timezone-aware") + rows = store.connection.execute( + "SELECT id, entity_id, kind, source, published_at FROM observation" + ).fetchall() + expired: list[str] = [] + by_source: dict[str, int] = {} + for row in rows: + observation = Observation( + id=row["id"], + entity_id=row["entity_id"], + kind=row["kind"], + source=row["source"], + published_at=datetime.fromisoformat(row["published_at"]), + value={}, + raw_hash="", + ) + if policy.expired(observation, as_of): + expired.append(observation.id) + by_source[observation.source] = by_source.get(observation.source, 0) + 1 + if expired and not dry_run: + placeholders = ",".join("?" for _ in expired) + with store.connection: + store.connection.execute( + f"DELETE FROM observation WHERE id IN ({placeholders})", + expired, + ) + return RetentionResult( + as_of=as_of.isoformat(), + scanned=len(rows), + deleted=len(expired), + kept=len(rows) - len(expired), + by_source=dict(sorted(by_source.items())), + deleted_ids=tuple(sorted(expired)), + ) + + +def redact_value(value: Any, fields: Iterable[str]) -> Any: + """Return a deep copy with the named keys masked.""" + + names = {str(field).lower() for field in fields} + if isinstance(value, dict): + result = {} + for key, item in value.items(): + if str(key).lower() in names: + result[key] = "***" + else: + result[key] = redact_value(item, names) + return result + if isinstance(value, list): + return [redact_value(item, names) for item in value] + return value + + +def redact_observation(observation: Observation, fields: Iterable[str]) -> dict[str, Any]: + payload = observation.model_dump(mode="json") + payload["value"] = redact_value(payload["value"], fields) + if "raw_uri" in {str(field).lower() for field in fields}: + payload["raw_uri"] = "***" + return payload + + +def export_redacted( + observations: Sequence[Observation], + path: Path, + *, + fields: Iterable[str], +) -> Path: + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + with target.open("w", encoding="utf-8") as handle: + for observation in observations: + handle.write( + json.dumps( + redact_observation(observation, fields), + sort_keys=True, + default=str, + ) + + "\n" + ) + return target diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md index f27cbdb..92a8367 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-020, 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_retention.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..4ce9bf4 100644 --- a/docs/DATA_MODEL.md +++ b/docs/DATA_MODEL.md @@ -76,6 +76,14 @@ 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. +## Retention and redaction + +`core/janus/memory/retention.py` applies source/kind retention windows and +deletes only observations whose expiration is at or before `as_of`; a dry run +reports the same counts without writing. `redact_value` masks named fields at +any depth, and `export_redacted` writes JSONL without mutating stored facts. +The CLI exposes `janus retention apply` and `janus retention export`. + ## As-of semantics There are two questions, and two modes: diff --git a/tests/test_retention.py b/tests/test_retention.py new file mode 100644 index 0000000..dc9bf02 --- /dev/null +++ b/tests/test_retention.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +import json +from datetime import datetime, timedelta, timezone + +import pytest + +from janus.memory.models import Observation, ObservationKind +from janus.memory.retention import ( + RetentionPolicy, + RetentionRule, + apply_retention, + export_redacted, + redact_observation, + redact_value, +) +from janus.memory.store import JanusStore + + +def _obs( + obs_id: str, + *, + source: str = "rss", + kind: ObservationKind = ObservationKind.news, + published_at: datetime | None = None, + value: dict | None = None, +) -> Observation: + return Observation( + id=obs_id, + entity_id="ACME", + kind=kind, + source=source, + published_at=published_at or datetime(2026, 1, 1, tzinfo=timezone.utc), + value=value or {"title": obs_id}, + raw_hash=f"hash:{obs_id}", + ) + + +def test_rule_matches_source_prefix_and_kind() -> None: + rule = RetentionRule(source="rss", kind="news", max_age_days=30) + assert rule.matches(_obs("a", source="rss:ir")) is True + assert rule.matches(_obs("a", source="gdelt")) is False + assert rule.matches(_obs("a", kind=ObservationKind.price)) is False + + +def test_apply_retention_deletes_only_expired() -> None: + store = JanusStore(":memory:") + as_of = datetime(2026, 2, 1, tzinfo=timezone.utc) + store.insert_observation(_obs("old", published_at=as_of - timedelta(days=45))) + store.insert_observation(_obs("new", published_at=as_of - timedelta(days=5))) + store.insert_observation( + _obs( + "price", + source="tiingo", + kind=ObservationKind.price, + published_at=as_of - timedelta(days=45), + ) + ) + policy = RetentionPolicy( + rules=( + RetentionRule(source="rss", kind="news", max_age_days=30), + RetentionRule(source="tiingo", kind="price", max_age_days=3650), + ) + ) + + result = apply_retention(store, as_of=as_of, policy=policy) + + assert result.scanned == 3 + assert result.deleted == 1 + assert result.kept == 2 + assert result.deleted_ids == ("old",) + assert result.by_source == {"rss": 1} + assert store.get_observation("old") is None + assert store.get_observation("new") is not None + assert store.get_observation("price") is not None + + +def test_dry_run_reports_without_deleting() -> None: + store = JanusStore(":memory:") + as_of = datetime(2026, 2, 1, tzinfo=timezone.utc) + store.insert_observation(_obs("old", published_at=as_of - timedelta(days=45))) + policy = RetentionPolicy(rules=(RetentionRule(max_age_days=30),)) + + result = apply_retention(store, as_of=as_of, policy=policy, dry_run=True) + + assert result.deleted == 1 + assert store.get_observation("old") is not None + + +def test_default_policy_keeps_unmatched_sources() -> None: + store = JanusStore(":memory:") + as_of = datetime(2026, 2, 1, tzinfo=timezone.utc) + store.insert_observation(_obs("rss", published_at=as_of - timedelta(days=45))) + store.insert_observation( + _obs("sec", source="sec_edgar", published_at=as_of - timedelta(days=45)) + ) + policy = RetentionPolicy( + rules=(RetentionRule(source="rss", max_age_days=30),), + default_max_age_days=None, + ) + + result = apply_retention(store, as_of=as_of, policy=policy) + + assert result.deleted_ids == ("rss",) + assert store.get_observation("sec") is not None + + +def test_policy_round_trips() -> None: + policy = RetentionPolicy( + rules=(RetentionRule(source="rss", kind="news", max_age_days=30),), + default_max_age_days=365, + ) + assert RetentionPolicy.from_dict(policy.to_dict()) == policy + + +def test_as_of_must_be_timezone_aware() -> None: + with pytest.raises(ValueError, match="timezone-aware"): + apply_retention( + JanusStore(":memory:"), + as_of=datetime(2026, 1, 1), + policy=RetentionPolicy(), + ) + + +def test_redaction_is_deep_and_does_not_mutate() -> None: + value = { + "email": "a@example.com", + "profile": {"phone": "123", "safe": "ok"}, + "list": [{"ssn": "x"}], + } + redacted = redact_value(value, {"email", "phone", "ssn"}) + assert redacted == { + "email": "***", + "profile": {"phone": "***", "safe": "ok"}, + "list": [{"ssn": "***"}], + } + assert value["email"] == "a@example.com" + + +def test_redact_observation_and_export(tmp_path) -> None: + observation = _obs( + "news", + value={"title": "hello", "email": "a@example.com"}, + ) + payload = redact_observation(observation, {"email"}) + assert payload["value"]["email"] == "***" + assert observation.value["email"] == "a@example.com" + + out = export_redacted([observation], tmp_path / "redacted.jsonl", fields={"email"}) + line = json.loads(out.read_text().strip()) + assert line["value"]["email"] == "***" + assert line["id"] == "news" + + +def test_retention_cli_apply_and_export(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, 2, 1, tzinfo=timezone.utc) + store.insert_observation( + _obs( + "old", + published_at=as_of - timedelta(days=45), + value={"title": "hello", "email": "a@example.com"}, + ) + ) + store.insert_observation(_obs("new", published_at=as_of - timedelta(days=2))) + monkeypatch.setenv("JANUS_DB", str(path)) + runner = CliRunner() + + applied = runner.invoke( + app, + [ + "retention", + "apply", + "--as-of", + as_of.isoformat(), + "--rule", + "rss:news:30", + "--json", + ], + ) + assert applied.exit_code == 0, applied.output + assert json.loads(applied.output)["deleted"] == 1 + assert store.get_observation("old") is None + + # fresh row for the export path + store.insert_observation( + _obs( + "export", + published_at=as_of - timedelta(days=1), + value={"title": "hello", "email": "a@example.com"}, + ) + ) + out = tmp_path / "redacted.jsonl" + exported = runner.invoke( + app, + [ + "retention", + "export", + "ACME", + "--as-of", + as_of.isoformat(), + "--out", + str(out), + "--field", + "email", + ], + ) + assert exported.exit_code == 0, exported.output + payloads = [json.loads(line) for line in out.read_text().splitlines()] + assert all(item["value"].get("email") in (None, "***") for item in payloads)