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
108 changes: 66 additions & 42 deletions Architecture.md

Large diffs are not rendered by default.

66 changes: 33 additions & 33 deletions README.md

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions _agents/skills/metadb_elephant/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ This skill loads the architectural history, foundational literature, subsystem c
* `metadb-storage`: `StorageBackend` trait, pure-Rust WAL-less SSTable LSM (4 KiB CRC32C blocks, Bloom filters including physical tombstones, 16-shard LRU `BlockCache`, atomic `MANIFEST`), `SnapshotGuard`-gated `MemMvccStore`, and bottommost-safe `LocalityCompactor`.
* `metadb-raft`: `openraft` Multi-Raft (`1-Voter` single-node to `3-Voter` distributed), segmented CRC32C log store, 3-watermark purge gate, `ReadIndex` batcher, and online `ConfChange`.
* `metadb-tx`: Deterministic `RaftStateMachine`, `1-RTT` `PushdownExecutor`, `AsyncAttrAggregator` (Coordinated Flush Barrier + Read-Path Reconciliation), FIFO `AuxOutbox` + `[0x07]` local spill, and Primary-Anchored crash-recoverable 2PC (`Rename`, cross-shard `Mkdir`/`Rmdir`).
* `metadb-cluster`: Unified `[0x01, 0x04)` sharding, `ShardEpoch` fencing, `PID`-boundary & `DualModeFineGrained` (`[0x04] DirShardDelta`) splitting, Jumbo dedicated-node isolation, `GlobalManager`, `CellLocalManager`, `MetaCache`, and `IdRangeAllocator`.
* `metadb-cluster`: Unified `[0x01, 0x04)` sharding, `ShardEpoch` fencing, `PID`-boundary splits, a `DualModeFineGrained` mode flag (a later split may use `[0x04] DirShardDelta`; the flag write does not copy keys), a `JumboIsolated` route flag (not dedicated-node placement), `GlobalManager`, `CellLocalManager`, `MetaCache`, and `IdRangeAllocator`.
* `metadb-proxy`: Tokenizing compiler for all 20 parameterized metadata SQL templates + Epoch-aware stateless router.
* `metadb-server`: Embedded `MetaDbEngine` SDK + `metadbd` multi-role daemon + `metadb-ctl` operator CLI.
* `metadb-server`: Persistent `MetaDbEngine::open` / `PersistentMetaDbCluster`, in-memory `new_single_node` simulator, `metadbd` (`all-in-one` only), and `metadb-ctl`.

## Implementation Status Policy

* **Current Baseline**: Phases 0–6 Completed & Verified across all 8 pure-Rust crates (`cargo fmt`, `cargo clippy -D warnings`, and `cargo test --workspace` passing).
* **Current baseline**: The 8 crates are in this repository. Phase labels are not a completed verification and not a first-launch pass. Crate tests exist. This file does not assert that `cargo test --workspace` is currently green. Multi-cell topology, role-split processes, and dedicated-host jumbo moves are not deployed. Jumbo isolation is a route flag.
* **Ongoing Maintenance**: Keep `Architecture.md`, `README.md`, `docs/designs/*.md`, and `docs/guides/{en,ja,fr,zh,de}/` synchronized with any future architectural extensions.

## Non-Negotiable Architectural Invariants
Expand Down
12 changes: 6 additions & 6 deletions docs/DEVELOPMENT_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ flowchart TD

## 2. Phase-by-Phase Implementation Plan

