﻿# CATRUSTDB – Feuille de route

> Moteur de migration catégorielle Rust — NDJSON TCP + column store natif + CQL

---

## État actuel — v1.2 ✅

Ce qui est **fait et testé** (357 tests workspace · cargo check ✅ · 0 clippy errors) :

| Composant | Fonctionnalité | Statut |
|-----------|---------------|--------|
| `catrustdb-store` | Column store dense (`Vec<Option<T>>`) | ✅ |
| | Index d'égalité O(1) + index de plage BTreeMap | ✅ |
| | **Lazy indexing** — `mark_all_indexes_dirty` + `ensure_index` / `ensure_range_index` | ✅ |
| | WAL NDJSON + `compact()` | ✅ |
| | WAL **fsync** + **checksum xxh3** par entrée | ✅ |
| | `persist()` / `from_wal()` — lignes actives seulement | ✅ |
| | **Format binaire V2** colonnaire + memmap2 — `persist_binary_v2` / `from_binary_v2` | ✅ |
| | `from_binary_v2` lazy : ouverture ~5 ms à 1 M lignes (**~700×** vs V1) | ✅ |
| | `persist_binary_v2` : snapshot 1 M lignes en **93 ms** (**13.5×** vs V1) | ✅ |
| | **Soft-delete** : `delete_row`, `is_deleted`, `all_active_rows` | ✅ |
| | **Update** : `update_attrs` — in-place + rafraîchissement index | ✅ |
| `catrustdb-eval` | Filtre natif `Pred` (∆) + fast-path O(1) sur index | ✅ |
| | `eval_cql_query` — FROM / WHERE / SELECT / FK traversal | ✅ |
| | **Agrégations** : COUNT, SUM, AVG, MIN, MAX | ✅ |
| | **ORDER BY** multi-clé (asc/desc) + **LIMIT** | ✅ |
| | **GROUP BY** par attribut ou chemin FK | ✅ |
| | `sigma_native` — migration Σ complète 2 phases | ✅ |
| | Scan séquentiel respecte les soft-deletes | ✅ |
| | **`filter_entity_lazy`** — build d'index à la demande (load V2) | ✅ |
| `catrustdb-store` | **Auto-index** — tous les attrs indexés après `load_instance` / `from_wal` | ✅ |
| | **Contrainte NOT NULL** — `validate_not_null()` par entité | ✅ |
| | **Validation pré-migration** — `validate_migration()` : NOT NULL + FK intuitée | ✅ |
| | **`sigma_validate`** commande serveur — rapport avant migration | ✅ |
| | **`sigma_delta_native`** — migration incrémentale par checkpoint de RowId | ✅ |
| | **`sigma_delta`** commande serveur — checkpoint persisté dans ServerState | ✅ |
| `catrustdb-server` | Serveur TCP tokio NDJSON | ✅ |
| | **Auth Bearer** constant-time + **rate limiting** Semaphore | ✅ |
| | **Path whitelist** canonicalize + prefix check | ✅ |
| | **Audit log** NDJSON mpsc non-bloquant | ✅ |
| | CLI : `--token`, `--data-dir`, `--max-connections`, `--audit-log` | ✅ |
| | Commandes RGPD : `delete`, `delete_where`, `update` | ✅ |
| | Transactions : `begin` / `commit` / `rollback` (snapshot Clone) | ✅ |
| | Export portabilité : `export_csv`, `export_jsonl` | ✅ |
| | **`sigma_dry`** — preview Σ sans écriture | ✅ |
| | **Registre de migrations (Flyway-style)** — `migrate` + `migrate_status` + `MigrationRecord` | ✅ |
| | **Lineage `σ`** — `LineageEvent` enregistré après chaque sigma + `{"cmd":"lineage"}` | ✅ |
| `catrust-parser` | **NOT NULL `!`** — `emp_name : Employee -> String!` propagé au schéma | ✅ |
| `catrust` CLI | Parse, validate, generate SQL/Cypher, export JSON | ✅ |
| | Apply (PostgreSQL), diff, viz, serve (Studio web) | ✅ |
| | Introspect, status, evolve, drift, snapshot, rollback, check | ✅ |
| | **Query SQL** (DataFusion REPL + `--sql`), serve-sql (pgwire), serve-flight | ✅ |
| `catrust-parser` | Parseur CQL nom 7 — schema, instance, mapping, query | ✅ |

