diff --git a/docs/reference/data-lake.md b/docs/reference/data-lake.md index 5896840..30c3fcd 100644 --- a/docs/reference/data-lake.md +++ b/docs/reference/data-lake.md @@ -297,12 +297,49 @@ snapshots with erased raw artefacts. opt-in maintenance (24 h margin) or the DAG's orphan removal removes them. * The Parquet `raw` files that exist from before the switch (`lake_files`) keep their retention until they are expired. +### One-off import of the Parquet lake + +`corvus-import-parquet` copies the live Parquet files of the lake (`corvus.lake_files`, `deleted_at IS NULL`) into the +Iceberg tables once, so that captures written before the switch are in the Iceberg tables too. It is run by hand, per +UTC date range, and it is idempotent (operator steps below). + +* `events`: the rows as stored, with the player key of their session. +* `raw`: the payloads are decrypted with the player's DEK and joined with the events of the same date on + `(session_id, seq)` for offset, direction, state, packet type and wire packet id. The payload is stored in plaintext, + like every Iceberg `raw` row. `protocol_version` is the client protocol of the session. +* `session_ends`: the sessions that ended, with their counters, from PostgreSQL. Only sessions that have rows in the + Parquet files of their day are imported; a session already in `capture.session_ends` (written by ingest) is not. + A day without Parquet files imports nothing. +* Not imported: `sessions` and `segments`. Their non-nullable columns `text_packets_captured`, `names_kept`, the CloudNet + fields and `stage` are not stored in PostgreSQL. Dashboards that join to `sessions` or `segments` do not see the + imported captures; the `events` and `raw` rows of those sessions are there. +* Never imported, each counted in the report: rows of an erased player, rows of a player without a DEK (including orphan + sessions), rows of sessions unknown to the catalog. A raw row without its event, a payload that does not decrypt and a + repeated `(session_id, seq)` of the lake's at-least-once duplicates are skipped too (a repeated event is copied once). +* Idempotency is data-based: before a file is appended, rows whose key already exists in the Iceberg partition of + their date are dropped (`(session_id, seq)` for `events` and `raw`, `session_id` for `session_ends`). The key columns + are read with a filter on `date`. A rerun, a resume after a failure, or a table whose snapshots were expired by the + maintenance imports nothing twice. Each commit is also tagged with `corvus.parquet-import-source` in its snapshot + summary; the tag only lets a rerun skip the key read of an already committed file and is not relied on. + +#### Running it once (operator) + +1. Run a Job from the services image (the one of the compact CronJob) with the command `corvus-import-parquet` + and the environment of the compact CronJob. The Job also needs `CORVUS_KEK` and `CORVUS_KEK_ID` from the same + secret the ingest Deployment uses: the compact template does not carry the KEK. Set `restartPolicy: Never` and + `backoffLimit: 0`; a failed run is resumed by starting a new Job, not by Kubernetes retrying it. +2. First run with `--dry-run`. It reads the lake and the catalog, creates nothing and prints the counts per table and + date. Check the skipped counts and the rows to import against the expectation. +3. Run it without `--dry-run`. Optional `--date-from YYYY-MM-DD` and `--date-to YYYY-MM-DD` (inclusive, UTC) split the + work by day. The events of one UTC date are read into memory at once, so size the Job's memory for the largest date. +4. Compare the row counts of the Iceberg tables with the report (`session_ends`, `events`, `raw` of the imported dates). + ### Not covered yet -Each is a separate step: backfill of the existing Parquet files into Iceberg, snapshot pins by Iceberg snapshot id, -reading Iceberg `raw` in the ML jobs (`corvus-ml` reads the Parquet `raw` layout only), a re-check of an erasure -after its request completed (rows that land after the grace period are not seen again), and removal of an erased -player's name from other players' payloads (see "Privacy and retention"). +Each is a separate step: snapshot pins by Iceberg snapshot id, reading Iceberg `raw` in the ML jobs (`corvus-ml` reads +the Parquet `raw` layout only), importing `sessions` and `segments` (needs the four columns above in PostgreSQL), a +re-check of an erasure after its request completed (rows that land after the grace period are not seen again), and +removal of an erased player's name from other players' payloads (see "Privacy and retention"). ## 3. Keys and erasure diff --git a/services/pyproject.toml b/services/pyproject.toml index 0fdd342..a8cc3bd 100644 --- a/services/pyproject.toml +++ b/services/pyproject.toml @@ -33,6 +33,7 @@ corvus-ingest = "corvus_services.ingest:main" corvus-migrate = "corvus_services.migrate:main" corvus-housekeeping = "corvus_services.housekeeping:main" corvus-compact = "corvus_services.compact:main" +corvus-import-parquet = "corvus_services.parquet_import:main" corvus-api = "corvus_services.api.app:main" corvus-score = "corvus_services.scoring.main:main" diff --git a/services/src/corvus_services/iceberg_sink.py b/services/src/corvus_services/iceberg_sink.py index b67dfa8..291fc6d 100644 --- a/services/src/corvus_services/iceberg_sink.py +++ b/services/src/corvus_services/iceberg_sink.py @@ -28,6 +28,8 @@ import random import time from collections.abc import Callable, Iterator +from datetime import date +from typing import Any import pyarrow as pa from pyiceberg.catalog import Catalog @@ -37,6 +39,7 @@ NoSuchTableError, TableAlreadyExistsError, ) +from pyiceberg.expressions import EqualTo from pyiceberg.partitioning import PartitionField, PartitionSpec from pyiceberg.schema import Schema from pyiceberg.table import Table @@ -67,6 +70,8 @@ ICEBERG_LAKE_VERSION = 2 LAKE_VERSION_PROPERTY = "corvus.lake-schema-version" +IMPORT_PROPERTY = "corvus.parquet-import-source" +"""Snapshot summary key of a one-off import commit: the Parquet object or Postgres source copied.""" DATE_COLUMN = "date" PARTITION_FIELD_ID = 1000 MAX_COMMIT_ATTEMPTS = 5 @@ -257,11 +262,47 @@ async def ping(self) -> None: def _write(self, buf: TableBuffer) -> None: self._append_with_retry(buf.table, _arrow_rows(buf)) - def _append_with_retry(self, name: str, rows: pa.Table) -> None: + def append_import(self, name: str, rows: pa.Table, source: str) -> None: + """One commit of imported rows (``lake_rows`` layout), tagged with ``source`` in the + snapshot summary under ``IMPORT_PROPERTY``. ``imported_sources`` reads the tags back.""" + self._append_with_retry(name, rows, {IMPORT_PROPERTY: source}) + + def existing_keys(self, name: str, day: date, columns: tuple[str, ...]) -> set[tuple[Any, ...]]: + """Values of ``columns`` of the rows in the ``date`` partition ``day`` of ``name``: a data + read of the key columns only, so it does not depend on snapshot history (one-off import).""" + try: + table = self._catalog.load_table(self.ident(name)) + except NoSuchTableError: + return set() + predicate = EqualTo(DATE_COLUMN, day) # type: ignore[call-arg,arg-type] + scan = table.scan(row_filter=predicate, selected_fields=columns) + arrow = scan.to_arrow() + return set(zip(*(arrow.column(c).to_pylist() for c in columns), strict=True)) + + def imported_sources(self, name: str) -> set[str]: + """Sources whose import committed to ``name``: the snapshots still in the table's history. + A fast path only: expired snapshots lose their tags, ``existing_keys`` is the check.""" + try: + table = self._catalog.load_table(self.ident(name)) + except NoSuchTableError: + return set() + found: set[str] = set() + for snapshot in table.metadata.snapshots: + summary = snapshot.summary + if summary is not None and IMPORT_PROPERTY in summary.additional_properties: + found.add(summary.additional_properties[IMPORT_PROPERTY]) + return found + + def _append_with_retry( + self, name: str, rows: pa.Table, snapshot_properties: dict[str, str] | None = None + ) -> None: for attempt in range(1, MAX_COMMIT_ATTEMPTS + 1): table = self._catalog.load_table(self.ident(name)) try: - table.append(rows) + if snapshot_properties: + table.append(rows, snapshot_properties=snapshot_properties) + else: + table.append(rows) return except CommitFailedException: if attempt == MAX_COMMIT_ATTEMPTS: @@ -304,6 +345,16 @@ def _arrow_rows(buf: TableBuffer) -> pa.Table: return rows.sort_by([(key, "ascending") for key in SORT_KEYS[buf.table]]) +def lake_rows(table: str, data: pa.Table, day: date) -> pa.Table: + """Rows of a lake table from ``data``, which holds every column of the table but ``date``. + Adds the ``date`` partition value and sorts like the sink does (one-off import).""" + schema = _ARROW_SCHEMAS[table] + columns = {name: data.column(name).cast(schema.field(name).type) for name in data.column_names} + columns[DATE_COLUMN] = [day] * data.num_rows + rows = pa.Table.from_pydict(columns, schema=schema) + return rows.sort_by([(key, "ascending") for key in SORT_KEYS[table]]) + + _ARROW_SCHEMAS: dict[str, pa.Schema] = { name: schema.as_arrow() for name, schema in ICEBERG_SCHEMAS.items() } diff --git a/services/src/corvus_services/parquet_import.py b/services/src/corvus_services/parquet_import.py new file mode 100644 index 0000000..46e4020 --- /dev/null +++ b/services/src/corvus_services/parquet_import.py @@ -0,0 +1,564 @@ +"""``corvus-import-parquet``: one-off copy of the Parquet lake into the Iceberg tables. + +Run once, after the switch to ``CORVUS_LAKE_FORMAT=iceberg``, so that the captures that live only +in the Parquet lake are read from the Iceberg tables as well (docs/reference/data-lake.md, +section 2a, "One-off import"). The sources are the live ``corvus.lake_files`` entries and the +sessions, players and wrapped DEKs of PostgreSQL; the Parquet objects are read from S3. + +Per UTC date, in this order: + +* ``events``: every events file of the date, the player key taken from the session; +* ``raw``: every raw file of the date. The payloads are decrypted with the player's DEK (AAD + ``session_id || seq``) and joined with the events of the same date on ``(session_id, seq)``, which + supply offset, direction, state, packet type and wire packet id. ``protocol_version`` is the + client protocol of the session; +* ``session_ends``: the sessions of the date that ended (counters and end time from PostgreSQL). + +Not imported: ``sessions`` and ``segments``. Their non-nullable Iceberg columns +(text_packets_captured, names_kept, the CloudNet fields, stage) are not stored in PostgreSQL, and a +null would not fit. + +Skipped, never imported, each counted in the report: rows of an erased player (``erased_at``), rows +of a player without a DEK, rows of orphan sessions (no player), rows of sessions unknown to the +catalog. A raw row without its event, a payload that does not decrypt and a repeated +``(session_id, seq)`` of the lake's at-least-once duplicates are skipped and counted too; a repeated +event is copied once, the first occurrence in file order. + +Idempotency is data-based. Before a file is appended, every row whose key already exists in the +Iceberg partition of its date is dropped: ``(session_id, seq)`` for events and raw, ``session_id`` +for session_ends. A rerun, a resume after a failure, or a table whose snapshots were expired and +rewritten therefore imports nothing twice. The snapshot tag (``IMPORT_PROPERTY``: the S3 key of a +Parquet file, or ``postgres:session_ends:``) is only a fast path that skips the key read of a +file already committed. Every file is still read on every run, because the join index and the +duplicate check need all events of a date. session_ends are imported only for sessions with rows in +the Parquet files of their day. +""" + +from __future__ import annotations + +import argparse +import io +import logging +import sys +from collections import Counter, defaultdict +from collections.abc import Sequence +from dataclasses import dataclass +from datetime import UTC, date, datetime +from typing import Any, Protocol + +import boto3 +import psycopg +import pyarrow as pa +import pyarrow.parquet as pq +from botocore.config import Config +from cryptography.exceptions import InvalidTag +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +from .config import Settings +from .crypto import Keyring, payload_aad +from .iceberg_sink import IcebergSink, lake_rows +from .schema import ICEBERG_LAYOUT + +log = logging.getLogger("corvus.import") + +EVENT_FIELDS = ("offset_nanos", "direction", "state", "packet_type", "wire_packet_id") +RAW_FIELDS = ("session_id", "segment", "seq", "payload_original_size", "nonce", "ciphertext") +SKIP_UNKNOWN = "skipped_unknown_session" +SKIP_NO_KEY = "skipped_no_key" +SKIP_ERASED = "skipped_erased" +SKIP_NO_EVENT = "skipped_no_event" +SKIP_DUPLICATE = "skipped_duplicate" +SKIP_DECRYPT = "skipped_decrypt_failed" +TABLES = ("events", "raw", "session_ends") + + +@dataclass(frozen=True) +class LiveFile: + """A live ``lake_files`` entry (``deleted_at IS NULL``: replaced and purged files are gone).""" + + id: int + s3_key: str + table_name: str + date: date + + +@dataclass(frozen=True) +class SessionRecord: + session_id: bytes + pseudonym: bytes | None # None: orphan session (no SessionStart) + client_protocol: int + started_at: datetime + ended_at: datetime | None + dropped_queue_full: int + dropped_privacy: int + listener_errors: int + dropped_transport: int + + +@dataclass(frozen=True) +class PlayerRecord: + pseudonym: bytes + erased: bool + wrapped_dek: bytes | None # None: no player_keys row + + +class ImportSource(Protocol): + def live_files(self) -> list[LiveFile]: ... + def session_records(self) -> list[SessionRecord]: ... + def player_records(self) -> list[PlayerRecord]: ... + + +class ObjectReader(Protocol): + def get(self, key: str) -> bytes: ... + + +class Report: + """Counts per (table, UTC date). Keys are the names used by the importer (see the constants).""" + + def __init__(self) -> None: + self._counts: dict[tuple[str, date], Counter[str]] = defaultdict(Counter) + + def add(self, table: str, day: date, key: str, n: int = 1) -> None: + self._counts[(table, day)][key] += n + + def count(self, table: str, day: date, key: str) -> int: + return self._counts.get((table, day), Counter())[key] + + def total(self, key: str) -> int: + return sum(counter[key] for counter in self._counts.values()) + + def render(self, dry_run: bool) -> str: + head = "dry run, nothing written" if dry_run else "import done" + lines = [f"corvus-import-parquet: {head}"] + for (table, day), counter in sorted(self._counts.items()): + detail = " ".join(f"{k}={v}" for k, v in sorted(counter.items())) + lines.append(f"{table} {day.isoformat()} {detail}") + return "\n".join(lines) + + +@dataclass(frozen=True) +class _Access: + pseudonym: bytes | None + dek: bytes | None + session: SessionRecord | None + reason: str | None # None: importable, else the skip counter + + +class _Resolver: + """Whether the rows of a session may be imported, and the DEK of its player.""" + + def __init__( + self, + sessions: Sequence[SessionRecord], + players: Sequence[PlayerRecord], + keyring: Keyring, + ) -> None: + self._sessions = {s.session_id: s for s in sessions} + self._players = {p.pseudonym: p for p in players} + self._keyring = keyring + self._cache: dict[bytes, _Access] = {} + self._deks: dict[bytes, bytes] = {} + + def access(self, session_id: bytes) -> _Access: + found = self._cache.get(session_id) + if found is None: + found = self._resolve(session_id) + self._cache[session_id] = found + return found + + def _resolve(self, session_id: bytes) -> _Access: + session = self._sessions.get(session_id) + if session is None: + return _Access(None, None, None, SKIP_UNKNOWN) + pseudonym = session.pseudonym + if pseudonym is None: + return _Access(None, None, session, SKIP_NO_KEY) + player = self._players.get(pseudonym) + if player is not None and player.erased: + return _Access(pseudonym, None, session, SKIP_ERASED) + if player is None or player.wrapped_dek is None: + return _Access(pseudonym, None, session, SKIP_NO_KEY) + dek = self._deks.get(pseudonym) + if dek is None: + # A wrong KEK raises UnwrapError and aborts the run before anything of it is written. + dek = self._keyring.unwrap(pseudonym, player.wrapped_dek) + self._deks[pseudonym] = dek + return _Access(pseudonym, dek, session, None) + + +@dataclass(slots=True) +class _Event: + offset_nanos: int + direction: int + state: int + packet_type: int + wire_packet_id: int + emitted: bool = False + + +def _utc_date(ts: datetime) -> date: + return ts.astimezone(UTC).date() + + +def _in_range(day: date, date_from: date | None, date_to: date | None) -> bool: + return (date_from is None or day >= date_from) and (date_to is None or day <= date_to) + + +def _read(data: bytes) -> pa.Table: + return pq.read_table(io.BytesIO(data)) + + +def _events_rows( + data: bytes, + resolver: _Resolver, + index: dict[tuple[bytes, int], _Event], + report: Report, + day: date, + seen: set[bytes], +) -> pa.Table: + """The importable rows of one events file (Parquet layout plus ``player_key``). Fills the + join index of the date with the rows it keeps; a repeated (session_id, seq) is dropped.""" + table = _read(data) + sids = table.column("session_id").to_pylist() + seen.update(sids) + seqs = table.column("seq").to_pylist() + fields = {name: table.column(name).to_pylist() for name in EVENT_FIELDS} + keep: list[int] = [] + keys: list[bytes] = [] + for i, (sid, seq) in enumerate(zip(sids, seqs, strict=True)): + report.add("events", day, "rows_read") + access = resolver.access(sid) + if access.reason is not None: + report.add("events", day, access.reason) + continue + assert access.pseudonym is not None + if (sid, seq) in index: + report.add("events", day, SKIP_DUPLICATE) + continue + index[(sid, seq)] = _Event(*(fields[name][i] for name in EVENT_FIELDS)) + keep.append(i) + keys.append(access.pseudonym) + kept = table.take(pa.array(keep, pa.int64())) + return kept.append_column("player_key", pa.array(keys, pa.binary(32))) + + +def _raw_rows( + data: bytes, + resolver: _Resolver, + index: dict[tuple[bytes, int], _Event], + report: Report, + day: date, + seen: set[bytes], +) -> pa.Table: + """The importable raw rows of one raw file in the Iceberg layout, payloads decrypted.""" + table = _read(data) + cols = {name: table.column(name).to_pylist() for name in RAW_FIELDS} + seen.update(cols["session_id"]) + out: dict[str, list[Any]] = {name: [] for name in ICEBERG_LAYOUT.schemas["raw"].names} + aeads: dict[bytes, AESGCM] = {} + for i in range(table.num_rows): + report.add("raw", day, "rows_read") + sid = cols["session_id"][i] + seq = cols["seq"][i] + access = resolver.access(sid) + if access.reason is not None: + report.add("raw", day, access.reason) + continue + assert access.dek is not None + assert access.session is not None + event = index.get((sid, seq)) + if event is None: + report.add("raw", day, SKIP_NO_EVENT) + continue + if event.emitted: + report.add("raw", day, SKIP_DUPLICATE) + continue + aead = aeads.get(access.dek) + if aead is None: + aead = aeads[access.dek] = AESGCM(access.dek) + try: + payload = aead.decrypt(cols["nonce"][i], cols["ciphertext"][i], payload_aad(sid, seq)) + except InvalidTag: + report.add("raw", day, SKIP_DECRYPT) + continue + event.emitted = True + out["session_id"].append(sid) + out["segment"].append(cols["segment"][i]) + out["seq"].append(seq) + out["offset_nanos"].append(event.offset_nanos) + out["direction"].append(event.direction) + out["state"].append(event.state) + out["packet_type"].append(event.packet_type) + out["wire_packet_id"].append(event.wire_packet_id) + out["protocol_version"].append(access.session.client_protocol) + out["player_key"].append(access.pseudonym) + out["payload_original_size"].append(cols["payload_original_size"][i]) + out["payload"].append(payload) + return pa.Table.from_pydict(out, schema=ICEBERG_LAYOUT.schemas["raw"]) + + +def _session_end_rows( + resolver: _Resolver, + sessions: Sequence[SessionRecord], + seen: set[bytes], + report: Report, + day: date, +) -> pa.Table: + """session_ends of the sessions that have rows in the Parquet files of ``day`` (``seen``).""" + out: dict[str, list[Any]] = {name: [] for name in ICEBERG_LAYOUT.schemas["session_ends"].names} + for s in sessions: + if s.ended_at is None or _utc_date(s.started_at) != day or s.session_id not in seen: + continue + report.add("session_ends", day, "rows_read") + access = resolver.access(s.session_id) + if access.reason is not None: + report.add("session_ends", day, access.reason) + continue + out["session_id"].append(s.session_id) + out["player_key"].append(access.pseudonym) + out["ended_at"].append(s.ended_at) + out["dropped_queue_full"].append(s.dropped_queue_full) + out["dropped_privacy"].append(s.dropped_privacy) + out["listener_errors"].append(s.listener_errors) + out["dropped_transport"].append(s.dropped_transport) + return pa.Table.from_pydict(out, schema=ICEBERG_LAYOUT.schemas["session_ends"]) + + +KEY_COLUMNS: dict[str, tuple[str, ...]] = { + "events": ("session_id", "seq"), + "raw": ("session_id", "seq"), + "session_ends": ("session_id",), +} + + +class _Committer: + """One commit per file. Rows whose key is already in the Iceberg partition of their date are + dropped first, so correctness does not depend on the snapshot tags (which expire).""" + + def __init__(self, sink: IcebergSink, report: Report, dry_run: bool) -> None: + self._sink = sink + self._report = report + self._dry_run = dry_run + self._done: dict[str, set[str]] = {} + self._existing: dict[tuple[str, date], set[tuple[Any, ...]]] = {} + + def load(self) -> None: + for name in TABLES: + self._done[name] = self._sink.imported_sources(name) + + def commit(self, table: str, day: date, source: str, rows: pa.Table) -> None: + self._report.add(table, day, "files") + if source in self._done[table]: + self._report.add(table, day, "files_already_imported") + return + key_columns = KEY_COLUMNS[table] + existing = self._existing.get((table, day)) + if existing is None: + existing = self._sink.existing_keys(table, day, key_columns) + self._existing[(table, day)] = existing + keys = list(zip(*(rows.column(c).to_pylist() for c in key_columns), strict=True)) + keep = [i for i, key in enumerate(keys) if key not in existing] + self._report.add(table, day, "skipped_in_iceberg", len(keys) - len(keep)) + if not keep: + return + new_rows = rows.take(pa.array(keep, pa.int64())) + existing.update(keys[i] for i in keep) + self._report.add(table, day, "rows_imported", new_rows.num_rows) + if not self._dry_run: + self._sink.append_import(table, lake_rows(table, new_rows, day), source) + + +def run_import( + source: ImportSource, + objects: ObjectReader, + sink: IcebergSink, + keyring: Keyring, + *, + dry_run: bool = False, + date_from: date | None = None, + date_to: date | None = None, +) -> Report: + """Copy the importable rows of the Parquet lake into the Iceberg tables; see the module doc. + + A dry run reads everything and counts what a run would write, but creates no table and commits + nothing. A run creates the missing tables first (``bootstrap``).""" + files = [ + f + for f in source.live_files() + if f.table_name in ("events", "raw") and _in_range(f.date, date_from, date_to) + ] + sessions = source.session_records() + resolver = _Resolver(sessions, source.player_records(), keyring) + if not dry_run: + sink.bootstrap() + report = Report() + committer = _Committer(sink, report, dry_run) + committer.load() + # Days without Parquet files produce nothing: session_ends follow the files of their day. + for day in sorted({f.date for f in files}): + _import_day(day, files, sessions, objects, resolver, committer, report) + return report + + +def _import_day( + day: date, + files: Sequence[LiveFile], + sessions: Sequence[SessionRecord], + objects: ObjectReader, + resolver: _Resolver, + committer: _Committer, + report: Report, +) -> None: + events_files = sorted( + (f for f in files if f.date == day and f.table_name == "events"), key=lambda f: f.s3_key + ) + raw_files = sorted( + (f for f in files if f.date == day and f.table_name == "raw"), key=lambda f: f.s3_key + ) + index: dict[tuple[bytes, int], _Event] = {} + seen: set[bytes] = set() + for f in events_files: + report.add("events", day, "files_read") + rows = _events_rows(objects.get(f.s3_key), resolver, index, report, day, seen) + committer.commit("events", day, f.s3_key, rows) + for f in raw_files: + report.add("raw", day, "files_read") + rows = _raw_rows(objects.get(f.s3_key), resolver, index, report, day, seen) + committer.commit("raw", day, f.s3_key, rows) + ends = _session_end_rows(resolver, sessions, seen, report, day) + committer.commit("session_ends", day, f"postgres:session_ends:{day.isoformat()}", ends) + + +# ----- adapters ------------------------------------------------------------------------------- + + +class PgImportSource: + """The catalog rows of the import, read with a session that is read-only by default.""" + + def __init__(self, conn: psycopg.Connection[Any]) -> None: + self._conn = conn + + @classmethod + def connect(cls, dsn: str) -> PgImportSource: + conn: psycopg.Connection[Any] = psycopg.connect(dsn, autocommit=True) + conn.execute("SET default_transaction_read_only = on") + return cls(conn) + + def close(self) -> None: + self._conn.close() + + def live_files(self) -> list[LiveFile]: + rows = self._conn.execute( + "SELECT id, s3_key, table_name, date FROM corvus.lake_files" + " WHERE deleted_at IS NULL AND table_name IN ('events', 'raw')" + " ORDER BY date, table_name, s3_key" + ).fetchall() + return [LiveFile(int(i), str(k), str(t), d) for i, k, t, d in rows] + + def session_records(self) -> list[SessionRecord]: + rows = self._conn.execute( + "SELECT session_id, pseudonym, client_protocol, started_at, ended_at," + " dropped_queue_full, dropped_privacy, listener_errors, dropped_transport" + " FROM corvus.sessions" + ).fetchall() + return [ + SessionRecord( + bytes(sid), + bytes(p) if p is not None else None, + int(proto), + started, + ended, + int(q), + int(pr), + int(le), + int(tr), + ) # fmt: skip + for sid, p, proto, started, ended, q, pr, le, tr in rows + ] + + def player_records(self) -> list[PlayerRecord]: + rows = self._conn.execute( + "SELECT p.pseudonym, p.erased_at IS NOT NULL, k.dek_wrapped" + " FROM corvus.players p LEFT JOIN corvus.player_keys k ON k.pseudonym = p.pseudonym" + ).fetchall() + return [ + PlayerRecord(bytes(p), bool(erased), bytes(w) if w is not None else None) + for p, erased, w in rows + ] + + +class S3Objects: + """Reads the Parquet objects of the lake bucket (boto3, same client settings as S3Store).""" + + def __init__(self, client: Any, bucket: str) -> None: + self._c = client + self._bucket = bucket + + @classmethod + def from_settings(cls, s: Settings) -> S3Objects: + client = boto3.client( + "s3", + endpoint_url=s.s3_endpoint_url, + region_name=s.s3_region, + aws_access_key_id=s.s3_access_key, + aws_secret_access_key=s.s3_secret_key.get_secret_value() if s.s3_secret_key else None, + config=Config( + s3={"addressing_style": "path"}, + retries={"max_attempts": 5, "mode": "standard"}, + ), + ) + return cls(client, s.s3_bucket) + + def get(self, key: str) -> bytes: + body: bytes = self._c.get_object(Bucket=self._bucket, Key=key)["Body"].read() + return body + + +# ----- command line --------------------------------------------------------------------------- + + +def parse_args(argv: Sequence[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser( + prog="corvus-import-parquet", + description="One-off copy of the Parquet lake into the Iceberg tables (run once).", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="read and count what would be imported; write nothing", + ) + parser.add_argument("--date-from", type=date.fromisoformat, help="first UTC date (YYYY-MM-DD)") + parser.add_argument("--date-to", type=date.fromisoformat, help="last UTC date, inclusive") + return parser.parse_args(argv) + + +def run_cli(argv: Sequence[str], settings: Settings) -> int: + args = parse_args(argv) + if settings.lake_format != "iceberg": + print( + "corvus-import-parquet needs CORVUS_LAKE_FORMAT=iceberg (the target)", file=sys.stderr + ) + return 2 + if args.date_from and args.date_to and args.date_from > args.date_to: + print("--date-from is after --date-to", file=sys.stderr) + return 2 + keyring = Keyring(settings.kek_bytes(), settings.kek_id) + source = PgImportSource.connect(settings.pg_dsn) + try: + report = run_import( + source, + S3Objects.from_settings(settings), + IcebergSink.from_settings(settings), + keyring, + dry_run=args.dry_run, + date_from=args.date_from, + date_to=args.date_to, + ) + finally: + source.close() + print(report.render(dry_run=args.dry_run)) + return 0 + + +def main() -> None: + raise SystemExit(run_cli(sys.argv[1:], Settings())) diff --git a/services/tests/test_parquet_import.py b/services/tests/test_parquet_import.py new file mode 100644 index 0000000..a2776f8 --- /dev/null +++ b/services/tests/test_parquet_import.py @@ -0,0 +1,512 @@ +"""One-off import of the Parquet lake into the Iceberg tables, on a local SqlCatalog in tmp_path. + +No network, no real S3 or PostgreSQL: the source of the catalog rows and the object store are +in-memory fakes, the Iceberg tables are a file-based pyiceberg SQL catalog. +""" + +from __future__ import annotations + +import io +from dataclasses import dataclass, field +from datetime import UTC, date, datetime +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pyarrow.parquet as pq +import pytest +from pyiceberg.catalog.sql import SqlCatalog +from pyiceberg.exceptions import NoSuchTableError + +from corvus_services.crypto import Keyring, UnwrapError, encrypt_payload +from corvus_services.iceberg_sink import IcebergSink, lake_rows +from corvus_services.parquet_import import ( + LiveFile, + PlayerRecord, + Report, + SessionRecord, + run_import, +) +from corvus_services.schema import ICEBERG_LAYOUT, SCHEMAS + +KEK = bytes(range(32)) +KEK_ID = "kek-1" +DAY = date(2026, 10, 15) +OTHER_DAY = date(2026, 10, 16) + +SESSION_A = bytes([1]) * 16 # player A, complete session +SESSION_B = bytes([2]) * 16 # player B, erased +SESSION_C = bytes([3]) * 16 # player C, no key row +SESSION_ORPHAN = bytes([4]) * 16 # no SessionStart +SESSION_LATER = bytes([5]) * 16 # player A, next day +SESSION_UNKNOWN = bytes([6]) * 16 # not in the catalog at all + +PLAYER_A = bytes([0xA]) * 32 +PLAYER_B = bytes([0xB]) * 32 +PLAYER_C = bytes([0xC]) * 32 +DEK_A = bytes([0x11]) * 32 +DEK_B = bytes([0x22]) * 32 + +EVENTS_KEY = "lake/events/date=2026-10-15/part-a.parquet" +EVENTS_KEY_2 = "lake/events/date=2026-10-15/part-b.parquet" +RAW_KEY = "lake/raw/date=2026-10-15/part-a.parquet" +EVENTS_LATER_KEY = "lake/events/date=2026-10-16/part-a.parquet" +RAW_LATER_KEY = "lake/raw/date=2026-10-16/part-a.parquet" +SESSION_ENDS_SOURCE = "postgres:session_ends:2026-10-15" + + +def _ts(day: date, hour: int) -> datetime: + return datetime(day.year, day.month, day.day, hour, tzinfo=UTC) + + +def _event(session_id: bytes, seq: int, **overrides: Any) -> dict[str, Any]: + """One events row in the Parquet layout (EVENTS_SCHEMA), defaults for every column.""" + row: dict[str, Any] = dict.fromkeys(SCHEMAS["events"].names) + row.update( + session_id=session_id, + segment=1, + seq=seq, + offset_nanos=seq * 1000, + direction=1, + state=2, + packet_type=0x0102, + wire_packet_id=-5, + payload_original_size=len(f"payload-{seq}"), + event_kind=0, + ) + row.update(overrides) + return row + + +def _raw(session_id: bytes, seq: int, dek: bytes, payload: bytes) -> dict[str, Any]: + """One raw row in the Parquet layout: the payload encrypted with the DEK, as ingest wrote it.""" + nonce, ciphertext = encrypt_payload(dek, session_id, seq, payload, nonce=bytes([seq]) * 12) + return { + "session_id": session_id, + "segment": 1, + "seq": seq, + "payload_original_size": len(payload), + "nonce": nonce, + "ciphertext": ciphertext, + } + + +def _parquet(table: str, rows: list[dict[str, Any]]) -> bytes: + schema = SCHEMAS[table] + columns = {name: [row[name] for row in rows] for name in schema.names} + buf = io.BytesIO() + pq.write_table(pa.Table.from_pydict(columns, schema=schema), buf) + return buf.getvalue() + + +@dataclass +class FakeSource: + """The catalog rows the import reads: lake files, sessions and players.""" + + files: list[LiveFile] = field(default_factory=list) + sessions: list[SessionRecord] = field(default_factory=list) + players: list[PlayerRecord] = field(default_factory=list) + + def live_files(self) -> list[LiveFile]: + return list(self.files) + + def session_records(self) -> list[SessionRecord]: + return list(self.sessions) + + def player_records(self) -> list[PlayerRecord]: + return list(self.players) + + +class FakeObjects: + def __init__(self, objects: dict[str, bytes]) -> None: + self._objects = objects + + def get(self, key: str) -> bytes: + return self._objects[key] + + +@pytest.fixture +def keyring() -> Keyring: + return Keyring(KEK, KEK_ID) + + +@pytest.fixture +def catalog(tmp_path: Path) -> SqlCatalog: + cat = SqlCatalog( + "test", + uri=f"sqlite:///{tmp_path / 'catalog.db'}", + warehouse=f"file://{tmp_path / 'warehouse'}", + ) + cat.create_namespace("capture") + return cat + + +@pytest.fixture +def sink(catalog: SqlCatalog) -> IcebergSink: + return IcebergSink(catalog, "capture", sleep=lambda _s: None) + + +def _players(keyring: Keyring) -> list[PlayerRecord]: + return [ + PlayerRecord(PLAYER_A, erased=False, wrapped_dek=keyring.wrap(PLAYER_A, DEK_A)), + PlayerRecord(PLAYER_B, erased=True, wrapped_dek=None), + PlayerRecord(PLAYER_C, erased=False, wrapped_dek=None), + ] + + +def _sessions() -> list[SessionRecord]: + return [ + SessionRecord( + SESSION_A, + PLAYER_A, + client_protocol=767, + started_at=_ts(DAY, 10), + ended_at=_ts(DAY, 11), + dropped_queue_full=1, + dropped_privacy=2, + listener_errors=3, + dropped_transport=4, + ), + SessionRecord(SESSION_B, PLAYER_B, 767, _ts(DAY, 9), _ts(DAY, 9), 0, 0, 0, 0), + SessionRecord(SESSION_C, PLAYER_C, 767, _ts(DAY, 9), None, 0, 0, 0, 0), + SessionRecord(SESSION_ORPHAN, None, 767, _ts(DAY, 9), None, 0, 0, 0, 0), + SessionRecord(SESSION_LATER, PLAYER_A, 768, _ts(OTHER_DAY, 8), None, 0, 0, 0, 0), + ] + + +def _files() -> list[LiveFile]: + return [ + LiveFile(1, EVENTS_KEY, "events", DAY), + LiveFile(2, RAW_KEY, "raw", DAY), + LiveFile(3, EVENTS_LATER_KEY, "events", OTHER_DAY), + LiveFile(4, RAW_LATER_KEY, "raw", OTHER_DAY), + ] + + +def _objects(keyring: Keyring) -> dict[str, bytes]: + session_a_events = [_event(SESSION_A, seq) for seq in (1, 2, 3)] + session_a_raw = [ + _raw(SESSION_A, 1, DEK_A, b"hello"), + _raw(SESSION_A, 2, DEK_A, b"world!!"), + ] + # Erased player B, player C without a key, an orphan and an unknown session: all skipped. + other_events = [ + _event(SESSION_B, 1), + _event(SESSION_C, 1), + _event(SESSION_ORPHAN, 1), + _event(SESSION_UNKNOWN, 1), + ] + other_raw = [_raw(SESSION_B, 1, DEK_B, b"secret")] + later_events = [_event(SESSION_LATER, 1)] + later_raw = [_raw(SESSION_LATER, 1, DEK_A, b"later")] + return { + EVENTS_KEY: _parquet("events", session_a_events + other_events), + RAW_KEY: _parquet("raw", session_a_raw + other_raw), + EVENTS_LATER_KEY: _parquet("events", later_events), + RAW_LATER_KEY: _parquet("raw", later_raw), + } + + +@pytest.fixture +def source(keyring: Keyring) -> FakeSource: + return FakeSource(_files(), _sessions(), _players(keyring)) + + +@pytest.fixture +def objects(keyring: Keyring) -> FakeObjects: + return FakeObjects(_objects(keyring)) + + +def _run( + source: FakeSource, + objects: FakeObjects, + sink: IcebergSink, + keyring: Keyring, + **kwargs: Any, +) -> Report: + return run_import(source, objects, sink, keyring, **kwargs) + + +def _scan(catalog: SqlCatalog, table: str) -> pa.Table: + return catalog.load_table(f"capture.{table}").scan().to_arrow() + + +def test_events_are_copied_with_the_player_key_of_their_session( + source, objects, sink, keyring, catalog +): + _run(source, objects, sink, keyring) + + events = _scan(catalog, "events").to_pylist() + session_a_rows = [r for r in events if r["session_id"] == SESSION_A] + assert len(session_a_rows) == 3 + assert {r["player_key"] for r in session_a_rows} == {PLAYER_A} + first = next(r for r in session_a_rows if r["seq"] == 1) + assert first["offset_nanos"] == 1000 + assert first["packet_type"] == 0x0102 + assert first["wire_packet_id"] == -5 + assert first["date"] == DAY + + +def test_raw_payloads_are_decrypted_and_joined_with_their_event_fields( + source, objects, sink, keyring, catalog +): + _run(source, objects, sink, keyring) + + raw = {r["seq"]: r for r in _scan(catalog, "raw").to_pylist() if r["session_id"] == SESSION_A} + assert set(raw) == {1, 2} + assert raw[1]["payload"] == b"hello" + assert raw[2]["payload"] == b"world!!" + assert raw[1]["player_key"] == PLAYER_A + assert raw[1]["offset_nanos"] == 1000 + assert raw[1]["direction"] == 1 + assert raw[1]["state"] == 2 + assert raw[1]["packet_type"] == 0x0102 + assert raw[1]["wire_packet_id"] == -5 + assert raw[1]["payload_original_size"] == len(b"hello") + + +def test_raw_rows_take_the_protocol_version_of_their_session( + source, objects, sink, keyring, catalog +): + _run(source, objects, sink, keyring) + + later = [r for r in _scan(catalog, "raw").to_pylist() if r["session_id"] == SESSION_LATER] + assert [r["protocol_version"] for r in later] == [768] + + +def test_raw_row_without_its_event_is_skipped_and_counted(keyring, objects, sink, catalog): + source = FakeSource( + files=[LiveFile(1, RAW_KEY, "raw", DAY)], + sessions=_sessions(), + players=_players(keyring), + ) + report = _run(source, objects, sink, keyring) + + assert report.count("raw", DAY, "skipped_no_event") == 2 + assert _scan(catalog, "raw").num_rows == 0 + + +def test_rows_of_an_erased_player_are_never_imported(source, objects, sink, keyring, catalog): + report = _run(source, objects, sink, keyring) + + assert all(r["session_id"] != SESSION_B for r in _scan(catalog, "events").to_pylist()) + assert all(r["session_id"] != SESSION_B for r in _scan(catalog, "raw").to_pylist()) + assert report.count("events", DAY, "skipped_erased") == 1 + assert report.count("raw", DAY, "skipped_erased") == 1 + + +def test_player_without_a_key_row_is_not_imported(source, objects, sink, keyring, catalog): + _run(source, objects, sink, keyring) + + assert all(r["session_id"] != SESSION_C for r in _scan(catalog, "events").to_pylist()) + + +def test_orphan_and_unknown_sessions_are_not_imported(source, objects, sink, keyring, catalog): + report = _run(source, objects, sink, keyring) + + imported = {r["session_id"] for r in _scan(catalog, "events").to_pylist()} + assert SESSION_ORPHAN not in imported + assert SESSION_UNKNOWN not in imported + assert report.count("events", DAY, "skipped_no_key") == 2 + assert report.count("events", DAY, "skipped_unknown_session") == 1 + + +def test_session_ends_are_imported_with_the_player_key_and_counters( + source, objects, sink, keyring, catalog +): + _run(source, objects, sink, keyring) + + ends = _scan(catalog, "session_ends").to_pylist() + assert len(ends) == 1 + assert ends[0]["session_id"] == SESSION_A + assert ends[0]["player_key"] == PLAYER_A + assert ends[0]["ended_at"] == _ts(DAY, 11) + assert ( + ends[0]["dropped_queue_full"], + ends[0]["dropped_privacy"], + ends[0]["listener_errors"], + ends[0]["dropped_transport"], + ) == (1, 2, 3, 4) + assert ends[0]["date"] == DAY + + +def test_session_ends_of_erased_players_are_not_imported(source, objects, sink, keyring, catalog): + # SESSION_B (erased, with an end) is part of the fixture. + _run(source, objects, sink, keyring) + + assert [r["session_id"] for r in _scan(catalog, "session_ends").to_pylist()] == [SESSION_A] + + +def test_a_second_run_imports_nothing_again(source, objects, sink, keyring, catalog): + _run(source, objects, sink, keyring) + before = {name: _scan(catalog, name).num_rows for name in ICEBERG_LAYOUT.schemas} + + second = _run(source, objects, sink, keyring) + + after = {name: _scan(catalog, name).num_rows for name in ICEBERG_LAYOUT.schemas} + assert after == before + assert second.count("events", DAY, "rows_imported") == 0 + assert second.count("events", DAY, "files_already_imported") == 1 + assert second.count("raw", DAY, "files_already_imported") == 1 + assert second.count("session_ends", DAY, "files_already_imported") == 1 + + +def test_dry_run_writes_no_table_and_reports_what_a_run_would_write( + source, objects, sink, keyring, catalog +): + dry = _run(source, objects, sink, keyring, dry_run=True) + + with pytest.raises(NoSuchTableError): + catalog.load_table("capture.events") + assert dry.count("events", DAY, "rows_imported") == 3 + assert dry.count("raw", DAY, "rows_imported") == 2 + assert dry.count("session_ends", DAY, "rows_imported") == 1 + + real = _run(source, objects, sink, keyring) + assert real.count("events", DAY, "rows_imported") == dry.count("events", DAY, "rows_imported") + assert real.count("raw", DAY, "rows_imported") == dry.count("raw", DAY, "rows_imported") + + +def test_a_failed_commit_is_resumed_by_the_next_run_without_duplicates( + source, objects, keyring, catalog +): + class FailRawOnce(IcebergSink): + failed = False + + def append_import(self, name, rows, source): # type: ignore[override] + if name == "raw" and not FailRawOnce.failed: + FailRawOnce.failed = True + raise RuntimeError("catalog went away") + return super().append_import(name, rows, source) + + failing = FailRawOnce(catalog, "capture", sleep=lambda _s: None) + with pytest.raises(RuntimeError, match="catalog went away"): + _run(source, objects, failing, keyring) + assert _scan(catalog, "events").num_rows == 3 + + resumed = IcebergSink(catalog, "capture", sleep=lambda _s: None) + _run(source, objects, resumed, keyring) + + assert _scan(catalog, "raw").num_rows == 3 + assert _scan(catalog, "events").num_rows == 4 + assert _scan(catalog, "session_ends").num_rows == 1 + + +def test_duplicate_events_of_the_lake_are_copied_once(keyring, sink, catalog): + dup = _parquet("events", [_event(SESSION_A, 1), _event(SESSION_A, 1)]) + source = FakeSource( + files=[LiveFile(1, EVENTS_KEY, "events", DAY)], + sessions=_sessions(), + players=_players(keyring), + ) + report = _run(source, FakeObjects({EVENTS_KEY: dup}), sink, keyring) + + assert _scan(catalog, "events").num_rows == 1 + assert report.count("events", DAY, "skipped_duplicate") == 1 + + +def test_files_and_sessions_outside_the_date_range_are_not_imported( + source, objects, sink, keyring, catalog +): + _run(source, objects, sink, keyring, date_from=OTHER_DAY, date_to=OTHER_DAY) + + days = {r["date"] for r in _scan(catalog, "events").to_pylist()} + assert days == {OTHER_DAY} + assert _scan(catalog, "session_ends").num_rows == 0 + + +def test_a_key_that_does_not_unwrap_aborts_the_import(source, objects, sink, catalog): + other = Keyring(bytes([9]) * 32, KEK_ID) + with pytest.raises(UnwrapError): + _run(source, objects, sink, other) + assert _scan(catalog, "events").num_rows == 0 + + +def test_cli_refuses_to_run_against_the_parquet_lake(capsys): + from corvus_services.config import Settings + from corvus_services.parquet_import import run_cli + + code = run_cli(["--dry-run"], Settings(lake_format="parquet")) + + assert code == 2 + assert "CORVUS_LAKE_FORMAT=iceberg" in capsys.readouterr().err + + +class UntaggedSink(IcebergSink): + """The table as it is after its snapshots were expired: the rows are there, the tags are not.""" + + def append_import(self, name, rows, source): # type: ignore[override] + self._append_with_retry(name, rows) + + +def test_a_rerun_without_snapshot_tags_imports_nothing(source, objects, sink, keyring, catalog): + _run(source, objects, UntaggedSink(catalog, "capture", sleep=lambda _s: None), keyring) + before = {name: _scan(catalog, name).num_rows for name in ICEBERG_LAYOUT.schemas} + + rerun = _run(source, objects, sink, keyring) + + after = {name: _scan(catalog, name).num_rows for name in ICEBERG_LAYOUT.schemas} + assert after == before + assert rerun.total("rows_imported") == 0 + + +def test_a_rerun_without_snapshot_tags_does_not_duplicate_raw_rows( + source, objects, sink, keyring, catalog +): + _run(source, objects, UntaggedSink(catalog, "capture", sleep=lambda _s: None), keyring) + + _run(source, objects, sink, keyring) + + seqs = sorted( + r["seq"] for r in _scan(catalog, "raw").to_pylist() if r["session_id"] == SESSION_A + ) + assert seqs == [1, 2] + + +def test_session_ends_of_a_session_already_in_iceberg_are_not_imported( + source, objects, sink, keyring, catalog +): + sink.bootstrap() + live_end = pa.Table.from_pydict( + { + "session_id": [SESSION_A], + "player_key": [PLAYER_A], + "ended_at": [_ts(DAY, 11)], + "dropped_queue_full": [9], + "dropped_privacy": [9], + "listener_errors": [9], + "dropped_transport": [9], + }, + schema=ICEBERG_LAYOUT.schemas["session_ends"], + ) + sink.append_import("session_ends", lake_rows("session_ends", live_end, DAY), "live-ingest") + + report = _run(source, objects, sink, keyring) + + ends = _scan(catalog, "session_ends").to_pylist() + assert len(ends) == 1 + assert ends[0]["dropped_queue_full"] == 9 + assert report.count("session_ends", DAY, "rows_imported") == 0 + + +def test_a_day_with_only_postgres_sessions_imports_nothing(keyring, sink, catalog): + ended = SessionRecord(SESSION_A, PLAYER_A, 767, _ts(DAY, 10), _ts(DAY, 11), 0, 0, 0, 0) + source = FakeSource(files=[], sessions=[ended], players=_players(keyring)) + + report = _run(source, FakeObjects({}), sink, keyring) + + assert _scan(catalog, "session_ends").num_rows == 0 + assert report.total("rows_imported") == 0 + + +def test_session_ends_are_only_imported_for_sessions_with_rows_in_the_day_files( + source, objects, sink, keyring, catalog +): + no_rows_in_files = SessionRecord( + bytes([7]) * 16, PLAYER_A, 767, _ts(DAY, 9), _ts(DAY, 10), 0, 0, 0, 0 + ) + source.sessions.append(no_rows_in_files) + + _run(source, objects, sink, keyring) + + assert [r["session_id"] for r in _scan(catalog, "session_ends").to_pylist()] == [SESSION_A]