### Phase 0: Architecture, EGM Specifications, Goldfish Review & Multilingual Guides (Current Gate)
### Phase 0: Architecture, EGM Specifications, Goldfish Review & Multilingual Guides (design documents, not a first-launch pass)
* **Objective**: Establish Zero-Decision architectural specifications, subsystem blueprints, phased engineering plan, adversarial zero-context Goldfish review resolutions, and 5-language user documentation (`en`, `ja`, `fr`, `zh`, `de`) before modifying Rust crate source code.
* **Deliverables**:
* `Architecture.md`
Expand Down Expand Up @@ -116,13 +116,13 @@ flowchart TD
* **Key Invariants**:
* **WAL-less Persistence**: `LsmStorageBackend` writes zero KV WAL files; durability before flush is owned by the Raft log, and `lsm_flushed_index` advances strictly after `L0` SSTable `fdatasync` + `MANIFEST` `fdatasync` + parent directory `fsync`.
* **SSTable Integrity**: 4 KiB prefix-compressed data blocks with 16-entry restart intervals, per-block CRC32C trailers, Kirsch-Mitzenmacher Bloom filter (`10 bits/key` indexing both live values and `PhysicalTombstone`s), sparse block index, length-framed `MetaBlock` with monotonic `flush_generation: u64`, and canonical **64-byte** magic/version/checksum footer.
* **Mathematical MVCC Visibility (`SnapshotGuard` & `ReadCut`)**: `SnapshotGuard` pins a total `ReadCut { max_raft_index, max_hlc }` + `Arc<Version>` + `Vec<Arc<ImmMemTable>>` with bounded per-page step leases. An `ImmMemTable` covering writes up to `H_imm` flushes to an unversioned L0 SSTable **only when** `min_active_snapshot_hlc >= H_imm` (`<= 5,000ms` timeout), guaranteeing zero future-read/phantom-scan anomalies and zero persisted MVCC tombstones.
* **MVCC visibility (`SnapshotGuard` & `ReadCut`)**: `SnapshotGuard` pins a `ReadCut { max_raft_index, max_hlc }` plus the version and immutable memtables, with bounded per-page step leases. An `ImmMemTable` covering writes up to `H_imm` collapse-flushes to an unversioned L0 SSTable only when `min_active_snapshot_hlc >= H_imm` (retention `5,000ms`). That gate does not guarantee zero future-read or phantom-scan anomalies. Collapse may keep only the latest value. A range read at `start_hlc` can include later values of keys an open 2PC lease does not cover. Point reads of keys that lease records stay at the pre-image until commit.
* **Bottommost-Safe Locality Compaction**: `LocalityCompactor` tracks tombstone density per 9-byte `[table_prefix][group_key: 8B]` bucket and compacts `[start_key, end_key)` across all overlapping levels (`L0..L_max`), dropping `PhysicalTombstone` entries **only** when no deeper overlapping SSTable can contain the key.
* **Verification Commands**:
* `cargo test -p metadb-storage`
* `cargo clippy -p metadb-storage --all-targets -- -D warnings`
* **Acceptance Criteria**:
* Crash/reopen tests verify `MANIFEST` recovery, orphan `.sst.tmp` cleanup, CRC32C corruption detection, Bloom filter zero false-negatives, `SnapshotGuard` isolation across concurrent `MemTable` seals and L0 flushes, `~60%` KV write reduction on rapid updates/deletes, and zero shadowed-key resurrection during multi-level `LocalityCompactor` runs.
* Crash/reopen tests cover `MANIFEST` recovery, orphan `.sst.tmp` cleanup, CRC32C corruption detection, one L0 tombstone shadowing an L1 value, `SnapshotGuard` isolation across concurrent memtable seals and L0 flushes, and a locality-compaction fixture that does not resurrect the shadowed key in that case. They do not measure a `~60%` KV write reduction. That percentage is a paper/model figure from `arXiv:2610.32247v1`, not a result of `mvcc_snapshot_tests.rs`. They also do not prove zero future-read anomalies for every range read.

---

Expand Down Expand Up @@ -184,7 +184,7 @@ flowchart TD
* `cargo test -p metadb-cluster -p metadb-proxy`
* `cargo clippy -p metadb-cluster -p metadb-proxy --all-targets -- -D warnings`
* **Acceptance Criteria**:
* Tests verify concurrent client writes during live `PID`-boundary shard splits (`EpochMismatch` auto-retry with zero lost/duplicate writes), Jumbo Shard dedicated-node isolation, `DualModeFineGrained` scatter-gather `dirstat` + paginated `listdir` + 2PC `rmdir`, `IdRangeAllocator` uniqueness across restarts, and all 20 SQL templates.
* In-process tests cover `PID`-boundary splits, a `JumboIsolated` route flag (not a move of peer shards onto a dedicated host), `DualModeFineGrained` scatter-gather inside one process, `IdRangeAllocator` uniqueness across restarts, and the 20 SQL templates. Dedicated-host jumbo placement is not what those tests run.

---