**Scores après v1.2 (performances + DX) :**

| Persona | v1.1 | **v1.2** | Cible v1.3 |
|---------|------|----------|------------|
| 🔒 CISO | 9/10 | **9/10** ✅ | 9/10 ✅ |
| 🛡️ RSSI | 9/10 | **9/10** ✅ | 9/10 ✅ |
| 🏢 DSI | 7/10 | **8/10** ↑ | 8/10 ✅ |
| 🤖 CAIO | 7/10 | **8/10** ↑ | 9/10 |
| 📊 Data Science | 8/10 | **9.5/10** ↑↑ | 9.5/10 ✅ |
| 📈 CDO | 7/10 | **8/10** ↑ | 9/10 |
| 🗄️ DBA | 7.5/10 | **9/10** ↑↑ | 9/10 ✅ |
| 🔄 Migration | 10/10 ✅ | **10/10** ✅ | 10/10 ✅ |
| 📋 Conformité / DPO | 7/10 | **9.5/10** ↑↑ | 9.5/10 ✅ |
| 📣 Marketing | 8/10 | **9/10** ↑ | 10/10 |
| 🏗️ CTO | 8/10 | **9.5/10** ↑↑ | 9.5/10 ✅ |

**Justification des deltas v1.1 → v1.2 :**
- **DSI +1** : Docker hub + CI release + binaires multi-OS = déploiement production
- **CAIO +1** : to_pandas/to_polars + Jupyter magic + 8 MCP tools = workflow LLM natif
- **Data Science +1.5** : Arrow Flight + to_pandas + Jupyter + EXPLAIN = pipeline ML complet
- **CDO +1** : lineage complète Σ/Δ/Π + audit entity/attr + rétention par durée
- **DBA +1.5** : mmap V2 ~700× + WAL auto-compaction + EXPLAIN + tests de charge P50/P99
- **DPO +2.5** : purge physique RGPD + audit granulaire + data_subject_access + anonymize (hash/mask/redact) + compliance_report + privacy-by-design.md
- **Marketing +1** : Studio 22 routes + benchmarks publiés + landing page comparatif + Docker
- **CTO +1.5** : Δ/Π natifs + 373 tests + 0 clippy warnings + Criterion benchmarks

**Profils des nouveaux personas :**

| Persona | Ce qu'il attend | Ce que Catrust lui apporte |
|---------|----------------|--------------------------|
| 🛡️ **RSSI** — Responsable Sécurité SI | Chiffrement, contrôle d'accès, audit trail, conformité PSSI | WAL AES-256-GCM, auth Bearer, audit log NDJSON, `--read-only`, path whitelist |
| 🏢 **DSI** — Directeur SI | Stabilité, support multi-plateforme, intégration stack, roadmap claire | CI ubuntu/macOS/Windows, pgwire (compatible psql), Docker, benchmarks, v1.0 stable |
| 📈 **CDO** — Chief Data Officer | Traçabilité des données, gouvernance, portabilité, multi-sources | Lineage σ complet, registre migrations, export CSV/JSONL/Parquet, multi-bases, `migrate_status` |
| 📋 **DPO** — Data Protection Officer | RGPD Art. 15/17/20/25/32/35, droit d’accès, effacement, portabilité, anonymisation | `data_subject_access`, `anonymize` (hash/mask/redact), `compliance_report`, `delete_where`, `export_csv`/`export_jsonl`, WAL chiffré, `docs/privacy-by-design.md` |

---

## v0.3 — Sécurité & durabilité WAL ✅ FAIT

> CISO 4→6, DBA 4→6 · **Implémenté Avril 2026.**

