- Project:
rustfs/MetaDB - Language & Toolchain: 100% Pure Rust (
edition = "2021", toolchain pinned to1.100.0inrust-toolchain.toml, zero C/C++ FFI) - Async & Distributed Stack:
tokio+tonic/prost(gRPC) +openraft(Multi-Raft) - Design Methodology: Google Elephant-Goldfish Model (EGM)
- Companion Specifications:
../Architecture.md— Master Architecture Specification./designs/SITEMAP.md— EGM Design Index./designs/storage_lsm_mvcc.md— Pure-Rust WAL-less LSM, In-Memory MVCC & Locality-Aware Compaction./designs/consensus_and_transactions.md— OpenRaft Multi-Raft, 1-RTT Pushdown, Off-Critical-Path Queues & 2PC./designs/sharding_and_control_plane.md— Topology Sharding, Two-Tier Control Plane, Protobuf Contracts & SQL Templates
Prior to Phase 1 execution, the repository contains an initial 6-crate synchronous in-memory prototype (metadb-core, metadb-storage, metadb-tx, metadb-cluster, metadb-proxy, metadb-server) that validates core data-model concepts in RAM (BTreeMap / VecDeque backed RaftLog and PersistentStoreInner), without disk persistence, SSTables, SnapshotGuard isolation, openraft consensus, tonic gRPC networking, crash-recoverable 2PC intents, epoch fencing, or server/CLI binaries.
Phases 1 through 6 evolve the repository step-by-step into an 8-crate asynchronous, crash-safe, production-grade distributed metadata engine with zero C/C++ FFI dependencies:
flowchart TD
Core["metadb-core\n(HLC, Binary Key/Value Codecs,\nShardEpoch, CompositeKey, Errors)"]
Proto["metadb-proto\n(Protobuf v1 Schemas,\ntonic/prost Services & Type Conversions)"]
Storage["metadb-storage\n(StorageBackend Trait, WAL-less SSTable LSM,\nManifest, BlockCache, Bloom, SnapshotGuard MVCC,\nLocalityCompactor)"]
Raft["metadb-raft\n(OpenRaft TypeConfig, Segmented CRC32C RaftLog,\n3-Watermark Purge Gate, ReadIndex Batcher,\ntonic RaftNetwork, 1->3 Voter ConfChange)"]
Tx["metadb-tx\n(1-RTT PushdownExecutor, AsyncAttrAggregator,\nFIFO AuxOutbox + Spill, Crash-Recoverable 2PC)"]
Cluster["metadb-cluster\n(PID-Boundary & DualMode Splitter, Epoch Fencing,\nJumbo Isolation, CellLocalManager, GlobalManager,\nMetaCache, IdRangeAllocator)"]
Proxy["metadb-proxy\n(20 Parameterized/Escaped SQL Templates,\nCursor Pagination, Stateless Epoch-Aware Router)"]
Server["metadb-server\n(Embedded MetaDbEngine SDK,\nmetadbd Multi-Role Daemon, metadb-ctl CLI)"]
Core --> Proto
Core --> Storage
Core --> Raft
Proto --> Raft
Storage --> Raft
Core --> Tx
Proto --> Tx
Storage --> Tx
Raft --> Tx
Core --> Cluster
Proto --> Cluster
Storage --> Cluster
Raft --> Cluster
Tx --> Cluster
Core --> Proxy
Proto --> Proxy
Cluster --> Proxy
Tx --> Proxy
Core --> Server
Proto --> Server
Storage --> Server
Raft --> Server
Tx --> Server
Cluster --> Server
Proxy --> Server
metadb-transport is not one of those eight data-path crates. It is a later policy crate. The only carried transport remains tonic gRPC over TCP. RDMA is recognized and rejected. See designs/rdma_transport.md.
- 100% Rust & 100% English: Zero
unsafeC/C++ bindings (rocksdb/leveldbFFI forbidden). All code, Rustdoc comments, error messages, commit messages, and technical specs must be written in English. - Documentation Synchronization: At the end of every phase, update the implementation status matrix in
Architecture.md,README.md, and the five multilingual usage guide suites (docs/guides/{en,ja,fr,zh,de}/) to reflect newly landed capabilities accurately. - Continuous Verification: No phase may be marked complete unless
cargo fmt --all -- --check,cargo clippy --workspace --all-targets -- -D warnings, andcargo test --workspacepass cleanly. - Git Delivery Rule (Phase 6): When pushing verified milestones to GitHub from a worktree branch onto the repository default branch, push via
git push origin HEAD:main.
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.mddocs/DEVELOPMENT_PLAN.mddocs/designs/{SITEMAP.md, concepts_brief.md, metadb_architecture.md, storage_lsm_mvcc.md, consensus_and_transactions.md, sharding_and_control_plane.md, review_report.md}_agents/skills/metadb_elephant/SKILL.mdandREADME.mddocs/README.mdanddocs/guides/{en,ja,fr,zh,de}/{README.md, deployment.md, client-apis-and-sql.md, operations-and-tuning.md}
- Acceptance Criteria:
- Zero-context Goldfish review subagent completes full specification audit with zero unresolved blocking findings.
- Existing prototype workspace continues to pass
cargo test --workspacewithout code modifications.
Phase 1: Core Binary Codecs, System Keyspaces & Protobuf/gRPC Contracts (metadb-core & metadb-proto)
- Objective: Solidify all deterministic binary encodings (including CRC32C framing, composite shard bounds,
ShardEpoch, and internal transactional keyspaces0x04..0x07) inmetadb-core, and introduce themetadb-protocrate defining wire protocols for single-node and multi-cell RPCs. - File Boundaries:
Cargo.toml(addcrates/metadb-protoand workspace dependenciesbytes,crc32c,thiserror,prost,tonic,tonic-build,tokio,serde)crates/metadb-core/Cargo.tomlcrates/metadb-core/src/{lib.rs, error.rs, hlc.rs, schema.rs, epoch.rs, system_keys.rs, checksum.rs}crates/metadb-proto/Cargo.tomlcrates/metadb-proto/build.rscrates/metadb-proto/proto/metadb/v1/{common.proto, metadata.proto, transaction.proto, raft.proto, control_plane.proto}crates/metadb-proto/src/{lib.rs, convert.rs}
- Key Invariants:
- Disjoint binary key prefixes:
0x01(MetaTable),0x02(QuotaTable),0x03(SecondaryIndexTable),0x04(DirShardDeltaforDualModeFineGrainedsub-shards),0x05(WriteIntentfor 2PC locks),0x06(TxnRecordfor Primary-Anchored 2PC decisions),0x07(SpilledAuxOutboxfor bounded Raft log retention). - Deterministic binary codecs with explicit format version byte and CRC32C validation for
InodeAttr,QuotaRecord(includingapplied_by_shard: BTreeMap<ShardId, (u64, u16)>withprev_uid_cursor),SecondaryIndexRecord(includingtombstone_ver),WriteIntent,TxnRecord, andAuxOutboxEntry. - Bounded HLC clock-skew check (
max_clock_drift_ms, default500ms) & 16-bit logical overflow safety:HybridLogicalClock::update_checked(remote)rejects timestamps drifting beyondmax_clock_drift_msahead of local physical wall clock withMetaDbError::ClockSkewExceeded; if the 16-bit logical counter reachesu16::MAX,HLCincrements the 48-bit physical component by+1ms(yielding briefly if approachingmax_clock_drift_ms) and never wrapsu16to0at the same physical millisecond. CompositeKeyBoundsupporting bothPID-boundary intervals[ (start_pid, ""), (end_pid, "") )andDualModeFineGrained(PID, name)intervals.
- Disjoint binary key prefixes:
- Verification Commands:
cargo test -p metadb-core -p metadb-protocargo clippy -p metadb-core -p metadb-proto --all-targets -- -D warnings
- Acceptance Criteria:
- Round-trip property/unit tests pass for every binary key/value codec, corrupted-byte CRC32C rejection, lexicographical byte ordering across
0x01..0x07, HLC drift rejection, and Protobuf<->metadb-coredomain conversions.
- Round-trip property/unit tests pass for every binary key/value codec, corrupted-byte CRC32C rejection, lexicographical byte ordering across
Phase 2: Pure-Rust WAL-less LSM Engine, SnapshotGuard MVCC & Locality-Aware Compaction (metadb-storage)
- Objective: Replace the in-memory
PersistentStoreInnermock with a real disk-backed pure-Rust sorted LSM engine behind a cleanStorageBackendtrait, paired withSnapshotGuard-protectedMemMvccStore, Coordinated Flush Barrier hooks, and bottommost-safeLocalityCompactor. - Detailed Specification:
./designs/storage_lsm_mvcc.md - File Boundaries:
crates/metadb-storage/Cargo.tomlcrates/metadb-storage/src/{lib.rs, backend.rs, sstable.rs, block.rs, bloom.rs, cache.rs, manifest.rs, version_set.rs, mvcc.rs, compaction.rs, engine.rs}crates/metadb-storage/tests/{lsm_recovery_tests.rs, mvcc_snapshot_tests.rs, locality_compaction_tests.rs}
- Key Invariants:
- WAL-less Persistence:
LsmStorageBackendwrites zero KV WAL files; durability before flush is owned by the Raft log, andlsm_flushed_indexadvances strictly afterL0SSTablefdatasync+MANIFESTfdatasync+ parent directoryfsync. - SSTable Integrity: 4 KiB prefix-compressed data blocks with 16-entry restart intervals, per-block CRC32C trailers, Kirsch-Mitzenmacher Bloom filter (
10 bits/keyindexing both live values andPhysicalTombstones), sparse block index, length-framedMetaBlockwith monotonicflush_generation: u64, and canonical 64-byte magic/version/checksum footer. - MVCC visibility (
SnapshotGuard&ReadCut):SnapshotGuardpins aReadCut { max_raft_index, max_hlc }plus the version and immutable memtables, with bounded per-page step leases. AnImmMemTablecovering writes up toH_immcollapse-flushes to an unversioned L0 SSTable only whenmin_active_snapshot_hlc >= H_imm(retention5,000ms). That gate does not guarantee zero future-read or phantom-scan anomalies. Collapse may keep only the latest value of a user key. An open 2PC lease also stores the value captured atstart_hlcunder prefix0x0Din that flush. A point read behind the flush watermark returns that capture, orTransactionTimeoutwhen it was not proved, and does not return a newer collapsed value. A range read behind the flush watermark returnsTransactionTimeoutfor the whole range. - Bottommost-Safe Locality Compaction:
LocalityCompactortracks tombstone density per 9-byte[table_prefix][group_key: 8B]bucket and compacts[start_key, end_key)across all overlapping levels (L0..L_max), droppingPhysicalTombstoneentries only when no deeper overlapping SSTable can contain the key.
- WAL-less Persistence:
- Verification Commands:
cargo test -p metadb-storagecargo clippy -p metadb-storage --all-targets -- -D warnings
- Acceptance Criteria:
- Crash/reopen tests cover
MANIFESTrecovery, orphan.sst.tmpcleanup, CRC32C corruption detection, one L0 tombstone shadowing an L1 value,SnapshotGuardisolation 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 fromarXiv:2610.32247v1, not a result ofmvcc_snapshot_tests.rs. They also do not prove zero future-read anomalies for every range read.
- Crash/reopen tests cover
Phase 3: OpenRaft Multi-Raft Consensus, 3-Watermark Log Storage & Linearizable ReadIndex (metadb-raft)
- Objective: Build
metadb-raftonopenraftto unify Stage 1 (1-Votersingle-node) and Stage 3 (3-Voterdistributed Multi-Raft) behind segmented CRC32C Raft logs, 3-watermark truncation safety, snapshot streaming,tonicgRPC transport, and batchedReadIndex. - Detailed Specification:
./designs/consensus_and_transactions.md(§1–§4) - File Boundaries:
crates/metadb-raft/Cargo.tomlcrates/metadb-raft/src/{lib.rs, types.rs, log_store.rs, state_machine.rs, network.rs, read_index.rs, group_host.rs, conf_change.rs}crates/metadb-raft/tests/{single_voter_recovery_tests.rs, multi_raft_failover_tests.rs}
- Key Invariants:
- Segmented CRC32C Raft Log: Append-only segment files (
segment_<first_index:020>.raftlog) withfdatasyncon batch append, persistentHardState(voted_for,current_term), and torn-tail recovery on startup. - 3-Watermark Safe Purge Gate: OpenRaft log purge is clamped to
safe_purge_index = min(state_flushed_index, aux_outbox_durable_index, last_snapshot_index), wherestate_flushed_indexadvances atomically only when bothMemMvccStoreand foldedAsyncAttrAggregatorupdates up toMare durable in L0 SSTables +MANIFEST. - Online Membership Evolution (
1-Voter -> 3-Voter):ConfChangeOrchestratorexecutesAddLearner(node_id)-> verifies snapshot/log replication lag< learner_promote_threshold_entries-> executes joint-consensusChangeMembershippromoting learners toVoters without write downtime. - Linearizable Reads:
ShardRaftNode::linearizable_read()uses OpenRaftensure_linearizable()with request coalescing (ReadIndexBatcher), resolving locally in0network hops for1-Votergroups and1quorum heartbeat RTT for3-Votergroups.
- Segmented CRC32C Raft Log: Append-only segment files (
- Verification Commands:
cargo test -p metadb-raftcargo clippy -p metadb-raft --all-targets -- -D warnings
- Acceptance Criteria:
- Automated tests pass for
1-VoterWAL-less crash recovery (verifying un-flushed MemTable state replays cleanly from Raft segments), 3-watermark log pinning and release,1-Voter -> Learner -> 3-Voterlive promotion under concurrent writes, leader kill/re-election, and stale-leader read fencing.
- Automated tests pass for
Phase 4: Replicated Pushdown Execution, Off-Critical-Path Queues & Crash-Recoverable 2PC (metadb-tx)
- Objective: Refactor
metadb-txso all single-shard pushdown operations,AsyncAttrAggregatordeltas,AuxOutboxtasks, and Primary-Anchored 2PC transactions execute deterministically throughmetadb-raft's state machine with full crash recovery. - Detailed Specification:
./designs/consensus_and_transactions.md(§5–§8) - File Boundaries:
crates/metadb-tx/Cargo.tomlcrates/metadb-tx/src/{lib.rs, state_machine_impl.rs, pushdown.rs, attr_aggregator.rs, aux_outbox.rs, two_pc.rs, recovery_worker.rs}crates/metadb-tx/tests/{attr_reconcile_race_tests.rs, aux_idempotency_tests.rs, two_pc_crash_tests.rs}
- Key Invariants:
- Coordinated Flush Barrier for
AsyncAttrAggregator: Folded(PID, "_attr_")updates (applied_index = M) are written inside the exact same L0 SSTable flush batch up toraft_index = M, and in-memory deltas<= Mare pruned strictly after the newVersionis published, preventing both crash data loss and read-reconciliation double/under-counting. - Authoritative
rmdir&DeletingDirIntent: Single-shardrmdirscans[target_dir_id, target_dir_id + 1)inside deterministic Raftapply; cross-shardrmdirlocks(target_dir_id, "_attr_")withWriteIntent::DeletingDirduring 2PC Prepare so concurrentcreate_file(target_dir_id, ...)cannot race between emptiness check and commit. - Exact-Once
AuxOutboxwith Local Overflow Spill: Tasks dispatch in strict FIFOorigin_raft_indexorder per(origin_shard_id, target_shard_id); overdue tasks spill to[0x07](SpilledAuxOutbox) during MemTable flush so Raft logs never stall;QuotaTablededuplicates viaapplied_index_by_shard[origin_shard_id]andSecondaryIndexTablevia monotonic(last_applied_hlc, tombstone_hlc). - Crash-Recoverable Primary-Anchored 2PC: Supports cross-shard
Rename(both exclusive and POSIX overwrite), cross-shardMkdir, and cross-shardRmdir. Primary Shard atomically commitsTxnRecord::Committed { commit_hlc }([0x06]) + primaryWriteIntentresolution ([0x05]);TxnRecoveryWorkerrolls forward committed secondaries and aborts pending transactions whose lease is no longer renewed. The initial lease is3,000ms. A live coordinator extends it, up to60,000ms, and the participant MVCC horizon moves with that lease. Default MVCC retention stays5,000ms.
- Coordinated Flush Barrier for
- Verification Commands:
cargo test -p metadb-txcargo clippy -p metadb-tx --all-targets -- -D warnings
- Acceptance Criteria:
- Fault-injection tests pass for coordinator crashes before/after Primary Commit, concurrent
rename(A->B)vsrename(B->A)conflict resolution without deadlock, concurrentrmdirvscreate_fileacross shards, leader failover mid-AuxOutboxdrain, and concurrentdirstatduring L0 flush barriers.
- Fault-injection tests pass for coordinator crashes before/after Primary Commit, concurrent
Phase 5: Epoch-Fenced Topology Sharding, Jumbo Dual-Mode & Two-Tier Control Plane (metadb-cluster & metadb-proxy)
- Objective: Upgrade
metadb-clusterandmetadb-proxyto distributed gRPC-capable routing withShardEpochfencing, Raft-replicatedExecuteSplit(PID-boundary +DualModeFineGrainedscatter-gather), distributedIdRangeAllocator, Two-Tier Control Plane RPCs, and all 20 parameterized/escaped SQL templates. - Detailed Specification:
./designs/sharding_and_control_plane.md - File Boundaries:
crates/metadb-cluster/Cargo.tomlcrates/metadb-cluster/src/{lib.rs, shard.rs, split_worker.rs, jumbo.rs, id_allocator.rs, meta_cache.rs, cell_manager.rs, global_manager.rs}crates/metadb-proxy/Cargo.tomlcrates/metadb-proxy/src/{lib.rs, sql_lexer.rs, sql_templates.rs, router.rs}crates/metadb-cluster/tests/{epoch_split_tests.rs, dual_mode_jumbo_tests.rs}crates/metadb-proxy/tests/sql_templates_tests.rs
- Key Invariants:
- Epoch Fencing: Every shard mutation/read checks
ShardEpoch { conf_ver, version }; stale routes returnEpochMismatch { latest_descriptor }and trigger transparentMetaCacherefresh + retry. - Dual-Mode Fine-Grained Sharding: When enabled on a Jumbo
PID, splits along(PID, name)boundaries initializeDirShardDelta([0x04][pid: 8B BE]) on non-anchor sub-shards socreate_file/unlinkremain lock-free1-RTTsingle-shard ops,dirstat(PID)executes a1-hopparallel scatter-gather across sub-shards ofPID, andlistdir(PID, after_name, limit)streams cursor-paginated pages across sub-shards. - Complete 20-Template SQL Compiler: Lexer-backed parser supporting escaped quotes,
?positional bind parameters, cursor-paginatedlistdir, POSIX/exclusiverename,setattr/chmod/chown/utimes, andQuotaTable/SecondaryIndexTablepoint & range queries.
- Epoch Fencing: Every shard mutation/read checks
- Verification Commands:
cargo test -p metadb-cluster -p metadb-proxycargo clippy -p metadb-cluster -p metadb-proxy --all-targets -- -D warnings
- Acceptance Criteria:
- In-process tests cover
PID-boundary splits, aJumboIsolatedroute flag (not a move of peer shards onto a dedicated host),DualModeFineGrainedscatter-gather inside one process,IdRangeAllocatoruniqueness across restarts, and the 20 SQL templates. Dedicated-host jumbo placement is not what those tests run. A later loopbackMOVE_STAGED/MOVE_LIVEplacement is documented indocs/en/scale-control-plane-status.md. It does not calltransfer_leader, does not replicate the cell directory, and is not this phase's acceptance.
- In-process tests cover
Phase 6: Unified metadbd Daemon, metadb-ctl CLI, End-to-End Evolution & Benchmark Suite (metadb-server)
- Objective: Deliver the full
metadb-serverlibrary SDK, standalone/distributedmetadbdgRPC server binary,metadb-ctladministration & benchmark CLI, graceful shutdown, observability metrics, and end-to-end Stage 1 -> Stage 2 -> Stage 3 cluster evolution tests. - File Boundaries:
crates/metadb-server/Cargo.tomlcrates/metadb-server/src/{lib.rs, config.rs, grpc_services.rs, metrics.rs}crates/metadb-server/src/bin/{metadbd.rs, metadb-ctl.rs}crates/metadb-server/tests/{integration_tests.rs, e2e_cluster_evolution_tests.rs}- Documentation status updates across
Architecture.md,README.md, anddocs/guides/{en,ja,fr,zh,de}/
- Key Invariants:
- Runnable roles:
all-in-onestill hosts the directory, one cell, and local Raft groups.global-managerhostsGLOBAL_CELL_DIRECTORYand the shared id allocator, and does not open Raft groups.cell-managerhosts one cell and its local Raft groups, canRegisterCellitself withcluster.global_manager, and forwardsAllocateIdBlockthere.behosts local Raft replicas, serves their metadata, and does not mint ids or publish a cell.proxydoes not open Raft. It loadsGLOBAL_CELL_DIRECTORYand dials the one registered cell that contains a metadata call,ExecuteSql, or a user-key transaction, withx-metadb-cell-forwarded. A missing directory, a request that is not contained, keys split across two cells, or a range that only overlaps a cell returns a placement error and is not sent to[cluster] upstream.CommitPrimary2pc,ApplyAuxBatch,ForwardRouter, andGetRoutesmay still use that upstream.AllocateIdBlockis refused. The directory file is not its own Raft group. A bootstrap leader replicates aGLOBAL_CELL_DIRECTORYandCELL_MANAGER_STATEsnapshot through the lowest local shard's existing Raft log; a joined replica does not publish, and aglobal-managerwith no shard group still has only the local file. A metadata or transaction request contained by one registered remote cell is forwarded to that cell. The proxy cell choice is not a production MetaCache of every shard. This is not automatictransfer_leader, not a cross-machine jumbo move, and not a heartbeat scheduler. A measured liveness hint is computed and is not applied. - Clean Lifecycle: Graceful SIGINT/SIGTERM drain flushes active MemTables, persists
MANIFESTand Raft state, and closes network listeners cleanly.
- Runnable roles:
- Verification Commands:
cargo fmt --all -- --checkcargo clippy --workspace --all-targets -- -D warningscargo test --workspace
- Acceptance Criteria:
e2e_cluster_evolution_tests.rsboots one persistent all-in-onePersistentMetaDbCluster, restarts it from the same directory, callsTriggerShardSplit, and runs a cross-shardRenameplus bulk deletion on that one process. It does not startmetadbd --role be, does not join two extra BE processes, and does not register a second Cell. A second all-in-one join isjoin_existing_group, not that end-to-end test. In-process 1-voter to 3-voter coverage ismulti_raft_failover_tests, not a three-VM rehearsal.
metadb-security is the single outbound transport policy, described in designs/transport_security.md. The default mode is plaintext. tls and mtls are refused before listen. The 2026-11-20 ring exception was revoked, so no TLS provider is linked and deny.toml has no ISC exceptions. [security.rbac], when present, installs method grants and fail-closes on deny. The shared bearer is still required and is not a role. The scale stream owns process role separation. The transaction stream owns 2PC leases. This workstream is not a first-launch pass, not encryption, and not a trillion-scale acceptance.
HeartbeatScheduler records a handler receive or a completed StoreHeartbeat round trip and will return HintLive only when that sample and the decision-time clock are trusted and fresh. A missing sample, an expired sample, the historical 1 ms wall-clock fallback, and a wall clock that disagrees with the monotonic age return Refuse. Maintenance computes the hint and does not apply it. The hint does not call transfer_leader, does not move a Jumbo shard onto another machine, does not change membership, and does not replicate GLOBAL_CELL_DIRECTORY. Splits still use local Raft and LSM state. Client shard descriptors stay annotations. Samples are in memory and are not a cell-wide bus for 20k–30k shards. This is not a phase completion, not a first-launch pass, and not a trillion-scale acceptance. Linux is the supported platform.