Expand All @@ -197,11 +197,11 @@ flowchart TD
* `crates/metadb-server/tests/{integration_tests.rs, e2e_cluster_evolution_tests.rs}`
* Documentation status updates across `Architecture.md`, `README.md`, and `docs/guides/{en,ja,fr,zh,de}/`
* **Key Invariants**:
* **Single Codebase Across Deployment Topologies**: `metadbd --role all-in-one` runs `GlobalManager + CellLocalManager + MetaCache + Proxy + BE (1-Voter OpenRaft)` in one process; `--role global-manager | cell-manager | be | proxy` runs disaggregated multi-node / multi-Cell clusters over `tonic` gRPC.
* **Single runnable role**: `metadbd --role all-in-one` runs `GlobalManager`, `CellLocalManager`, `MetaCache`, `Proxy`, and a `1-Voter` OpenRaft group in one process. `open_and_serve` rejects `global-manager`, `cell-manager`, `be`, and `proxy`. Those names are not a disaggregated deployment.
* **Clean Lifecycle**: Graceful SIGINT/SIGTERM drain flushes active MemTables, persists `MANIFEST` and Raft state, and closes network listeners cleanly.
* **Verification Commands**:
* `cargo fmt --all -- --check`
* `cargo clippy --workspace --all-targets -- -D warnings`
* `cargo test --workspace`
* **Acceptance Criteria**:
* End-to-end integration suite boots a persistent `1-Voter` `metadbd` node on disk, restarts and verifies crash recovery, splits shards across `PID` boundaries, joins two additional `metadbd` BE nodes over real local TCP/gRPC sockets, promotes shards to `3-Voter` Multi-Raft under live load, adds a second `Cell`, executes cross-shard 2PC `rename` and bulk-delete `LocalityCompactor` scans via `metadb-ctl` and gRPC clients, and updates all documentation status tables to `Implemented`.
* `e2e_cluster_evolution_tests.rs` boots one persistent all-in-one `PersistentMetaDbCluster`, restarts it from the same directory, calls `TriggerShardSplit`, and runs a cross-shard `Rename` plus bulk deletion on that one process. It does not start `metadbd --role be`, does not join two extra BE processes, and does not register a second Cell. A second all-in-one join is `join_existing_group`, not that end-to-end test. In-process 1-voter to 3-voter coverage is `multi_raft_failover_tests`, not a three-VM rehearsal.
7 changes: 4 additions & 3 deletions docs/de/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ Diese Seite folgt dem Code in `crates/`. Sie beschreibt keinen Mehrprozess-Zelle
`PersistentMetaDbCluster::open_and_serve` (`crates/metadb-server/src/lib.rs`):

1. Weist jedes `node.role` außer `all-in-one` zurück.
2. Weist eine Wildcard oder eine andere Nicht-Loopback-Adresse in `grpc_listen_addr` oder `metrics_listen_addr` zurück, wenn `shared_secret` leer ist. Bindet danach `node.grpc_listen_addr` (Vorgabe `127.0.0.1:7800`; `127.0.0.1:0` lässt das Betriebssystem einen Port wählen).
2. An empty `shared_secret` does not start the process unless `allow_unauthenticated = true`, and that flag is loopback-only. A whitespace-only secret is rejected even with the flag. A usable secret plus the flag is rejected. A wildcard or other non-loopback address cannot use the opt-in. It then binds `node.grpc_listen_addr` (default `127.0.0.1:7800`; `127.0.0.1:0` asks the OS for a port).
3. Öffnet `DurableIdAllocator` unter `<data_dir>/global_allocator`.
4. Öffnet `ShardGroupHost` unter `<data_dir>/be`.
5. Öffnet oder bootstrapt `DurableCellManager` unter `<data_dir>/cell_<cell_id>`.
6. Registriert diese eine Zelle bei `DurableGlobalManager` für den Schlüsselbereich `[0x01, 0x04)`.
7. Stellt sicher, dass Wurzel-Inode `1` (`ROOT_INODE_ID`) einen Attributsatz hat.
8. Bedient vier gRPC-Dienste auf demselben Listener. Alle vier nehmen denselben Bearer-Interceptor. Wenn `metrics_listen_addr` gesetzt ist, verlangt `GET /metrics` auf dieser Adresse dasselbe Geheimnis. Ein nicht leeres Geheimnis weist einen fehlenden oder falschen Bearer zurück. Ein leeres Geheimnis wird nur für Loopback-Binds akzeptiert. Dieser Prozess beendet TLS nicht.
8. Serves four gRPC services on one listener. All four use the same bearer interceptor. When `metrics_listen_addr` is set, `GET /metrics` on that address requires the same secret. A non-empty secret rejects a missing or wrong bearer. An empty secret does not listen unless `allow_unauthenticated = true`, and that flag is loopback-only. A whitespace-only secret is rejected even with the flag. A usable secret combined with the flag is rejected. This process does not terminate TLS.
9. Startet eine Wartungsaufgabe im Abstand von 250 ms.

`metadbd` ist eine dünne Hülle: Es lädt TOML, wendet CLI-Überschreibungen an, ruft `open_and_serve` auf, ruft optional `RegisterNode` an `--cell-manager` auf und ruft bei Strg-C `shutdown` auf. Metriken werden, wenn konfiguriert, in `open_and_serve` bedient.
Expand Down Expand Up @@ -86,7 +86,8 @@ MVCC-Versionen leben `storage.mvcc_retention_ms` (Vorgabe 5.000) lang im Speiche

## Raft