- ✅ **Token Bearer** constant-time — flag `--token` ou `CATRUSTDB_TOKEN`
- ✅ **Path whitelist** — `persist`/`from_wal`/`compact` confinés dans `--data-dir`
- ✅ **Rate limiting** — Semaphore tokio (`--max-connections`, défaut 128)
- ✅ **Payload guard** — rejet si > `--max-payload-bytes` (défaut 64 Mo)
- ✅ **Audit log NDJSON** — `{ts, peer, cmd, ok, duration_ms}` via mpsc non-bloquant
- ✅ **WAL fsync** — `File::sync_all()` après chaque flush
- ✅ **Checksum xxh3** — `{"e":<entry>,"h":<u64>}`, backward-compatible

> TLS (`rustls`) — livré en v1.1 (`--tls-cert` / `--tls-key`).

---

## v0.4 — Requêtes avancées & types

> **Objectif :** Porter Data Science de 5→7, DBA de 6→7.

### 📊 Déjà implémenté ✅

- ✅ Agrégations : COUNT, SUM, AVG, MIN, MAX
- ✅ ORDER BY multi-clé (asc/desc) + LIMIT
- ✅ **GROUP BY** : `group by e.works_in.dept_name` — agrégation par groupe

### 📊 Restant

- [ ] **GROUP BY** : agrégation par valeur d'attribut
  ```cql
  query ByDept : Company {
    from e : Employee
    group_by e.works_in.dept_name
    select e.works_in.dept_name  COUNT(*)  AVG(e.salary)
  }
  ```
  ~~Parser CQL : `group_by` dans `CqlQueryDef` · Eval : `HashMap<Vec<Val>, AggState>`~~ **✅ FAIT**

- ✅ **Auto-index sur FK** : `rebuild_all_indexes()` appelé par `load_instance` + `from_wal`
  — Tous les attributs ont un index eq O(1) et range O(log n) après chargement

- ✅ **Contrainte NOT NULL** : annotation `!` dans le schéma CQL
  ```cql
  attributes  emp_name : Employee -> String!
  ```
  `store.insert_row()` retourne `Err` si un attribut `NOT NULL` est absent ou `Null`

- ✅ **Types supplémentaires** : `Val::Date` (ISO 8601 validé) + `Val::Uuid` (UUID 36-car validé + normalisé minuscules) — `Decimal` reporté

### 🔒 Mode lecture seule

- ✅ Flag `--read-only` : refuse 12 commandes d'écriture (`load`, `sigma`, `sigma_delta`, `migrate`, `persist`, `compact`, `from_wal`, `delete`, `delete_where`, `update`, `begin`, `commit`, `rollback`)

---

## v0.5 — Conformité RGPD & transactions ✅ FAIT

> Conformité 2→5 · **Implémenté Avril 2026.**

- ✅ **`delete_row`** — suppression douce + retrait des index (Art. 17)
- ✅ **`delete_where`** — suppression par prédicat (Art. 17)
- ✅ **`update_row`** — mise à jour d'attributs + refraîchissement index (Art. 16)
- ✅ **`persist()`** — n'écrit que les lignes actives (WAL propre)
- ✅ **Transactions** — `begin` / `commit` / `rollback` (snapshot `Database::clone()`)
- ✅ **`export_csv`** / **`export_jsonl`** — portabilité données actives (Art. 20)

> WAL chiffré (AES-256-GCM) → livré en v0.9.

---

## v0.6 — Migration 10/10

> **Objectif :** Porter Migration de 7→10.

### 🔄 Dry-run & preview

- ✅ **`sigma_dry`** — Σ sans écriture, retourne `{entities:[{name, rows_would_create}], warnings:[]}`

### 🔄 Validation pré-migration

- ✅ **`validate_migration()`** — vérifie NOT NULL couverts + FK intuitées dans source
- ✅ **`{"cmd":"sigma_validate"}`** — rapport JSON avant migration (bloquant ou warnings)

### 🔄 Rollback automatique

- ✅ **Rollback implicite** — `sigma_native` est une fonction pure ; si elle retourne `Err`, aucun état n'est modifié. La transaction implicite est garantie par design (pas d'état partiel possible).

