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
2 changes: 1 addition & 1 deletion docs/reference/control-plane-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ the key, UUID endpoints answer `503`; erasure by pseudonym still works. The API
logs only the first 12 hex characters of the pseudonym.

**Erasure semantics.** In one transaction: (1) delete the `player_keys` row, which crypto-shreds the player's `raw`
payloads; (2) set `players.erased_at` (ingest stops storing data for that pseudonym); (3) put the pseudonym on the
payloads in the Parquet layout (Iceberg `raw` is plaintext and not covered yet, see [data-lake.md](data-lake.md) 2a); (2) set `players.erased_at` (ingest stops storing data for that pseudonym); (3) put the pseudonym on the
blocklist with `source = erasure`; (4) delete the player's rows in `scores_latest` and `score_history`; (5) insert an `erasure_requests` row (who, when,
pseudonym, `status = completed`, `player_known`, `key_deleted`, `compaction_pending = true`). If any step fails nothing is changed. A pseudonym that was
never captured is still blocklisted and audited. Erasure can be repeated. `events` files are not rewritten here:
Expand Down
77 changes: 62 additions & 15 deletions docs/reference/data-lake.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ _staging/<table>/<ulid>.parquet upload target before promotion

Rows are sorted by (`session_id`, `seq`) within a file.

### Table `raw` (short retention, crypto-shredded)
### Table `raw` (Parquet: short retention, crypto-shredded; Iceberg: section 2a)

| Column | Arrow type | Notes |
|---|---|---|
Expand All @@ -86,8 +86,10 @@ shorten the life of data nobody else uses, and keep a file longer than the defau
## 2a. Iceberg tables (target format, opt-in)

Status: the target format of the lake. `CORVUS_LAKE_FORMAT=parquet` stays the default and keeps everything above;
`iceberg` is chosen per deployment (Helm `lake.format`). Layout version 1 (`ICEBERG_LAKE_VERSION` in
`services/src/corvus_services/iceberg_sink.py`).
`iceberg` is chosen per deployment (Helm `lake.format`). Layout version 2 (`ICEBERG_LAKE_VERSION` in
`services/src/corvus_services/iceberg_sink.py`). Decision of 2026-11-18: in this layout raw packets are stored in
plaintext and kept permanently. Crypto-shredding does not apply to it; sections 2 (`raw`) and 3 describe the Parquet
layout only.

| Item | Value |
|---|---|
Expand All @@ -100,20 +102,58 @@ Settings: `CORVUS_LAKE_FORMAT` (`parquet` | `iceberg`); with `iceberg`, these ar
`CORVUS_LAKE_CATALOG_URI`, `CORVUS_LAKE_OAUTH_TOKEN_URL`, `CORVUS_LAKE_OAUTH_SCOPE`, `CORVUS_LAKE_CLIENT_ID`,
`CORVUS_LAKE_CLIENT_SECRET` (secret), `CORVUS_LAKE_S3_ENDPOINT_URL`, `CORVUS_LAKE_S3_ACCESS_KEY`,
`CORVUS_LAKE_S3_SECRET_KEY` (secret). Optional: `CORVUS_LAKE_WAREHOUSE` (`corvus`), `CORVUS_LAKE_NAMESPACE` (`capture`),
`CORVUS_LAKE_S3_REGION` (`us-east-1`).
`CORVUS_LAKE_S3_REGION` (`us-east-1`). No further setting exists for the raw layout: it is the layout of this format.

### Privacy and retention

