Skip to content
Merged
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
45 changes: 41 additions & 4 deletions docs/reference/data-lake.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions services/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
55 changes: 53 additions & 2 deletions services/src/corvus_services/iceberg_sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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()
}
Loading