### 🔄 Migration incrémentale

- ✅ **`sigma_delta_native()`** — ne traite que les RowIds > checkpoint
- ✅ **`{"cmd":"sigma_delta"}`** — checkpoint persisté dans `ServerState.sigma_checkpoints` ; `reset_checkpoint:true` pour repàrtir de zéro

### 🔄 Registre de migrations (Flyway-style)

- ✅ `migrations/V001__init.cql`, `V002__rename.cql`… (pattern `V{N}__{description}.cql`)
- ✅ `{"cmd":"migrate","dir":"/migrations"}` — applique les non-appliquées dans l'ordre
- ✅ `MigrationRecord {version, name, hash, ts, status, rows_loaded}` dans `ServerState`
- ✅ `{"cmd":"migrate_status","dir":"/migrations"}` — liste appliquées vs en attente

### 🔄 Lineage + ∆/Π complets

- ✅ Chaque `sigma` enregistre `LineageEvent {ts, source_schema, target_schema, entity_stats, duration_ms}`
- ✅ `{"cmd":"lineage"}` — historique des transformations (count + liste JSON)
- ✅ `delta_native` (pullback) + tests adjonction `∆ ⊣ Σ` — Sprint 4
- ✅ **Π** (right Kan extension) — jointure universelle — Sprint 4

---

## v0.7 — Écosystème IA & Data Science

> **Objectif :** Porter CAIO de 5→9, Data Science de 7→8.

### 🤖 Arrow Flight ⭐

- ✅ **`catrust-engine`** feature `flight` — serveur Arrow Flight gRPC au-dessus de DataFusion
  - `catrust serve-flight --schema schema.cql [--port 32100]`
  - `ListFlights()` → une `FlightInfo` par entité CQL
  - `GetSchema(descriptor)` → Arrow schema par entité
  - `DoGet(ticket)` → stream `RecordBatch` (zero-copy depuis DataFusion)
  - Tickets: `{"entity":"Employee"}` ou `{"sql":"SELECT ..."}` 
  - Compatible PyArrow, Polars, ADBC
  ```python
  import pyarrow.flight as fl
  client = fl.connect("grpc://localhost:32100")
  df = client.do_get(fl.Ticket(b'{"entity":"Employee"}')).read_all().to_pandas()
  ```

### 📊 Import / Export

- ✅ Export / Import Parquet (quasi zero-copy depuis column store)
- ✅ Import CSV — `{"cmd":"import_csv"}` avec inférence automatique de types

### 🤖 Client Python (`pip install catrustdb`) — PyO3/maturin

- ✅ Client Python TCP NDJSON pure stdlib (`python/catrustdb/`) — zéro dépendance externe
  - `connect(host, port, token)` → `Connection` context manager
  - Toutes les commandes du serveur exposées en méthodes Python
  - `pip install ./python` — installation locale
  - Tests pytest dans `python/tests/`
  - ✅ `.to_pandas()` / `.to_polars()` sur `QueryResult` — Sprint 5
  - ✅ Jupyter magic `%catrustdb` : `%load_ext catrustdb`, `%cql SELECT ...`, `%%cql` multi-ligne — Sprint 5

### 🤖 MCP server + `/schema-as-text` pour LLM

- ✅ `GET /mcp/schema-text` — renvoie le CQL brut pour injection dans un system prompt LLM
- ✅ `GET /mcp/tools` — tableau JSON (format OpenAI/Anthropic) de **8 outils** Studio découvrables par agents
  - `render_schema`, `evolve_plan`, `schema_info`, `cql_query`, `sigma_migrate`, `get_schema_text`, `delta_migrate`, `lineage`

### 📊 `%catrustdb` magic Jupyter — Sprint 5 ✅

- ✅ `%load_ext catrustdb` → `catrustdb/magic.py`
- ✅ `%catrustdb connect [port]` / `disconnect` / `status`
- ✅ `%cql SELECT * FROM Employee LIMIT 10` → DataFrame inline
- ✅ `%%cql` multi-ligne (cell magic)