Jeder lokale Shard ist eine `openraft`-0.10-Gruppe. Das Log ist eine segmentierte CRC32C-Datei unter `.../shards/<id>/raft`. Vorgaben, die **nicht** aus TOML geladen werden (`raft_options` ist `#[serde(skip)]`):
Jeder lokale Shard ist eine `openraft`-0.10-Gruppe. Das Log ist eine segmentierte CRC32C-Datei unter `.../shards/<id>/raft`. Defaults are loaded from `[raft]` when that table or a field is omitted. `raft_options` is not `#[serde(skip)]`. Unknown keys in `[raft]` fail parsing. Values apply at group start and are not reloaded. `max_segment_bytes` does not rewrite segments already on disk. `/readyz` is 200 only after startup has finished, shutdown has not started, and every local Raft group has finished startup replay, applied a log entry, is a voter, and has a known leader. A bound socket is not enough. There is no gRPC health RPC. See [Operability](../en/operability.md).


| Feld | Vorgabe |
| :--- | :--- |
Expand Down
34 changes: 24 additions & 10 deletions docs/de/build-and-run.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,27 +44,41 @@ Flags von `metadbd` (`crates/metadb-server/src/bin/metadbd.rs`):

Jede Rolle außer `all-in-one` scheitert, bevor der Listener gebunden wird, mit `server role ... is not implemented; only all-in-one runs a process`.

Beispiel, nur Loopback:
`metadbd` with no config file uses an empty `shared_secret` and `allow_unauthenticated = false`, so that process does not start. The file below is the explicit loopback development opt-in. It is not a credential. Bind only a literal loopback IP (`127.0.0.1`). The hostname `localhost` is not accepted for this flag. Do not use it on a non-loopback address.

```bash
mkdir -p /tmp/metadb-data
cargo run -p metadb-server --bin metadbd -- \
--data-dir /tmp/metadb-data \
--listen 127.0.0.1:7800 \
--node-id 1 \
--cell-id 1 \
--role all-in-one
cat > /tmp/metadb-loopback.toml <<'EOF'
[node]
data_dir = "/tmp/metadb-data"
grpc_listen_addr = "127.0.0.1:7800"

[security]
allow_unauthenticated = true
EOF
cargo run -p metadb-server --bin metadbd -- --config /tmp/metadb-loopback.toml
```

Mit einer Datei, siehe [Konfiguration](./configuration.md):
A usable secret is a different file. Replace the `[security]` block. Do not set `allow_unauthenticated` in that same file. Both together are rejected. A whitespace-only secret is rejected.

```bash
cargo run -p metadb-server --bin metadbd -- --config ./standalone.toml
mkdir -p /tmp/metadb-data
cat > /tmp/metadb-auth.toml <<'EOF'
[node]
data_dir = "/tmp/metadb-data"
grpc_listen_addr = "127.0.0.1:7800"

[security]
shared_secret = "replace-with-a-long-random-string"
EOF
cargo run -p metadb-server --bin metadbd -- --config /tmp/metadb-auth.toml
```

Pass that same secret to the client as `metadb-ctl --auth-token` or `METADB_AUTH_TOKEN`.

Logs verwenden den `EnvFilter` von `tracing-subscriber`. Der Standardfilter ist `info`. Überschreiben mit der üblichen Variable `RUST_LOG`, zum Beispiel `RUST_LOG=debug`.

Beim Start mit leerem `security.shared_secret` schreibt der Prozess eine Warnung, dass Loopback-gRPC keine Authentifizierung hat. Die Standardbindung ist `127.0.0.1`. Eine Wildcard oder eine andere Nicht-Loopback-Adresse mit leerem, fehlendem oder falsch geschriebenem Geheimnis verweigert das Binden. Ein nicht leeres `[security].shared_secret` verlangt denselben Bearer für Metadaten-, Transaktions-, Control-Plane- und Raft-Transport-RPCs sowie für `GET /metrics`. Der Prozess beendet TLS nicht. Ein TLS- oder Zertifikatsschlüssel in der Konfiguration lässt den Start fehlschlagen, statt Klartext zu dienen. Den Listener in einem vertrauenswürdigen Netz lassen, oder jeden Dienst hinter einen Proxy setzen, der Clients authentifiziert, und den direkten Zugriff auf diesen Prozess sperren.
An empty `security.shared_secret` does not start the process. Loopback is not an implicit exception. Development without credentials sets `allow_unauthenticated = true` and keeps every listener on a literal loopback IP (`127.0.0.1` or `::1`). The hostname `localhost` is not accepted for that opt-in. A wildcard or other non-loopback address refuses to listen. A whitespace-only secret is rejected even with the flag. A usable secret combined with the flag is rejected. A non-empty `[security].shared_secret` requires the same bearer for metadata, transaction, control-plane, and Raft transport RPCs, and for `GET /metrics`. The process does not terminate TLS. A TLS, certificate, anonymous, or insecure key in the configuration fails startup instead of serving plaintext. Keep an opted-in listener on a trusted network, or put every service behind a proxy that authenticates the client and block direct access to this process.

Strg-C schreibt den Shard-Zustand und stoppt die OpenRaft-Gruppen (`cluster.shutdown()`).

Expand Down
Loading