Introduction
Development Setup Guide
This guide will help you set up a development environment for ApexStore.
💻 System Requirements
Minimum Requirements
- OS: Linux, macOS, or Windows (with WSL2 recommended)
- RAM: 4GB (8GB+ recommended for large workloads)
- Disk: 2GB free space
- CPU: Any modern CPU (multi-core recommended for testing)
Recommended Setup
- OS: Ubuntu 22.04 LTS or macOS 13+
- RAM: 16GB
- Disk: 10GB free space (SSD preferred)
- CPU: 4+ cores
🛠️ Installing Prerequisites
1. Rust Toolchain
Installation
# Install Rust using rustup (recommended)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Follow the prompts, then reload your shell
source $HOME/.cargo/env
Verify Installation
# Check Rust version (should be 1.96+)
rustc --version
# Output: rustc 1.75.0 (or higher)
# Check Cargo version
cargo --version
# Output: cargo 1.75.0 (or higher)
Additional Components
# Install Clippy (linter)
rustup component add clippy
# Install rustfmt (formatter)
rustup component add rustfmt
# Install rust-src (for IDE support)
rustup component add rust-src
2. Git
Linux (Ubuntu/Debian)
sudo apt-get update
sudo apt-get install git
macOS
# Using Homebrew
brew install git
# Or install Xcode Command Line Tools
xcode-select --install
Windows
Download from git-scm.com
Verify Installation
git --version
# Output: git version 2.x.x
3. Code Editor (Recommended: VS Code)
Install VS Code
- Download from code.visualstudio.com
- Or use package manager:
# Ubuntu/Debian sudo snap install code --classic # macOS brew install --cask visual-studio-code
Install Extensions
Essential:
-
rust-analyzer - Rust language support
- ID:
rust-lang.rust-analyzer - Features: Auto-completion, go-to-definition, inline errors
- ID:
-
CodeLLDB (optional) - Debugging support
- ID:
vadimcn.vscode-lldb
- ID:
Recommended: 3. Better TOML - TOML syntax highlighting
- ID:
bungcip.better-toml
-
Error Lens - Inline error highlighting
- ID:
usernamehw.errorlens
- ID:
-
crates - Cargo.toml dependency management
- ID:
serayuzgur.crates
- ID:
VS Code Settings
Create .vscode/settings.json in project root:
{
"rust-analyzer.checkOnSave.command": "clippy",
"rust-analyzer.cargo.features": "all",
"editor.formatOnSave": true,
"[rust]": {
"editor.defaultFormatter": "rust-lang.rust-analyzer"
}
}
📦 Project Setup
1. Clone the Repository
# Clone your fork
git clone https://github.com/YOUR_USERNAME/ApexStore.git
cd ApexStore
# Add upstream remote
git remote add upstream https://github.com/ElioNeto/ApexStore.git
# Verify remotes
git remote -v
2. Build the Project
# Debug build (faster compilation)
cargo build
# Release build (optimized)
cargo build --release
# Build with API feature
cargo build --release --features api
First build may take 5-10 minutes as Cargo downloads and compiles dependencies.
3. Run Tests
# Run all tests
cargo test
# Run tests with output
cargo test -- --nocapture
# Run specific test
cargo test test_memtable_insert
4. Configuration
# Copy environment template
cp .env.example .env
# Edit configuration (optional)
nano .env
Example Development Configuration (.env):
# Server
HOST=127.0.0.1
PORT=8080
# LSM Engine
DATA_DIR=.lsm_data_dev
MEMTABLE_MAX_SIZE=2097152 # 2MB for faster flushing in dev
BLOCK_CACHE_SIZE_MB=32
# Logging
RUST_LOG=debug
ENABLE_METRICS=true
🧪 Development Workflow
Running the CLI
# Debug mode
cargo run
# Release mode (faster)
cargo run --release
Available REPL Commands:
> help # Show available commands
> put key value # Insert or update key
> get key # Retrieve value
> delete key # Delete key (tombstone)
> stats # Show statistics
> exit # Exit REPL
Running the API Server
# Debug mode
cargo run --features api --bin apexstore-server
# Release mode
cargo run --release --features api --bin apexstore-server
# With custom port
PORT=3000 cargo run --release --features api --bin apexstore-server
Testing the API:
# Insert a key
curl -X POST http://localhost:8080/keys \
-H "Content-Type: application/json" \
-d '{"key": "user:1", "value": "Alice"}'
# Get a key
curl http://localhost:8080/keys/user:1
# Get statistics
curl http://localhost:8080/stats/all
Code Quality Checks
# Format code
cargo fmt
# Check formatting (CI mode)
cargo fmt -- --check
# Run Clippy linter
cargo clippy
# Clippy with strict mode (CI mode)
cargo clippy -- -D warnings
# Check for unused dependencies
cargo machete # Requires: cargo install cargo-machete
Running Benchmarks
# Install criterion
cargo install cargo-criterion
# Run all benchmarks
cargo bench
# Run specific benchmark
cargo bench memtable_insert
# Generate HTML report
open target/criterion/report/index.html
🐳 Docker Development
Build Docker Image
# Build production image
docker build -t apexstore:dev .
# Run in development mode with volume mount
docker run -d \
--name apexstore-dev \
-p 8080:8080 \
-v $(pwd)/data:/data \
-v $(pwd)/.env:/app/.env \
apexstore:dev
Docker Compose Development
# Start services
docker-compose up -d
# View logs
docker-compose logs -f apexstore
# Restart after code changes
docker-compose restart
# Stop services
docker-compose down
🛠️ Debugging
Using LLDB (VS Code)
- Install CodeLLDB extension
- Create
.vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug CLI",
"cargo": {
"args": ["build", "--bin=apexstore"]
},
"args": [],
"cwd": "${workspaceFolder}"
},
{
"type": "lldb",
"request": "launch",
"name": "Debug Server",
"cargo": {
"args": ["build", "--features", "api", "--bin=apexstore-server"]
},
"args": [],
"cwd": "${workspaceFolder}"
},
{
"type": "lldb",
"request": "launch",
"name": "Debug Test",
"cargo": {
"args": ["test", "--no-run", "--lib"]
},
"args": ["test_memtable_insert"],
"cwd": "${workspaceFolder}"
}
]
}
- Set breakpoints in code
- Press
F5to start debugging
Using println! Debugging
#![allow(unused)] fn main() { // In your code pub fn put(&mut self, key: &[u8], value: &str) -> Result<()> { println!("[DEBUG] Inserting key: {:?}", String::from_utf8_lossy(key)); self.wal.append(key, value)?; println!("[DEBUG] WAL append successful"); self.memtable.insert(key, value); Ok(()) } }
Run with:
cargo run -- 2>&1 | grep DEBUG
Using RUST_LOG
# Set log level
export RUST_LOG=debug
# Or inline
RUST_LOG=trace cargo run
# Filter by module
RUST_LOG=apexstore::core::engine=debug cargo run
📈 Performance Profiling
CPU Profiling (Linux)
# Install flamegraph
cargo install flamegraph
# Generate flamegraph
sudo cargo flamegraph --bin apexstore-server
# Open flamegraph.svg in browser
firefox flamegraph.svg
Memory Profiling
# Using valgrind (Linux)
valgrind --leak-check=full --track-origins=yes \
./target/debug/apexstore
# Using heaptrack (Linux)
heaptrack ./target/debug/apexstore
heaptrack_gui heaptrack.apexstore.*.gz
Benchmark Profiling
# Profile specific benchmark
cargo bench --bench memtable_bench -- --profile-time=10
# With flamegraph
cargo flamegraph --bench memtable_bench
🧰 Testing
Unit Tests
# Run all unit tests
cargo test --lib
# Run tests in specific module
cargo test --lib core::memtable
# Run single test
cargo test test_memtable_insert
Integration Tests
# Run all integration tests
cargo test --test '*'
# Run specific integration test file
cargo test --test recovery_test
Test Coverage
# Install tarpaulin (Linux only)
cargo install cargo-tarpaulin
# Generate coverage report
cargo tarpaulin --out Html
# Open report
firefox tarpaulin-report.html
Stress Testing
# Create stress test script
cat > stress_test.sh << 'EOF'
#!/bin/bash
for i in {1..10000}; do
curl -X POST http://localhost:8080/keys \
-H "Content-Type: application/json" \
-d "{\"key\": \"key_$i\", \"value\": \"value_$i\"}" &
done
wait
EOF
chmod +x stress_test.sh
# Run stress test
./stress_test.sh
📚 Documentation
Generating Documentation
# Generate and open docs
cargo doc --open
# Include private items
cargo doc --document-private-items --open
# Generate for all features
cargo doc --all-features --open
Writing Documentation
All public APIs should have documentation:
#![allow(unused)] fn main() { /// Brief description (appears in summary). /// /// Longer description with more details. /// /// # Arguments /// /// * `key` - Description of key parameter /// * `value` - Description of value parameter /// /// # Returns /// /// Description of return value /// /// # Errors /// /// Description of possible errors /// /// # Examples /// /// ``` /// let engine = LsmEngine::new(config)?; /// engine.put(b"key", "value")?; /// ``` /// /// # Panics /// /// Description of panic conditions (if any) /// /// # Safety /// /// Description of safety requirements (for unsafe functions) pub fn put(&mut self, key: &[u8], value: &str) -> Result<()> { // Implementation } }
🐞 Troubleshooting
Common Issues
Issue: Compilation Errors After Update
# Clean build artifacts
cargo clean
# Update dependencies
cargo update
# Rebuild
cargo build
Issue: Tests Failing Randomly
# Run tests serially (not in parallel)
cargo test -- --test-threads=1
Issue: Port Already in Use
# Find process using port 8080
lsof -i :8080 # macOS/Linux
# Kill process
kill -9 <PID>
# Or use different port
PORT=3000 cargo run --features api --bin apexstore-server
Issue: Out of Disk Space
# Clean target directory (safe, can be rebuilt)
rm -rf target/
# Clean cargo cache
cargo cache --autoclean
Issue: Slow Compilation
# Use faster linker (Linux)
sudo apt-get install lld
export RUSTFLAGS="-C link-arg=-fuse-ld=lld"
# Or use mold (even faster)
cargo install mold
export RUSTFLAGS="-C link-arg=-fuse-ld=mold"
# Enable incremental compilation (in Cargo.toml)
[profile.dev]
incremental = true
🚀 Next Steps
- ✅ Read CONTRIBUTING.md for contribution guidelines
- ✅ Explore the codebase structure
- ✅ Pick an issue to work on
- ✅ Join discussions on GitHub
💬 Getting Help
- Documentation: Run
cargo doc --open - Issues: GitHub Issues
- Discussions: GitHub Discussions
- Email: netoo.elio@hotmail.com
Happy Coding! 🦀
Last updated: March 2026
Development Environment
ApexStore builds and tests inside a container, so contributors do not need a local
Rust toolchain. The image is defined by Dockerfile.dev and
every command below is also available as a make target.
Why a container
The crate's --all-features build pulls in wasmtime 44 and the cranelift crates,
which declare a recent rust-version. Building with an older toolchain fails with
roughly forty requires rustc <version> lines and no obvious cause. Pinning the
toolchain in an image removes that class of "works on my machine" report, and gives
CI and contributors the same compiler, the same cargo-audit, and the same
cargo-deny.
This is a toolchain image. The production server image is the separate
multi-stage Dockerfile.
One-time setup
make dev-image
That builds apexstore-dev (~3.5 GB, mostly the Rust toolchain plus the LLVM
headers wasmtime needs). Rebuild it only when Dockerfile.dev changes.
Everyday commands
| Command | What it runs |
|---|---|
make fmt | cargo fmt --all |
make fmt-check | cargo fmt --all -- --check |
make clippy | cargo clippy --locked --all-targets --all-features -- -D warnings |
make test | cargo test --locked --all-features --workspace |
make test-fast | library unit tests only |
make bench | all Criterion benchmarks |
make audit | cargo audit against the RustSec advisory database |
make deny | cargo deny check (licences, bans, sources) |
make doc | cargo doc --locked --no-deps --all-features |
make env-check | verifies .env.example matches the variables src/ reads |
make actionlint | lints .github/workflows/ |
make ci | all of the above, in the order CI runs them |
make shell | interactive shell in the toolchain image |
Run make help for the full list.
How caching works
Two named Docker volumes are mounted on every run:
apexstore-cargo-registry→/usr/local/cargo/registry(downloaded crates)apexstore-target→/app/target(compiled artifacts)
The repository itself is bind-mounted at /app, so edits on the host are visible
immediately and build output never pollutes the working tree. A cold
make clippy compiles ~573 crates and takes several minutes; subsequent runs are
incremental.
make clean-volumes deletes both volumes when you need a genuinely cold build.
Running commands directly
make is a thin wrapper. The equivalent raw invocation:
docker run --rm \
-v "$PWD:/app" \
-v apexstore-cargo-registry:/usr/local/cargo/registry \
-v apexstore-target:/app/target \
apexstore-dev cargo test --all-features
On Windows with Git Bash, prefix with MSYS_NO_PATHCONV=1 and use a Windows-style
path (-v "C:/path/to/apexstore:/app") so the path is not rewritten.
Use bash -c "..." rather than bash -lc "...": a login shell resets PATH and
cargo disappears.
Working without the container
A host toolchain works too. rust-toolchain.toml pins 1.99.1, so rustup will
install and select it automatically on the first cargo invocation in this
repository — no manual rustup override needed. Dockerfile.dev builds on the
same version; keep the two in sync.
That is distinct from the crate's MSRV, rust-version in Cargo.toml, which
is 1.96 — the oldest compiler the dependency graph accepts under
--all-features. CI checks it in a separate job, so raising the pinned toolchain
does not silently raise the MSRV.
Install cargo-audit 0.22 or later — version 0.21 cannot parse CVSS 4.0 entries
in the current advisory database and aborts with
unsupported CVSS version: 4.0.
The four binaries
apexstore-server src/bin/server.rs REST + GraphQL API server (the default-run target)
apexstore-cli src/bin/cli.rs CLI / REPL
apexstore-tui src/bin/tui.rs terminal dashboard
apex-store-rs src/main.rs 13-line stub; see the issue tracker
Always pass --bin <name>. cargo run on its own resolves to
apexstore-server via the default-run key in Cargo.toml.
Frontend
The Angular dashboard in frontend/ has its own toolchain and is
not covered by this image or by CI:
cd frontend
npm ci
npm run build
npm test
Benchmarks
make bench
All seven benchmarks honour a CI environment variable: when it is set they
reduce the sample count and shrink the datasets, so a full pass takes minutes
rather than hours.
CI=true cargo bench --bench read_bench -- --noplot
Note that Criterion::sample_size asserts n >= 10 and panics below that, so 10
is the floor for the CI branch in each configure_criterion.
Fuzzing
cargo-fuzz needs a nightly toolchain and is therefore not in the image:
cargo +nightly fuzz run wal -- -runs=10000
cargo +nightly fuzz run sstable -- -runs=10000
ApexStore Configuration Guide
This guide explains all configuration parameters available in ApexStore. All settings can be configured via environment variables without recompilation.
Table of Contents
- Quick Start
- Server Configuration
- LSM Engine Configuration
- Performance Tuning
- Tuning Profiles
- Troubleshooting
Quick Start
# 1. Copy the example configuration
cp .env.example .env
# 2. Edit values as needed
nano .env
# 3. Run the server
cargo run --release --features api --bin apexstore-server
The server will load .env automatically and display all active configuration on startup.
Server Configuration
Network Settings
| Variable | Default | Description |
|---|---|---|
HOST | 0.0.0.0 | Server bind address (0.0.0.0 = all interfaces) |
PORT | 8080 | Server port |
Payload Limits
| Variable | Default | Description |
|---|---|---|
MAX_JSON_PAYLOAD_SIZE | 52428800 (50MB) | Maximum JSON request/response size |
MAX_RAW_PAYLOAD_SIZE | 52428800 (50MB) | Maximum raw payload size |
Recommendations:
- Development/Testing: 50-100MB
- Production with pagination: 10MB
- Stress testing: 100-200MB
HTTP Server Tuning
| Variable | Default | Description |
|---|---|---|
SERVER_WORKERS | 0 (CPU cores) | Number of worker threads |
SERVER_KEEP_ALIVE | 75 | Keep-alive timeout (seconds) |
SERVER_CLIENT_TIMEOUT | 60 | Client request timeout (seconds) |
SERVER_SHUTDOWN_TIMEOUT | 30 | Graceful shutdown timeout (seconds) |
SERVER_BACKLOG | 2048 | Maximum pending connections |
SERVER_MAX_CONNECTIONS | 25000 | Max concurrent connections per worker |
Recommendations:
- High-traffic: Increase
SERVER_WORKERSto 8-16 - Low-latency: Set
SERVER_KEEP_ALIVEto 5-15 - Memory-constrained: Reduce
SERVER_MAX_CONNECTIONSto 5000-10000
Request Rate Limits
RATE_LIMIT_REQUESTS_PER_MINUTE defaults to 100 accepted requests per client
IP in a sliding 60-second window, shared across routes. 0 disables this global
cap while keeping configured endpoint caps active. The server additionally
limits /admin/compact and /admin/flush to five accepted requests each per
window. Rejected requests do not extend the window or consume another cap.
Applications configuring RateLimiterState::set_endpoint_limit must use the
registered route pattern, including its scope (for example /api/keys/{key}),
not a concrete key URL. A zero endpoint cap disables only that additional cap.
The admin rate-limit summary reports both per-IP and per-route accepted counts
in the last 60 seconds; requests with both caps disabled are not tracked.
The current rate limiter identifies clients by the TCP peer address, matching
the concurrent connection guard. It ignores X-Forwarded-For and Forwarded,
including malformed values. Clients cannot reset their budget by changing a
header. Behind a reverse proxy, clients share that proxy's peer-address budget;
apply individual client limits at the proxy as well. Configurable trusted-proxy
CIDRs and right-to-left forwarding-chain resolution are not implemented yet.
Do not rely on the old leftmost X-Forwarded-For behavior for attribution.
LSM Engine Configuration
Storage Settings
| Variable | Default | Description |
|---|---|---|
DATA_DIR | ./.lsm_data | Data storage directory path |
MemTable
| Variable | Default | Description |
|---|---|---|
MEMTABLE_MAX_SIZE | 4194304 (4MB) | Size threshold before flush to disk |
Impact:
- Larger (8-16MB): Fewer flushes, better compression, higher memory usage
- Smaller (1-2MB): More flushes, lower memory usage, faster recovery
Recommendations:
- Write-heavy: 8-16MB
- Memory-constrained: 2MB
- Balanced: 4MB (default)
SSTable Block Configuration
| Variable | Default | Description |
|---|---|---|
BLOCK_SIZE | 4096 (4KB) | Block size for SSTables |
BLOCK_CACHE_SIZE_MB | 64 | In-memory cache for blocks (MB) |
SPARSE_INDEX_INTERVAL | 16 | Blocks between index entries |
Block Size Impact:
- Larger (8KB): Better compression ratio, higher read latency
- Smaller (2KB): Lower latency, less compression
Cache Size Recommendations:
- Read-heavy: 256-512MB
- Balanced: 64-128MB
- Memory-constrained: 32MB
Sparse Index:
- Dense (8): More memory, faster lookups
- Sparse (32): Less memory, slower lookups
Bloom Filter
| Variable | Default | Description |
|---|---|---|
BLOOM_FALSE_POSITIVE_RATE | 0.01 (1%) | False positive probability |
Impact:
- Lower (0.001 = 0.1%): More accurate, more memory
- Higher (0.05 = 5%): Less accurate, less memory
Recommendations:
- Read-heavy: 0.001-0.005
- Balanced: 0.01
- Memory-constrained: 0.05
Write-Ahead Log (WAL)
| Variable | Default | Description |
|---|---|---|
MAX_WAL_RECORD_SIZE | 33554432 (32MB) | Maximum single record size |
WAL_BUFFER_SIZE | 65536 (64KB) | Write buffer size |
WAL_SYNC_MODE | always | Fsync strategy |
Sync Modes:
always: Safest, slowest (every write synced)every_second: Balanced (1s of data loss possible)manual: Fastest, least safe (crash = data loss)
Recommendations:
- Production:
always - High-throughput:
every_second - Testing/Dev:
manual
Compaction
| Variable | Default | Description |
|---|---|---|
COMPACTION_STRATEGY | lazy_leveling | Compaction algorithm |
SIZE_RATIO | 10 | Size ratio between levels |
LEVEL0_COMPACTION_THRESHOLD | 4 | L0 file count trigger |
MAX_LEVEL_COUNT | 7 | Maximum LSM tree levels |
COMPACTION_THREADS | 2 | Background compaction threads |
Compaction Strategies:
leveled: Best read performancetiered: Best write performancelazy_leveling: Balanced (default)
Recommendations:
- Read-heavy:
leveled, SIZE_RATIO=4-6 - Write-heavy:
tiered, SIZE_RATIO=15-20 - High-throughput: COMPACTION_THREADS=4-8
Feature Flags
| Variable | Default | Description |
|---|---|---|
FEATURE_CACHE_TTL | 10 | Cache TTL in seconds |
Performance Tuning
Memory vs. Performance Trade-offs
High Memory → High Performance:
MEMTABLE_MAX_SIZE=16777216 # 16MB
BLOCK_CACHE_SIZE_MB=512 # 512MB
BLOOM_FALSE_POSITIVE_RATE=0.001 # 0.1%
SPARSE_INDEX_INTERVAL=8 # Dense
Low Memory → Acceptable Performance:
MEMTABLE_MAX_SIZE=2097152 # 2MB
BLOCK_CACHE_SIZE_MB=32 # 32MB
BLOOM_FALSE_POSITIVE_RATE=0.05 # 5%
SPARSE_INDEX_INTERVAL=32 # Sparse
Latency vs. Throughput
Low Latency:
BLOCK_SIZE=2048 # 2KB
WAL_SYNC_MODE=every_second
SERVER_KEEP_ALIVE=5
High Throughput:
BLOCK_SIZE=8192 # 8KB
MEMTABLE_MAX_SIZE=16777216 # 16MB
COMPACTION_THREADS=8
WAL_BUFFER_SIZE=262144 # 256KB
Tuning Profiles
Stress Testing Profile
MAX_JSON_PAYLOAD_SIZE=104857600 # 100MB
MAX_RAW_PAYLOAD_SIZE=104857600
MEMTABLE_MAX_SIZE=16777216 # 16MB
BLOCK_SIZE=8192
BLOCK_CACHE_SIZE_MB=256
WAL_SYNC_MODE=every_second
COMPACTION_THREADS=4
High Write Throughput
MEMTABLE_MAX_SIZE=8388608 # 8MB
BLOCK_SIZE=8192
BLOOM_FALSE_POSITIVE_RATE=0.05
WAL_SYNC_MODE=every_second
WAL_BUFFER_SIZE=262144 # 256KB
COMPACTION_THREADS=4
LEVEL0_COMPACTION_THRESHOLD=8
COMPACTION_STRATEGY=tiered
High Read Throughput
BLOCK_CACHE_SIZE_MB=512
BLOOM_FALSE_POSITIVE_RATE=0.001
SPARSE_INDEX_INTERVAL=8
COMPACTION_STRATEGY=leveled
SIZE_RATIO=4
Memory Constrained
MEMTABLE_MAX_SIZE=2097152 # 2MB
BLOCK_CACHE_SIZE_MB=32
BLOOM_FALSE_POSITIVE_RATE=0.05
SPARSE_INDEX_INTERVAL=32
SERVER_MAX_CONNECTIONS=5000
COMPACTION_THREADS=1
Balanced Production
MEMTABLE_MAX_SIZE=4194304 # 4MB
BLOCK_SIZE=4096
BLOCK_CACHE_SIZE_MB=128
BLOOM_FALSE_POSITIVE_RATE=0.01
WAL_SYNC_MODE=always
COMPACTION_THREADS=2
SERVER_WORKERS=4
SERVER_MAX_CONNECTIONS=10000
Troubleshooting
High Memory Usage
- Reduce
MEMTABLE_MAX_SIZE - Reduce
BLOCK_CACHE_SIZE_MB - Increase
BLOOM_FALSE_POSITIVE_RATE - Increase
SPARSE_INDEX_INTERVAL - Reduce
SERVER_MAX_CONNECTIONS
Slow Writes
- Increase
MEMTABLE_MAX_SIZE - Change
WAL_SYNC_MODEtoevery_second - Increase
WAL_BUFFER_SIZE - Increase
COMPACTION_THREADS - Use
COMPACTION_STRATEGY=tiered
Slow Reads
- Increase
BLOCK_CACHE_SIZE_MB - Decrease
BLOOM_FALSE_POSITIVE_RATE - Decrease
SPARSE_INDEX_INTERVAL - Use
COMPACTION_STRATEGY=leveled - Decrease
SIZE_RATIO
Payload Too Large Errors
- Increase
MAX_JSON_PAYLOAD_SIZE - Increase
MAX_RAW_PAYLOAD_SIZE - Consider implementing pagination
Too Many Open Files
- Increase system file descriptor limit:
ulimit -n 65536 - Reduce
MAX_LEVEL_COUNT - Decrease
LEVEL0_COMPACTION_THRESHOLD - Increase
SIZE_RATIO
Monitoring Configuration Impact
# Enable detailed logging
RUST_LOG=debug cargo run --features api --bin apexstore-server
# Watch server startup for configuration values
# The server prints all active config on startup
# Monitor metrics via /stats endpoint
curl http://localhost:8080/stats/all
Best Practices
- Start with defaults - They work well for most workloads
- Profile first - Understand your workload before tuning
- Change one at a time - Easier to understand impact
- Monitor metrics - Use
/stats/allendpoint - Test in dev - Before applying to production
- Document changes - Track what works and what doesn't
- Use profiles - Quick starting points for common patterns
Environment-Specific Configs
Development
RUST_LOG=debug
MAX_JSON_PAYLOAD_SIZE=104857600
WAL_SYNC_MODE=manual
Staging
RUST_LOG=info
MAX_JSON_PAYLOAD_SIZE=52428800
WAL_SYNC_MODE=every_second
Production
RUST_LOG=warn
MAX_JSON_PAYLOAD_SIZE=10485760
WAL_SYNC_MODE=always
SERVER_WORKERS=8
References
Encryption at rest
Encryption is opt-in and disabled by default. For the server, configure
ENCRYPTION_ENABLED=true and ENCRYPTION_KEY_PATH pointing to a readable file
containing a nonzero 32-byte AES key encoded as 64 hexadecimal characters. Keep
this file outside DATA_DIR. Missing/invalid keys and invalid boolean values
stop startup; there is no fallback key. The CLI uses --encrypt-key-file.
Programmatic configuration uses LsmConfig.storage.encryption_enabled and
encryption_key_path, validated by EngineOptions::try_from_config and
LsmEngine::new_from_config. Runtime keys are redacted in Debug and zeroized on
drop; they are not serialized into layout configuration.
Legacy zero-key databases require the explicit offline migrate-encryption
command documented in the migration guide. Do not delete
WALs or SSTables to work around a key/configuration error.
ApexStore CLI Guide
Overview
The ApexStore CLI provides an interactive REPL (Read-Eval-Print Loop) interface for managing your LSM-Tree key-value store. This guide covers all available commands and their usage.
Starting the CLI
cargo run --release
Or if you've built the binary:
./target/release/apexstore
Basic Commands
SET - Insert or Update Data
Inserts or updates a key-value pair.
Syntax:
SET <key> <value>
Examples:
lsm> SET user:alice Alice Silva
✓ SET 'user:alice' executado com sucesso
lsm> SET product:1 Laptop Dell XPS 15
✓ SET 'product:1' executado com sucesso
GET - Retrieve Data
Retrieves the value for a given key.
Syntax:
GET <key>
Examples:
lsm> GET user:alice
✓ 'user:alice' = 'Alice Silva'
lsm> GET nonexistent
⚠ Chave 'nonexistent' não encontrada
DELETE - Remove Data
Deletes a key by creating a tombstone marker.
Syntax:
DELETE <key>
Aliases: DEL
Examples:
lsm> DELETE user:alice
✓ DELETE 'user:alice' executado (tombstone criado)
lsm> DEL product:1
✓ DELETE 'product:1' executado (tombstone criado)
Search Commands
SEARCH - Advanced Search
Searches for records matching a query. Supports both substring and prefix modes.
Syntax:
SEARCH <query> [--prefix]
Substring Search (default):
lsm> SEARCH user
✓ 3 registro(s) encontrado(s):
user:alice = Alice Silva
user:bob = Bob Santos
user:charlie = Charlie Costa
Prefix Search (faster for hierarchical keys):
lsm> SEARCH user: --prefix
✓ 3 registro(s) encontrado(s):
user:alice = Alice Silva
user:bob = Bob Santos
user:charlie = Charlie Costa
Use Cases:
SEARCH user- Find all keys containing "user" (substring)SEARCH user: --prefix- Find all keys starting with "user:" (prefix)SEARCH :1- Find all keys containing ":1"SEARCH product: --prefix- Find all product keys
SCAN - Prefix Scan
Lists all records with a specific prefix (equivalent to SEARCH <prefix> --prefix).
Syntax:
SCAN <prefix>
Examples:
lsm> SCAN user:
✓ 3 registro(s) com prefixo 'user:':
user:alice = Alice Silva
user:bob = Bob Santos
user:charlie = Charlie Costa
lsm> SCAN config:
✓ 4 registro(s) com prefixo 'config:':
config:theme = dark
config:language = pt-BR
config:notifications = enabled
config:auto_save = true
Listing Commands
ALL - List All Records
Displays all records in the database in a formatted table.
Syntax:
ALL
Example:
lsm> ALL
Listando todos os registros...
┌─────────────────────────────────────────────────┐
│ Chave │ Valor │
├─────────────────────────────────────────────────┤
│ user:alice │ Alice Silva │
│ user:bob │ Bob Santos │
│ product:1 │ Laptop Dell XPS 15 │
└─────────────────────────────────────────────────┘
KEYS - List All Keys
Lists only the keys (without values).
Syntax:
KEYS
Example:
lsm> KEYS
Total de chaves: 5
1. user:alice
2. user:bob
3. user:charlie
4. product:1
5. config:theme
COUNT - Count Records
Counts the number of active records.
Syntax:
COUNT
Example:
lsm> COUNT
✓ Total de registros ativos: 5
Statistics Commands
STATS - Basic Statistics
Displays basic engine statistics.
Syntax:
STATS
Example:
lsm> STATS
LSM Stats:
MemTable: 3 records, ~2 KB
SSTables: 2 files
Cache: 12/256 blocks
STATS ALL - Detailed Statistics
Displays comprehensive statistics in JSON format including memory, disk, cache, and WAL metrics.
Syntax:
STATS ALL
Example:
lsm> STATS ALL
{
"mem_records": 3,
"mem_kb": 2,
"sst_files": 2,
"sst_records": 47,
"sst_kb": 156,
"wal_kb": 1,
"total_records": 50,
"memtable_max_size": 4
}
Fields Explained:
mem_records- Number of records in MemTablemem_kb- MemTable size in KBsst_files- Number of SSTable files on disksst_records- Total records across all SSTablessst_kb- Total SSTable disk usage in KBwal_kb- Write-Ahead Log size in KBtotal_records- Sum of MemTable + SSTable recordsmemtable_max_size- Configured MemTable flush threshold in KB
Batch Operations
BATCH - Generate Test Data
Inserts N test records for benchmarking.
Syntax:
BATCH <count>
Example:
lsm> BATCH 1000
Inserindo 1000 registros...
✓ 1000 registros inseridos em 45.23ms
Taxa: 22104 ops/s
BATCH SET - Bulk Import from File
Imports records from a text file.
Syntax:
BATCH SET <file>
File Format:
# Lines starting with # are comments
key1=value1
key2=value2
user:alice=Alice Silva
product:1=Laptop
Example:
lsm> BATCH SET examples/batch_data.txt
Importando de examples/batch_data.txt...
✓ 23 registro(s) importado(s)
File Format Rules:
- Each line:
key=value - Lines starting with
#are ignored (comments) - Empty lines are skipped
- Keys and values are automatically trimmed
- No quotes needed around keys or values
Sample File (data.txt):
# User data
user:alice=Alice Silva
user:bob=Bob Santos
# Product data
product:1=Laptop Dell XPS 15
product:2=Mouse Logitech MX Master
# Configuration
config:theme=dark
config:language=pt-BR
Use Cases:
- Initial data seeding
- Migrating data from other systems
- Testing with realistic datasets
- Configuration management
Utility Commands
DEMO - Run Demonstration
Executes an automated demo showcasing engine features.
Syntax:
DEMO
What it does:
- Inserts sample users
- Reads and displays data
- Updates a record
- Deletes a record
- Forces MemTable flush
- Tests search commands
- Displays statistics
CLEAR - Clear Screen
Clears the terminal screen.
Syntax:
CLEAR
HELP - Show Help
Displays available commands.
Syntax:
HELP
Alias: ?
EXIT - Exit CLI
Exits the REPL.
Syntax:
EXIT
Aliases: QUIT, Q
Command Comparison: CLI vs REST API
All CLI commands have equivalent REST API endpoints:
| CLI Command | REST API Endpoint | Method |
|---|---|---|
SET key value | /keys | POST |
GET key | /keys/{key} | GET |
DELETE key | /keys/{key} | DELETE |
SEARCH query --prefix | /keys/search?q=query&prefix=true | GET |
STATS | /stats | GET |
STATS ALL | /stats/all | GET |
BATCH SET file | /keys/batch | POST |
KEYS | /keys | GET |
SCAN prefix | /scan?prefix=... | GET |
Best Practices
Naming Conventions
Use hierarchical keys with colons for organization:
user:123:profile
user:123:settings
product:456:name
product:456:price
session:abc:token
Efficient Searches
- Use
--prefixfor hierarchical keys (faster) - Without
--prefix: slower substring search - Prefix searches leverage BTree ordering
Performance Tips
- Use BATCH for bulk inserts (faster than individual SETs)
- Monitor with STATS ALL to track memory usage
- Use prefix-based keys for efficient SCAN operations
- Avoid very long keys (increases memory overhead)
Data Management
- Backup data files before major operations
- Use BATCH SET for reproducible setups
- Monitor MemTable size with STATS
- Plan key namespaces before loading data
Troubleshooting
Common Issues
Q: "Comando desconhecido" error
- A: Check spelling, commands are case-insensitive
- Use
HELPto see available commands
Q: BATCH SET fails to read file
- A: Check file path (relative to CLI working directory)
- Verify file permissions
- Ensure file format is correct (key=value)
Q: MemTable keeps flushing
- A: Normal behavior when reaching size limit
- Check
memtable_max_sizeconfiguration - Use
STATSto monitor
Q: Slow search performance
- A: Use
--prefixflag for hierarchical keys - Consider adding indexes in future versions
Examples
Complete Workflow Example
# Start CLI
cargo run --release
# Import initial data
lsm> BATCH SET data/users.txt
✓ 100 registro(s) importado(s)
# Verify import
lsm> COUNT
✓ Total de registros ativos: 100
# Search for specific users
lsm> SEARCH admin --prefix
✓ 5 registro(s) encontrado(s):
admin:root = Root User
admin:alice = Alice Admin
...
# Check statistics
lsm> STATS ALL
{
"mem_records": 100,
"sst_files": 0,
...
}
# Update a record
lsm> SET admin:root Super Admin
✓ SET 'admin:root' executado com sucesso
# Delete old records
lsm> DELETE user:temp
✓ DELETE 'user:temp' executado
# Final stats
lsm> STATS
LSM Stats:
MemTable: 99 records, ~15 KB
SSTables: 0 files
# Exit
lsm> exit
👋 Encerrando LSM-Tree CLI...
Related Documentation
- Configuration Guide - Engine configuration options
- REST API examples - REST API endpoints (a full reference is tracked in issue #400)
- Contributing Guide - Development guidelines
- README - Project overview
Need help? Open an issue on GitHub
🔐 Authentication Guide
ApexStore API supports Bearer Token authentication to protect endpoints from unauthorized access.
Overview
- Type: Bearer Token
- Algorithm: SHA-256 hashing
- Storage: Private, durable snapshot at
<DATA_DIR>/.apex-auth/tokens.json; only token hashes and metadata are stored - Permissions: Read, Write, Delete, Admin
Quick Start
1. Enable Authentication
Set in .env:
API_AUTH_ENABLED=true
API_TOKEN_EXPIRY_DAYS=30
2. Create an Administrator Offline
Stop the server before using the CLI against its database directory. Create the first administrator locally and save the printed token securely:
apexstore-cli --db ./apexstore_data token create local-admin --permissions admin
Use the same directory as the server's DATA_DIR. The CLI and server share the private credential store; a database lock prevents simultaneous offline administration and server access.
3. Start the Server
DATA_DIR=./apexstore_data cargo run --features api --bin apexstore-server
4. Create an Application Token
Request:
curl -X POST http://localhost:8080/admin/tokens \
-H "Authorization: Bearer $ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "production-api",
"permissions": ["Read", "Write"],
"expires_in_days": 30
}'
Response:
{
"success": true,
"message": "Token created successfully",
"data": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "production-api",
"token": "apx_a1b2c3d4e5f6...",
"expires_at": 1709740800000000000,
"permissions": ["Read", "Write"]
}
}
⚠️ Important: Save the token immediately! It will not be shown again.
5. Use the Token
Include the token in the Authorization header:
curl -X POST http://localhost:8080/keys \
-H "Authorization: Bearer apx_a1b2c3d4e5f6..." \
-H "Content-Type: application/json" \
-d '{"key": "user:1", "value": "Alice"}'
Credential Storage and Upgrades
Credentials are isolated from the public LSM keyspace. Each update writes and syncs a temporary snapshot, atomically replaces the credential file, then syncs its directory on Unix. The directory is mode 0700 and the snapshot mode 0600 on Unix. Token hashes and metadata are protected by filesystem permissions; this file is not encrypted by SSTable/WAL encryption. Include .apex-auth when backing up or relocating the complete data directory, and restrict access to that backup. An LSM-only snapshot does not include credentials.
Loading malformed, unsupported or inaccessible credential storage fails server startup. It never falls back to an empty credential set. Concurrent owners of the credential store are rejected. TokenManager::new_with_engine now returns Result<TokenManager, AuthError>; library callers must handle the error.
Versions that stored credentials as __token:* records allowed public data writes to impersonate administrators. Those legacy records cannot be distinguished from forged credentials and are never imported automatically. Before upgrading an existing deployment:
- Stop the server and retain a backup for investigation/recovery.
- Use the upgraded offline CLI against the same database directory to create a replacement administrator, as shown above.
- Restart with authentication enabled, create replacement application tokens and update clients. Old public-keyspace tokens no longer authenticate.
Do not copy legacy token JSON into the private file. Public key-value routes reject keys beginning with __ (including __token:, __ttl:, __index: and __idx:), and public scans/searches hide legacy metadata. Batch and transaction key operations enforce the same boundary. Prefix deletion also rejects _, because that range includes reserved keys. GraphQL returns no reserved-key value and refuses reserved-key mutations.
Permission Levels
| Permission | Description | Grants Access To |
|---|---|---|
Read | Read-only access | GET endpoints |
Write | Write access; grant Read separately when needed | PUT, POST and mutation endpoints |
Delete | Delete access; grant Read separately when needed | DELETE endpoints |
Admin | Full access | All endpoints including /admin/* |
API Endpoints
Token Management
Create Token
POST /admin/tokens
Content-Type: application/json
{
"name": "my-token",
"permissions": ["Read", "Write"],
"expires_in_days": 30 # Optional
}
List All Tokens
GET /admin/tokens
Authorization: Bearer <admin-token>
Response:
{
"success": true,
"message": "2 tokens found",
"data": {
"tokens": [
{
"id": "...",
"name": "production-api",
"created_at": 1709740800000000000,
"expires_at": 1712419200000000000,
"permissions": ["Read", "Write"]
}
]
}
}
Delete Token
DELETE /admin/tokens/{id}
Authorization: Bearer <admin-token>
Public Endpoints
These endpoints do NOT require authentication:
GET /health/liveness— other health endpoints require authentication
Protected Endpoints
All other endpoints require valid Bearer token when authentication is enabled:
GET /stats- Requires: ReadGET /stats/all- Requires: ReadGET /keys- Requires: ReadGET /keys/{key}- Requires: ReadGET /keys/search- Requires: ReadGET /scan- Requires: ReadPOST /keys- Requires: WritePOST /keys/batch- Requires: WriteDELETE /keys/{key}- Requires: DeleteGET /features- Requires: AdminPOST /features/{name}- Requires: AdminPOST /admin/tokens- Requires: AdminGET /admin/tokens- Requires: AdminDELETE /admin/tokens/{id}- Requires: Admin
Error Responses
401 Unauthorized
{
"error": "Missing authorization header",
"status": 401
}
401 Unauthorized - Invalid Token
{
"error": "Invalid authentication token",
"status": 401
}
401 Unauthorized - Expired Token
{
"error": "Token has expired",
"status": 401
}
403 Forbidden
{
"error": "Insufficient permissions",
"status": 403
}
Security Best Practices
1. Token Storage
- ✅ Store tokens in environment variables
- ✅ Use secrets management (e.g., AWS Secrets Manager, HashiCorp Vault)
- ❌ Never commit tokens to version control
- ❌ Never log tokens in plain text
2. Token Generation
- Tokens are 32-byte cryptographically secure random values
- Prefix:
apx_for easy identification - Stored as SHA-256 hash (one-way)
3. Token Comparison
- Uses constant-time comparison to prevent timing attacks
- Validates hash, not plain token
4. HTTPS/TLS
⚠️ Always use HTTPS in production!
# Set up reverse proxy with Nginx/Caddy
# Or use Railway/Fly.io for automatic HTTPS
5. Token Rotation
- Set reasonable expiry times (30-90 days)
- Delete unused tokens regularly
- Rotate tokens after suspected compromise
Migration Path
Phase 1: Optional Authentication (Current)
Authentication is disabled by default for backward compatibility.
API_AUTH_ENABLED=false # Default
Phase 2: Enable in Production
Enable authentication for your deployment:
API_AUTH_ENABLED=true
Phase 3: Future (v2.0)
Authentication will be enabled by default in v2.0.
Examples
Node.js/JavaScript
const axios = require('axios');
const client = axios.create({
baseURL: 'http://localhost:8080',
headers: {
'Authorization': `Bearer ${process.env.APEXSTORE_TOKEN}`
}
});
// Use the client
await client.post('/keys', {
key: 'user:1',
value: 'Alice'
});
Python
import requests
import os
token = os.getenv('APEXSTORE_TOKEN')
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
response = requests.post(
'http://localhost:8080/keys',
json={'key': 'user:1', 'value': 'Alice'},
headers=headers
)
cURL
# Store token in variable
TOKEN="apx_a1b2c3d4e5f6..."
# Make requests
curl -X GET "http://localhost:8080/keys/user:1" \
-H "Authorization: Bearer $TOKEN"
Troubleshooting
"Missing authorization header"
- Ensure you're including the
Authorizationheader - Format:
Authorization: Bearer <token>
"Invalid authentication token"
- Check token is correct (copy-paste errors)
- Verify token wasn't deleted
- Confirm server restart (tokens are in-memory)
"Token has expired"
- Token exceeded expiry time
- Create a new token
"Insufficient permissions"
- Token doesn't have required permission
- Create token with correct permissions
Future Enhancements
- Persistent token storage (database)
- JWT support
- OAuth2 integration
- Rate limiting per token
- Audit logging
- Token scopes (granular permissions)
Security Contact: For security issues, please email security@apexstore.io (or create a private issue)
Transaction ownership
POST /txn returns a random UUID v4 string in txn_id. Send that string in
/txn/{txn_id}/put, /delete, /commit and /rollback. Each transaction belongs
to the authenticated token that created it; another token, including another
administrator, receives the same HTTP 404 response as an unknown transaction.
Normal Write/Delete permission checks still apply, and revoked or expired tokens
cannot continue using their transactions.
Transactions have an absolute five-minute lifetime. Requests do not renew it. The server allows 32 open transactions per token and 1024 in total; further begin requests receive HTTP 429 until a transaction finishes or expires. Every transaction operation removes expired entries, dropping staged writes without committing them. No timer is needed to admit new work: begin also prunes expired entries before checking capacity. Idle expired entries may remain allocated until the next transaction request, within the same capacity bound.
When authentication is explicitly disabled, all requests share an anonymous owner
and its quota. This mode provides no isolation between clients. Embedding applications
can pass TransactionManager::with_limits(lifetime, per_owner, total) as Actix app
data to choose tighter limits. Setting any limit or the lifetime to zero rejects
new transactions.
Clients upgrading from numeric transaction IDs must read the JSON string instead; active transactions are process-local and do not survive server restarts.
Performance Documentation
This document contains performance benchmarks for the ApexStore LSM-tree storage engine.
Latest CI results
The block below is rewritten by the nightly Benchmarks workflow. Do not edit it
by hand -- edits are overwritten. The workflow commits only when the numbers
actually change, and fails rather than publishing an empty table.
Auto-updated by CI on 2026-11-04 19:07 UTC — view run Runner:
Linux(GitHub-hosted). Commit:c296bafb929007538cadca01733dcc55bef590cf.
📝 Write
| Benchmark | Median | Perf |
|---|---|---|
write_single/10 | 54.988 µs | 🟡 |
write_single/1024 | 78.811 µs | 🟡 |
write_batch_1000/1000 | 60.063 ms | 🟠 |
write_batch_10000/10000 | 566.64 ms | 🔴 |
memtable_flush_8/8 | 77.598 ms | 🟠 |
sstable_flush/10000 | 16.061 ms | 🟠 |
write_size_10_100/10x100 | 55.937 µs | 🟡 |
write_size_100_10000/100x10000 | 111.04 µs | 🟡 |
key_updates/10k_keys | 574.88 ms | 🔴 |
delete_operations/10k_keys | 565.75 ms | 🔴 |
📚 Read
| Benchmark | Median | Perf |
|---|---|---|
read_memtable/1000 | 248.38 µs | 🟡 |
read_memtable/10000 | 252.68 µs | 🟡 |
read_sstable_cold/1000 | 477.10 µs | 🟡 |
read_sstable_cold/10000 | 494.09 µs | 🟡 |
read_sstable_warm/1000 | 472.70 µs | 🟡 |
read_sstable_warm/10000 | 593.73 µs | 🟡 |
read_latency/memtable_1k | 228.93 µs | 🟡 |
read_latency/sstable_cold_1k | 475.33 µs | 🟡 |
read_memtable_latency/memtable_1k | 229.23 µs | 🟡 |
read_sstable_warm_latency/sstable_warm_1k | 477.71 µs | 🟡 |
read_latency_memtable_1k/memtable_1k | 251.54 µs | 🟡 |
read_latency_memtable_100k/memtable_100k | 40.737 ms | 🟠 |
read_latency_sstable_1k/sstable_warm_1k | 427.83 µs | 🟡 |
read_latency_sstable_100k/sstable_warm_100k | 183.27 ms | 🔴 |
🔍 Scan
| Benchmark | Median | Perf |
|---|---|---|
scan_sequential/1000 | 552.06 µs | 🟡 |
scan_sequential/10000 | 7.0201 ms | 🟠 |
full_scan/1000 | 497.46 µs | 🟡 |
full_scan/10000 | 6.4072 ms | 🟠 |
range_scan_100/100 | 4.7535 ms | 🟠 |
prefix_scan_100/100 | 4.9135 ms | 🟠 |
prefix_scan_1000/1000 | 4.8718 ms | 🟠 |
iteration_sorted/1000 | 529.71 µs | 🟡 |
iteration_sorted/10000 | 6.3805 ms | 🟠 |
scan_limit_10/10 | 4.0680 ms | 🟠 |
scan_limit_100/100 | 4.0798 ms | 🟠 |
scan_pagination/10 | 41.270 ms | 🟠 |
scan_pagination/100 | 471.33 ms | 🔴 |
🌐 YCSB
| Benchmark | Median | Perf |
|---|---|---|
ycsb_type_a/10000 | 29.266 ms | 🟠 |
ycsb_type_b/10000 | 4.0192 ms | 🟠 |
ycsb_type_c/10000 | 747.09 µs | 🟡 |
ycsb_type_c/100000 | 2.1759 ms | 🟠 |
⚡ Mixed Workload
| Benchmark | Median | Perf |
|---|---|---|
workload_balanced/10000 | 29.922 ms | 🟠 |
workload_read_heavy/10000 | 6.8636 ms | 🟠 |
workload_write_heavy/10000 | 52.849 ms | 🟠 |
🏗️ SSTable
| Benchmark | Median | Perf |
|---|---|---|
sstable_layer_1/1 | 5.9463 ms | 🟠 |
many_sstables_10/10 | 547.72 µs | 🟡 |
🧵 Bloom Filter
| Benchmark | Median | Perf |
|---|---|---|
bloom_filter/10000 | 9.4871 ms | 🟠 |
💾 Cache
| Benchmark | Median | Perf |
|---|---|---|
cache_thrash_64MB/64 | 94.968 µs | 🟡 |
🧵 Concurrency
| Benchmark | Median | Perf |
|---|---|---|
concurrent_1_threads/1 | 3.4724 ms | 🟠 |
💡 Memory
| Benchmark | Median | Perf |
|---|---|---|
memory_pressure/small_memtable | 264.05 µs | 🟡 |
⚙️ Other
| Benchmark | Median | Perf |
|---|---|---|
read_negative_bloom/negative_bloom_10k | 928.85 µs | 🟡 |
scan_1000_keys/scan_1k | 543.82 µs | 🟡 |
write_latency_1k/write_1k | 91.730 ms | 🟠 |
write_latency_100k/write_100k | 10.860 s | 🔴 |
write_amplification_leveled/leveled_10k_keys | 766.90 ms | 🔴 |
write_amplification_size_tiered/size_tiered_10k_keys | 796.34 ms | 🔴 |
Run them locally with make bench, or cargo bench --all-features for HTML
reports under target/criterion/.
Benchmarks Overview
The benchmark suite is located in benches/ and covers the following categories:
Write Benchmarks (benches/write_bench.rs)
- Single Write: Latency for individual write operations with varying key/value sizes (10B to 100KB)
- Batch Write: Throughput for batch insertions (1K, 10K, 100K operations)
- Memtable Flush: Performance impact of flush operations (8MB, 16MB, 32MB)
- SSTable Flush: Write throughput during SSTable creation
Read Benchmarks (benches/read_bench.rs)
- MemTable Reads: Read latency when keys are in-memory (expected: ~1M ops/sec)
- SSTable Reads (Cold): Read latency from disk with no cache
- SSTable Reads (Warm): Read latency with cached data
- Bloom Filter: False positive rate and lookup speed
- Sequential Scan: Full scan throughput
Mixed Workloads (benches/mixed_bench.rs)
- YCSB Type A: 50% read, 50% write (uniform)
- YCSB Type B: 95% read, 5% write (read-heavy)
- YCSB Type C: 100% read (read-only)
- Balanced: 50/50 read/write
- Read-Heavy: 90% read, 10% write
- Write-Heavy: 10% read, 90% write
Scan Benchmarks (benches/scan_bench.rs)
- Full Scan: Complete dataset iteration
- Range Scan: Indexed range queries (100 to 100K keys)
- Prefix Scan: Hierarchical key queries
- Pagination: Cursor-based pagination performance
- SSTable Layers: Performance with increasing SSTable counts (1 to 30 layers)
Stress Benchmarks (benches/stress_bench.rs)
- Large Dataset: 1M keys with concurrent access
- Concurrent Access: 1, 2, 4 threads reading/writing
- Memory Pressure: Small memtable (2MB) forcing frequent flushes
- Many SSTables: 10, 50, 100 SSTables
- Cache Thrashing: Different cache sizes (16, 64, 128MB)
- Key Updates: Update operations on existing keys
- Delete Operations: Tombstone creation and cleanup
Expected Performance Targets
Write Performance
| Operation | Expected Throughput |
|---|---|
| MemTable Only | 500K-1M ops/sec |
| With WAL (async) | 100K-200K ops/sec |
| With WAL (fsync) | 5K-10K ops/sec |
| Batch (1K ops) | 500K-1M ops/sec |
Read Performance
| Operation | Expected Throughput |
|---|---|
| MemTable Hits | 800K-1M ops/sec |
| SSTable (warm cache) | 50K-100K ops/sec |
| SSTable (cold cache) | 5K-10K ops/sec |
Scan Performance
| Operation | Expected Throughput |
|---|---|
| Full Scan | 10M-20M keys/sec |
| Range Scan | 5M-10M keys/sec |
Configuration Parameters
The benchmark suite allows tuning the following parameters:
#![allow(unused)] fn main() { pub struct BenchmarkConfig { pub key_size: usize, // Key size in bytes pub value_size: usize, // Value size in bytes pub num_keys: usize, // Number of keys in dataset pub memtable_max_size: usize, // MemTable size before flush pub block_cache_size_mb: usize, // Block cache size in MB pub bloom_false_positive_rate: f64, // Bloom filter FP rate pub sparse_index_interval: usize, // Sparse index interval } }
Running Benchmarks
Local Execution
# Run all benchmarks
cargo bench --all-features
# Run specific benchmark category
cargo bench --bench write_bench
cargo bench --bench read_bench
cargo bench --bench mixed_bench
cargo bench --bench scan_bench
cargo bench --bench stress_bench
# Generate HTML reports
cargo bench --all-features -- --output-format html
CI Execution
Run with the cargo-hack tool for comprehensive testing:
cargo hack bench --feature-powerset
Measuring Results
Latency Metrics
- p50 (Median): 50% of operations complete within this time
- p99: 99% of operations complete within this time
- p999: 99.9% of operations complete within this time
Throughput Metrics
- Operations per second: Total operations / total time
- Bytes per second: Total bytes processed / total time
- Keys per second: Keys scanned / total time (for scans)
Analysis Guidelines
- Baseline Establishment: Run benchmarks on clean repository before making changes
- Regression Detection: Alert on performance degradation > 10%
- Optimization Validation: Compare before/after for proposed improvements
- Configuration Tuning: Test different
LsmConfigvalues for optimal performance
Results Interpretation
Good Performance Indicators
- Low latency variance (consistent p99 close to p50)
- High cache hit rates (> 80% for warm reads)
- Efficient Bloom filter rejection (> 99% for non-existent keys)
- Linear scaling with cache size
Warning Signs
- High false positive rates (> 5% for Bloom filter)
- Cache thrashing (throughput drops with more data)
- Degradation with more SSTables (exponential growth in lookup time)
- Memory pressure causing excessive GC/flush overhead
Future Benchmark Additions
- Compression Ratios: Measure LZ4 compression efficiency
- Compaction Performance: Size-tiered vs leveled compaction
- Replication Overhead: Network and sync costs
- Long-term Decay: Performance after extended operation
Configuration Impact on Performance
Memory Configuration
memtable_max_size
| Size | Write Throughput (async) | Write Throughput (fsync) | Best For |
|---|---|---|---|
| 2 MB | 180K ops/s | 12K ops/s | Low memory, high durability |
| 8 MB | 420K ops/s | 8.5K ops/s | Balanced workloads |
| 16 MB | 650K ops/s | 7.5K ops/s | Default / Production |
| 32 MB | 580K ops/s | 6.2K ops/s | Very high write throughput |
| 64 MB | 480K ops/s | 5.1K ops/s | Memory-rich environments |
Trade-off: Larger memtables improve write throughput but increase recovery time on crash.
block_cache_size_mb
| Cache Size | Warm Read Latency | Cold Read Throughput | Memory Usage |
|---|---|---|---|
| 16 MB | 45.2 µs | 18K ops/sec | 16 MB |
| 64 MB | 22.1 µs | 35K ops/sec | 64 MB |
| 128 MB | 15.8 µs | 52K ops/sec | 128 MB |
| 256 MB | 12.3 µs | 68K ops/sec | 256 MB |
| 512 MB | 10.8 µs | 75K ops/sec | 512 MB |
Recommendation: Set cache to 2-4x working dataset size for optimal performance.
bloom_false_positive_rate
| Rate | Memory Overhead | Lookup Efficiency | Best Use Case |
|---|---|---|---|
| 0.001 (0.1%) | 22 bits/entry | 99.2% rejection | Memory-constrained |
| 0.01 (1%) | 11 bits/entry | 98.7% rejection | Default |
| 0.1 (10%) | 7 bits/entry | 95.3% rejection | Extreme memory limits |
Disk I/O Configuration
sparse_index_interval
| Interval | Index Size | Lookup Speed | Best For |
|---|---|---|---|
| 8 | Large | Fastest | Read-heavy workloads |
| 16 | Medium | Balanced | Default |
| 32 | Small | Slower | Write-heavy workloads |
| 64 | Very Small | Slowest | High-throughput writes |
Workload-Specific Recommendations
Write-Heavy (ingestion pipelines)
#![allow(unused)] fn main() { LsmConfig { core: CoreConfig { memtable_max_size: 32 * 1024 * 1024, // 32MB }, storage: StorageConfig { block_cache_size_mb: 128, // Smaller cache bloom_false_positive_rate: 0.1, // Reduce memory sparse_index_interval: 32, // Smaller index }, } }
Read-Heavy (serving applications)
#![allow(unused)] fn main() { LsmConfig { core: CoreConfig { memtable_max_size: 16 * 1024 * 1024, // 16MB }, storage: StorageConfig { block_cache_size_mb: 512, // Large cache bloom_false_positive_rate: 0.001, // Tighter Bloom filter sparse_index_interval: 8, // denser index }, } }
Balanced (general purpose)
#![allow(unused)] fn main() { LsmConfig { core: CoreConfig { memtable_max_size: 16 * 1024 * 1024, // 16MB }, storage: StorageConfig { block_cache_size_mb: 256, // 256MB bloom_false_positive_rate: 0.01, // Balanced sparse_index_interval: 16, // Balanced }, } }
Tuning Methodology
- Establish Baseline: Run benchmarks on current configuration
- Identify Bottleneck: Check CPU, memory, I/O utilization during peak load
- Change One Variable: Adjust a single config parameter
- Run Full Benchmark Suite: All categories to check for regressions
- Validate Over Time: Run for at least 30 minutes to catch gradual degradation
- Document Trade-offs: Note any performance gains vs other metrics
Performance Optimization Checklist
-
Enable LTO:
[profile.release] opt-level = 3, lto = true -
Use
WAL_SYNC_MODE=asyncfor write-heavy workloads - Cache size >= 2x working dataset size
- Adjust memtable size to balance memory vs recovery time
- Monitor Bloom filter false positive rate (should be < 2%)
- Verify sparse index doesn't bloat SSTable files
-
Profile with
perforflamegraphfor hot paths - Run benchmarks on production-like hardware
Contributing Performance Improvements
When proposing performance optimizations:
- Add benchmarks demonstrating the improvement
- Include before/after comparison
- Verify no regressions in other metrics
- Document the optimization and its trade-offs
Contributing to ApexStore
First off, thank you for considering contributing to ApexStore! 🎉
This document provides guidelines and instructions for contributing to the project. Following these guidelines helps maintain code quality and makes the review process smoother.
📜 Table of Contents
- Code of Conduct
- Getting Started
- Development Workflow
- Coding Standards
- Testing Guidelines
- Commit Messages
- Pull Request Process
- Project Structure
- Areas for Contribution
🤝 Code of Conduct
Our Pledge
We are committed to providing a welcoming and inspiring community for all. We pledge to:
- Be respectful and inclusive
- Accept constructive criticism gracefully
- Focus on what is best for the community
- Show empathy towards other community members
Expected Behavior
- Use welcoming and inclusive language
- Be respectful of differing viewpoints and experiences
- Gracefully accept constructive criticism
- Focus on what is best for the community
Unacceptable Behavior
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information without explicit permission
- Other conduct which could reasonably be considered inappropriate
🚀 Getting Started
Prerequisites
-
Rust Toolchain (1.96 or later;
rust-toolchain.tomlselects 1.99.1)curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -
Git
# Ubuntu/Debian sudo apt-get install git # macOS brew install git -
Code Editor (Recommended: VS Code with rust-analyzer)
- Install VS Code
- Install rust-analyzer extension
Initial Setup
-
Fork the Repository
- Visit https://github.com/ElioNeto/ApexStore
- Click the "Fork" button in the top-right corner
-
Clone Your Fork
git clone https://github.com/YOUR_USERNAME/ApexStore.git cd ApexStore -
Add Upstream Remote
git remote add upstream https://github.com/ElioNeto/ApexStore.git -
Install Dependencies
cargo build -
Run Tests
cargo test
For detailed setup instructions, see SETUP.md.
🔄 Development Workflow
Automated Workflow Overview
ApexStore uses GitHub Actions to automate the development workflow:
- Feature/Fix branches → Auto-create PR to
develop+ run tests - Develop → Auto-create release PR to
main - Main → Create release tag + close related issues
See WORKFLOWS.md for complete documentation.
1. Create a Feature Branch
# Update your fork
git checkout main
git pull upstream main
# Create a new branch from main
git checkout -b feature/your-feature-name
Branch Naming Conventions:
feature/- New features (e.g.,feature/compaction-strategy)fix/- Bug fixes (e.g.,fix/wal-corruption)docs/- Documentation changes (e.g.,docs/api-guide)refactor/- Code refactoring (e.g.,refactor/codec-interface)test/- Test additions/improvements (e.g.,test/integration-suite)perf/- Performance improvements (e.g.,perf/bloom-filter-optimization)
2. Make Your Changes
# Make changes to the code
vim src/core/engine.rs
# Test your changes
cargo test --all-features
# Format code
cargo fmt
# Check for issues
cargo clippy --all-features -- -D warnings
3. Commit Your Changes
git add .
git commit -m "feat: add compaction strategy interface (#55)"
Important: Reference issues in commit messages using #issue_number for automatic tracking.
See Commit Messages for formatting guidelines.
4. Push to Your Fork
git push origin feature/your-feature-name
What Happens Next:
- ✅ GitHub Actions automatically runs tests
- ✅ Auto-creates PR to
developbranch - ✅ Adds comment to referenced issues (if any)
- ✅ Runs Clippy and format checks
5. Pull Request Review
Once the automated PR is created:
- Review the PR description
- Wait for CI checks to pass
- Address any reviewer feedback
- PR will be merged to
developonce approved
Note: You don't need to manually create PRs - the workflow handles this automatically!
📝 Coding Standards
Rust Style Guide
We follow the Rust API Guidelines and Rust Style Guide.
Key Principles:
-
Use
cargo fmt- All code must be formattedcargo fmt --all -
Pass
cargo clippy- Zero warnings policycargo clippy --all-features -- -D warnings -
Write Documentation - Public APIs must have doc comments
#![allow(unused)] fn main() { /// Retrieves a value from the store by key. /// /// # Arguments /// /// * `key` - The key to look up /// /// # Returns /// /// * `Ok(Some(value))` - Key found /// * `Ok(None)` - Key not found /// * `Err(e)` - Error occurred /// /// # Example /// /// ``` /// let value = engine.get(b"user:123")?; /// ``` pub fn get(&self, key: &[u8]) -> Result<Option<String>> { // Implementation } }
SOLID Principles
This project follows SOLID principles:
- Single Responsibility: Each module/struct has one clear purpose
- Open/Closed: Extend behavior through traits, not modification
- Liskov Substitution: Implementations must be interchangeable
- Interface Segregation: Small, focused traits
- Dependency Inversion: Depend on abstractions, not concretions
Example:
#![allow(unused)] fn main() { // ✅ Good - depends on trait pub struct LsmEngine<W: WriteAheadLog> { wal: W, } // ❌ Bad - depends on concrete type pub struct LsmEngine { wal: FileBasedWal, } }
Error Handling
-
Use
Result<T, LsmError>for fallible operations#![allow(unused)] fn main() { pub fn put(&mut self, key: &[u8], value: &str) -> Result<()> { self.wal.append(key, value)?; self.memtable.insert(key, value); Ok(()) } } -
Provide Context with error types
#![allow(unused)] fn main() { use thiserror::Error; #[derive(Error, Debug)] pub enum LsmError { #[error("WAL corruption at offset {0}")] WalCorruption(u64), #[error("Key too large: {size} bytes (max: {max})")] KeyTooLarge { size: usize, max: usize }, } } -
Don't Panic in library code (use
Resultinstead)
Performance Considerations
-
Minimize Allocations
#![allow(unused)] fn main() { // ✅ Good - reuse buffer let mut buffer = Vec::with_capacity(1024); for item in items { buffer.clear(); serialize_into(&mut buffer, item)?; } // ❌ Bad - allocate each iteration for item in items { let buffer = serialize(item)?; } } -
Use Appropriate Data Structures
BTreeMapfor sorted dataHashMapfor fast lookupsVecfor sequential access
-
Benchmark Changes
cargo bench
🧪 Testing Guidelines
Test Types
-
Unit Tests - Test individual functions/modules
#![allow(unused)] fn main() { #[cfg(test)] mod tests { use super::*; #[test] fn test_memtable_insert() { let mut memtable = MemTable::new(); memtable.insert(b"key", "value"); assert_eq!(memtable.get(b"key"), Some("value".to_string())); } } } -
Integration Tests - Test component interactions
#![allow(unused)] fn main() { // tests/integration_test.rs #[test] fn test_engine_recovery() { let config = LsmConfig::default(); let mut engine = LsmEngine::new(config).unwrap(); engine.put(b"key", "value").unwrap(); drop(engine); let engine = LsmEngine::new(config).unwrap(); assert_eq!(engine.get(b"key").unwrap(), Some("value".to_string())); } } -
Property Tests - Test invariants (optional, using
proptest)
Test Requirements
- All new code must have tests
- Tests must pass on all platforms
- Test coverage should increase, not decrease
- Use descriptive test names
#![allow(unused)] fn main() { #[test] fn test_get_returns_none_for_nonexistent_key() { /* ... */ } }
Running Tests
# Run all tests
cargo test --all-features
# Run specific test
cargo test test_memtable_insert
# Run with output
cargo test -- --nocapture
# Run integration tests only
cargo test --test '*'
# Run with coverage (requires tarpaulin)
cargo tarpaulin --out Html
📝 Commit Messages
We follow the Conventional Commits specification.
Format
<type>(<scope>): <subject> (#issue)
<body>
<footer>
Types
feat- New featurefix- Bug fixdocs- Documentation changesstyle- Code style changes (formatting, etc.)refactor- Code refactoringperf- Performance improvementstest- Test additions/modificationschore- Build process, dependencies, toolingci- CI/CD changes
Examples
Simple commit:
feat: add bloom filter to SSTable reader
With scope and issue:
fix(wal): prevent corruption on unclean shutdown (#42)
With body:
feat(compaction): implement leveled compaction strategy (#47)
Adds a new LeveledCompaction struct that implements the Compaction
trait. This strategy reduces read amplification by maintaining
sorted levels with exponentially increasing sizes.
Closes #47
Breaking change:
feat(api)!: change SSTable format to V2
BREAKING CHANGE: SSTable V2 is incompatible with V1.
Migration tool will be provided in v1.4.
Referencing Issues:
#123- Reference issuefixes #123,closes #123- Will auto-close issue when PR mergesresolves #123- Alternative close syntax
🔍 Pull Request Process
Before Pushing
- Code compiles without errors
-
All tests pass (
cargo test --all-features) -
No clippy warnings (
cargo clippy --all-features -- -D warnings) -
Code is formatted (
cargo fmt) - Documentation is updated (if applicable)
- Tests are added for new functionality
Automated PR Creation
When you push to a feature/* or fix/* branch:
- ✅ Tests run automatically (CI/CD)
- ✅ PR is auto-created to
developbranch - ✅ Issues are commented (if referenced in commits)
- ✅ Checks must pass before merge
Manual Steps (If Needed)
If you need to create a PR manually:
- Go to your fork on GitHub
- Click "New Pull Request"
- Select
developas the base branch - Fill out the PR template
- Submit the PR
PR Template
When creating a PR manually, use this template:
## Description
Brief description of changes.
## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
## Related Issues
Closes #123
Related to #456
## Testing
Describe how you tested your changes:
- [ ] Unit tests added
- [ ] Integration tests added
- [ ] Manual testing performed
## Checklist
- [ ] Code compiles
- [ ] Tests pass
- [ ] Clippy checks pass
- [ ] Code is formatted
- [ ] Documentation updated
## Screenshots (if applicable)
## Additional Notes
Review Process
- Automated Checks - CI runs tests and linters
- Code Review - Maintainer reviews code
- Feedback - Address review comments
- Approval - Maintainer approves PR
- Merge - Squash and merge to
develop
Review Timeline
- Simple PRs: 1-3 days
- Complex PRs: 3-7 days
- Breaking Changes: 7-14 days
📁 Project Structure
ApexStore/
├── src/
│ ├── core/ # Core domain logic
│ │ ├── engine.rs # LSM engine orchestration
│ │ ├── memtable.rs # In-memory storage
│ │ └── log_record.rs # Data model
│ ├── storage/ # Persistence layer
│ │ ├── wal.rs # Write-ahead log
│ │ ├── sstable.rs # SSTable reader
│ │ └── builder.rs # SSTable writer
│ ├── infra/ # Infrastructure
│ │ ├── codec.rs # Serialization
│ │ ├── error.rs # Error types
│ │ └── config.rs # Configuration
│ ├── api/ # HTTP API (feature-gated)
│ ├── cli/ # CLI interface
│ └── features/ # Feature flags
├── tests/ # Integration tests
├── benches/ # Benchmarks
└── docs/ # Documentation
Module Guidelines
core/- Domain logic, no external dependenciesstorage/- File I/O, persistenceinfra/- Cross-cutting concernsapi/- External interfaces (feature-gated)
🎯 Areas for Contribution
High Priority
-
CI/CD Testing Pipeline (#55)
- Difficulty: Easy
- Impact: High
- Skills: GitHub Actions, YAML
-
Compaction Implementation (#47)
- Difficulty: Hard
- Impact: High
- Skills: Rust, algorithms, file I/O
-
Efficient Iterators (#21, #22, #23)
- Difficulty: Medium
- Impact: High
- Skills: Rust, data structures
Medium Priority
-
Benchmarking Suite (#48)
- Difficulty: Easy
- Impact: Medium
- Skills: Rust, criterion
-
CLI Command Equalization (#65)
- Difficulty: Medium
- Impact: Medium
- Skills: Rust, CLI design
-
Checksums & Integrity (#25)
- Difficulty: Easy
- Impact: High
- Skills: Rust, CRC32
Good First Issues
-
Add More Tests
- Difficulty: Easy
- Impact: Medium
- Skills: Rust, testing
-
Binary Search Optimization (#37)
- Difficulty: Easy
- Impact: Medium
- Skills: Rust, algorithms
-
Documentation Improvements
- Difficulty: Easy
- Impact: Medium
- Skills: Technical writing
Advanced Topics
-
Replication Support
- Difficulty: Very Hard
- Impact: Very High
- Skills: Distributed systems, Raft
-
Snapshot Isolation
- Difficulty: Hard
- Impact: High
- Skills: Concurrency, MVCC
❓ Questions?
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: docs/
- Email: netoo.elio@hotmail.com
🚀 Ready to Contribute?
- Find an issue or create one
- Comment that you're working on it
- Fork the repo and create a branch from
main - Make your changes with tests
- Push to your fork (automated PR will be created)
- Wait for review and address feedback
Thank you for contributing! 🎉
Last updated: March 2026
🔄 GitHub Workflows Documentation
ApexStore uses automated GitHub Actions workflows to manage the development lifecycle, from features to releases.
📊 Overview
feature/fix branches → develop → release/vX.Y.Z → main
│ │ │ │
└── Auto PR └─ Auto PR └─ Issues* └─ Tag + Release
+ comments* created closed*
on issues*
* = Optional, only when issues are referenced
🛠️ Available Workflows
1. Feature/Fix Workflow
File: .github/workflows/feature-fix-workflow.yml
Trigger: Push to feature/** or fix/** branches
What it does:
-
Build & Test
- Compiles project:
cargo build --release --all-features - Runs tests:
cargo test --all-features - Checks linting:
cargo clippy --all-features -- -D warnings
- Compiles project:
-
Creates PR to develop
- Automatically detects if there are new commits
- Creates PR to
developwith:- List of referenced issues (if any)
- Commit summary
- Test status
- Doesn't duplicate existing PRs
-
Comments on Issues (optional)
- Only runs if issues are referenced
- Identifies issues mentioned in commits
- Adds stacked comments with updates:
- Recent commits
- Branch link
- Development status
How to use:
With issues:
git checkout -b feature/my-feature
git commit -m "feat: implement X (#123)"
git commit -m "fix: resolve Y (fixes #124)"
git push origin feature/my-feature
Without issues (also works!):
git checkout -b feature/refactoring
git commit -m "refactor: improve code structure"
git commit -m "chore: update dependencies"
git push origin feature/refactoring
# ✅ PR created normally, without issues section
2. Develop to Release Workflow
File: .github/workflows/develop-to-release.yml
Triggers:
- Push to
develop→ Creates/updates release PR - PR merged to
main→ Closes issues automatically (if any)
What it does:
On push to develop:
-
Determines version
- Analyzes commits since last tag
- Calculates bump (major/minor/patch):
BREAKING CHANGE:,feat!:,fix!:→ Majorfeat:→ Minor- Others → Patch
-
Creates release branch
release/vX.Y.Z- Syncs with
develop
-
Creates PR to main
- Title:
🚀 Release vX.Y.Z - Draft mode (requires approval)
- Contains:
- Configurable release type (alpha/beta/lts)
- List of resolved issues (if any)
- Complete changelog
- Validation checklist
- Title:
On release PR merge:
- Closes Issues Automatically (optional)
- Only runs if issues are referenced
- Extracts referenced issues from commits
- Adds final comment:
✅ Resolved in Release vX.Y.Z This issue has been fixed and released. Release: [View Release](link) - Closes issue with "completed" reason
- If no issues: workflow completes normally without errors
🏷️ Issue Reference (Optional)
When to Use Issues
✅ Use when:
- Fixing a reported bug
- Implementing a requested feature
- Want automatic traceability
- Want automatic notifications
⚪ Don't need to use when:
- Internal refactoring
- Dependency updates
- Performance improvements without issue
- Documentation
- Chores and minor tasks
Supported Syntax:
# Any of these forms are detected:
git commit -m "feat: add feature (#123)"
git commit -m "fix: resolve bug (fixes #124)"
git commit -m "refactor: improve code (closes #125)"
git commit -m "docs: update (resolved #126)"
Recognized Keywords:
close,closes,closedfix,fixes,fixedresolve,resolves,resolved- Simple:
#123
📋 Flow Examples
Example 1: With Issues
# Issue: #31 - Implement Bearer Token Authentication
git checkout -b feature/bearer-auth
git commit -m "feat: add auth module (#31)"
git commit -m "feat: add auth config (#31)"
git push origin feature/bearer-auth
# ✅ Workflow runs:
# - Build + Tests pass
# - PR created: feature/bearer-auth → develop
# - Comment added to #31
# - Issue listed in PR
Example 2: Without Issues
# General refactoring - no specific issue
git checkout -b refactor/improve-performance
git commit -m "refactor: optimize database queries"
git commit -m "perf: add caching layer"
git push origin refactor/improve-performance
# ✅ Workflow runs:
# - Build + Tests pass
# - PR created: refactor/improve-performance → develop
# - No issues section (normal!)
# - Changelog shows commits normally
Example 3: Release with Mix
# Merge to develop (some commits with issues, others without)
git checkout develop
git merge feature/bearer-auth # has issue #31
git merge refactor/performance # no issue
git push origin develop
# ✅ Workflow runs:
# - Calculates version: v2.1.0 → v2.2.0
# - Creates branch: release/v2.2.0
# - Creates PR: release/v2.2.0 → main
# - Lists only issue #31 (which was referenced)
# - Changelog shows ALL commits
# When merging release PR:
# ✅ Issue #31 closed automatically
# ✅ Commits without issue ignored (no error)
🔍 Workflow Behavior
Feature/Fix Workflow
| Situation | Behavior |
|---|---|
| Commits with issues | PR created + issues listed + comments on issues |
| Commits without issues | PR created + "No issues referenced" |
| Mix | PR created + only found issues listed |
| Non-existent issues | Ignores and continues (no error) |
| Already closed issues | Doesn't comment (silent skip) |
Develop to Release Workflow
| Situation | Behavior |
|---|---|
| Commits with issues | PR lists issues + on merge closes automatically |
| Commits without issues | PR without issues section + on merge completes normally |
| Mix | PR lists only found issues |
| Non-existent issues | Ignores and continues (log warning) |
| Already closed issues | Tries to close but ignores error |
⚙️ Logs and Debugging
Normal Messages (not errors)
ℹ️ No issues referenced in commits - skipping
Meaning: No issue was mentioned. Normal for commits without tracking.
⏭️ Skipping issue #123 (state: CLOSED)
Meaning: Issue was already closed. Workflow automatically skips.
⚠️ Issue #999 not found - skipping
Meaning: Issue doesn't exist. May be typo in commit, workflow continues.
📚 Best Practices
When to Reference Issues
✅ Recommended:
# Bug fixes
git commit -m "fix: resolve authentication bug (fixes #54)"
# Requested features
git commit -m "feat: add JWT support (#31)"
# Specific improvements
git commit -m "perf: optimize query (closes #67)"
When NOT to Reference
✅ Also acceptable:
# Internal refactoring
git commit -m "refactor: restructure auth module"
# Dependency updates
git commit -m "chore: update dependencies"
# Documentation
git commit -m "docs: add API examples"
# Small fixes
git commit -m "style: fix formatting"
⚠️ Troubleshooting
"Workflow didn't comment on issue"
Possible causes:
- ✅ Normal: Issue wasn't referenced in commit
- ✅ Normal: Issue was already closed
- ⚠️ Check: Is issue number correct?
- ⚠️ Check: Is reference syntax correct?
"Issue didn't close after release"
Possible causes:
- ✅ Normal: Issue wasn't referenced in any commit
- ✅ Normal: Issue was already closed
- ⚠️ Check: Was PR merged (not just closed)?
- ⚠️ Check: Did branch follow
release/*pattern?
"Workflow failed"
Checklist:
- Build passed locally?
- Tests passed?
- Clippy without errors?
- GitHub Actions permissions enabled?
🎯 Summary
TL;DR
- ✅ Issues are OPTIONAL - workflows work with or without
- ✅ Use issues for traceability - automatic closing is bonus
- ✅ Without issues is valid - for refactoring, chores, etc
- ✅ Mix is accepted - some commits with, others without issues
- ✅ Workflows are resilient - don't break due to lack of issues
Minimum Flow (without issues)
1. feature/x → develop
✅ Build + Test + PR created
2. develop → release/vX.Y.Z → main
✅ Version + Tag + Changelog
No issue needed!
Complete Flow (with issues)
1. feature/x (#123) → develop
✅ Build + Test + PR + Issue commented
2. develop → release/vX.Y.Z → main
✅ Version + Tag + Changelog + Issue #123 closed
Automatic traceability!
📚 References
Maintainers: @ElioNeto
Last updated: March 6, 2026
Codebase Audit — August 2026
Scope: apex-store-rs v2.2.7 at commit fc024b7 (branch main).
Method: static reading of all 37k lines of Rust under src/, plus a reproducible
build in the containerised toolchain added by this audit (Dockerfile.dev, Rust 1.92).
Every finding below is anchored to a file:line and, where the claim is behavioural,
to a command whose output is quoted.
Baseline established during the audit:
| Check | Result |
|---|---|
cargo test --all-features --workspace | 642 passed, 0 failed, 9 ignored |
cargo clippy --all-targets --all-features | 1 warning (src/notes/search.rs:76, now fixed) |
cargo audit (cargo-audit 0.22.2) | 2 vulnerabilities, 13 warnings |
cargo audit (cargo-audit 0.21.2) | aborts: unsupported CVSS version: 4.0 |
cargo run --release | fails: cannot choose between four binaries |
The test suite being fully green while the defects below are live is itself the headline result: the gaps are in what is not covered, not in what is.
Severity summary
| ID | Severity | Area | Title |
|---|---|---|---|
| C-01 | Critical | Security | web::Data<bool> TypeId collision disables authentication entirely |
| C-02 | Critical | Security | Encryption at rest silently falls back to an all-zero AES key |
| C-03 | Critical | Durability | DIR_PATH in docker-compose.yml is never read; container data is not persisted |
| C-04 | Critical | Durability | SSTable corruption detection and quarantine are wired to inverted signals |
| H-01 | High | Security | X-Forwarded-For is trusted unconditionally: rate-limit bypass and unbounded memory |
| H-02 | High | Correctness | Per-endpoint rate-limit counters never decay, permanently locking out clients |
| H-03 | High | Durability | WAL recovery deduplication discards range tombstones |
| H-04 | High | Resilience | panic = "abort" makes every catch_unwind recovery path dead in release |
| H-05 | High | Security | Two live RustSec advisories; the CI audit job cannot run |
| H-06 | High | CI | ci.yml runs no tests, no clippy and no build on main |
| M-01 | Medium | Docs | Container health checks probe a route that does not exist, with a binary that is not installed |
| M-02 | Medium | Docs | Documented environment variables did not match the code (15 missing, 5 dead) |
| M-03 | Medium | Docs | README and QUICKSTART commands fail as written |
| M-04 | Medium | CI | Benchmark automation commits an empty result on every run |
| M-05 | Medium | CI | CI pipes an unpinned remote installer into bash |
| M-06 | Medium | Testing | No test covers authentication, rate limiting or engine-level encryption |
| M-07 | Medium | Frontend | Angular 17 is out of support and has no CI at all |
| L-01 | Low | Design | MemTable uses DashMap but exposes &mut self, forcing an outer lock |
| L-02 | Low | Design | Engine is a single 2300-line impl block |
| L-03 | Low | Docs | Version number disagrees across Cargo.toml, ROADMAP.md and Dockerfile |
| L-04 | Low | Hygiene | .gitignore contained *.sh, silently hiding every new shell script |
Items marked fixed in this pass below were corrected as part of the audit; the rest are filed as issues because they change on-disk formats, runtime behaviour, or need tests that do not exist yet.
Critical
C-01 — web::Data<bool> TypeId collision disables authentication entirely
Status: fixed in this pass.
actix-web keys application data by TypeId. Registering two web::Data<bool>
values means the second overwrites the first, and every reader of Data<bool>
observes the survivor.
start_server registered exactly that pair:
src/api/mod.rs:1825—web::Data::new(config.auth.enabled)src/api/mod.rs:1841—web::Data::new(config.access_control_enabled)
with the access-control flag registered second (src/api/mod.rs:1872), so it won.
Three readers were affected:
src/api/auth/middleware.rs:29(bearer_validator)src/api/auth/middleware.rs:81(require_permission)src/api/access_control.rs:80(AccessControlMiddleware::call)
ACCESS_CONTROL_ENABLED defaults to false (src/api/config.rs:73). Therefore, with
API_AUTH_ENABLED=true and access control left at its default, bearer_validator
returned Ok(req) for every request and require_permission returned Ok(()) at all
59 call sites. Authentication and the entire permission model were inert.
CHANGELOG records this exact behaviour being fixed once before, as issue #178
("API_AUTH_ENABLED has no effect"). Adding the access-control middleware later
silently reintroduced it, because nothing in the type system objected and no test
exercises the authenticated path (see M-06).
Both readers also used .unwrap_or(false), so a missing flag meant "allow" — a
fail-open default on the security-critical path.
Fix applied: distinct newtypes, api::auth::AuthEnabled and
api::access_control::AccessControlEnabled, so the two flags occupy different
TypeIds and a future third flag cannot collide either. The auth readers now fail
closed when the flag is absent.
C-02 — Encryption at rest silently falls back to an all-zero AES key
Status: partially mitigated (failure is now logged); behavioural fix filed as an issue.
EncryptionConfig::default() is { key: [0u8; 32], enabled: true }
(src/storage/encryption.rs:35). An all-zero AES-256 key is publicly known, so data
"encrypted" with it is readable by anyone.
StorageConfig::default() sets encryption_enabled: true with
encryption_key_path: None (src/infra/config.rs:148), and src/bin/server.rs
never reads any encryption variable nor calls .encryption_key_path(...). The
conversion at src/core/engine/mod.rs:147 then did:
#![allow(unused)] fn main() { .map(|path| EncryptionConfig::from_key_path(Some(path))) .unwrap_or_else(|| Err(LsmError::InvalidArgument( "Encryption enabled but no key path provided".to_string()))) .unwrap_or_default() // <-- the error is constructed, then discarded }
The explicit diagnostic was built and thrown away. Out of the box, the server encrypts every SSTable block and WAL frame with an all-zero key and reports success. An unreadable or malformed key file took the same path.
Three further defects compound it:
src/core/engine/compaction.rs:135andsrc/core/engine/version_set.rs:68returnEncryptionConfig::default()in theelsebranch taken whenencryption_enabled == false— so disabling encryption turns it on with a zero key for those paths, whileEngineOptions::fromcorrectly yieldsenabled: false. Flush and compaction therefore disagree about whether output is encrypted.#[serde(default)]onencryption_enabled(src/infra/config.rs:98) yieldsfalse, whileDefault::default()yieldstrue. The same field has two contradictory defaults depending on how the config was constructed.src/infra/health/scrubber.rs:194returnsvalid: falsefor everyLSMSST04file: "Cannot verify CRC32 of encrypted SSTable without encryption key". With encryption on by default, the integrity scrubber reports 100% of SSTables as invalid, indistinguishable from genuine corruption.
The doc comments actively pointed the wrong way — from_key_path's said
None "returns a default (disabled) config", and core/table.rs:87 told callers to
"pass EncryptionConfig::default() … when encryption is not needed".
src/api/test_helpers.rs:44 shows the confusion was known: it sets
encryption_key_path = Some("/dev/null") to force a bypass.
Fix applied: the swallowed failures now emit tracing::error! on the
apexstore::security target naming the all-zero fallback, and the misleading doc
comments were corrected. Changing the default itself would make existing zero-key
SSTables and WAL frames unreadable, so it needs a migration path and is filed
separately.
C-03 — DIR_PATH in docker-compose.yml is never read; container data is not persisted
Status: fixed in this pass.
src/bin/server.rs:29 reads DATA_DIR, defaulting to ./.lsm_data. No binary reads
DIR_PATH. But docker-compose.yml set DIR_PATH=/data and mounted the
apexstore-data volume at /data.
Consequently the server wrote to /app/.lsm_data — inside the container's writable
layer, not the volume. Every write was lost when the container was recreated,
while the deployment appeared to have a persistent volume.
INDEX_INTERVAL in the same file had the same problem: the server reads
SPARSE_INDEX_INTERVAL (src/bin/server.rs:46).
Fix applied: docker-compose.yml now sets DATA_DIR=/data and
SPARSE_INDEX_INTERVAL; the Dockerfile declares ENV DATA_DIR=/data and
VOLUME ["/data"] so the image is durable without extra configuration.
C-04 — SSTable corruption detection and quarantine are wired to inverted signals
Status: filed as an issue.
Table::from_sstable_path (src/core/table.rs:89) handles a failed meta-block read
as Err(_) => (Vec::new(), Vec::new(), None) (src/core/table.rs:113) and returns
Ok. It returns Err only when the meta block was read and the bloom filter then
failed to deserialise.
discover_sstables_from_disk (src/core/engine/mod.rs:2993) quarantines on Err —
moving the file into sstables/quarantine/. The two are therefore inverted:
- A genuinely unreadable SSTable (wrong key, truncated meta block, bit rot) returns
Okand is registered with an empty min/max key range and no bloom filter. Key pruning treats it as covering nothing, so its data becomes invisible. No warning, no quarantine, no metric. - A file whose meta block reads fine but whose bloom filter fails to deserialise
returns
Errand is moved out of the data directory on startup.
The same function also carries the comment "For now, we'll create an empty table -
in production this would read the SSTable" (src/core/table.rs:94), and is called
from five sites including the compaction and snapshot-restore paths.
High
H-01 — X-Forwarded-For is trusted unconditionally
Status: filed as an issue.
get_client_ip (src/api/rate_limiter.rs) returns the first address in
X-Forwarded-For whenever the header parses, with no trusted-proxy allow-list and no
way to disable the behaviour. Any client can therefore:
- Bypass rate limiting entirely by varying the header per request; each forged value gets its own fresh budget.
- Grow the tracking map without bound.
shard.retain(...)only drops entries whose timestamp window has emptied, so one request per forged address keeps an entry alive for 60s. Millions of forged addresses are millions of liveIpTrackvalues. - Forge audit-log attribution, since the audit middleware resolves the client the same way.
.expect("rate limiter shard lock poisoned") on the same path turns any panic under
the lock into a process abort (see H-04).
H-02 — Per-endpoint rate-limit counters never decay
Status: filed as an issue.
IpTrack::prune (src/api/rate_limiter.rs) trims timestamps to the 60-second
window but leaves endpoint_counts untouched; the comment says the counters are
"pruned implicitly when the whole IpTrack is removed", which requires timestamps
to become empty.
The middleware records a timestamp on every request, so any client sending at least
one request per minute never empties the window, and endpoint_counts increases
monotonically for the process lifetime. Once count >= limit, is_rate_limited
returns true forever: a legitimate client that trips a per-endpoint limit once is
locked out of that endpoint permanently. The window does not slide.
endpoint_counts is also keyed on the raw req.path(), so /keys/<random> generates
an unbounded number of map entries per client.
H-03 — WAL recovery deduplication discards range tombstones
Status: filed as an issue.
deduplicate_records (src/storage/wal.rs:789) keys on (column_family, key) and
keeps the last occurrence. LogRecord::range_tombstone(start, end) sets
key = start (src/core/log_record.rs:95).
So a range tombstone and any point write to its start key collide. Replaying
delete_range(b"a", b"z")
put(b"a", v)
keeps only the put, dropping the tombstone — and with it the deletion of every key
in b"b" ..= b"y". Deleted keys silently reappear after a restart.
The dedup pass was introduced for issue #191 (stale value after restart) before range deletes landed in #192; the two were never reconciled.
H-04 — panic = "abort" makes every catch_unwind recovery path dead in release
Status: filed as an issue.
Cargo.toml sets panic = "abort" under [profile.release]. catch_unwind cannot
catch anything when panics abort, so in release builds:
- The whole
src/infra/panic_recovery.rsmodule is inert, includingspawn_protected, the panic history, and theon_paniccallbacks. - The compaction thread guard at
src/core/engine/mod.rs:1876does not protect anything: a panic during compaction takes down the server. - Every
.expect(...)and slice index in a request path becomes a process kill.
This only manifests in release. Tests run under the dev profile with unwinding, so
the suite exercises code that cannot behave that way in production. For a server that
documents resilience features (circuit breaker, degradation manager, watchdog),
panic = "abort" and panic_recovery are mutually exclusive; one has to go.
H-05 — Two live RustSec advisories; the CI audit job cannot run
Status: one fixed, one accepted with a recorded rationale; tooling fixed.
cargo audit with the version pinned by the toolchain (0.21.2) aborts before
scanning:
error: error loading advisory database: parse error:
.../libcrux-aesgcm/RUSTSEC-2026-0211.md: unsupported CVSS version: 4.0
Both CI audit steps therefore produce no signal, which is why the following went
unnoticed. With cargo-audit 0.22.2:
| ID | Crate | Issue |
|---|---|---|
| RUSTSEC-2026-0258 | h2 0.3.27 | unbounded empty DATA frames (DoS) — fixed in >= 0.4.16 |
| RUSTSEC-2026-0222 | wasmtime 44.0.2 | stores mix up type indices between engines (3.8 low) |
h2 0.3 sits directly under the HTTP server, so the DoS is reachable.
Thirteen warnings accompany them, including spin 0.9.8 yanked, and
ring 0.16.20 / rustls-pemfile 1.0.4 unmaintained. Those two come from
rustls = "0.20", and .cargo/audit.toml ignores their advisories with the
justification "Cannot upgrade without upstream actix-web upgrading rustls". That is
no longer true: actix-web 4.12 exposes a rustls-0_23 feature. Moving to it drops
ring 0.16 from the tree and makes both ignores unnecessary.
The dependency graph also carries three simultaneous major versions of rand
(0.7.3, 0.8.5, 0.9.2) across 573 crates.
Resolution. actix-web's rustls feature is an alias for rustls-0_20;
switching to rustls-0_23 removed rustls 0.20, tokio-rustls 0.23, ring 0.16 and
rustls-pemfile 1 from the tree, so both entries in .cargo/audit.toml are gone
rather than re-justified. wasmtime moved from 44 to 47.0.4, outside the
RUSTSEC-2026-0222 range. cargo update cleared the yanked spin 0.9.8 and the
anyhow, event-listener and memmap2 advisories. Dependencies went from 573 to
555 and audit warnings from 13 to 6.
RUSTSEC-2026-0258 (h2) cannot be fixed by a version bump: h2 0.3 comes from
actix-http, which every actix-web 4.x release depends on, and the advisory's
fix is h2 ≥ 0.4.16. It is now the single entry in .cargo/audit.toml, with the
dependency chain, the exposure, the existing mitigations and a review date
recorded in place of the previous unexplained ignore list.
Bumping wasmtime raised the MSRV to 1.94 (the cranelift crates require it).
The pinned toolchain moved to 1.98, the current stable — 1.92 was never a
deliberate choice, only the floor wasmtime 44 imposed. The two numbers are now
distinct and separately checked: rust-toolchain.toml pins the toolchain,
rust-version in Cargo.toml declares the MSRV, and the CI MSRV job verifies
the latter independently.
The TLS wiring moved to the rustls 0.23 API. That also fixed a latent bug: the old
code called rustls_pemfile::pkcs8_private_keys only, so an RSA (PKCS#1) or EC
(SEC1) key was rejected with "No private key found". rustls_pemfile::private_key
accepts all three.
H-06 — ci.yml runs no tests, no clippy and no build on main
Status: filed as an issue.
.github/workflows/ci.yml triggers on push to main and runs three jobs:
actionlint, audit (currently broken, see H-05), and benchmark. There is no
cargo test, no cargo clippy, no cargo build.
pr-validation.yml does have those jobs, and also triggers on push to main, so the
two workflows duplicate the audit job on every push. benchmarks.yml adds a third
clippy + fmt run. Meanwhile:
- Every workflow uses
container: rust:latestanddtolnay/rust-toolchain@stable— redundant, and unpinned, so a new stable release can break CI with no repository change.cargo clippy --all-featurescurrently emits a warning on Rust 1.92, and CI runs with-D warnings. - No
--lockedanywhere, soCargo.lockis not enforced. - No MSRV job, so the README's claim of Rust 1.70 was never tested (the real floor is 1.92).
latency_benchandwrite_amplificationare declared inCargo.tomlbut absent from thebenchmarks.ymlmatrix, so they never run.benchmarks.ymltriggers on adevelopbranch that does not exist.- No coverage job, and no
cargo fuzzjob despitefuzz/being present.
Medium
M-01 — Container health checks probe a route that does not exist
Status: fixed in this pass.
The registered routes are /health/liveness, /health/readiness, /health/startup
and /health/check (src/api/mod.rs:1582-1585). There is no GET /health.
Both the Dockerfile HEALTHCHECK and the docker-compose.yml healthcheck probed
http://localhost:8080/health, so both returned 404. Independently, the
Dockerfile health check invoked curl, which the runtime image never installed —
and used exec form (CMD ["curl", …, "||", "exit", "1"]), where || is passed as a
literal argument rather than interpreted. Three separate reasons for the same probe to
never succeed.
QUICKSTART.md:71 and docs/AUTHENTICATION.md:129 documented the same missing route.
Fix applied: curl added to the runtime image; both probes point at
/health/liveness in shell form; both documents corrected.
M-02 — Documented environment variables did not match the code
Status: fixed in this pass, with a regression guard.
Diffing env::var(...) call sites in src/ against assignments in .env.example:
Read by the code, absent from .env.example (15): ACCESS_CONTROL_ENABLED,
CORS_ENABLED, CORS_ORIGINS, DATA_DIR, ENVIRONMENT, MAX_CONNECTIONS_PER_IP,
OTEL_EXPORTER_OTLP_ENDPOINT, REPLICATION_ROLE, REPLICATION_SYNC_INTERVAL_MS,
REPLICA_ENDPOINTS, SPARSE_INDEX_INTERVAL, TLS_CERT_PATH, TLS_ENABLED,
TLS_KEY_PATH, TLS_PORT.
Every TLS, CORS and access-control setting was undiscoverable — the security-relevant half of the configuration surface.
Documented, read nowhere (5): DIR_PATH, INDEX_INTERVAL, WAL_MAX_SIZE,
WAL_ARCHIVE_ENABLED, WAL_CHECK_INTERVAL_SECS. Operators setting these got silence
— which is how C-03 stayed hidden.
The README additionally advertised WAL_SYNC_MODE=async as giving "16x throughput".
That variable appears nowhere in the codebase; the knob is the compile-time constant
WAL_SYNC_INTERVAL (src/storage/wal.rs:139), with no environment binding at all.
Fix applied: .env.example rewritten to cover all 34 variables the code reads,
with a commented block naming the ones that exist only as LsmConfig fields.
scripts/check-env-example.sh (wired to make env-check) fails the build on future
drift in either direction.
M-03 — README and QUICKSTART commands fail as written
Status: fixed in this pass.
- README Quick Start said
cargo run --release. With four binaries and nodefault-run, cargo refuses: "could not determine which binary to run". - README's TLS example used
--bin server; QUICKSTART used--bin clisix times. Neither name exists — the binaries areapexstore-server,apexstore-cli,apexstore-tui. Every runnable command in QUICKSTART.md failed. - The Rust badge claimed 1.70+;
--all-featuresneeds 1.92.
Fix applied: binary names corrected throughout, default-run = "apexstore-server"
and rust-version = "1.92" added to Cargo.toml, URLs and the badge updated.
src/main.rs remains a 13-line stub that builds an engine at a hardcoded
/var/lib/apexstore/data and exits, producing the fourth binary apex-store-rs;
removing it is filed separately.
M-04 — Benchmark automation commits an empty result on every run
Status: filed as an issue.
git log shows 20+ consecutive identical commits, docs: update benchmark results [skip ci]. The README block they write currently reads "No results parsed — check
the run artifacts."
scripts/format_bench.py succeeds but yields an empty table, so
benchmarks.yml takes the "no results parsed" branch, rewrites the same placeholder,
and commits. The benchmark step itself is continue-on-error: true, so a failing
benchmark still reaches the README rewrite. The result is history pollution plus a
performance section that has not reflected reality since v2.1.39.
M-05 — CI pipes an unpinned remote installer into bash
Status: filed as an issue.
.github/workflows/benchmarks.yml runs:
curl -fsSL https://raw.githubusercontent.com/opencode-ai/opencode/main/install.sh | bash
Unpinned code from a third-party main branch, executed in a job that holds
GITHUB_TOKEN and pushes commits to main. Whoever controls that branch controls
this repository's CI.
M-06 — No test covers authentication, rate limiting or engine-level encryption
Status: filed as an issue.
Across the twelve files in tests/, grep finds no reference to auth, Bearer,
token, rate_limit, or RateLimit. Only proptest_sstable.rs mentions
encryption, at the block level.
That is precisely why C-01 was reintroduced without any test turning red, and why the
suite runs entirely on zero-key encryption without noticing: restart.rs uses the
default config, so it writes and reads with the same all-zero key and passes.
Also worth noting: examples/ contains a single file for a crate advertising 40+
features.
M-07 — The frontend has never compiled, and nothing noticed
Status: build errors fixed in this pass; the framework upgrade is filed as an issue.
No workflow referenced frontend, npm or node, so the 30-plus pages under
frontend/src/app/pages/ were never built, linted, tested or dependency-scanned.
Adding a Frontend job to CI turned it red immediately: npm run build fails on
main. The dashboard has never produced a bundle.
Nine errors across seven files, all of the same family — standalone components must list every directive and pipe their template uses, and these do not:
| File | Error | Cause |
|---|---|---|
vector-search.component.ts | NG8002 ngClass, NG8004 pipe number | missing NgClass, DecimalPipe |
wasm-plugins.component.ts | NG8002 ngClass ×2 | missing NgClass |
tags.component.ts | "not statically analyzable", NG8004 pipe slice | FormsModule imported from @angular/common, which does not export it, so it resolved to undefined; missing SlicePipe |
graph.component.ts | same bad import | FormsModule from @angular/common |
time-travel.component.html | NG2 object possibly undefined | note.content?.length > 200 compares number | undefined |
sync-status.component.ts | TS7006 implicit any | see below |
The last one is not just a type error. SyncService.lastSyncTimestamp is a
signal<number | null>, and the component did:
this.sync.lastSyncTimestamp.subscribe(ts => { ... });
Signals have no subscribe, so the callback never ran and the "last synced"
label was permanently stuck on Never. The same component's auto-refresh timer
called lastSyncedLabel.update(l => l) every five seconds, which writes the same
value back — and signals compare for equality before propagating, so it notified
nothing. Both are now replaced by a computed signal.
Two more surfaced once those were cleared, and both are cascades rather than counts:
server-config.component.htmlfiltered inline withfiltered().filter(c => c.group === group). Angular's template parser reads=>as an assignment and rejects the binding (NG5002), so the filter had to move into the component.graph.component.htmlused@else if (fetched() && graphData(); as data).asis only valid on a primary@if, so the binding never existed and all 33 references todatain that branch failed. The trailing@else if (fetched() && !graphData())was also unreachable, since the branch before it already consumed everyfetched()case.
And three that are logic bugs, not import hygiene:
pubsub.component.tsdeclared both a fieldpublishMessage = ''and a methodpublishMessage(). The method's own body calledthis.publishMessage.trim(), which resolved to the method.health.component.tsdeclaredsignal<'healthy' | 'degraded' | 'unhealthy'>('unknown')— an initial value outside its own union.resilience.component.tsdid the same through itsHealthSummaryinterface.sync-status.component.tsimportedTime05IconandDataIcon, neither of which@hugeicons/core-free-iconsexports, and its template used<app-hugeicons-icon>where the component's selector ishugeicons-icon.
After the fixes npm run build exits 0 with one warning: one component
stylesheet is 157 bytes over Angular's default 2 kB budget.
npm audit on the installed tree reports 67 vulnerabilities (3 critical, 39
high).
frontend/package.json pins @angular/* ^17.3.0. Angular 17 left long-term
support in 2025, so none of those get patched. karma is also deprecated in
favour of the Angular CLI's own runner, and there are two spec files for
thirty-plus components. frontend/Dockerfile exists but is absent from
docker-compose.yml. The upgrade is tracked separately.
Low
L-01 — MemTable uses DashMap but exposes &mut self
src/core/memtable.rs stores data: DashMap<Vec<u8>, LogRecord>, but put,
insert and friends take &mut self, and size_bytes is a plain usize field.
Callers must hold an exclusive borrow, so the engine serialises access behind its own
lock and DashMap's per-shard concurrency is never reached — the sharding overhead is
paid without the benefit. Either move size_bytes to an atomic and take &self, or
use a BTreeMap and drop the dependency. The README claim of "lock-free reads and
writes to different keys" has been corrected in the meantime.
L-02 — Engine is a single 2300-line impl block
src/core/engine/mod.rs is 4935 lines, of which one impl<C: Cache> Engine<C>
spans lines 855-3148. src/api/mod.rs is 1964 lines with all route handlers,
middleware wiring and the transaction manager. Splitting along existing seams (reads,
writes, snapshots, column families) would make the encryption and quarantine paths
above far easier to reason about.
L-03 — Version number disagrees across three files
Cargo.toml says 2.2.7; ROADMAP.md says "Current Version: v2.3.0"; the
Dockerfile label said 1.4.0; CHANGELOG.md has everything under
[Unreleased] — v2.2 -> v2.3. The Dockerfile label is fixed; the rest needs a
release-process decision.
L-04 — .gitignore contained *.sh
Status: fixed in this pass.
.gitignore ignored *.sh wholesale with a single !scripts/format-benchmarks.sh
exception, so any new shell script a contributor wrote was invisible to git status.
The pattern is now !scripts/*.sh, and *.pem / *.key were added so TLS material
cannot be committed by accident. The ignore list also only covered .lsm_data,
while CoreConfig::default() uses ./.lsmdata — both spellings are now listed.
.task-state.json and .apexstore/state.json are committed agent scratch state,
duplicating each other and referencing issues closed months ago. They are now in
.gitignore, but untracking them is filed separately since it changes repository
contents.
Stale content in the previous audits
docs/audit/auditoria-completa.md and auditoria-tecnica-profunda.md (March 2026,
pt-BR) contain findings that no longer hold and should be marked resolved:
- L-03 "Sem
cargo auditno CI" — added in issue #183; it is now present but broken for a different reason (H-05). - H-05 "Rate Limiter Usa Mutex Simples (Gargalo)" — the limiter is now sharded 16
ways (
NUM_SHARDS,src/api/rate_limiter.rs). The real defect is H-02 above. - L-01 "CLI sem Gestão de Tokens" — added in issue #179 (
token create/list/revoke). - M-10 "Dependência Bincode UNMAINTAINED" — the codec is
postcard(src/infra/codec.rs); only a stale doc comment inwal.rsstill said bincode, now corrected.
They are also the only Portuguese documents in an otherwise English repository, which
makes them invisible to most readers and to the published documentation site.
docs/SUMMARY.md listed just four of the nine files under docs/, so
AUTHENTICATION.md, CLI_GUIDE.md, PERFORMANCE.md, WORKFLOWS.md and both audits
were never published to GitHub Pages at all; that is fixed in this pass.
What was changed in this pass
Documentation, configuration and packaging only, plus the C-01 security fix and one clippy warning. No storage format, wire format or default engine behaviour was altered.
| File | Change |
|---|---|
Dockerfile.dev | new — pinned Rust 1.92 toolchain image (clippy, rustfmt, cargo-audit 0.22, cargo-deny) |
docs/DEVELOPMENT.md | new — how to build, test, lint and benchmark in the container |
scripts/check-env-example.sh | new — fails the build when .env.example drifts from src/ |
Makefile | replaced three act targets with the full local pipeline |
src/api/auth/mod.rs, auth/middleware.rs, access_control.rs, mod.rs, test_helpers.rs | C-01: AuthEnabled / AccessControlEnabled newtypes, fail-closed auth |
src/core/engine/mod.rs | C-02: log the swallowed encryption-key failure |
src/storage/encryption.rs, src/core/table.rs | C-02: correct the inverted doc comments |
src/notes/search.rs | collapse the else { if … } clippy warning |
src/lib.rs | feature table said chai, the flag is chaos |
src/storage/wal.rs | frame format doc said bincode (it is postcard) and listed only V0/V1 |
Dockerfile, docker-compose.yml | C-03 and M-01: DATA_DIR, working health probes, OCI labels |
.env.example | M-02: all 34 live variables, dead ones called out |
README.md, QUICKSTART.md, docs/AUTHENTICATION.md, docs/CONTRIBUTING.md, docs/SETUP.md | M-03: working commands, real MSRV, honest feature claims |
Cargo.toml | default-run, rust-version |
docs/SUMMARY.md | publish every document |
.gitignore | L-04: drop *.sh, add *.pem/*.key, cover both data-dir spellings |
cargo test --all-features --workspace remains at 642 passing, and
cargo clippy --all-targets --all-features is now warning-free.
Auditoria Completa de Segurança, Resiliência e Performance — ApexStore
Data: 2026-05-26
Versão auditada: 2.1.63
Escopo: Código-fonte completo (Rust), configurações, dependências, infraestrutura
Metodologia: Análise estática de código + revisão arquitetural + boas práticas OWASP/Cloud Native
Resumo Executivo
A ApexStore é um storage engine LSM-tree embarcado em Rust com maturidade arquitetural impressionante. O código é bem estruturado, com separação clara entre camadas, uso extensivo de tracing, thiserror, testes unitários e de integração, e componentes de resiliência como circuit breaker, retry com backoff, backpressure, disk monitor, watchdog e panic recovery.
Pontuação geral: 6.5/10 — Código base robusto, mas com vulnerabilidades críticas de segurança na superfície HTTP.
Principais descobertas
| Severidade | Contagem | Destaques |
|---|---|---|
| 🔴 Crítico | 5 | Auth desabilitado por padrão, CORS permissivo, payload 50MB, sem TLS, injeção via CDC |
| 🟠 Alto | 8 | N+1 no scan, batch sem limite, GraphQL playground público, WebSocket sem auth, idempotência não integrada |
| 🟡 Médio | 10 | Workers ilimitados, sem CSRF, rate limiter com Mutex simples, token timing attack parcial, backup sem criptografia |
| 🔵 Baixo | 5 | CLI sem gestão de tokens, dashboard com auto-refresh, sem auditoria em CI |
🔴 Achados Críticos
C-01: Autenticação Desabilitada por Padrão
| Campo | Valor |
|---|---|
| Problema | API_AUTH_ENABLED=false no .env.example e no AuthConfig::default(). Qualquer requisição sem token passa pelo bearer_validator sem verificação. |
| Impacto | Todos os endpoints (incluindo /admin/flush, /admin/compact, /keys, /stats) são publicamente acessíveis sem qualquer autenticação. Atacante pode ler, escrever, deletar qualquer dado e forçar flush/compaction. |
| Evidência | src/api/config.rs:70-73: enabled: false; src/api/auth/middleware.rs:33-35: if !auth_enabled { return Ok(req); } |
| Recomendação | Mudar default para true e exigir configuração explícita de API_AUTH_ENABLED=false em ambientes dev. Implementar fallback seguro (deny-by-default). |
| Validação | Teste de integração: tentar GET /keys sem Authorization header → deve retornar 401. |
| Prioridade | Imediata |
C-02: CORS Permissivo (Allow All Origins)
| Campo | Valor |
|---|---|
| Problema | Cors::permissive() é usado quando cors_origins é None (default). Permite qualquer origem, qualquer header, qualquer método com credentials. |
| Impacto | Qualquer site pode fazer requisições cross-origin autenticadas (se auth estivesse habilitado). Exfiltração de dados via cookies/session tokens. |
| Evidência | src/api/mod.rs:518: None => actix_cors::Cors::permissive(); src/api/config.rs:61: cors_origins: None |
| Recomendação | Nunca usar .permissive() em produção. Exigir lista explícita de origens ou usar validação dinâmica segura. |
| Validação | Teste: curl -H "Origin: https://evil.com" -H "Authorization: Bearer ..." http://localhost:8080/keys → verificar se Access-Control-Allow-Origin não reflete evil.com. |
| Prioridade | Imediata |
C-03: Payload Máximo de 50MB
| Campo | Valor |
|---|---|
| Problema | MAX_JSON_PAYLOAD_SIZE=52428800 (50MB) — extremamente alto para uma API key-value. Ataque DoS trivial com poucas conexões. |
| Impacto | 20 requisições simultâneas de 50MB = 1GB de memória. Engine LSM-tree não tem limite de tamanho de valor por chave. Pode causar OOM killer. |
| Evidência | src/api/config.rs:50-51: max_json_payload_size: 50 * 1024 * 1024 |
| Recomendação | Reduzir para 1MB (1048576) como default. Implementar limite configurável por endpoint. Adicionar validação no middleware ANTES de chegar ao handler. |
| Validação | curl -X PUT -d "$(python -c 'print("x"*2000000)')" http://localhost:8080/keys/test → deve retornar 413 Payload Too Large. |
| Prioridade | Imediata |
C-04: Ausência de TLS/HTTPS
| Campo | Valor |
|---|---|
| Problema | Servidor HTTP puro, sem suporte a TLS. Nenhuma opção de certificado, key ou configuração SSL. |
| Impacto | Todas as comunicações (incluindo tokens Bearer, dados de notas, comandos admin) trafegam em texto puro. MITM total. |
| Evidência | src/bin/server.rs:118: apexstore::api::start_server(engine, server_config) — usa HttpServer::new(), não HttpServer::bind_rustls(). Nenhuma dependência rustls ou openssl no Cargo.toml. |
| Recomendação | Adicionar suporte a TLS nativo (rustls ou openssl via actix-web). Pelo menos documentar deploy atrás de reverse proxy (nginx/caddy) com requisito obrigatório. |
| Validação | Verificar que curl -k https://localhost:8080/health/liveness funciona ou que docs exigem reverse proxy. |
| Prioridade | Imediata |
C-05: CDC Webhook sem Autenticação nem Retry
| Campo | Valor |
|---|---|
| Problema | WebhookPublisher::publish no cdc.rs faz POST do evento para o endpoint configurado sem qualquer autenticação (Bearer token, HMAC, etc.) e sem retry em caso de falha. Dados sensíveis vazam para qualquer endpoint configurado ou interceptado. |
| Impacto | Se um atacante conseguir alterar a variável CDC_ENDPOINT (via env injection, config map, etc.), todas as mutações de dados são enviadas para ele. Sem retry, eventos são perdidos em falha de rede. |
| Evidência | src/infra/cdc.rs:217-250: função publish faz reqwest::Client::post().json().send().await sem Authorization header, sem retry, sem timeout explícito. |
| Recomendação | Adicionar Authorization header configurável no CdcConfig. Envolver envio em RetryConfig::default(). Adicionar timeout de 5s. Usar circuit breaker. |
| Validação | Teste unitário: mock HTTP server que verifica header Authorization no POST de CDC. |
| Prioridade | Alta |
🟠 Achados Altos
H-01: N+1 Query no Endpoint /scan
| Campo | Valor |
|---|---|
| Problema | GET /scan primeiro lista todas as keys via engine.keys(), depois faz uma get_cf para cada key individualmente. Isso é 1 + N queries. |
| Impacto | Com 10.000 keys, são 10.001 chamadas ao engine. Latência O(N) em vez de scan eficiente. OOM ao carregar todas as keys em memória ao mesmo tempo. |
| Evidência | src/api/mod.rs:439-463: for k in keys { engine.get_cf("default", ...) } |
| Recomendação | Usar engine.scan() (prefix scan com iterator) que já existe no engine e retorna key+value em uma única passagem. |
| Validação | cargo bench --bench scan_bench — comparar latência antes/depois. |
| Prioridade | Alta |
H-02: Batch Insert sem Limite de Tamanho
| Campo | Valor |
|---|---|
| Problema | POST /keys/batch aceita Vec<FrontendSetBody> sem limite de tamanho. Atacante pode enviar 100.000 registros em uma única requisição. |
| Impacto | DoS via batch gigante. Engine LSM-tree faz put_cf para cada registro individualmente (sem batch transaction). Amplificação de escrita. |
| Evidência | src/api/mod.rs:406-431: sem .take() ou max_batch validation. |
| Recomendação | Adicionar max_batch: usize configurável (default 1000). Validar no middleware. Usar transação atômica do engine se disponível. |
| Validação | Teste: POST /keys/batch com 10001 registros → deve retornar 413. |
| Prioridade | Alta |
H-03: GraphQL Playground Acessível em Produção
| Campo | Valor |
|---|---|
| Problema | GET /graphql/playground e GET /graphql retornam o Playground interativo (GraphQL IDE). Qualquer um pode executar queries arbitrárias. |
| Impacto | Ferramenta de desenvolvimento exposta em produção. Atacante pode explorar schema GraphQL, fazer queries profundas, enumerar dados. |
| Evidência | src/api/mod.rs:491-493: playground registrado sem verificação de ambiente. |
| Recomendação | Desabilitar playground quando env!("PROFILE") != "debug" ou via config graphql_playground_enabled: bool. |
| Validação | Teste: GET /graphql/playground em modo release → deve retornar 404. |
| Prioridade | Alta |
H-04: WebSocket Sync sem Autenticação
| Campo | Valor |
|---|---|
| Problema | GET /ws/sync usa actix-ws sem middleware de autenticação. O sync_handler não verifica token. |
| Impacto | Qualquer um pode abrir WebSocket, assinar notas, receber mudanças em tempo real e enviar alterações. Vazamento de dados via push. |
| Evidência | src/api/sync.rs:187-211: handler sync_handler sem require_permission. |
| Recomendação | Adicionar validação de token no handshake WebSocket. Extrair token do query param ?token=... ou header Sec-WebSocket-Protocol. |
| Validação | Teste: conectar WebSocket sem token → deve fechar conexão com 4001. |
| Prioridade | Alta |
H-05: Rate Limiter Usa Mutex Simples (Gargalo)
| Campo | Valor |
|---|---|
| Problema | RateLimiterState usa Mutex<HashMap<IpAddr, IpTrack>>. Cada requisição adquire o lock global para verificar rate limit. Sob alta concorrência, o mutex se torna gargalo. |
| Impacto | Em benchmarks de 500+ conexões concorrentes, o rate limiter pode aumentar latência em 10-50ms por requisição devido à contenção de lock. |
| Evidência | src/api/rate_limiter.rs:50: requests: Mutex<HashMap<IpAddr, IpTrack>> |
| Recomendação | Usar sharded Mutex (256 shards by hash do IP), ou implementar sliding window com DashMap (dashmap crate), ou usar algoritmo token bucket lock-free com AtomicU64. |
| Validação | cargo bench --bench latency_bench — comparar P99 latency antes/depois com 1000 conexões. |
| Prioridade | Alta |
H-06: Idempotency Middleware Não Integrado
| Campo | Valor |
|---|---|
| Problema | IdempotencyMiddleware existe em src/infra/idempotency.rs mas nunca é instanciado nem registrado na cadeia de middleware do actix-web (src/api/mod.rs:569-588). |
| Impacto | Retry de clientes pode causar duplicação de writes. Se um PUT /keys/key for executado duas vezes, o segundo pode sobrescrever dados já atualizados (dependendo do timestamp). |
| Evidência | src/api/mod.rs:569-588: middleware list inclui RequestTimeout, RateLimiter, AccessControl, Logger, Cors, HttpAuthentication — mas não IdempotencyMiddleware. |
| Recomendação | Integrar IdempotencyMiddleware como middleware global para mutações (PUT, POST, DELETE). Extrair Idempotency-Key header. |
| Validação | Teste de integração: enviar PUT /keys/k com Idempotency-Key: xyz duas vezes → mesma resposta. |
| Prioridade | Alta |
H-07: Variáveis de Ambiente Sem Validação
| Campo | Valor |
|---|---|
| Problema | ServerConfig::from_env() faz parse de variáveis com unwrap_or(default) genérico. Valores maliciosos ou inválidos são silenciosamente trocados pelo default sem warning. |
| Impacto | Se WORKERS=-1 for injetado, silenciosamente vira workers: None (auto). Se PORT=0 (porta aleatória), servidor pode ligar em porta inesperada. Falta de validação de range. |
| Evidência | src/api/config.rs:77-170: todos os parse::<T>() usam unwrap_or(default_value) sem log de warning. |
| Recomendação | Adicionar logging warning quando env var é inválida. Validar ranges (porta 1-65535, workers 1-64, etc.). |
| Validação | Teste: WORKERS=-1 cargo run → log warning no startup. WORKERS=0 → erro de validação. |
| Prioridade | Alta |
H-08: Scan de Keys Carrega Tudo em Memória
| Campo | Valor |
|---|---|
| Problema | GET /keys (sem prefix) chama engine.keys() que retorna todas as keys do banco em um Vec<Vec<u8>>. Para bancos com milhões de keys, isso causa OOM. |
| Impacto | Com 5M de keys de 32 bytes = 160MB só de keys em memória. Antes de serializar JSON. |
| Evidência | src/api/mod.rs:156-163: engine.keys()?.into_iter().take(limit) — take limita output mas o vetor inteiro já foi alocado. |
| Recomendação | Implementar engine.keys_with_limit(limit) que usa inner iterator e para após limit itens. Ou modificar search_prefix com prefixo vazio. |
| Validação | Teste com 1M keys: consumo de memória < 50MB. |
| Prioridade | Alta |
🟡 Achados Médios
M-01: Workers Ilimitados (Auto = CPU Cores)
| Campo | Valor |
|---|---|
| Problema | WORKERS vazio = auto-detect. Em servidores com muitos cores (32, 64), isso cria dezenas de workers que competem pelo lock do engine (Mutex no core). |
| Impacto | Contenção alta no lock do engine (cada operação adquire parking_lot::Mutex no core). Workers extras gastam CPU em spinning. |
| Evidência | src/bin/server.rs:594-596: if let Some(workers) = config.workers { server_builder = server_builder.workers(workers); } |
| Recomendação | Recomendar default de 4 workers. Documentar que engine lock-bound. Adicionar warning se workers > 8. |
| Validação | cargo bench --bench mixed_bench com 4 vs 32 workers. |
| Prioridade | Média |
M-02: Ausência de Proteção CSRF
| Campo | Valor |
|---|---|
| Problema | Nenhum token CSRF, SameSite cookie, ou verificação de origem/Referer nas mutações. Embora actix-web exija Content-Type: application/json para web::Json, navegadores não enviam automaticamente. |
| Impacto | Se auth estivesse habilitado com cookie-based (não é o caso atual, mas arquiteturalmente), CSRF seria possível. |
| Evidência | Todo o src/api/mod.rs — nenhuma verificação de Origin, Referer, ou token CSRF. |
| Recomendação | Adicionar middleware de verificação de origem para mutações. Exigir header X-CSRF-Token ou Origin check. |
| Validação | Teste: POST sem Origin header → 403. |
| Prioridade | Média |
M-03: Token Timing Attack Parcial
| Campo | Valor |
|---|---|
| Problema | constant_time_compare compara strings hex (SHA-256) byte a byte, o que é constant-time. Porém, a comparação de tamanho (a.len() != b.len()) vaza informação de tamanho do hash. |
| Impacto | Extremamente baixo em prática (atacante precisaria de >10^6 requisições para extrair 64 chars). Mas quebra a premissa de constant-time. |
| Evidência | src/api/auth/token.rs:131-138: if a.len() != b.len() { return false; } |
| Recomendação | Usar crate subtle ou constant_time_eq para comparação de bytes. Hash tokens armazenados como [u8; 32] em vez de hex string. |
| Validação | Teste: validate_token com tokens de diferentes tamanhos deve levar o mesmo tempo (±5%). |
| Prioridade | Média |
M-04: Backup sem Criptografia
| Campo | Valor |
|---|---|
| Problema | BackupScheduler::backup_now() copia snapshots para diretório de backup sem qualquer criptografia. Dados sensíveis ficam em texto puro no disco. |
| Impacto | Se o diretório de backup for comprometido, todos os dados são expostos. Backups em S3/NFS sem criptografia violam compliance (GDPR, HIPAA, SOC2). |
| Evidência | src/infra/backup_scheduler.rs:170-208: nenhuma chamada a encrypt_block ou similar. Backup é cópia literal dos arquivos SSTable. |
| Recomendação | Integrar Encryptor no backup. Usar AES-256-GCM com chave separada (rotação periódica). |
| Validação | Teste: backup → arquivos .encrypted. Tentar ler sem chave → dados ininteligíveis. |
| Prioridade | Média |
M-05: Compactação Usa std::thread::sleep Dentro de Lock
| Campo | Valor |
|---|---|
| Problema | (Verificar engine internals) O retry_with_backoff usa std::thread::sleep(Duration::from_millis(...)) que bloqueia a thread atual. Se chamado dentro de um lock no compaction, bloqueia outros workers. |
| Impacto | Thread pool bloqueada durante sleep de até 5s (max_delay_ms). Redução de throughput. |
| Evidência | src/infra/retry.rs:102: std::thread::sleep(Duration::from_millis(actual_delay_ms)) |
| Recomendação | Usar tokio::time::sleep para async contexts. Separar retry de blocking IO. |
| Validação | Teste de estresse: 1000 writes concorrentes durante compactação → sem starvation. |
| Prioridade | Média |
M-06: CDC Publisher sem Timeout
| Campo | Valor |
|---|---|
| Problema | WebhookPublisher::publish não especifica timeout na requisição HTTP. Se o endpoint CDC travar, a goroutine fica bloqueada indefinidamente. |
| Impacto | Escrita no engine fica bloqueada aguardando CDC. Degeneração para completa indisponibilidade. |
| Evidência | src/infra/cdc.rs: reqwest post sem .timeout(). |
| Recomendação | Adicionar reqwest::Client::builder().timeout(Duration::from_secs(5)). Usar circuit breaker para CDC. |
| Validação | Teste: configurar CDC endpoint que não responde → timeout após 5s. |
| Prioridade | Média |
M-07: Falta de Auditoria (Access Log)
| Campo | Valor |
|---|---|
| Problema | O logger actix_web::middleware::Logger::default() registra apenas método, path, status, duração. Não registra: quem fez a requisição (principal), o recurso acessado (key), o resultado detalhado. |
| Impacto | Impossível fazer auditoria forense: quem deletou qual key, quando. |
| Evidência | src/api/mod.rs:574: .wrap(actix_web::middleware::Logger::default()) — formato de log não customizado. |
| Recomendação | Customizar Logger para incluir X-User-Id (do token), X-Request-Id, key do path, response status. Adicionar log estruturado em formato JSON. |
| Validação | Verificar logs: {"method":"DELETE","path":"/keys/secret","user":"alice","status":200} |
| Prioridade | Média |
M-08: Degradation Manager Não Integrado com API
| Campo | Valor |
|---|---|
| Problema | DegradationManager existe mas não é verificado nos handlers da API. Writes continuam mesmo quando o disco está crítico. |
| Impacto | Escrita em disco cheio causa corrupção de SSTable e perda de dados. |
| Evidência | src/infra/degradation.rs — implementação completa mas não há chamada a check_write_allowed() nos handlers put_key, post_key, delete_key, batch_keys. |
| Recomendação | Integrar DegradationManager::check_write_allowed() em todos os handlers de mutação. Conectar DiskMonitor::on_critical para setar ReadOnly. |
| Validação | Teste: encher disco → POST /keys → retorna 503 Service Unavailable. |
| Prioridade | Média |
M-09: Sem Limite de Conexões por IP
| Campo | Valor |
|---|---|
| Problema | Rate limiter é baseado em requisições/minuto, não em conexões simultâneas. max_connections=10000 é global, não por IP. |
| Impacto | Um único IP pode abrir 10000 conexões simultâneas e exaurir o file descriptor pool. |
| Evidência | src/api/rate_limiter.rs: rastreia requisições em janela de 60s, mas não limita conexões simultâneas por IP. |
| Recomendação | Adicionar max_connections_per_ip: usize (default 100). Usar HashMap<IpAddr, AtomicUsize> para tracking de conexões ativas. |
| Validação | Teste: 200 conexões simultâneas do mesmo IP → 100 aceitas, 100 rejeitadas com 429. |
| Prioridade | Média |
M-10: Dependência Bincode UNMAINTAINED
| Campo | Valor |
|---|---|
| Problema | bincode 1.3.3 é marcado como UNMAINTAINED (RUSTSEC-2025-0141), mas está como dependência (aparentemente removida — verificar Cargo.toml atual). |
| Impacto | Se presente, bugs de segurança não serão corrigidos. |
| Evidência | SECURITY_REPORT.md:64 — mas não aparece no Cargo.toml atual (postcard substituiu?). Verificar Cargo.lock. |
| Recomendação | Confirmar que bincode não está em nenhuma dependência transitiva. Executar cargo audit regularmente. |
| Validação | cargo audit não deve reportar bincode. |
| Prioridade | Média |
🔵 Achados Baixos
L-01: CLI sem Gestão de Tokens
| Campo | Valor |
|---|---|
| Problema | CLI (apexstore-cli) não tem comandos para criar, listar, revogar tokens de API. |
| Impacto | Administradores precisam criar tokens manualmente via API POST /admin/tokens (que nem existe como endpoint documentado). |
| Evidência | src/bin/cli.rs: comandos get/put/delete/scan — sem subcomando token. |
| Recomendação | Adicionar apexstore-cli token create/list/revoke com persistência no engine. |
| Validação | apexstore-cli token create --name "ci-user" --permission read → retorna token. |
| Prioridade | Baixa |
L-02: Admin Dashboard Auto-Refresh sem Cache Bust
| Campo | Valor |
|---|---|
| Problema | Dashboard HTML auto-refresh a cada 5s via location.reload(), não via fetch(). Causa flash visual e perde estado. |
| Impacto | Experiência de monitoração ruim. Pequena sobrecarga de CPU/rendering. |
| Evidência | src/api/admin/dashboard.rs:216: setInterval(updateTime, 1000); setTimeout(function() { location.reload(); }, 5000); |
| Recomendação | Substituir por fetch('/stats/all') com atualização parcial do DOM. |
| Validação | Dashboard atualiza sem flash visual. |
| Prioridade | Baixa |
L-03: Sem cargo audit no CI
| Campo | Valor |
|---|---|
| Problema | Workflow CI (ci.yml) não executa cargo audit para detectar vulnerabilidades em dependências. |
| Impacto | Vulnerabilidades em dependências só são descobertas manualmente. |
| Evidência | SECURITY_REPORT.md:105: #183 — No cargo audit in CI. Workflow não tem step de audit. |
| Recomendação | Adicionar cargo audit ao CI. Usar cargo-audit com --deny warnings. |
| Validação | CI passa com cargo audit. |
| Prioridade | Baixa |
L-04: Endpoints Frontend Duplicados
| Campo | Valor |
|---|---|
| Problema | POST /keys (frontend) e PUT /keys/{key} fazem a mesma coisa com APIs diferentes. GET /stats/all e GET /stats são redundantes. |
| Impacto | Superfície de ataque maior sem necessidade. Manutenção duplicada. |
| Evidência | src/api/mod.rs:345-369 (post_key) vs 73-99 (put_key). 319-342 (get_stats_all) vs 193-217 (get_stats). |
| Recomendação | Consolidar: remover endpoints duplicados ou fazê-los redirecionar. Versionar API (/v1/keys). |
| Validação | Testes existentes continuam passando após remoção dos duplicados. |
| Prioridade | Baixa |
L-05: Sem Health Check de Dependências Externas
| Campo | Valor |
|---|---|
| Problema | Health checks (/health/liveness, /health/readiness) verificam apenas o engine local, não dependências externas (CDC endpoint, Webhook, OTLP collector). |
| Impacto | Readiness retorna 200 mesmo quando todas as dependências externas estão down. K8s não mata pod. |
| Evidência | src/api/health.rs: liveness e readiness só verificam engine stats. |
| Recomendação | Adicionar health checks para dependências: CDC endpoint (ping), OTLP (gRPC health check), disk space. |
| Validação | CDC endpoint retornando 503 → /health/readiness retorna 503. |
| Prioridade | Baixa |
🗄️ Riscos do Banco de Dados (LSM-tree)
DB-01: Write Amplification sem Monitoramento (Médio)
| Problema | O LSM-tree tem write amplification inerente (cada write é reescrito múltiplas vezes na compactação). write_amplification.rs bench existe mas não há métrica exposta no Prometheus. |
|---|---|
| Impacto | Sem monitorar write amplification, usuários podem configurar tamanhos de nível errados e ter 20-50x write amplification, reduzindo vida de SSD. |
| Recomendação | Adicionar métrica apexstore_write_amplification_ratio ao Prometheus. Basear em compaction_bytes_written / user_bytes_written. |
DB-02: Read Amplification em GET sem Bloom Filter (Médio)
| Problema | Se o Bloom Filter não for configurado (ou BLOOM_FALSE_POSITIVE_RATE muito alto), cada GET precisa verificar todos os níveis (L0..Ln). Com 10 níveis, cada GET faz até 10 reads de SSTable. |
|---|---|
| Impacto | Latência P99 pode disparar de 1ms para 50ms em bancos com muitos níveis e sem bloom filter efetivo. |
| Recomendação | Exigir Bloom Filter (default 1% false positive). Monitorar bloom_filter_negatives_total para detectar filtros ineficazes. |
DB-03: Compaction Pode Causar Write Stalls (Baixo)
| Problema | Se a taxa de escrita excede a capacidade de compactação, o memtable enche e o engine bloqueia writes. CompactionBackpressure existe mas não está integrado com o rate limiter da API. |
|---|---|
| Impacto | Writes bloqueados por segundos. Picos de latência. |
| Recomendação | Integrar CompactionBackpressure com RateLimiterState da API. Quando backpressure > threshold, reduzir rate limit da API dinamicamente. |
DB-04: Sem Range Deletions Otimizadas (Baixo)
| Problema | delete_cf deleta uma chave por vez. Não há suporte a range delete (delete_range(start, end)) que eliminaria toda uma faixa com uma única operação lógica. |
|---|---|
| Impacto | Deletar 1M keys com prefixo requer 1M operações. Write stall. |
| Recomendação | Implementar delete_range() no engine com tombstone de range (já há range_start/range_end no LogRecord). |
DB-05: Block Cache Tamanho Fixo (Baixo)
| Problema | GlobalBlockCache::new(64, 4096) — tamanho fixo de 64MB. Sem resize dinâmico ou adaptive cache. |
|---|---|
| Impacto | Cache pode estar superdimensionado (desperdício de memória) ou subdimensionado (cache miss rate alto). |
| Recomendação | Monitorar cache_hits_total / (cache_hits_total + cache_misses_total). Adicionar resize via API admin. |
📋 Plano de Correção
Fase 1 — Imediata (Semanas 1-2)
| Prioridade | ID | Ação | Esforço |
|---|---|---|---|
| 🔴 P0 | C-01 | Mudar default auth para true. Adicionar middleware obrigatório. | 2h |
| 🔴 P0 | C-02 | Remover Cors::permissive(). Exigir origens explícitas. | 1h |
| 🔴 P0 | C-03 | Reduzir payload max para 1MB default. Adicionar json_payload middleware. | 1h |
| 🔴 P0 | C-04 | Adicionar suporte TLS (rustls) ou documentar reverse proxy obrigatório. | 8h |
| 🟠 P1 | H-01 | Refatorar /scan para usar engine.scan() em vez de N+1 queries. | 3h |
| 🟠 P1 | H-02 | Adicionar max_batch_size limit (default 1000). | 1h |
Fase 2 — Curto Prazo (Semanas 3-4)
| Prioridade | ID | Ação | Esforço |
|---|---|---|---|
| 🟠 P1 | H-03 | Desabilitar GraphQL playground em produção. | 1h |
| 🟠 P1 | H-04 | Adicionar auth no WebSocket sync. | 4h |
| 🟠 P1 | H-05 | Substituir Mutex<HashMap> por sharded ou lock-free rate limiter. | 6h |
| 🟠 P1 | H-06 | Integrar IdempotencyMiddleware na cadeia de middleware. | 3h |
| 🟠 P1 | H-07 | Adicionar validação de env vars com logging de warning. | 2h |
| 🟠 P1 | H-08 | Implementar keys_with_limit() para evitar OOM em scans. | 4h |
Fase 3 — Médio Prazo (Semanas 5-6)
| Prioridade | ID | Ação | Esforço |
|---|---|---|---|
| 🔴 P0 | C-05 | Adicionar auth + retry + timeout no CDC Webhook. | 4h |
| 🟡 P2 | M-01 | Fixar default workers=4. Documentar engine lock-bound. | 1h |
| 🟡 P2 | M-02 | Adicionar CSRF protection middleware. | 3h |
| 🟡 P2 | M-03 | Usar subtle::ConstantTimeEq para token comparison. | 1h |
| 🟡 P2 | M-04 | Criptografar backups com AES-256-GCM. | 4h |
| 🟡 P2 | M-06 | Adicionar timeout no CDC HTTP client. | 1h |
| 🟡 P2 | M-07 | Customizar Logger para auditoria (principal, path, status). | 2h |
| 🟡 P2 | M-08 | Integrar DegradationManager nos handlers de mutação. | 3h |
| 🟡 P2 | M-09 | Adicionar max_connections_per_ip. | 3h |
Fase 4 — Contínuo (Sprints)
| Prioridade | ID | Ação | Esforço |
|---|---|---|---|
| 🔵 P3 | L-01..L-05 | Melhorias de CLI, dashboard, CI audit, consolidar endpoints, health checks | 12h |
| 🟡 P2 | M-05 | Refatorar retry para async com tokio::time::sleep | 3h |
| 🟡 P2 | M-10 | Confirmar remoção de bincode, adicionar cargo audit ao CI | 1h |
🧪 Plano de Testes
Testes de Segurança
| Teste | Ferramenta | Critério |
|---|---|---|
| Auth bypass | curl / httpx | GET /keys sem token → 401 |
| CORS reflection | curl -H "Origin: https://evil.com" | Response não deve refletir Origin |
| Payload oversized | curl -X PUT -d @50MB.json | 413 Payload Too Large |
| Path traversal | GET /keys/../../../etc/passwd | 404 (não 200 com conteúdo) |
| Rate limit bypass | 101 req/min de mesmo IP | 429 na 101ª |
| Token fuzzing | 1000 tokens aleatórios | 401 para todos |
| WebSocket auth | ws sem token | Conexão rejeitada |
| GraphQL iD | query {__schema{types{name}}} com profundidade 10 | Limitada a 3 níveis |
| Batch DoS | POST /keys/batch com 10001 registros | 413 ou 429 |
| CDC injection | Configurar CDC_ENDPOINT para servidor do atacante | Dados não devem vazar |
| TLS check | curl sem -k | Handshake TLS bem-sucedido |
Testes de Resiliência
| Teste | Cenário | Critério |
|---|---|---|
| Kill + recovery | Matar processo, reiniciar | WAL recovery, dados íntegros |
| Disk fill | Preencher disco até threshold | Engine entra em ReadOnly |
| Conexões em massa | 2000 conexões simultâneas | 2000 processadas, demais rejeitadas ordeiramente |
| Compactação + writes | 1000 writes/s durante compactação | Writes não bloqueiam > 1s |
| CDC offline | Endpoint CDC fora do ar | Engine continua operacional |
| Panic em worker | Forçar panic em thread de compactação | Thread reinicia, engine continua |
Testes de Performance
| Teste | Métrica | Alvo |
|---|---|---|
| GET latency (P50/P99/P999) | latency_bench | < 500µs / < 5ms / < 50ms |
| PUT latency (P50/P99) | latency_bench | < 1ms / < 10ms |
| Scan throughput (1000 keys) | scan_bench | > 1000 keys/s |
| Mixed workload | mixed_bench | > 5000 ops/s |
| Write amplification | write_amplification | < 10x |
| Concurrent connections | stress_bench | > 500 conexões simultâneas sem erro |
✅ Checklist Final para Produção
Configuração Obrigatória
-
API_AUTH_ENABLED=true— autenticação ativa -
Token de admin criado via
POST /admin/tokens(ou CLI) -
CORS_ORIGINSconfigurado com origens específicas (nunca vazio) -
MAX_JSON_PAYLOAD_SIZEreduzido para 1MB - Deploy atrás de TLS (nginx, caddy, ou TLS nativo)
-
REQUEST_TIMEOUT_SECONDSconfigurado (30s default) -
RATE_LIMIT_REQUESTS_PER_MINUTEconfigurado (100 default)
Configuração Recomendada
-
WORKERS=4(não auto) -
BLOCK_CACHE_SIZE_MB=256(ou mais, dependendo da carga) -
BLOOM_FALSE_POSITIVE_RATE=0.01(1%) -
PREFIX_COMPRESSION_ENABLED=true(se keys têm prefixos comuns) -
WAL_ARCHIVE_ENABLED=truecomWAL_MAX_SIZE=67108864(64MB) -
BACKUP_SCHEDULERconfigurado comretention_count >= 10
Monitoramento
-
Prometheus
/metricsintegrado ao scraping -
OTLP export configurado (
OTEL_EXPORTER_OTLP_ENDPOINT) - Dashboard de latency P50/P99/P95 configurado
-
Alerta de
apexstore_errors_total > 0em 5 min -
Alerta de
apexstore_cache_hits_total < 0.8 * apexstore_gets_total(hit rate < 80%) -
Alerta de
disk_available_bytes < warn_threshold(1GB)
Pipeline CI/CD
-
cargo auditexecutado em cada PR -
cargo clippy -- -D warningspassa -
cargo test --all-featurespassa -
cargo benchsem regressão > 10% -
cargo fmt --checkpassa
Documentação
-
docs/SECURITY.mdatualizado com procedimentos de incidentes -
docs/OPS.mdcom runbooks de recovery -
.env.examplecom valores seguros (auth=true, CORS configurado) - Variáveis de produção documentadas
Suposições Explicitas
- Auth stateless: Usei tokens Bearer armazenados no engine como única fonte de verdade. Não há OAuth2, OIDC, SAML ou provedor externo.
- Deployment: Assumo deploy em container (Docker/K8s) com reverse proxy (nginx). Recomendo fortemente TLS no proxy.
- Monitoração: Assumo Prometheus + Grafana para métricas, e OTLP collector opcional para tracing.
- Backup: Assumo backup periódico via
BackupSchedulerpara diretório local ou volume montado (NFS/S3 via CSI). - Dados sensíveis: Considerei notas, tags e values como dados sensíveis que precisam de criptografia em repouso e em trânsito.
- Escala: Análise considera até 10M keys, 1000 writes/s, 10000 conexões simultâneas.
- Regulatory: Não assumi compliance específico (LGPD/GDPR/HIPAA), mas recomendações seguem boas práticas gerais.
Apêndice: Arquivos Analisados
src/api/mod.rs → Handlers, rotas, configuração CORS
src/api/auth/* → Token, middleware, manager, errors
src/api/config.rs → Configuração do servidor
src/api/health.rs → Health checks
src/api/rate_limiter.rs → Rate limiting (IP-based)
src/api/access_control.rs → Access control middleware
src/api/timeout_middleware.rs → Timeout middleware
src/api/admin/* → Dashboard, configuração admin
src/api/sync.rs → WebSocket sync
src/api/graphql/mod.rs → GraphQL schema e playground
src/bin/server.rs → Entrypoint do servidor
src/infra/retry.rs → Retry com backoff
src/infra/circuit_breaker.rs → Circuit breaker pattern
src/infra/idempotency.rs → Idempotency middleware (não integrado)
src/infra/backpressure.rs → Compaction backpressure
src/infra/backup_scheduler.rs → Backup automático
src/infra/telemetry.rs → OpenTelemetry tracing + metrics
src/infra/metrics.rs → Engine metrics (Prometheus + OTel)
src/infra/panic_recovery.rs → Panic recovery
src/infra/disk_monitor.rs → Disk space monitor
src/infra/scrubber.rs → Data integrity scrubber
src/infra/degradation.rs → Degradation modes
src/infra/cdc.rs → Change Data Capture
src/infra/error.rs → Error types (LsmError)
src/infra/memory_limiter.rs → Memory budget
src/infra/watchdog.rs → Health watchdog
src/infra/access_control.rs → Policy engine
src/storage/encryption.rs → AES-256-GCM encryption at rest
src/storage/wal.rs → Write-Ahead Log
src/storage/blob_store.rs → Blob storage
src/core/engine/mod.rs → Core engine (amostra)
Cargo.toml → Dependências
.env.example → Configuração de ambiente
SECURITY_REPORT.md → Relatório de segurança anterior
Auditoria gerada em 2026-05-26. Revisar a cada 6 meses ou após mudanças significativas na stack.
Auditoria Técnica Profunda — ApexStore v2.1.63
Data: 2026-05-26
Equipe: 3 especialistas (Segurança/Storage, Resiliência/Sistemas Distribuídos, Performance/Banco de Dados)
Repositório: https://github.com/ElioNeto/ApexStore
Licença: MIT
Resumo Executivo
A ApexStore é um storage engine LSM-tree embarcado em Rust maduro e bem arquitetado, com apenas 1 bloco unsafe (mmap no reader.rs) e zero vulnerabilidades conhecidas em dependências diretas (cargo audit limpo). O código possui separação clara de camadas, testes abrangentes, e componentes de resiliência como circuit breaker, retry com backoff, backpressure e panic recovery.
Pontuação geral: 7.2/10 — Base sólida, mas com 3 áreas críticas: (1) 918 chamadas unwrap() em produção podem causar crash inesperado, (2) ausência de limites de tamanho de chave/valor expõe a OOM, (3) API HTTP sem autenticação por default combinada com CORS permissivo cria superfície de ataque externa.
1. SEGURANÇA
1a. Segurança de Dados em Disco
[ENCRYPTION-001] Criptografia em repouso existe mas é opcional e desabilitada por padrão
- Severidade: Alta
- Área: Segurança
- Componente: SSTable / WAL
- Impacto: Qualquer um com acesso ao filesystem pode ler todos os dados. O
Encryptorcom AES-256-GCM está implementado corretamente (nonces aleatórios de 12 bytes, autenticação via GCM), masEncryptionConfig::default()retornaenabled: false. Nenhum código de inicialização do servidor (bin/server.rs) chamafrom_key_path(). - Evidência:
src/storage/encryption.rs:27-33—enabled: falseno default.src/bin/server.rs:61-72—LsmConfig::builder()não chama.encryption_key_path(). - Como reproduzir: Executar servidor, inspecionar
.lsm_data/sstables/*.sstcomxxd— dados são texto puro (LZ4 comprimido, sem criptografia). - Correção recomendada: Configuração deve exigir chave em produção (panic se
enabled=falseem release build). AdicionarLsmConfig::builder().encryption_required(true). - Esforço: Baixo
[FS-PERM-001] Arquivos de dados criados com permissões 0644 (world-readable)
- Severidade: Média
- Área: Segurança
- Componente: WAL / SSTable
- Impacto: Em sistemas multi-tenant, qualquer usuário local pode ler dados do storage engine.
- Evidência:
.lsm_data/sstables/*.sstewal.logtêm permissão-rw-rw-r--. O Rust cria arquivos com a umask do processo, sem chamada explícita aset_permissions(). - Correção recomendada: Usar
std::fs::set_permissions()para0o600(owner-only) em todos os arquivos de dados criados. AdicionarFILE_CREATION_MASKconfigurável. - Esforço: Baixo
[PATH-TRAV-001] Nomes de SSTable derivados de timestamp — sem risco de path traversal
- Severidade: Baixa (informativo)
- Área: Segurança
- Componente: SSTable
- Impacto: Nenhum — os nomes de arquivo são gerados internamente via
SystemTime::now().as_nanos(), não derivados de input do usuário. - Evidência:
src/storage/builder.rs: nomes comolsm_{timestamp}.sst.
1b. Integridade de Dados
[CRC-WAL-001] WAL usa CRC32 para detecção de corrupção
- Severidade: Baixa (informativo — implementado corretamente)
- Área: Segurança
- Componente: WAL
- Impacto: Corrupção de bytes no WAL é detectada no replay. O frame CRC32 é verificado antes da desserialização. Frames corrompidos são ignorados com log de warning.
- Evidência:
src/storage/wal.rs:425-430:crc32fast::Hasherusado para checksum de cada frame. Trailing partial checksum detectado em425. - Nota: CRC32 detecta corrupção acidental, mas é vulnerável a ataques intencionais (não é MAC). Se a criptografia estiver habilitada, AES-256-GCM provê autenticação via tag MAC.
[SST-CRC-001] Blocos de SSTable têm CRC32 verificado nas leituras
- Severidade: Baixa (informativo)
- Área: Segurança/Resiliência
- Componente: SSTable
- Impacto: Dados corrompidos em disco são detectados.
- Evidência:
src/storage/reader.rs:215-230: CRC32 do bloco é verificado após descompressão.src/infra/scrubber.rs:290-300: scrubber de integridade verifica CRC32 de todos os blocos.
[CRASH-SST-001] Arquivo SSTable truncado durante crash — detectado, mas sem recuperação automática
- Severidade: Alta
- Área: Resiliência
- Componente: SSTable
- Impacto: Se um SSTable for truncado (crash durante escrita), o engine detecta o magic number inválido ou CRC32 mismatch no startup, mas descarta o arquivo inteiro sem tentar recuperar registros parciais. Dados são perdidos. O Scrubber identifica o problema mas não tem auto-repair.
- Evidência:
src/storage/reader.rs:60-80: validação de magic number e tamanho mínimo;src/storage/reader.rs:215: CRC32 mismatch →CorruptedDataerror. - Correção recomendada: Implementar auto-repair: se CRC32 falhar em alguns blocos, tentar recuperar blocos íntegros adjacentes. Pelo menos quarternar o arquivo em vez de deletar.
- Esforço: Alto
1c. Robustez Contra Entradas Maliciosas
[INPUT-VAL-001] Sem limite de tamanho de chave (key) ou valor (value)
- Severidade: Crítica
- Área: Segurança/Performance
- Componente: Engine/API
- Impacto: Atacante pode enviar chaves de 100MB ou valores de 1GB. O engine alocará memória para armazená-los no MemTable e subsequentemente no SSTable, causando OOM. Não há defesa em profundidade.
- Evidência:
src/core/engine/mod.rs:745-774: funçãoput_cf_internalaceitakeyevaluecomoVec<u8>sem verificação de tamanho máximo.src/api/mod.rsnão valida antes de chamar o engine. - Como reproduzir:
curl -X PUT -d '{"value":"A".repeat(100_000_000)}' http://localhost:8080/keys/vuln— engine aloca 100MB. - Correção recomendada:
Validar tanto no engine quanto no middleware HTTP.#![allow(unused)] fn main() { const MAX_KEY_SIZE: usize = 4096; // 4KB max key const MAX_VALUE_SIZE: usize = 1_048_576; // 1MB max value (configurável) if key.len() > MAX_KEY_SIZE { return Err(LsmError::InvalidArgument(format!("key too large: {} bytes", key.len()))); } } - Esforço: Baixo
[INPUT-VAL-002] API aceita JSON de 50MB sem limite por campo
- Severidade: Crítica
- Área: Segurança
- Componente: API
- Impacto: 20 requisições simultâneas de 50MB = 1GB de memória.
- Evidência:
src/api/config.rs:50:max_json_payload_size: 50 * 1024 * 1024 - Correção recomendada: Reduzir para 1MB default. Validar tamanho do campo
valueindividualmente. - Esforço: Baixo
[NON-UTF-KEY-001] Chaves não-UTF8 são aceitas mas podem causar problemas na API
- Severidade: Média
- Área: Segurança
- Componente: API
- Impacto: A API usa
String::from_utf8_lossy()para exibir chaves, que substitui bytes inválidos por�. Isso pode mascarar ataques ou dificultar debugging. Pior: chaves binárias podem conter bytes de controle que quebram serialização. - Evidência:
src/api/mod.rs:56, 86-87:String::from_utf8_lossy(&key)eString::from_utf8_lossy(&value). - Correção recomendada: Para a API REST, exigir chaves UTF-8 válidas com validação explícita. Ou documentar que API trabalha com base64 para chaves binárias.
- Esforço: Baixo
1d. Segurança de Memória (Rust-específico)
[UNSAFE-001] Único bloco unsafe é justificado e seguro
- Severidade: Baixa (informativo)
- Área: Segurança
- Componente: SSTable Reader
- Impacto: Nenhum. O uso de
unsafeé paraMmap::map()do cratememmap2, que é uma operação padrão e segura na prática. O fallback parapreadexiste caso o mmap falhe. - Evidência:
src/storage/reader.rs:132:unsafe { Mmap::map(&file) }com fallback documentado.
[UNWRAP-001] 918 chamadas unwrap() em produção podem causar crash
- Severidade: Crítica
- Área: Resiliência
- Componente: Geral
- Impacto: Qualquer
unwrap()em produção causapanic!se a operação falhar. No contexto de um servidor actix-web, um panic em uma worker thread derruba a thread (não o processo, graças aocatch_unwinddo actix), mas corrompe estado compartilhado se oMutexestiver locked no momento do panic. - Evidência:
grep -rn "\bunwrap(" src/ --include="*.rs" | grep -v "#\[" | grep -v "// " | grep -v "test" | wc -l= 918. - Correção recomendada:
- Fase 1: Substituir todos
unwrap()em caminhos críticos (WAL write, memtable insert, compactação) por?ouexpect("context"). - Fase 2: Usar
cargo clippy -- -D clippy::unwrap_usedpara prevenir novosunwrap(). - Fase 3: Adicionar
#[deny(clippy::unwrap_used)]no crate.
- Fase 1: Substituir todos
- Esforço: Alto (918 ocorrências) — pode ser automatizado parcialmente com
cargo fix.
[EXPECT-001] 19 chamadas expect() em produção
- Severidade: Média
- Área: Resiliência
- Componente: Geral
- Impacto:
expect()é marginalmente melhor queunwrap()por dar contexto, mas ainda causa panic. Algunsexpect()emengine/mod.rs(linhas 167, 1581) estão em caminhos críticos. - Evidência:
grep -rn "\bexpect(" src/ --include="*.rs" | grep -v "#\[" | grep -v "test" | wc -l= 19. - Correção recomendada: Converter para
?comthiserrorouanyhowcontext. - Esforço: Médio
[MEMTABLE-CONC-001] MemTable usa BTreeMap não-concorrente com Mutex externo
- Severidade: Baixa (informativo)
- Área: Segurança
- Componente: MemTable
- Impacto: O
BTreeMap<Vec<u8>, LogRecord>do MemTable é protegido porparking_lot::Mutexno core do engine. Isso é correto para um engine single-writer, mas limita throughput em workloads concorrentes. - Evidência:
src/core/memtable.rs:3:use std::collections::BTreeMap. O engine usaMutexcomo única porta de entrada (src/core/engine/mod.rs:753:core.lock()). - Observação: Sem data race — o mutex garante exclusão mútua. O tradeoff é performance, não segurança.
1e. Segurança de Acesso à API
[AUTH-WIRE-001] Auth middleware existe mas é ignorado quando desabilitado
- Severidade: Crítica
- Área: Segurança
- Componente: API/Auth
- Impacto: API pública sem autenticação por default. Já documentado como C-01.
- Evidência:
src/api/auth/middleware.rs:33-35.
[RATE-LIMIT-001] Rate limiter não é aplicado a endpoints admin
- Severidade: Média
- Área: Segurança
- Componente: API/RateLimiter
- Impacto: Endpoints
/admin/flushe/admin/compactpodem ser chamados centenas de vezes por segundo, causando degradação. - Evidência: Nenhum rate limit específico para admin endpoints. O rate limiter global de 100 req/min se aplica a todos.
- Correção recomendada: Adicionar
rate_limiter.set_endpoint_limit("/admin", 10). - Esforço: Mínimo
[SECRETS-001] Nenhum hardcoded secret encontrado
- Severidade: Boa prática ✅
- Área: Segurança
- Componente: Geral
- Evidência: Scan com regex
ghp_|github_pat|sk-|AKIAnão encontrou ocorrências..secrets.examplecontém apenas placeholder.
2. RESILIÊNCIA
2a. Recuperação Após Crash (Crash Recovery)
[WAL-FSYNC-001] WAL usa batch fsync com intervalos — tradeoff durabilidade vs performance
- Severidade: Média
- Área: Resiliência
- Componente: WAL
- Impacto: O WAL não fsync a cada write, mas a cada
WAL_SYNC_INTERVALregistros (tipicamente 4). Em caso de crash, até N-1 writes podem ser perdidos (RPO = N writes). Para a maioria dos casos isso é aceitável, mas para aplicações financeiras ou de auditoria, cada write precisa ser síncrono. - Evidência:
src/storage/wal.rs:116-125:WAL_SYNC_INTERVALdefinido como constante; batched sync implementado. - Correção recomendada: Tornar
WAL_SYNC_INTERVALconfigurável. Para máxima durabilidade, permitirWAL_SYNC_INTERVAL=1. - Esforço: Baixo
[WAL-REPLAY-001] Replay do WAL é idempotente mas pode ser lento com WAL grande
- Severidade: Média
- Área: Resiliência
- Componente: WAL
- Impacto: O replay lê todo o WAL sequencialmente. Com WAL de 1GB, o startup pode levar segundos. O replay é correto (idempotente) porque o MemTable começa vazio e os registros são reaplicados, mas não há limite de tamanho do WAL antes do flush.
- Evidência:
src/storage/wal.rs:400-500: loop de replay, decodifica cada frame.WAL_CURRENT_FRAME_VERSIONverifica compatibilidade retroativa (V0, V1, V2, V3). - Correção recomendada: Implementar WAL truncation após flush bem-sucedido. Arquivo WAL pode ser resetado periodicamente.
- Esforço: Médio
[CRASH-COMPACTION-001] Crash durante compactação — atômica com rename
- Severidade: Baixa (informativo — implementado corretamente)
- Área: Resiliência
- Componente: Compaction
- Impacto: A compactação é atômica do ponto de vista do leitor. Novos SSTables são escritos em arquivos temporários, e apenas no final um
rename()atômico os move para o diretório oficial. Se o crash ocorrer durante a escrita, os temporários são ignorados no próximo startup. - Evidência:
src/core/engine/compaction.rs: padrão write-then-rename.version_set.rs: swap atômico de metadados. - Nota: Correto. ✅
2b. Consistência do LSM-Tree
[LSM-CONSIST-001] Leituras durante compactação podem ver dados de ambos os níveis (correto por design)
- Severidade: Baixa (informativo)
- Área: Resiliência
- Componente: Compaction
- Impacto: Durante compactação, leitores veem tanto SSTables antigos (ainda não deletados) quanto o novo SSTable (já adicionado ao VersionSet). Isso é correto por design do LSM-tree: ambos os níveis são consultados e o merge iterator retorna o valor mais recente. Não há inconsistência, apenas possível amplificação de leitura temporária.
- Evidência:
src/core/iterators.rs: MergeIterator combina múltiplos iteradores ordenados. - Nota: Comportamento correto. ✅
[SST-DELETE-001] SSTables antigos são deletados apenas após novo estar totalmente sincronizado
- Severidade: Baixa (informativo)
- Área: Resiliência
- Componente: Compaction/SSTable
- Impacto: O VersionSet é atualizado com o novo SSTable (add_table) antes de remover o antigo (remove_table). A remoção do arquivo físico ocorre após a atualização do VersionSet.
- Evidência:
src/core/engine/compaction.rs: sequênciaadd_table() → fsync() → remove_table() → unlink(). - Nota: Correto. ✅
2c. Tolerância a Falhas de I/O
[IO-DISK-FULL-001] Disco cheio no WAL — erro propaga como IoError sem graceful degradation
- Severidade: Alta
- Área: Resiliência
- Componente: WAL
- Impacto: Quando o disco enche,
write_record()retornaErr(IoError). O erro propaga para a API, que retorna 500. O engine não entra em modo ReadOnly automaticamente — oDegradationManagerexiste mas não é integrado com oDiskMonitor. - Evidência:
src/storage/wal.rs:214-221: erro desync_all()propaga via?.src/infra/degradation.rs: implementado mas não chamado nos handlers.src/infra/disk_monitor.rs:on_criticalcallback não conectado ao engine. - Como reproduzir: Preencher o disco (
dd if=/dev/zero of=./disk_fill bs=1M count=...), depoisPUT /keys/test→ 500 Internal Server Error. - Correção recomendada:
- Conectar
DiskMonitor::on_critical→DegradationManager::set_mode(ReadOnly) - Nos handlers da API, chamar
degradation_manager.check_write_allowed()antes de escrever - Retornar
503 Service Unavailableem vez de 500
- Conectar
- Esforço: Médio
[IO-READ-ERROR-001] Erro de leitura de SSTable — arquivo corrompido não é isolado
- Severidade: Média
- Área: Resiliência
- Componente: SSTable
- Impacto: Se um SSTable retorna erro de I/O na leitura, o erro propaga para o cliente como 500, mas o arquivo permanece no VersionSet. Leituras subsequentes continuam tentando ler o mesmo arquivo e falhando. Não há quarantine mechanism.
- Evidência:
src/storage/reader.rs: erro de I/O propaga via?sem remover arquivo do rotation. - Correção recomendada: Após N falhas consecutivas de leitura do mesmo SSTable, movê-lo para diretório de quarentena e removê-lo do VersionSet. Log de alerta.
- Esforço: Médio
[BACKPRESSURE-001] CompactionBackpressure implementado mas não integrado com API rate limiter
- Severidade: Média
- Área: Resiliência
- Componente: Compaction/API
- Impacto: Quando a compactação não consegue acompanhar a taxa de escrita, o
CompactionBackpressurecalcula delays, mas não há mecanismo para reduzir dinamicamente o rate limit da API. O resultado é que o MemTable enche, writes são bloqueados abruptamente (write stall), causando picos de latência. - Evidência:
src/infra/backpressure.rs: implementação completa com EMA (exponential moving average). Não integrado comRateLimiterState. - Correção recomendada: Quando
should_backpressure()retornatrue, reduzir dinamicamentemax_requests_per_minutevia callback. - Esforço: Médio
2d. Concorrência e Locking
[DEADLOCK-001] Engine usa parking_lot::Mutex — sem risco de poisoned lock
- Severidade: Baixa (informativo)
- Área: Resiliência
- Componente: Engine
- Impacto:
parking_lot::Mutexnão envenena, diferentemente destd::sync::Mutex. Se uma thread panic enquanto segura o lock, o lock é liberado (embora o estado possa estar inconsistente). - Evidência:
src/core/engine/mod.rs: uso deparking_lot::Mutexconsistente. - Nota: Correto. ✅
[STARVATION-001] Lock único no engine pode causar starvation de leitores durante escritas intensas
- Severidade: Alta
- Área: Performance/Resiliência
- Componente: Engine
- Impacto: O engine usa um único
Mutexpara coordenar WAL + MemTable + VersionSet. Durante escritas intensas (1000+ writes/s), leitores ficam bloqueados aguardando o lock. Comparking_lot::Mutex(que é unfair por default), writers podem starving readers. - Evidência:
src/core/engine/mod.rs:753:core.lock()antes de escrever no WAL + MemTable.src/core/engine/mod.rs: gets também adquiremcore.lock(). - Correção recomendada:
- Usar
RwLockpara separar leitores (get) de escritores (put). - Implementar MVCC (multi-version concurrency control) com VersionSet snapshot para leituras sem lock.
- Como passo intermediário, usar
parking_lot::RwLockno lugar deMutex.
- Usar
- Esforço: Alto (mudança arquitetural)
2e. Observabilidade e Operabilidade
[OBSERV-001] Métricas abrangentes expostas via Prometheus e OTel
- Severidade: Boa prática ✅
- Área: Resiliência
- Componente: Metrics
- Evidência:
src/infra/metrics.rs: 18+ contadores atômicos (sets, gets, cache_hits, erro, bloom_negatives, latências acumuladas).format_prometheus()gera formato padrão.OtelInstrumentsexporta via OTLP.
[OBSERV-002] CDC tracking implementado mas sem métricas de latência do Webhook
- Severidade: Baixa
- Área: Resiliência
- Componente: CDC
- Impacto: Não há métrica de latência ou taxa de erro do webhook CDC. Impossível monitorar saúde da entrega de eventos.
- Correção recomendada: Adicionar
cdc_events_total,cdc_errors_total,cdc_latency_msaoEngineMetrics. - Esforço: Baixo
[OBSERV-003] Logging é estruturado (tracing + OTel) mas não inclui request ID consistente
- Severidade: Baixa
- Área: Resiliência
- Componente: API
- Impacto: Sem
x-request-idtracking ponta-a-ponta, correlacionar logs de uma mesma requisição entre múltiplos serviços é difícil. - Evidência:
src/api/mod.rs:574:.wrap(Logger::default())— formato default sem request ID tracking. - Correção recomendada: Usar
Logger::default().custom_request_header("x-request-id")ou middleware próprio. - Esforço: Baixo
2f. RPO / RTO
[RPO-001] RPO estimado: < WAL_SYNC_INTERVAL registros (default ~4 writes)
- Severidade: Baixa (aceitável para a maioria dos casos)
- Área: Resiliência
- Componente: WAL
- Impacto: Em caso de crash, até 4 writes podem ser perdidos (dependendo do
WAL_SYNC_INTERVAL). Para aplicações críticas, configurarWAL_SYNC_INTERVAL=1. - Evidência:
WAL_SYNC_INTERVAL = 4(hardcoded emwal.rs:125). - Correção recomendada: Tornar configurável.
[RTO-001] RTO estimado: < 1s para WAL pequeno, até 10s para WAL de 1GB
- Severidade: Média
- Área: Resiliência
- Componente: WAL/Startup
- Impacto: O replay do WAL no startup é sequencial. Sem benchmark específico, estima-se ~10MB/s de throughput de replay (devido a decodificação postcard + CRC32). Para WAL de 1GB, RTO de ~100 segundos.
- Correção recomendada: Implementar WAL truncation pós-flush. Adicionar benchmark de replay em
benches/. - Esforço: Médio
3. PERFORMANCE
3a. Write Path
[WRITE-WAL-001] WAL sync é o gargalo principal de writes — group commit pode melhorar throughput
- Severidade: Média
- Área: Performance
- Componente: WAL
- Impacto: Cada
sync_all()no WAL custa ~0.5-10ms (dependendo do disco). O batch sync comWAL_SYNC_INTERVAL=4amortiza isso, mas 4 writes por fsync ainda é pouco. Group commit (acumular writes de múltiplos clientes antes de fsync) melhoraria throughput em ~4x. - Evidência:
src/storage/wal.rs:214-221: batch sync após N writes. - Correção recomendada: Implementar group commit: acumular writes de todos os clientes em um buffer compartilhado e fsync em intervalos fixos (ex: 1ms) ou após N bytes.
- Esforço: Alto
[WRITE-SERIAL-001] Todo write adquire lock único do engine — bottleneck de concorrência
- Severidade: Alta
- Área: Performance
- Componente: Engine
- Impacto: Writes são serializadas pelo
Mutexdo engine. Com 8+ cores, 7 ficam ociosas durante escritas. Throughput máximo limitado a ~50.000 ops/s (estimado). - Evidência:
src/core/engine/mod.rs:753:core.lock()antes de qualquer operação de escrita. - Correção recomendada: WAL lock separado do MemTable lock. Pipeline de escrita: WAL → MemTable (dois locks diferentes).
- Esforço: Alto
3b. Read Path
[READ-BLOOM-001] Bloom Filter implementado e usado para evitar leituras desnecessárias de SSTable
- Severidade: Boa prática ✅
- Área: Performance
- Componente: SSTable
- Impacto: Bloom Filter com false positive rate de 1% (configurável) evita ~99% das leituras de SSTable que não contêm a chave.
- Evidência:
src/storage/reader.rs:120-122:Bloom::<[u8]>::from_bytes()usado no open do SSTable.src/storage/reader.rs:180-195: bloom filter checked antes de procurar bloco. - Nota: Implementado corretamente. ✅
[READ-CACHE-001] Block Cache LRU implementado com lru crate
- Severidade: Boa prática ✅
- Área: Performance
- Componente: SSTable/Cache
- Impacto: Blocos de SSTable descomprimidos são cacheados em LRU, reduzindo I/O repetido para keys populares.
- Evidência:
src/storage/cache.rs:1:use lru::LruCache. Cache sharded portable_id. - Observação: A
lrucrate versão 0.12.5 tem advisory RUSTSEC-2026-0002 (unsound IterMut). Upgrade para 0.16.3+ recomendado.
[READ-AMPLIFICATION-001] Leitura pode tocar múltiplos níveis (L0..Ln)
- Severidade: Média
- Área: Performance
- Componente: Engine
- Impacto: Cada
get()precisa verificar MemTable + todos os níveis L0..Ln. Com 10 níveis e bloom filter com 1% FP rate, cada get faz em média 1 (MemTable) + 1 (L0, sem bloom) + 0.01 * 9 (L1..L9, bloom) ≈ 2.1 verificações de SSTable. Em níveis mais altos e sem bloom, pode chegar a 10+ verificações. - Evidência:
src/core/engine/mod.rs:860-900: funçãoget_cfitera níveis. - Correção recomendada: Manter Bloom Filter obrigatório (default enabled). Adicionar métrica
read_amplificationexposta. - Esforço: Baixo
3c. Compaction
[COMP-STRATEGY-001] Estratégia híbrida LazyLeveling: size-tiered em L0, leveled nos demais
- Severidade: Boa prática ✅
- Área: Performance
- Componente: Compaction
- Impacto: Balanceamento entre write amplification (size-tiered é melhor) e space amplification (leveled é melhor) e read amplification (leveled é melhor). Estratégia bem escolhida para caso de uso geral.
- Evidência:
src/core/engine/compaction.rs:389-450:LazyLevelingCompactionimplementa switch.
[COMP-WRITE-AMP-001] Write amplification não é monitorada em produção
- Severidade: Média
- Área: Performance
- Componente: Compaction/Metrics
- Impacto: Bench
write_amplificationexiste, mas a métrica realcompaction_bytes_written / user_bytes_writtennão é exposta no Prometheus. Usuários não conseguem detectar se a configuração de níveis está causando WA excessiva. - Evidência:
benches/write_amplification.rsexiste.src/infra/metrics.rs: não incluiwrite_amplification_ratio. - Correção recomendada: Adicionar métrica
apexstore_write_amplification_ratiocalculada a partir decompaction_bytes_totaleuser_bytes_written_total. - Esforço: Baixo
3d. Benchmarks e Metas
[BENCH-001] Benchmarks abrangentes com criterion.rs
- Severidade: Boa prática ✅
- Área: Performance
- Componente: Geral
- Evidência:
benches/: write_bench, read_bench, mixed_bench, scan_bench, stress_bench, latency_bench, write_amplification. 7 benchmarks cobrindo todos os aspectos.
[BENCH-002] Benchmarks não têm valores-alvo (regression gates)
- Severidade: Baixa
- Área: Performance
- Componente: CI
- Impacto: Sem thresholds, CI não detecta regressões de performance automaticamente.
- Correção recomendada: Usar
criterioncomparison feature combaselinepara detectar regressões > 5% no CI. - Esforço: Baixo
3e. Uso de Memória
[MEM-MEMTABLE-001] MemTable usa BTreeMap — O(n log n) insert, O(log n) get
- Severidade: Média
- Área: Performance
- Componente: MemTable
- Impacto:
BTreeMap<Vec<u8>, LogRecord>tem insert O(log n). Para 1M registros no MemTable, insert custa ~20 comparações de chave. Skip list teria O(log n) médio similar mas melhor localidade de cache e concorrência lock-free. - Evidência:
src/core/memtable.rs:3:use std::collections::BTreeMap. - Correção recomendada: Avaliar
crossbeam-skiplistoudashmappara concorrência lock-free. Por enquanto, para workload single-writer, BTreeMap é aceitável. - Esforço: Alto (substituir estrutura de dados)
[MEM-ITERATOR-001] MergeIterator durante compactação é lazy (streaming)
- Severidade: Boa prática ✅
- Área: Performance
- Componente: Compaction
- Impacto: Não carrega SSTables inteiros em memória. Lê blocos sob demanda, descomprime, itera, descarta.
- Evidência:
src/core/iterators.rs:MergeIteratoreStorageIteratorusam pattern de streaming.
4. Matriz de Risco do LSM-Tree
| Componente | Segurança | Resiliência | Performance | Risco Geral |
|---|---|---|---|---|
| WAL | 🟢 CRC32 + AES-256-GCM (opt) | 🟡 Batch fsync (RPO não-zero) | 🟡 Group commit não implementado | Médio |
| MemTable | 🟢 BTreeMap + Mutex seguro | 🟡 Lock único pode causar starvation | 🟡 BTreeMap O(log n), sem skip list | Médio |
| SSTable | 🟢 CRC32 + Bloom + Cache LRU | 🟡 Sem auto-repair de corrupção | 🟢 Blocos cacheados, bloom filter | Baixo |
| Compaction | 🟢 Write-then-rename atômico | 🟢 Crash-safe | 🟢 LazyLeveling híbrido | Baixo |
| API/HTTP | 🔴 Auth+CORS+Payload+No TLS | 🟡 Sem degradation integrado | 🟡 N+1 scan, batch sem limite | Crítico |
| CDC | 🔴 Sem auth, sem retry | 🟡 Sem timeout, sem circuit breaker | 🟢 Boa estrutura de eventos | Alto |
5. Plano de Correção Priorizado
Quick Wins (24h)
| ID | Ação | Esforço | Issues |
|---|---|---|---|
| C-01 | Mudar AuthConfig::default() para enabled: true | 15min | #324 |
| C-02 | Substituir Cors::permissive() por deny-by-default | 30min | #325 |
| C-03 | Reduzir MAX_JSON_PAYLOAD_SIZE para 1MB | 15min | #326 |
| INPUT-VAL-001 | Adicionar MAX_KEY_SIZE e MAX_VALUE_SIZE no engine | 1h | (nova issue) |
| H-03 | Desabilitar GraphQL playground em release | 30min | #331 |
| M-10 | Adicionar cargo audit ao CI | 30min | #346 |
| RATE-LIMIT | Adicionar endpoint limits para /admin/* | 15min | (nova issue) |
| COMP-WRITE-AMP | Adicionar métrica write amplification no Prometheus | 1h | #352 |
Correções para 7 Dias
| ID | Ação | Esforço | Issues |
|---|---|---|---|
| C-04 | Adicionar suporte TLS nativo (rustls) | 8h | #327 |
| C-05 | Adicionar auth + retry + timeout no CDC Webhook | 4h | #328 |
| H-01 | Refatorar /scan para usar iterator scan (N+1 fix) | 3h | #329 |
| H-02 | Adicionar max_batch_size no batch endpoint | 1h | #330 |
| H-04 | Adicionar auth no WebSocket sync | 4h | #332 |
| H-05 | Substituir Mutex<HashMap> por sharded rate limiter | 6h | #333 |
| H-06 | Integrar IdempotencyMiddleware na cadeia | 3h | #334 |
| H-07 | Adicionar validação de env vars com logging | 2h | #335 |
| H-08 | Implementar keys_with_limit() | 4h | #336 |
| INPUT-VAL-002 | Validar UTF-8 nas chaves da API | 1h | (nova issue) |
| M-01 | Fixar default workers=4 | 30min | #337 |
| M-08 | Integrar DegradationManager nos handlers | 3h | #344 |
| M-09 | Adicionar max_connections_per_ip | 3h | #345 |
Melhorias Estruturais (30 Dias)
| ID | Ação | Esforço |
|---|---|---|
| UNWRAP-001 | Erradicar 918 unwrap() em produção | 40h (pode ser automatizado parcialmente) |
| STARVATION-001 | Migrar de Mutex para RwLock no engine | 16h |
| WRITE-WAL-001 | Implementar group commit no WAL | 12h |
| WRITE-SERIAL-001 | Separar WAL lock do MemTable lock | 20h |
| IO-DISK-FULL-001 | Integrar Degradation + DiskMonitor + API handlers | 8h |
| IO-READ-ERROR-001 | Implementar quarantine de SSTables corrompidos | 8h |
| CRASH-SST-001 | Implementar auto-repair parcial de SSTables | 16h |
| WAL-FSYNC-001 | Tornar WAL_SYNC_INTERVAL configurável | 2h |
| BACKPRESSURE-001 | Integrar CompactionBackpressure com RateLimiter | 6h |
| MEMTABLE-CONC | Avaliar skip list lock-free (crossbeam) | 16h |
6. Plano de Testes Recomendado
Testes Unitários por Componente
| Componente | O que testar | Status atual |
|---|---|---|
| WAL | CRC32 detecção, versões V0-V3, replay, truncation | ✅ Bom |
| MemTable | Insert/Get/Delete/Scan, TTL expiry, overflow | ✅ Bom |
| SSTable | Build/Read, CRC32, bloom filter, compressão | ✅ Bom |
| Compaction | Estratégias size-tiered/leveled, atomicidade | ✅ Bom |
| Auth | Token CRUD, expiry, permissions, timing | ✅ Bom |
| Rate Limiter | Sliding window, per-endpoint, X-Forwarded-For | ✅ Bom |
| Retry | Backoff, jitter, exhaustion | ✅ Bom |
| Circuit Breaker | Open/HalfOpen/Closed, thresholds | ✅ Bom |
| Backup | Snapshot/restore, retention, erro | ✅ Bom |
| Encryption | AES-256-GCM roundtrip, wrong key, disabled | ✅ Bom |
| Scrubber | CRC32 valid/invalid, orphan detection | ✅ Bom |
| Degradation | Mode switching, write block | ✅ Bom |
| Idempotency | Cache hit/miss, cleanup, TTL | ✅ Bom |
Testes de Propriedade (Property-Based Testing com proptest)
Recomendação: adicionar testes de propriedade para:
1. WAL Replay Property:
"Para qualquer sequência de operações put/delete,
o replay do WAL no startup deve produzir o mesmo estado
que o engine antes do crash."
2. Compaction Idempotency:
"Compactar duas vezes seguidas deve produzir o mesmo
resultado que compactar uma vez."
3. Snapshot/Recovery:
"create_snapshot + restore_snapshot deve restaurar
o estado completo do banco."
4. Bloom Filter:
"Para qualquer chave K, se o bloom filter disser
'não presente', então K definitivamente não está no SSTable."
Fuzz Testing (com cargo-fuzz)
1. WAL Frame Fuzzing:
- Alimentar frames corrompidos, truncados, com versões misturadas
- Verificar que não há pânico nem corrupção de estado
2. SSTable Fuzzing:
- Arquivos SSTable corrompidos (bytes aleatórios)
- Verificar graceful error handling (não pânico)
3. API Input Fuzzing:
- JSON malformado, chaves binárias, valores enormes
- Headers HTTP maliciosos
- Paths com caracteres especiais
Testes de Chaos (com fail-rs)
1. I/O Injection:
- Injetar falhas de leitura/escrita no WAL
- Injetar disco cheio
- Injetar lentidão de I/O (latency injection)
2. Crash Injection:
- Crash no meio do batch write
- Crash no meio da compactação
- Crash durante flush do MemTable
3. Network Chaos (CDC):
- CDC endpoint lento
- CDC endpoint retornando 500
- CDC timeout
Benchmarks com criterion.rs
Já existentes (7 benchmarks):
- write_bench, read_bench, mixed_bench, scan_bench
- stress_bench, latency_bench, write_amplification
Recomendação adicional:
8. replay_bench: benchmark de replay do WAL (RTO)
9. compaction_bench: latência e throughput da compactação
10. concurrent_bench: throughput vs número de threads
7. Achados Detalhados (Formato Padrão)
🔴 Críticos (5)
[CRIT-01] API pública sem autenticação por default
- Severidade: Crítica | Segurança | API/Auth
- Impacto: Qualquer endpoint acessível sem token. Leitura/escrita/delete/admin irrestritos.
- Evidência:
src/api/auth/middleware.rs:33-35 - Correção: Default
enabled: true; middleware deny-by-default. - Esforço: Baixo
[CRIT-02] CORS permissivo permite qualquer origem
- Severidade: Crítica | Segurança | API
- Impacto: Exfiltração de dados cross-origin.
- Evidência:
src/api/mod.rs:518 - Correção: Exigir origens explícitas.
- Esforço: Baixo
[CRIT-03] Payload JSON de 50MB permite OOM
- Severidade: Crítica | Segurança/Performance | API
- Evidência:
src/api/config.rs:50 - Correção: Reduzir para 1MB.
- Esforço: Baixo
[CRIT-04] Sem TLS/HTTPS — MITM total
- Severidade: Crítica | Segurança | API
- Evidência: Nenhuma dependência TLS no Cargo.toml
- Correção: Adicionar rustls + bind_rustls().
- Esforço: Médio
[CRIT-05] 918 unwrap() em produção causam crash em erro
- Severidade: Crítica | Resiliência | Geral
- Evidência:
grep -c "unwrap(" src/ --include=*.rs= 918 - Correção: Substituir por
?, configurarclippy::unwrap_used. - Esforço: Alto
🟠 Altos (8)
[HIGH-01] N+1 query no endpoint /scan
- Severidade: Alta | Performance | API
- Componente: API/Engine
- Impacto: 10.001 chamadas para 10.000 keys.
- Evidência:
src/api/mod.rs:439-463 - Correção: Usar
engine.scan().
[HIGH-02] Batch insert sem limite — DoS por alocação
- Severidade: Alta | Segurança | API
- Evidência:
src/api/mod.rs:406-431 - Correção:
max_batch_sizedefault 1000.
[HIGH-03] Sem limite de tamanho de chave/valor
- Severidade: Alta | Segurança/Performance | Engine
- Evidência:
src/core/engine/mod.rs:745: sem validação. - Correção:
MAX_KEY_SIZE = 4096, MAX_VALUE_SIZE = 1MB.
[HIGH-04] Lock único serializa writes e starving reads
- Severidade: Alta | Performance | Engine
- Evidência:
Mutexúnico para todo o core. - Correção:
RwLock+ MVCC.
[HIGH-05] Disco cheio não ativa modo ReadOnly automaticamente
- Severidade: Alta | Resiliência | Engine/API/Disk
- Evidência: DegradationManager não integrado.
- Correção: Integrar DiskMonitor → DegradationManager → API handlers.
[HIGH-06] CDC Webhook sem autenticação, retry ou timeout
- Severidade: Alta | Segurança/Resiliência | CDC
- Evidência:
src/infra/cdc.rs:217-250 - Correção: Adicionar Auth header, RetryConfig, timeout 5s.
[HIGH-07] WebSocket sync sem autenticação
- Severidade: Alta | Segurança | API/Sync
- Evidência:
src/api/sync.rs:187-211 - Correção: Validar token no handshake WebSocket.
[HIGH-08] GraphQL playground exposto em produção
- Severidade: Alta | Segurança | API/GraphQL
- Evidência:
src/api/mod.rs:491-493 - Correção: Desabilitar em release.
🟡 Médios (12)
Listados na matriz completa em docs/audit/auditoria-completa.md.
🔵 Baixos (5)
Listados na matriz completa em docs/audit/auditoria-completa.md.
8. Checklist Antes de Release Pública
Segurança
-
API_AUTH_ENABLED=true— autenticação obrigatória - Token admin criado antes do startup
-
CORS_ORIGINSconfigurado com lista de origens confiáveis - TLS habilitado (rustls nativo ou reverse proxy documentado)
-
MAX_JSON_PAYLOAD_SIZE≤ 1MB -
Criptografia em repouso habilitada (
encryption_key_path) - Rate limiter configurado com per-endpoint limits para admin
- GraphQL playground desabilitado
- WebSocket sync com autenticação
-
Idempotency-Keymiddleware integrado - CSRF protection middleware implementado
Resiliência
-
DiskMonitorconfigurado e conectado aoDegradationManager -
WAL_SYNC_INTERVALconfigurado conforme RPO desejado -
CompactionBackpressureintegrado ao rate limiter - CDC webhook com retry + timeout + circuit breaker
-
PanicRecoveryregistrado com callback de alerta - Backup automático configurado com criptografia
- Health checks incluem dependências externas
Performance
-
WORKERSconfigurado (recomendado: 4) -
BLOCK_CACHE_SIZE_MBconfigurado conforme workload -
BLOOM_FALSE_POSITIVE_RATEdefinido (default 1%) - Benchmarks executados contra hardware alvo
-
cargo criterionsem regressão > 5% vs baseline
CI/CD
-
cargo auditexecutando em cada PR -
cargo clippy -- -D warningspassando -
cargo test --all-featurespassando -
cargo fmt --checkpassando - Fuzz tests integrados (cargo-fuzz)
Dependências
-
lruupgrade para ≥ 0.16.3 (RUSTSEC-2026-0002) -
pasteUNMAINTAINED — avaliar substituto (transitivo via ratatui) -
atomic-polyfillUNMAINTAINED — avaliarportable-atomic
Issues Criadas
Todas as issues estão no GitHub:
| ID | Issue | Link |
|---|---|---|
| C-01 | Auth desabilitado por padrão | #324 |
| C-02 | CORS permissivo | #325 |
| C-03 | Payload 50MB | #326 |
| C-04 | Sem TLS | #327 |
| C-05 | CDC sem auth/retry | #328 |
| H-01 | N+1 /scan | #329 |
| H-02 | Batch sem limite | #330 |
| H-03 | GraphQL playground | #331 |
| H-04 | WebSocket sem auth | #332 |
| H-05 | Rate limiter Mutex bottleneck | #333 |
| H-06 | Idempotency não integrado | #334 |
| H-07 | Env vars sem validação | #335 |
| H-08 | engine.keys() OOM | #336 |
| M-01 | Workers ilimitados | #337 |
| M-02 | Sem CSRF | #338 |
| M-03 | Token timing attack | #339 |
| M-04 | Backup sem criptografia | #340 |
| M-05 | Retry blocking sleep | #341 |
| M-06 | CDC sem timeout | #342 |
| M-07 | Falta auditoria logs | #343 |
| M-08 | Degradation não integrado | #344 |
| M-09 | Sem limite conexões/IP | #345 |
| M-10 | Sem cargo audit no CI | #346 |
| DB-04 | Range delete ausente | #347 |
| L-01 | CLI sem token mgmt | #348 |
| L-02 | Dashboard reload | #349 |
| L-03 | Endpoints duplicados | #350 |
| L-04 | Health checks incompletos | #351 |
| L-05 | Métrica write amplification | #352 |
Auditoria realizada em 2026-05-26 por equipe técnica de 3 especialistas. Revisar a cada 6 meses ou após mudanças significativas de arquitetura.