---

## v0.8 — Studio Web & go-to-market ✅ FAIT

> **Objectif :** Porter Marketing de 7→9.

- ✅ Studio Web : **22 routes HTTP** — Schema / Query / Données / Migration / WAL / Instance / MCP
- ✅ Docker one-liner — `docker run -p 7878:7878 catrustdb/catrust serve --host 0.0.0.0`
- ✅ `catrust init --example` — scaffold projet avec `company.cql` pré-chargé
- ✅ Page "vs Flyway/Liquibase/dbt" — `docs/landing.md` avec tableau comparatif
- ✅ Benchmarks Criterion publiés — Insert 2.2M rows/s, Scan 105M rows/s, V2 persist 13.5×
- 🟡 Playground en ligne — WASM build OK, hébergement en attente de domaine

---

## v0.9 — Persistance avancée ✅ FAIT

> **Objectif :** Porter DBA vers le plafond 7/10.

- ✅ **Format binaire bincode** — `Database::persist_binary()` / `from_binary()`, magic `CATRUSTDB\x01`, commandes serveur `persist_bin` / `from_bin`, 3 tests dédiés
- ✅ **Mmap V2** : colonnes mappées en mémoire via `memmap2` (zero-copy, ~700× vs heap) — Sprint 6
- ✅ **Multi-bases simultanées** — `ServerState.databases: HashMap<String, Database>`, commandes `db_save` / `db_use` / `db_drop` / `db_list`, 4 tests dédiés
- ✅ **WAL chiffré AES-256-GCM** — `WalCipher::from_passphrase()`, `Wal::open_encrypted()`, `--wal-key` flag, format `base64(nonce‖ct)` par ligne, rétrocompat plain WAL, 3 tests dédiés

---

## v1.0 — Production-Ready ✅ FAIT

> **Scores cibles :** CISO 8 · CAIO 9 · DS 8 · DBA 7 · Migration 10 · Conformité 7 · Marketing 9

| Critère | Statut | Détail |
|---------|--------|--------|
| Tests | ✅ **357 tests** | 0 échec — unitaires + intégration workspace complet |
| CI multi-OS | ✅ | Matrix ubuntu / macOS / Windows — `.github/workflows/ci.yml` |
| cargo-deny | ✅ | Audit licences + advisories — `deny.toml` |
| Coverage | ✅ | cargo-tarpaulin → Codecov intégré au CI |
| Benchmarks | ✅ | Criterion — `catrustdb-store/benches/store.rs` (8 groupes) |
| Licence | ✅ | Propriétaire — © 2026 Clément Lecomte, tous droits réservés |

---

## v1.1 — Sécurité enterprise ✅ FAIT

> **Scores atteints :** CISO 9 ✅ · RSSI 9 ✅ · Conformité/DPO 9.5 ✅ · DSI 8 · **373 tests**

| Fonctionnalité | Flag | Détail |
|---------------|------|--------|
| **TLS natif rustls** | `--tls-cert` / `--tls-key` | Certificat PEM + clé privée — connexion chiffrée sans proxy |
| **RBAC 3 niveaux** | `--token-ro` / `--token-rw` / `--token-admin` | `ro` : lecture seule · `rw` : données · `admin` : toutes commandes |
| **Rotation clé WAL** | `{"cmd":"rotate_wal_key","path":"...","new_key":"..."}` | Re-chiffrement AES-GCM à chaud sans arrêt du serveur |
| **Rotation audit log** | `--audit-log-max-mb <n>` | Archive automatique `audit.log.{ts}` quand la taille est dépassée |
| **Rapport sécurité** | `{"cmd":"security_report"}` | TLS, mode auth, rôles, WAL chiffré, audit log, read-only, rate limit |

> Backward compatible : `--token` (token unique legacy) fonctionne toujours sans RBAC.

---

## v1.2 — DX & Hardening production ✅ FAIT

> **Scores atteints :** CAIO 8 ↑ · Data Science 9.5 ↑ · DBA 9 ↑ · CTO 9.5 ↑ · **357 tests**