* **`capture.raw` is personal data in plaintext.** Each row holds the packet payload exactly as the plugin sent it,
without any further filtering by ingest. Payloads can contain names, chat and command text, depending on what the
capture plugin records. The plugin still decides what it sends: `PrivacyFilter` drops chat, commands, signing and
player-list frames and `PayloadPolicy` strips the payload of text-bearing types (see `docs/pilot.md`, payload policy).
Ingest does not re-admit anything the plugin dropped.
* **Access** is only through the Polaris grants on the `capture` namespace. Data files live in the `polaris-corvus`
bucket and are reached through the catalog only; nothing copies `raw` out of the catalog.
* **Retention is permanent.** No housekeeping job expires Iceberg rows. The contents are reviewed once a year.
* **Erasure** of a player is planned as Iceberg row deletes (`player_key` below) in both tables, with immediate snapshot
expiry. That is a separate change. Until it lands, a completed erasure request (section 3) does not remove any Iceberg
row, because the Iceberg rows are not encrypted with the player's DEK.
* **Player attribution** is the pseudonym (section 3's HMAC, 32 bytes, `player_key`), never the Mojang UUID or name.
Frames of orphan sessions (no `SessionStart` seen) have a null `player_key` and a null `protocol_version`. They cannot
be attributed to a player, so they cannot be erased by player either.

### Schema

The columns of the two tables in sections 2 and 2a are the same, with these changes:
Iceberg has no unsigned integers: `uint8`, `uint32` and `uint64` become `int` or `long` (`int` for `uint8`, `long`
for `uint32` and `uint64`). Values are unchanged. Every table has a `date` column (`date`, not null): the UTC date of
the session start (`SessionInfo.partition_date`), the partition source.

* Iceberg has no unsigned integers: `uint8` becomes `int`, `uint32` and `uint64` become `long`. Values are unchanged.
* New column `date` (`date`, not null): the UTC date of the session start (`SessionInfo.partition_date`), the partition source.
`events`: the columns of section 2, plus `player_key` (`fixed(32)`, nullable, the pseudonym of the session's player).

Table properties: `format-version` 2, `write.parquet.compression-codec` zstd, `corvus.lake-schema-version` 1.
`raw`: the columns below. Only frames that carry a payload get a row.

| Column | Iceberg type | Notes |
|---|---|---|
| `session_id` | `fixed(16)` | |
| `segment` | `long` | |
| `seq` | `long` | dedup key together with `session_id` |
| `offset_nanos` | `long` | since session start, as in `events` |
| `direction` | `int` | proto `Direction` value |
| `state` | `int` | proto `ConnectionState` value |
| `packet_type` | `long` | Corvus vocabulary id |
| `wire_packet_id` | `int` | |
| `protocol_version` | `int` (nullable) | the client's protocol version from the session's `SessionStart`, repeated in every row; null for orphan sessions |
| `player_key` | `fixed(32)` (nullable) | the pseudonym of the session's player; null for orphan sessions |
| `payload_original_size` | `long` | size before truncation; larger than the payload length means it was truncated |
| `payload` | `binary` | the payload bytes as received, plaintext |
| `date` | `date` | partition column |

Table properties: `format-version` 2, `write.parquet.compression-codec` zstd, `corvus.lake-schema-version` 2.
Partition spec: identity(`date`). Sort order: `session_id`, `seq` ascending, nulls first.

Changes to the columns: add an Iceberg schema evolution (append-only), bump `corvus.lake-schema-version` and
`ICEBERG_LAKE_VERSION` together. The writer refuses at start-up a table whose columns or partition differ from this layout.
`ICEBERG_LAKE_VERSION` together. The writer refuses at start-up a table whose lake schema version is not 2, and a table
whose columns or partition differ from this layout. Version 1 tables (encrypted `raw`, no `player_key`) were never in
production and are not migrated: drop the table and let ingest recreate it.

### Writes

Expand All @@ -129,21 +169,28 @@ Changes to the columns: add an Iceberg schema evolution (append-only), bump `cor
* No `lake_files` or `lake_file_sessions` rows in Iceberg mode. Session membership is read from the tables (filter on
`session_id`, prune by `date`). Everything else in the catalog (players, keys, sessions, segments, counters, batch
log) is unchanged.
* Raw rows stay AES-256-GCM encrypted with the player's DEK, as in section 3.
* Raw payloads are written as plaintext. In Iceberg mode ingest does not read or unwrap a player's DEK. Session start
still stores a `player_keys` row, which nothing reads in this mode (see the open points of the change that introduced
it).
* Erased players: frames of a session whose player is erased are acknowledged and not written (as in Parquet mode).
The check uses the session cache (`CORVUS_SESSION_CACHE_TTL_S`, 60 s), so frames of a player erased less than that
time ago can still be written.

### Not covered yet

Each is a separate step: backfill of the existing Parquet files, erasure of Iceberg rows (Iceberg deletes plus immediate
snapshot expiry), snapshot pins by Iceberg snapshot id, and retention of `raw` in Iceberg. Until those land,
`corvus-compact` and `corvus-housekeeping` do not see Iceberg data: erasure requests complete for the Parquet files only
and `raw` in Iceberg is not expired.
Each is a separate step: backfill of the existing Parquet files, erasure of Iceberg rows (row deletes by `player_key`,
then immediate snapshot expiry), snapshot pins by Iceberg snapshot id, and reading Iceberg `raw` in the ML jobs
(`corvus-ml` reads the Parquet `raw` layout only). Until those land, `corvus-compact` and `corvus-housekeeping` do not
see Iceberg data: erasure requests complete for the Parquet files only, and Iceberg `raw` is neither expired nor
rewritten.

## 3. Keys and erasure

- Every pseudonymised player gets a random 256-bit data encryption key (DEK) on first sight.
- The DEK is stored wrapped (AES-256-GCM) with a key encryption key (KEK) from `CORVUS_KEK` (base64, 32 bytes),
identified by `CORVUS_KEK_ID`. The KEK never touches the database or the lake.
- Erasure of a player: delete the `player_keys` row (crypto-shredding of `raw`), mark `players.erased_at`, add the
- Erasure of a player: delete the `player_keys` row (crypto-shredding of `raw`, Parquet layout only; Iceberg rows are
plaintext and not covered, see 2a), mark `players.erased_at`, add the
pseudonym to the blocklist; `corvus-compact` later rewrites `events` and still-existing `raw` files without the player's sessions (section 7).

## 4. Catalog (PostgreSQL, schema `corvus`)
Expand Down
4 changes: 2 additions & 2 deletions docs/reference/raw-byte-tokenizer.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ lake events + raw ──decrypt──> frames of a session ──BPE──> pack

## 2. Reading raw bytes

Payloads are AES-256-GCM encrypted with the player's DEK; the AAD is `session_id || seq` (8 bytes
big-endian); see [data-lake.md](data-lake.md). `corvus_ml.raw.crypto` repeats the services' algorithm
Payloads of the Parquet `raw` table are AES-256-GCM encrypted with the player's DEK; the AAD is `session_id || seq`
(8 bytes big-endian); see [data-lake.md](data-lake.md). The Iceberg `raw` table stores plaintext and is not read by these jobs yet (section 2a). `corvus_ml.raw.crypto` repeats the services' algorithm
(the ML package must not depend on `corvus_services`); `tests/test_raw_crypto.py` checks it against
vectors computed with `corvus_services.crypto`.

Expand Down
28 changes: 23 additions & 5 deletions services/src/corvus_services/buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import io
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from typing import Any
Expand Down Expand Up @@ -30,11 +31,15 @@ class Ticket:


class TableBuffer:
def __init__(self, table: str, day: date, now: datetime) -> None:
def __init__(
self, table: str, day: date, now: datetime, schema: pa.Schema | None = None
) -> None:
"""``schema`` is the layout of the rows (default: the Parquet layout of ``table``)."""
self.table = table
self.day = day
self.first_added = now
self.columns: dict[str, list[Any]] = {f.name: [] for f in SCHEMAS[table]}
self.schema = schema if schema is not None else SCHEMAS[table]
self.columns: dict[str, list[Any]] = {f.name: [] for f in self.schema}
self.rows = 0
self.bytes = 0
self.session_ids: set[bytes] = set()
Expand All @@ -57,18 +62,25 @@ def attach(self, ticket: Ticket) -> None:


class BufferSet:
def __init__(self, max_rows: int, max_bytes: int, max_age: timedelta) -> None:
def __init__(
self,
max_rows: int,
max_bytes: int,
max_age: timedelta,
schemas: Mapping[str, pa.Schema] = SCHEMAS,
) -> None:
self._max_rows = max_rows
self._max_bytes = max_bytes
self._max_age = max_age
self._schemas = schemas
self._buffers: dict[BufferKey, TableBuffer] = {}
self.total_bytes = 0

def get(self, table: str, day: date, now: datetime) -> TableBuffer:
key = (table, day)
buf = self._buffers.get(key)
if buf is None:
buf = self._buffers[key] = TableBuffer(table, day, now)
buf = self._buffers[key] = TableBuffer(table, day, now, self._schemas[table])
return buf

def note_bytes(self, n: int) -> None:
Expand Down Expand Up @@ -97,7 +109,13 @@ def __len__(self) -> int:


def encode_parquet(buf: TableBuffer) -> bytes:
"""Sort by (session_id, seq) and encode as zstd Parquet. Runs in the worker pool."""
"""Sort by (session_id, seq) and encode as zstd Parquet. Runs in the worker pool.

Only the Parquet layout is accepted: the Iceberg layout holds plaintext raw payloads and must
never reach a Parquet file (docs/reference/data-lake.md section 2a).
"""
if buf.schema is not SCHEMAS[buf.table]:
raise ValueError(f"{buf.table} rows in the Iceberg layout must not be written as Parquet")
table = pa.Table.from_pydict(buf.columns, schema=SCHEMAS[buf.table])
table = table.sort_by([("session_id", "ascending"), ("seq", "ascending")])
sink = io.BytesIO()
Expand Down
30 changes: 30 additions & 0 deletions services/src/corvus_services/codec.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,33 @@ def raw_row(session_id: bytes, segment: int, frame: Any, dek: bytes) -> Row | No
"nonce": nonce,
"ciphertext": ciphertext,
}


def plain_raw_row(
session_id: bytes,
segment: int,
frame: Any,
player_key: bytes | None,
protocol_version: int | None,
) -> Row | None:
"""One plaintext ``raw`` row of the Iceberg layout (section 2a), or None without a payload.

The payload is stored as received. ``player_key`` and ``protocol_version`` come from the session
and are None for orphan sessions.
"""
if not frame.payload:
return None
return {
"session_id": session_id,
"segment": segment,
"seq": frame.seq,
"offset_nanos": frame.offset_nanos,
"direction": frame.direction,
"state": frame.state,
"packet_type": frame.packet_type,
"wire_packet_id": frame.wire_packet_id,
"protocol_version": protocol_version,
"player_key": player_key,
"payload_original_size": frame.payload_original_size,
"payload": bytes(frame.payload),
}
31 changes: 22 additions & 9 deletions services/src/corvus_services/iceberg_sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

Target layout (docs/reference/data-lake.md section 2a):

* columns = the Arrow schemas of ``schema.py``, unsigned integers widened to the signed Iceberg
types (Iceberg has none), plus ``date`` (UTC date of the session start);
* columns = the Iceberg layout of ``schema.py`` (plaintext ``raw`` payloads, ``player_key`` on both
tables), unsigned integers widened to the signed Iceberg types (Iceberg has none), plus ``date``
(UTC date of the session start);
* identity partition on ``date``; sort order (``session_id``, ``seq``); format version 2;
``write.parquet.compression-codec=zstd``;
* table property ``corvus.lake-schema-version`` = ``ICEBERG_LAKE_VERSION``. Bump it (and add a
Expand Down Expand Up @@ -55,18 +56,19 @@
from .buffer import TableBuffer
from .config import Settings
from .ports import Committed
from .schema import SCHEMAS
from .schema import ICEBERG_LAYOUT, Layout

log = logging.getLogger("corvus.ingest.iceberg")

ICEBERG_LAKE_VERSION = 1
ICEBERG_LAKE_VERSION = 2
LAKE_VERSION_PROPERTY = "corvus.lake-schema-version"
DATE_COLUMN = "date"
PARTITION_FIELD_ID = 1000
MAX_COMMIT_ATTEMPTS = 5
TABLE_PROPERTIES = {
"format-version": "2",
"write.parquet.compression-codec": "zstd",
"corvus.lake-schema-version": str(ICEBERG_LAKE_VERSION),
LAKE_VERSION_PROPERTY: str(ICEBERG_LAKE_VERSION),
}

_SCALARS: dict[pa.DataType, IcebergType] = {
Expand All @@ -90,16 +92,18 @@ def _iceberg_type(t: pa.DataType) -> IcebergType:
raise TypeError(f"no Iceberg type for Arrow type {t}") from e


def iceberg_schema(table: str) -> Schema:
def iceberg_schema(arrow: pa.Schema) -> Schema:
"""Iceberg schema of a lake table: the Arrow columns in order, then ``date``."""
fields: list[NestedField] = []
for field_id, f in enumerate(SCHEMAS[table], start=1):
for field_id, f in enumerate(arrow, start=1):
fields.append(NestedField(field_id, f.name, _iceberg_type(f.type), required=not f.nullable))
fields.append(NestedField(len(fields) + 1, DATE_COLUMN, DateType(), required=True))
return Schema(*fields)


ICEBERG_SCHEMAS: dict[str, Schema] = {name: iceberg_schema(name) for name in SCHEMAS}
ICEBERG_SCHEMAS: dict[str, Schema] = {
name: iceberg_schema(arrow) for name, arrow in ICEBERG_LAYOUT.schemas.items()
}


def partition_spec(schema: Schema) -> PartitionSpec:
Expand Down Expand Up @@ -156,6 +160,8 @@ def open_catalog(s: Settings) -> Catalog:


class IcebergSink:
layout: Layout = ICEBERG_LAYOUT

def __init__(
self,
catalog: Catalog,
Expand Down Expand Up @@ -185,7 +191,7 @@ def ident(self, table: str) -> str:
def bootstrap(self) -> None:
"""Make sure both tables exist with the expected layout. Idempotent, race-safe: a table
created by another replica in the meantime is loaded instead. The namespace must exist."""
for name in SCHEMAS:
for name in ICEBERG_SCHEMAS:
self._ensure_table(name)

def _ensure_table(self, name: str) -> Table:
Expand Down Expand Up @@ -242,6 +248,13 @@ def _append_with_retry(self, name: str, rows: pa.Table) -> None:


def _check_layout(table: Table, ident: str, name: str) -> None:
version = table.properties.get(LAKE_VERSION_PROPERTY)
if version != str(ICEBERG_LAKE_VERSION):
raise RuntimeError(
f"{ident} has lake schema version {version or 'unset'}, this writer needs "
f"{ICEBERG_LAKE_VERSION}; version 1 tables (encrypted raw payloads) are not migrated: "
"drop the table and let ingest recreate it"
)
expected = ICEBERG_SCHEMAS[name]
actual = [f.name for f in table.schema().fields]
if actual != [f.name for f in expected.fields]:
Expand Down
4 changes: 3 additions & 1 deletion services/src/corvus_services/lake.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@
from .config import Settings
from .iceberg_sink import IcebergSink
from .ports import Catalog, Committed, FileRecord, LakeSink, ObjectStore
from .schema import SCHEMA_VERSION
from .schema import PARQUET_LAYOUT, SCHEMA_VERSION, Layout


class ParquetSink:
"""staging -> final copy -> ``lake_files`` / ``lake_file_sessions`` in one transaction."""

layout: Layout = PARQUET_LAYOUT

def __init__(
self, store: ObjectStore, catalog: Catalog, executor: Executor, clock: Clock
) -> None:
Expand Down
13 changes: 10 additions & 3 deletions services/src/corvus_services/pgcatalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,8 @@ async def start_session(
)
srow = await cur.fetchone()
assert srow is not None
return SessionInfo(data.session_id, data.pseudonym, srow[0], erased), stored
info = SessionInfo(data.session_id, data.pseudonym, srow[0], erased, data.client_protocol)
return info, stored

async def create_orphan_session(self, session_id: bytes, started_at: datetime) -> SessionInfo:
async with self._pool.connection() as conn:
Expand Down Expand Up @@ -162,16 +163,22 @@ async def start_segment(self, data: SegmentData) -> None:
async def get_session(self, session_id: bytes) -> SessionInfo | None:
async with self._pool.connection() as conn:
cur = await conn.execute(
"SELECT s.pseudonym, s.started_at, COALESCE(p.erased_at IS NOT NULL, false)"
"SELECT s.pseudonym, s.started_at, COALESCE(p.erased_at IS NOT NULL, false),"
" s.client_protocol"
" FROM corvus.sessions s LEFT JOIN corvus.players p USING (pseudonym)"
" WHERE s.session_id = %s",
(session_id,),
)
row = await cur.fetchone()
if row is None:
return None
pseudonym = None if row[0] is None else bytes(row[0])
return SessionInfo(
session_id, None if row[0] is None else bytes(row[0]), row[1], bool(row[2])
session_id,
pseudonym,
row[1],
bool(row[2]),
None if pseudonym is None else int(row[3]),
)

async def get_dek(self, pseudonym: bytes) -> WrappedDek | None:
Expand Down
Loading
Loading