| Fonctionnalité | Détail |
|---------------|--------|
| **mmap V2** | `memmap2` sur colonnes V2 — zero-copy load, ~700× vs heap (1M lignes) |
| **WAL auto-compaction** | `--wal-compact-threshold <n>` — compaction tokio::spawn en arrière-plan |
| **EXPLAIN** | DataFusion `EXPLAIN` via pgwire + Studio. Stats `/stats` par entité |
| **to_pandas() / to_polars()** | `QueryResult` Python → DataFrame natif (dépendances optionnelles) |
| **Jupyter magic** | `%load_ext catrustdb` · `%cql SELECT ...` · `%%cql` multi-ligne |
| **Studio /rows** | `GET /rows?entity=<name>&limit=<n>` — onglet Données paginé |
| **MCP 8 outils** | +`delta_migrate` +`lineage` — format OpenAI/Anthropic compatible |
| **Tests de charge** | Criterion benchmarks: Insert 2.2M rows/s, Scan 105M rows/s, P50/P99 |
| **Δ natif** | `delta_native` (pullback) + commande TCP `{"cmd":"delta"}` |
| **Π natif** | `pi_native` (right Kan extension) + commande TCP `{"cmd":"pi"}` |
| **Audit granulaire** | `entity` + `attr` dans chaque entrée · `--audit-log-max-days` rétention |
| **Purge RGPD** | `compact` réécriture WAL sans soft-deleted · `docs/rgpd-purge.md` |

---

## Résumé chronologique

```
v0.2  ██████████████████████ Avril 2026 ✅
       Column store · Index O(1)+BTree · WAL · Σ natif · TCP · CLI catrust

v0.3  ██████████████████████ Avril 2026 ✅  🔒🗄️
       Auth Bearer · fsync · xxh3 · Audit log · Rate limiting · Path whitelist

v0.4  ██████████████████████ Avril 2026 ✅  📊🗄️
       GROUP BY · Auto-index FK · NOT NULL · Val::Date · Val::Uuid

v0.5  ██████████████████████ Avril 2026 ✅  📋🗄️
       delete_row · update_row · Transactions · export_csv/jsonl

v0.6  ██████████████████████ Avril 2026 ✅  🔄
       sigma_dry · Validation · Rollback auto · Registre · Lineage

v0.7  ██████████████████████ Avril 2026 ✅  🤖📊
       --read-only · MCP 8 outils · Arrow Flight · Python SDK · Val::Date+Uuid

v0.8  ██████████████████████ Avril 2026 ✅  📣
       Studio 22 routes · Docker one-liner · Benchmarks Criterion · Landing page

v0.9  ██████████████████████ Avril 2026 ✅  🗄️🔒
       WAL chiffré AES-256-GCM · Format binaire bincode · Multi-bases

v1.0  ██████████████████████ Avril 2026 ✅  ✅
       CI matrix · cargo-deny · Benchmarks Criterion · Licence propriétaire

v1.1  ██████████████████████ Avril 2026 ✅  🔒🛡️
       TLS rustls · RBAC 3 niveaux · Argon2id KDF · Injection SQL fix · HTTP headers

v1.2  ██████████████████████ Avril 2026 ✅  🗄️🤖
       mmap V2 · WAL auto-compaction · EXPLAIN · to_pandas/to_polars · Jupyter magic · 357 tests
```

---

## Idées futures (post-v1.0)

- **Clustering** : réplication master/replica via stream WAL en temps réel
- **LSP CQL** : extension VSCode avec autocomplétion, validation inline, go-to-definition
- **WebAssembly** : CATRUSTDB dans le navigateur (wasm-bindgen)
- **Formal verification** : preuves Coq/Lean des propriétés de Σ et Δ (adjonction, cohérence)
- **Distributed Σ** : migration parallèle sur plusieurs shards
- **Intégration MLflow/DVC** : versioning de datasets aligné sur les versions de schéma CQL

---

*Catrust — La base de données comme foncteur.*

