Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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)
  • 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

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:

  1. rust-analyzer - Rust language support

    • ID: rust-lang.rust-analyzer
    • Features: Auto-completion, go-to-definition, inline errors
  2. CodeLLDB (optional) - Debugging support

    • ID: vadimcn.vscode-lldb

Recommended: 3. Better TOML - TOML syntax highlighting

  • ID: bungcip.better-toml
  1. Error Lens - Inline error highlighting

    • ID: usernamehw.errorlens
  2. crates - Cargo.toml dependency management

    • ID: serayuzgur.crates

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)

  1. Install CodeLLDB extension
  2. 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}"
    }
  ]
}
  1. Set breakpoints in code
  2. Press F5 to 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

  1. ✅ Read CONTRIBUTING.md for contribution guidelines
  2. ✅ Explore the codebase structure
  3. ✅ Pick an issue to work on
  4. ✅ Join discussions on GitHub

💬 Getting Help


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

CommandWhat it runs
make fmtcargo fmt --all
make fmt-checkcargo fmt --all -- --check
make clippycargo clippy --locked --all-targets --all-features -- -D warnings
make testcargo test --locked --all-features --workspace
make test-fastlibrary unit tests only
make benchall Criterion benchmarks
make auditcargo audit against the RustSec advisory database
make denycargo deny check (licences, bans, sources)
make doccargo doc --locked --no-deps --all-features
make env-checkverifies .env.example matches the variables src/ reads
make actionlintlints .github/workflows/
make ciall of the above, in the order CI runs them
make shellinteractive 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

  1. Quick Start
  2. Server Configuration
  3. LSM Engine Configuration
  4. Performance Tuning
  5. Tuning Profiles
  6. 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

VariableDefaultDescription
HOST0.0.0.0Server bind address (0.0.0.0 = all interfaces)
PORT8080Server port

Payload Limits

VariableDefaultDescription
MAX_JSON_PAYLOAD_SIZE52428800 (50MB)Maximum JSON request/response size
MAX_RAW_PAYLOAD_SIZE52428800 (50MB)Maximum raw payload size

Recommendations:

  • Development/Testing: 50-100MB
  • Production with pagination: 10MB
  • Stress testing: 100-200MB

HTTP Server Tuning

VariableDefaultDescription
SERVER_WORKERS0 (CPU cores)Number of worker threads
SERVER_KEEP_ALIVE75Keep-alive timeout (seconds)
SERVER_CLIENT_TIMEOUT60Client request timeout (seconds)
SERVER_SHUTDOWN_TIMEOUT30Graceful shutdown timeout (seconds)
SERVER_BACKLOG2048Maximum pending connections
SERVER_MAX_CONNECTIONS25000Max concurrent connections per worker

Recommendations:

  • High-traffic: Increase SERVER_WORKERS to 8-16
  • Low-latency: Set SERVER_KEEP_ALIVE to 5-15
  • Memory-constrained: Reduce SERVER_MAX_CONNECTIONS to 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

VariableDefaultDescription
DATA_DIR./.lsm_dataData storage directory path

MemTable

VariableDefaultDescription
MEMTABLE_MAX_SIZE4194304 (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

VariableDefaultDescription
BLOCK_SIZE4096 (4KB)Block size for SSTables
BLOCK_CACHE_SIZE_MB64In-memory cache for blocks (MB)
SPARSE_INDEX_INTERVAL16Blocks 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

VariableDefaultDescription
BLOOM_FALSE_POSITIVE_RATE0.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)

VariableDefaultDescription
MAX_WAL_RECORD_SIZE33554432 (32MB)Maximum single record size
WAL_BUFFER_SIZE65536 (64KB)Write buffer size
WAL_SYNC_MODEalwaysFsync 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

VariableDefaultDescription
COMPACTION_STRATEGYlazy_levelingCompaction algorithm
SIZE_RATIO10Size ratio between levels
LEVEL0_COMPACTION_THRESHOLD4L0 file count trigger
MAX_LEVEL_COUNT7Maximum LSM tree levels
COMPACTION_THREADS2Background compaction threads

Compaction Strategies:

  • leveled: Best read performance
  • tiered: Best write performance
  • lazy_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

VariableDefaultDescription
FEATURE_CACHE_TTL10Cache 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

  1. Reduce MEMTABLE_MAX_SIZE
  2. Reduce BLOCK_CACHE_SIZE_MB
  3. Increase BLOOM_FALSE_POSITIVE_RATE
  4. Increase SPARSE_INDEX_INTERVAL
  5. Reduce SERVER_MAX_CONNECTIONS

Slow Writes

  1. Increase MEMTABLE_MAX_SIZE
  2. Change WAL_SYNC_MODE to every_second
  3. Increase WAL_BUFFER_SIZE
  4. Increase COMPACTION_THREADS
  5. Use COMPACTION_STRATEGY=tiered

Slow Reads

  1. Increase BLOCK_CACHE_SIZE_MB
  2. Decrease BLOOM_FALSE_POSITIVE_RATE
  3. Decrease SPARSE_INDEX_INTERVAL
  4. Use COMPACTION_STRATEGY=leveled
  5. Decrease SIZE_RATIO

Payload Too Large Errors

  1. Increase MAX_JSON_PAYLOAD_SIZE
  2. Increase MAX_RAW_PAYLOAD_SIZE
  3. Consider implementing pagination

Too Many Open Files

  1. Increase system file descriptor limit: ulimit -n 65536
  2. Reduce MAX_LEVEL_COUNT
  3. Decrease LEVEL0_COMPACTION_THRESHOLD
  4. 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

  1. Start with defaults - They work well for most workloads
  2. Profile first - Understand your workload before tuning
  3. Change one at a time - Easier to understand impact
  4. Monitor metrics - Use /stats/all endpoint
  5. Test in dev - Before applying to production
  6. Document changes - Track what works and what doesn't
  7. 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

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 MemTable
  • mem_kb - MemTable size in KB
  • sst_files - Number of SSTable files on disk
  • sst_records - Total records across all SSTables
  • sst_kb - Total SSTable disk usage in KB
  • wal_kb - Write-Ahead Log size in KB
  • total_records - Sum of MemTable + SSTable records
  • memtable_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:

  1. Inserts sample users
  2. Reads and displays data
  3. Updates a record
  4. Deletes a record
  5. Forces MemTable flush
  6. Tests search commands
  7. 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 CommandREST API EndpointMethod
SET key value/keysPOST
GET key/keys/{key}GET
DELETE key/keys/{key}DELETE
SEARCH query --prefix/keys/search?q=query&prefix=trueGET
STATS/statsGET
STATS ALL/stats/allGET
BATCH SET file/keys/batchPOST
KEYS/keysGET
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 --prefix for hierarchical keys (faster)
  • Without --prefix: slower substring search
  • Prefix searches leverage BTree ordering

Performance Tips

  1. Use BATCH for bulk inserts (faster than individual SETs)
  2. Monitor with STATS ALL to track memory usage
  3. Use prefix-based keys for efficient SCAN operations
  4. Avoid very long keys (increases memory overhead)

Data Management

  1. Backup data files before major operations
  2. Use BATCH SET for reproducible setups
  3. Monitor MemTable size with STATS
  4. Plan key namespaces before loading data

Troubleshooting

Common Issues

Q: "Comando desconhecido" error

  • A: Check spelling, commands are case-insensitive
  • Use HELP to 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_size configuration
  • Use STATS to monitor

Q: Slow search performance

  • A: Use --prefix flag 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...

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:

  1. Stop the server and retain a backup for investigation/recovery.
  2. Use the upgraded offline CLI against the same database directory to create a replacement administrator, as shown above.
  3. 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

PermissionDescriptionGrants Access To
ReadRead-only accessGET endpoints
WriteWrite access; grant Read separately when neededPUT, POST and mutation endpoints
DeleteDelete access; grant Read separately when neededDELETE endpoints
AdminFull accessAll 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: Read
  • GET /stats/all - Requires: Read
  • GET /keys - Requires: Read
  • GET /keys/{key} - Requires: Read
  • GET /keys/search - Requires: Read
  • GET /scan - Requires: Read
  • POST /keys - Requires: Write
  • POST /keys/batch - Requires: Write
  • DELETE /keys/{key} - Requires: Delete
  • GET /features - Requires: Admin
  • POST /features/{name} - Requires: Admin
  • POST /admin/tokens - Requires: Admin
  • GET /admin/tokens - Requires: Admin
  • DELETE /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 Authorization header
  • 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

BenchmarkMedianPerf
write_single/1054.988 µs🟡
write_single/102478.811 µs🟡
write_batch_1000/100060.063 ms🟠
write_batch_10000/10000566.64 ms🔴
memtable_flush_8/877.598 ms🟠
sstable_flush/1000016.061 ms🟠
write_size_10_100/10x10055.937 µs🟡
write_size_100_10000/100x10000111.04 µs🟡
key_updates/10k_keys574.88 ms🔴
delete_operations/10k_keys565.75 ms🔴

📚 Read

BenchmarkMedianPerf
read_memtable/1000248.38 µs🟡
read_memtable/10000252.68 µs🟡
read_sstable_cold/1000477.10 µs🟡
read_sstable_cold/10000494.09 µs🟡
read_sstable_warm/1000472.70 µs🟡
read_sstable_warm/10000593.73 µs🟡
read_latency/memtable_1k228.93 µs🟡
read_latency/sstable_cold_1k475.33 µs🟡
read_memtable_latency/memtable_1k229.23 µs🟡
read_sstable_warm_latency/sstable_warm_1k477.71 µs🟡
read_latency_memtable_1k/memtable_1k251.54 µs🟡
read_latency_memtable_100k/memtable_100k40.737 ms🟠
read_latency_sstable_1k/sstable_warm_1k427.83 µs🟡
read_latency_sstable_100k/sstable_warm_100k183.27 ms🔴

🔍 Scan

BenchmarkMedianPerf
scan_sequential/1000552.06 µs🟡
scan_sequential/100007.0201 ms🟠
full_scan/1000497.46 µs🟡
full_scan/100006.4072 ms🟠
range_scan_100/1004.7535 ms🟠
prefix_scan_100/1004.9135 ms🟠
prefix_scan_1000/10004.8718 ms🟠
iteration_sorted/1000529.71 µs🟡
iteration_sorted/100006.3805 ms🟠
scan_limit_10/104.0680 ms🟠
scan_limit_100/1004.0798 ms🟠
scan_pagination/1041.270 ms🟠
scan_pagination/100471.33 ms🔴

🌐 YCSB

BenchmarkMedianPerf
ycsb_type_a/1000029.266 ms🟠
ycsb_type_b/100004.0192 ms🟠
ycsb_type_c/10000747.09 µs🟡
ycsb_type_c/1000002.1759 ms🟠

⚡ Mixed Workload

BenchmarkMedianPerf
workload_balanced/1000029.922 ms🟠
workload_read_heavy/100006.8636 ms🟠
workload_write_heavy/1000052.849 ms🟠

🏗️ SSTable

BenchmarkMedianPerf
sstable_layer_1/15.9463 ms🟠
many_sstables_10/10547.72 µs🟡

🧵 Bloom Filter

BenchmarkMedianPerf
bloom_filter/100009.4871 ms🟠

💾 Cache

BenchmarkMedianPerf
cache_thrash_64MB/6494.968 µs🟡

🧵 Concurrency

BenchmarkMedianPerf
concurrent_1_threads/13.4724 ms🟠

💡 Memory

BenchmarkMedianPerf
memory_pressure/small_memtable264.05 µs🟡

⚙️ Other

BenchmarkMedianPerf
read_negative_bloom/negative_bloom_10k928.85 µs🟡
scan_1000_keys/scan_1k543.82 µs🟡
write_latency_1k/write_1k91.730 ms🟠
write_latency_100k/write_100k10.860 s🔴
write_amplification_leveled/leveled_10k_keys766.90 ms🔴
write_amplification_size_tiered/size_tiered_10k_keys796.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

OperationExpected Throughput
MemTable Only500K-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

OperationExpected Throughput
MemTable Hits800K-1M ops/sec
SSTable (warm cache)50K-100K ops/sec
SSTable (cold cache)5K-10K ops/sec

Scan Performance

OperationExpected Throughput
Full Scan10M-20M keys/sec
Range Scan5M-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

  1. Baseline Establishment: Run benchmarks on clean repository before making changes
  2. Regression Detection: Alert on performance degradation > 10%
  3. Optimization Validation: Compare before/after for proposed improvements
  4. Configuration Tuning: Test different LsmConfig values 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

  1. Compression Ratios: Measure LZ4 compression efficiency
  2. Compaction Performance: Size-tiered vs leveled compaction
  3. Replication Overhead: Network and sync costs
  4. Long-term Decay: Performance after extended operation

Configuration Impact on Performance

Memory Configuration

memtable_max_size

SizeWrite Throughput (async)Write Throughput (fsync)Best For
2 MB180K ops/s12K ops/sLow memory, high durability
8 MB420K ops/s8.5K ops/sBalanced workloads
16 MB650K ops/s7.5K ops/sDefault / Production
32 MB580K ops/s6.2K ops/sVery high write throughput
64 MB480K ops/s5.1K ops/sMemory-rich environments

Trade-off: Larger memtables improve write throughput but increase recovery time on crash.

block_cache_size_mb

Cache SizeWarm Read LatencyCold Read ThroughputMemory Usage
16 MB45.2 µs18K ops/sec16 MB
64 MB22.1 µs35K ops/sec64 MB
128 MB15.8 µs52K ops/sec128 MB
256 MB12.3 µs68K ops/sec256 MB
512 MB10.8 µs75K ops/sec512 MB

Recommendation: Set cache to 2-4x working dataset size for optimal performance.

bloom_false_positive_rate

RateMemory OverheadLookup EfficiencyBest Use Case
0.001 (0.1%)22 bits/entry99.2% rejectionMemory-constrained
0.01 (1%)11 bits/entry98.7% rejectionDefault
0.1 (10%)7 bits/entry95.3% rejectionExtreme memory limits

Disk I/O Configuration

sparse_index_interval

IntervalIndex SizeLookup SpeedBest For
8LargeFastestRead-heavy workloads
16MediumBalancedDefault
32SmallSlowerWrite-heavy workloads
64Very SmallSlowestHigh-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

  1. Establish Baseline: Run benchmarks on current configuration
  2. Identify Bottleneck: Check CPU, memory, I/O utilization during peak load
  3. Change One Variable: Adjust a single config parameter
  4. Run Full Benchmark Suite: All categories to check for regressions
  5. Validate Over Time: Run for at least 30 minutes to catch gradual degradation
  6. 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=async for 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 perf or flamegraph for hot paths
  • Run benchmarks on production-like hardware

Contributing Performance Improvements

When proposing performance optimizations:

  1. Add benchmarks demonstrating the improvement
  2. Include before/after comparison
  3. Verify no regressions in other metrics
  4. 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

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

  1. Rust Toolchain (1.96 or later; rust-toolchain.toml selects 1.99.1)

    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    
  2. Git

    # Ubuntu/Debian
    sudo apt-get install git
    
    # macOS
    brew install git
    
  3. Code Editor (Recommended: VS Code with rust-analyzer)

Initial Setup

  1. Fork the Repository

  2. Clone Your Fork

    git clone https://github.com/YOUR_USERNAME/ApexStore.git
    cd ApexStore
    
  3. Add Upstream Remote

    git remote add upstream https://github.com/ElioNeto/ApexStore.git
    
  4. Install Dependencies

    cargo build
    
  5. 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 develop branch
  • ✅ Adds comment to referenced issues (if any)
  • ✅ Runs Clippy and format checks

5. Pull Request Review

Once the automated PR is created:

  1. Review the PR description
  2. Wait for CI checks to pass
  3. Address any reviewer feedback
  4. PR will be merged to develop once 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:

  1. Use cargo fmt - All code must be formatted

    cargo fmt --all
    
  2. Pass cargo clippy - Zero warnings policy

    cargo clippy --all-features -- -D warnings
    
  3. 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

  1. 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(())
    }
    }
  2. 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 },
    }
    }
  3. Don't Panic in library code (use Result instead)

Performance Considerations

  1. 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)?;
    }
    }
  2. Use Appropriate Data Structures

    • BTreeMap for sorted data
    • HashMap for fast lookups
    • Vec for sequential access
  3. Benchmark Changes

    cargo bench
    

🧪 Testing Guidelines

Test Types

  1. 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()));
        }
    }
    }
  2. 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()));
    }
    }
  3. 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 feature
  • fix - Bug fix
  • docs - Documentation changes
  • style - Code style changes (formatting, etc.)
  • refactor - Code refactoring
  • perf - Performance improvements
  • test - Test additions/modifications
  • chore - Build process, dependencies, tooling
  • ci - 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 issue
  • fixes #123, closes #123 - Will auto-close issue when PR merges
  • resolves #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:

  1. ✅ Tests run automatically (CI/CD)
  2. ✅ PR is auto-created to develop branch
  3. ✅ Issues are commented (if referenced in commits)
  4. ✅ Checks must pass before merge

Manual Steps (If Needed)

If you need to create a PR manually:

  1. Go to your fork on GitHub
  2. Click "New Pull Request"
  3. Select develop as the base branch
  4. Fill out the PR template
  5. 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

  1. Automated Checks - CI runs tests and linters
  2. Code Review - Maintainer reviews code
  3. Feedback - Address review comments
  4. Approval - Maintainer approves PR
  5. 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 dependencies
  • storage/ - File I/O, persistence
  • infra/ - Cross-cutting concerns
  • api/ - External interfaces (feature-gated)

🎯 Areas for Contribution

High Priority

  1. CI/CD Testing Pipeline (#55)

    • Difficulty: Easy
    • Impact: High
    • Skills: GitHub Actions, YAML
  2. Compaction Implementation (#47)

    • Difficulty: Hard
    • Impact: High
    • Skills: Rust, algorithms, file I/O
  3. Efficient Iterators (#21, #22, #23)

    • Difficulty: Medium
    • Impact: High
    • Skills: Rust, data structures

Medium Priority

  1. Benchmarking Suite (#48)

    • Difficulty: Easy
    • Impact: Medium
    • Skills: Rust, criterion
  2. CLI Command Equalization (#65)

    • Difficulty: Medium
    • Impact: Medium
    • Skills: Rust, CLI design
  3. Checksums & Integrity (#25)

    • Difficulty: Easy
    • Impact: High
    • Skills: Rust, CRC32

Good First Issues

  1. Add More Tests

    • Difficulty: Easy
    • Impact: Medium
    • Skills: Rust, testing
  2. Binary Search Optimization (#37)

    • Difficulty: Easy
    • Impact: Medium
    • Skills: Rust, algorithms
  3. Documentation Improvements

    • Difficulty: Easy
    • Impact: Medium
    • Skills: Technical writing

Advanced Topics

  1. Replication Support

    • Difficulty: Very Hard
    • Impact: Very High
    • Skills: Distributed systems, Raft
  2. Snapshot Isolation

    • Difficulty: Hard
    • Impact: High
    • Skills: Concurrency, MVCC

❓ Questions?


🚀 Ready to Contribute?

  1. Find an issue or create one
  2. Comment that you're working on it
  3. Fork the repo and create a branch from main
  4. Make your changes with tests
  5. Push to your fork (automated PR will be created)
  6. 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:

  1. Build & Test

    • Compiles project: cargo build --release --all-features
    • Runs tests: cargo test --all-features
    • Checks linting: cargo clippy --all-features -- -D warnings
  2. Creates PR to develop

    • Automatically detects if there are new commits
    • Creates PR to develop with:
      • List of referenced issues (if any)
      • Commit summary
      • Test status
    • Doesn't duplicate existing PRs
  3. 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:

  1. Determines version

    • Analyzes commits since last tag
    • Calculates bump (major/minor/patch):
      • BREAKING CHANGE:, feat!:, fix!: → Major
      • feat: → Minor
      • Others → Patch
  2. Creates release branch

    • release/vX.Y.Z
    • Syncs with develop
  3. 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

On release PR merge:

  1. 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, closed
  • fix, fixes, fixed
  • resolve, 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

SituationBehavior
Commits with issuesPR created + issues listed + comments on issues
Commits without issuesPR created + "No issues referenced"
MixPR created + only found issues listed
Non-existent issuesIgnores and continues (no error)
Already closed issuesDoesn't comment (silent skip)

Develop to Release Workflow

SituationBehavior
Commits with issuesPR lists issues + on merge closes automatically
Commits without issuesPR without issues section + on merge completes normally
MixPR lists only found issues
Non-existent issuesIgnores and continues (log warning)
Already closed issuesTries 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:

  1. ✅ Normal: Issue wasn't referenced in commit
  2. ✅ Normal: Issue was already closed
  3. ⚠️ Check: Is issue number correct?
  4. ⚠️ Check: Is reference syntax correct?

"Issue didn't close after release"

Possible causes:

  1. ✅ Normal: Issue wasn't referenced in any commit
  2. ✅ Normal: Issue was already closed
  3. ⚠️ Check: Was PR merged (not just closed)?
  4. ⚠️ 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:

CheckResult
cargo test --all-features --workspace642 passed, 0 failed, 9 ignored
cargo clippy --all-targets --all-features1 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 --releasefails: 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

IDSeverityAreaTitle
C-01CriticalSecurityweb::Data<bool> TypeId collision disables authentication entirely
C-02CriticalSecurityEncryption at rest silently falls back to an all-zero AES key
C-03CriticalDurabilityDIR_PATH in docker-compose.yml is never read; container data is not persisted
C-04CriticalDurabilitySSTable corruption detection and quarantine are wired to inverted signals
H-01HighSecurityX-Forwarded-For is trusted unconditionally: rate-limit bypass and unbounded memory
H-02HighCorrectnessPer-endpoint rate-limit counters never decay, permanently locking out clients
H-03HighDurabilityWAL recovery deduplication discards range tombstones
H-04HighResiliencepanic = "abort" makes every catch_unwind recovery path dead in release
H-05HighSecurityTwo live RustSec advisories; the CI audit job cannot run
H-06HighCIci.yml runs no tests, no clippy and no build on main
M-01MediumDocsContainer health checks probe a route that does not exist, with a binary that is not installed
M-02MediumDocsDocumented environment variables did not match the code (15 missing, 5 dead)
M-03MediumDocsREADME and QUICKSTART commands fail as written
M-04MediumCIBenchmark automation commits an empty result on every run
M-05MediumCICI pipes an unpinned remote installer into bash
M-06MediumTestingNo test covers authentication, rate limiting or engine-level encryption
M-07MediumFrontendAngular 17 is out of support and has no CI at all
L-01LowDesignMemTable uses DashMap but exposes &mut self, forcing an outer lock
L-02LowDesignEngine is a single 2300-line impl block
L-03LowDocsVersion number disagrees across Cargo.toml, ROADMAP.md and Dockerfile
L-04LowHygiene.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:

  1. src/core/engine/compaction.rs:135 and src/core/engine/version_set.rs:68 return EncryptionConfig::default() in the else branch taken when encryption_enabled == false — so disabling encryption turns it on with a zero key for those paths, while EngineOptions::from correctly yields enabled: false. Flush and compaction therefore disagree about whether output is encrypted.
  2. #[serde(default)] on encryption_enabled (src/infra/config.rs:98) yields false, while Default::default() yields true. The same field has two contradictory defaults depending on how the config was constructed.
  3. src/infra/health/scrubber.rs:194 returns valid: false for every LSMSST04 file: "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 Ok and 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 Err and 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 live IpTrack values.
  • 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.rs module is inert, including spawn_protected, the panic history, and the on_panic callbacks.
  • The compaction thread guard at src/core/engine/mod.rs:1876 does 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:

IDCrateIssue
RUSTSEC-2026-0258h2 0.3.27unbounded empty DATA frames (DoS) — fixed in >= 0.4.16
RUSTSEC-2026-0222wasmtime 44.0.2stores 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:latest and dtolnay/rust-toolchain@stable — redundant, and unpinned, so a new stable release can break CI with no repository change. cargo clippy --all-features currently emits a warning on Rust 1.92, and CI runs with -D warnings.
  • No --locked anywhere, so Cargo.lock is not enforced.
  • No MSRV job, so the README's claim of Rust 1.70 was never tested (the real floor is 1.92).
  • latency_bench and write_amplification are declared in Cargo.toml but absent from the benchmarks.yml matrix, so they never run.
  • benchmarks.yml triggers on a develop branch that does not exist.
  • No coverage job, and no cargo fuzz job despite fuzz/ 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 no default-run, cargo refuses: "could not determine which binary to run".
  • README's TLS example used --bin server; QUICKSTART used --bin cli six times. Neither name exists — the binaries are apexstore-server, apexstore-cli, apexstore-tui. Every runnable command in QUICKSTART.md failed.
  • The Rust badge claimed 1.70+; --all-features needs 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:

FileErrorCause
vector-search.component.tsNG8002 ngClass, NG8004 pipe numbermissing NgClass, DecimalPipe
wasm-plugins.component.tsNG8002 ngClass ×2missing NgClass
tags.component.ts"not statically analyzable", NG8004 pipe sliceFormsModule imported from @angular/common, which does not export it, so it resolved to undefined; missing SlicePipe
graph.component.tssame bad importFormsModule from @angular/common
time-travel.component.htmlNG2 object possibly undefinednote.content?.length > 200 compares number | undefined
sync-status.component.tsTS7006 implicit anysee 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.html filtered inline with filtered().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.html used @else if (fetched() && graphData(); as data). as is only valid on a primary @if, so the binding never existed and all 33 references to data in that branch failed. The trailing @else if (fetched() && !graphData()) was also unreachable, since the branch before it already consumed every fetched() case.

And three that are logic bugs, not import hygiene:

  • pubsub.component.ts declared both a field publishMessage = '' and a method publishMessage(). The method's own body called this.publishMessage.trim(), which resolved to the method.
  • health.component.ts declared signal<'healthy' | 'degraded' | 'unhealthy'>('unknown') — an initial value outside its own union. resilience.component.ts did the same through its HealthSummary interface.
  • sync-status.component.ts imported Time05Icon and DataIcon, neither of which @hugeicons/core-free-icons exports, and its template used <app-hugeicons-icon> where the component's selector is hugeicons-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 audit no 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 in wal.rs still 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.

FileChange
Dockerfile.devnew — pinned Rust 1.92 toolchain image (clippy, rustfmt, cargo-audit 0.22, cargo-deny)
docs/DEVELOPMENT.mdnew — how to build, test, lint and benchmark in the container
scripts/check-env-example.shnew — fails the build when .env.example drifts from src/
Makefilereplaced three act targets with the full local pipeline
src/api/auth/mod.rs, auth/middleware.rs, access_control.rs, mod.rs, test_helpers.rsC-01: AuthEnabled / AccessControlEnabled newtypes, fail-closed auth
src/core/engine/mod.rsC-02: log the swallowed encryption-key failure
src/storage/encryption.rs, src/core/table.rsC-02: correct the inverted doc comments
src/notes/search.rscollapse the else { if … } clippy warning
src/lib.rsfeature table said chai, the flag is chaos
src/storage/wal.rsframe format doc said bincode (it is postcard) and listed only V0/V1
Dockerfile, docker-compose.ymlC-03 and M-01: DATA_DIR, working health probes, OCI labels
.env.exampleM-02: all 34 live variables, dead ones called out
README.md, QUICKSTART.md, docs/AUTHENTICATION.md, docs/CONTRIBUTING.md, docs/SETUP.mdM-03: working commands, real MSRV, honest feature claims
Cargo.tomldefault-run, rust-version
docs/SUMMARY.mdpublish every document
.gitignoreL-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

SeveridadeContagemDestaques
🔴 Crítico5Auth desabilitado por padrão, CORS permissivo, payload 50MB, sem TLS, injeção via CDC
🟠 Alto8N+1 no scan, batch sem limite, GraphQL playground público, WebSocket sem auth, idempotência não integrada
🟡 Médio10Workers ilimitados, sem CSRF, rate limiter com Mutex simples, token timing attack parcial, backup sem criptografia
🔵 Baixo5CLI sem gestão de tokens, dashboard com auto-refresh, sem auditoria em CI

🔴 Achados Críticos

C-01: Autenticação Desabilitada por Padrão

CampoValor
ProblemaAPI_AUTH_ENABLED=false no .env.example e no AuthConfig::default(). Qualquer requisição sem token passa pelo bearer_validator sem verificação.
ImpactoTodos 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ênciasrc/api/config.rs:70-73: enabled: false; src/api/auth/middleware.rs:33-35: if !auth_enabled { return Ok(req); }
RecomendaçãoMudar default para true e exigir configuração explícita de API_AUTH_ENABLED=false em ambientes dev. Implementar fallback seguro (deny-by-default).
ValidaçãoTeste de integração: tentar GET /keys sem Authorization header → deve retornar 401.
PrioridadeImediata

C-02: CORS Permissivo (Allow All Origins)

CampoValor
ProblemaCors::permissive() é usado quando cors_origins é None (default). Permite qualquer origem, qualquer header, qualquer método com credentials.
ImpactoQualquer site pode fazer requisições cross-origin autenticadas (se auth estivesse habilitado). Exfiltração de dados via cookies/session tokens.
Evidênciasrc/api/mod.rs:518: None => actix_cors::Cors::permissive(); src/api/config.rs:61: cors_origins: None
RecomendaçãoNunca usar .permissive() em produção. Exigir lista explícita de origens ou usar validação dinâmica segura.
ValidaçãoTeste: curl -H "Origin: https://evil.com" -H "Authorization: Bearer ..." http://localhost:8080/keys → verificar se Access-Control-Allow-Origin não reflete evil.com.
PrioridadeImediata

C-03: Payload Máximo de 50MB

CampoValor
ProblemaMAX_JSON_PAYLOAD_SIZE=52428800 (50MB) — extremamente alto para uma API key-value. Ataque DoS trivial com poucas conexões.
Impacto20 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ênciasrc/api/config.rs:50-51: max_json_payload_size: 50 * 1024 * 1024
RecomendaçãoReduzir para 1MB (1048576) como default. Implementar limite configurável por endpoint. Adicionar validação no middleware ANTES de chegar ao handler.
Validaçãocurl -X PUT -d "$(python -c 'print("x"*2000000)')" http://localhost:8080/keys/test → deve retornar 413 Payload Too Large.
PrioridadeImediata

C-04: Ausência de TLS/HTTPS

CampoValor
ProblemaServidor HTTP puro, sem suporte a TLS. Nenhuma opção de certificado, key ou configuração SSL.
ImpactoTodas as comunicações (incluindo tokens Bearer, dados de notas, comandos admin) trafegam em texto puro. MITM total.
Evidênciasrc/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çãoAdicionar 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çãoVerificar que curl -k https://localhost:8080/health/liveness funciona ou que docs exigem reverse proxy.
PrioridadeImediata

C-05: CDC Webhook sem Autenticação nem Retry

CampoValor
ProblemaWebhookPublisher::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.
ImpactoSe 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ênciasrc/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çãoAdicionar Authorization header configurável no CdcConfig. Envolver envio em RetryConfig::default(). Adicionar timeout de 5s. Usar circuit breaker.
ValidaçãoTeste unitário: mock HTTP server que verifica header Authorization no POST de CDC.
PrioridadeAlta

🟠 Achados Altos

H-01: N+1 Query no Endpoint /scan

CampoValor
ProblemaGET /scan primeiro lista todas as keys via engine.keys(), depois faz uma get_cf para cada key individualmente. Isso é 1 + N queries.
ImpactoCom 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ênciasrc/api/mod.rs:439-463: for k in keys { engine.get_cf("default", ...) }
RecomendaçãoUsar engine.scan() (prefix scan com iterator) que já existe no engine e retorna key+value em uma única passagem.
Validaçãocargo bench --bench scan_bench — comparar latência antes/depois.
PrioridadeAlta

H-02: Batch Insert sem Limite de Tamanho

CampoValor
ProblemaPOST /keys/batch aceita Vec<FrontendSetBody> sem limite de tamanho. Atacante pode enviar 100.000 registros em uma única requisição.
ImpactoDoS via batch gigante. Engine LSM-tree faz put_cf para cada registro individualmente (sem batch transaction). Amplificação de escrita.
Evidênciasrc/api/mod.rs:406-431: sem .take() ou max_batch validation.
RecomendaçãoAdicionar max_batch: usize configurável (default 1000). Validar no middleware. Usar transação atômica do engine se disponível.
ValidaçãoTeste: POST /keys/batch com 10001 registros → deve retornar 413.
PrioridadeAlta

H-03: GraphQL Playground Acessível em Produção

CampoValor
ProblemaGET /graphql/playground e GET /graphql retornam o Playground interativo (GraphQL IDE). Qualquer um pode executar queries arbitrárias.
ImpactoFerramenta de desenvolvimento exposta em produção. Atacante pode explorar schema GraphQL, fazer queries profundas, enumerar dados.
Evidênciasrc/api/mod.rs:491-493: playground registrado sem verificação de ambiente.
RecomendaçãoDesabilitar playground quando env!("PROFILE") != "debug" ou via config graphql_playground_enabled: bool.
ValidaçãoTeste: GET /graphql/playground em modo release → deve retornar 404.
PrioridadeAlta

H-04: WebSocket Sync sem Autenticação

CampoValor
ProblemaGET /ws/sync usa actix-ws sem middleware de autenticação. O sync_handler não verifica token.
ImpactoQualquer um pode abrir WebSocket, assinar notas, receber mudanças em tempo real e enviar alterações. Vazamento de dados via push.
Evidênciasrc/api/sync.rs:187-211: handler sync_handler sem require_permission.
RecomendaçãoAdicionar validação de token no handshake WebSocket. Extrair token do query param ?token=... ou header Sec-WebSocket-Protocol.
ValidaçãoTeste: conectar WebSocket sem token → deve fechar conexão com 4001.
PrioridadeAlta

H-05: Rate Limiter Usa Mutex Simples (Gargalo)

CampoValor
ProblemaRateLimiterState 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.
ImpactoEm 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ênciasrc/api/rate_limiter.rs:50: requests: Mutex<HashMap<IpAddr, IpTrack>>
RecomendaçãoUsar 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çãocargo bench --bench latency_bench — comparar P99 latency antes/depois com 1000 conexões.
PrioridadeAlta

H-06: Idempotency Middleware Não Integrado

CampoValor
ProblemaIdempotencyMiddleware existe em src/infra/idempotency.rs mas nunca é instanciado nem registrado na cadeia de middleware do actix-web (src/api/mod.rs:569-588).
ImpactoRetry 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ênciasrc/api/mod.rs:569-588: middleware list inclui RequestTimeout, RateLimiter, AccessControl, Logger, Cors, HttpAuthentication — mas não IdempotencyMiddleware.
RecomendaçãoIntegrar IdempotencyMiddleware como middleware global para mutações (PUT, POST, DELETE). Extrair Idempotency-Key header.
ValidaçãoTeste de integração: enviar PUT /keys/k com Idempotency-Key: xyz duas vezes → mesma resposta.
PrioridadeAlta

H-07: Variáveis de Ambiente Sem Validação

CampoValor
ProblemaServerConfig::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.
ImpactoSe 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ênciasrc/api/config.rs:77-170: todos os parse::<T>() usam unwrap_or(default_value) sem log de warning.
RecomendaçãoAdicionar logging warning quando env var é inválida. Validar ranges (porta 1-65535, workers 1-64, etc.).
ValidaçãoTeste: WORKERS=-1 cargo run → log warning no startup. WORKERS=0 → erro de validação.
PrioridadeAlta

H-08: Scan de Keys Carrega Tudo em Memória

CampoValor
ProblemaGET /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.
ImpactoCom 5M de keys de 32 bytes = 160MB só de keys em memória. Antes de serializar JSON.
Evidênciasrc/api/mod.rs:156-163: engine.keys()?.into_iter().take(limit) — take limita output mas o vetor inteiro já foi alocado.
RecomendaçãoImplementar engine.keys_with_limit(limit) que usa inner iterator e para após limit itens. Ou modificar search_prefix com prefixo vazio.
ValidaçãoTeste com 1M keys: consumo de memória < 50MB.
PrioridadeAlta

🟡 Achados Médios

M-01: Workers Ilimitados (Auto = CPU Cores)

CampoValor
ProblemaWORKERS vazio = auto-detect. Em servidores com muitos cores (32, 64), isso cria dezenas de workers que competem pelo lock do engine (Mutex no core).
ImpactoContenção alta no lock do engine (cada operação adquire parking_lot::Mutex no core). Workers extras gastam CPU em spinning.
Evidênciasrc/bin/server.rs:594-596: if let Some(workers) = config.workers { server_builder = server_builder.workers(workers); }
RecomendaçãoRecomendar default de 4 workers. Documentar que engine lock-bound. Adicionar warning se workers > 8.
Validaçãocargo bench --bench mixed_bench com 4 vs 32 workers.
PrioridadeMédia

M-02: Ausência de Proteção CSRF

CampoValor
ProblemaNenhum 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.
ImpactoSe auth estivesse habilitado com cookie-based (não é o caso atual, mas arquiteturalmente), CSRF seria possível.
EvidênciaTodo o src/api/mod.rs — nenhuma verificação de Origin, Referer, ou token CSRF.
RecomendaçãoAdicionar middleware de verificação de origem para mutações. Exigir header X-CSRF-Token ou Origin check.
ValidaçãoTeste: POST sem Origin header → 403.
PrioridadeMédia

M-03: Token Timing Attack Parcial

CampoValor
Problemaconstant_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.
ImpactoExtremamente baixo em prática (atacante precisaria de >10^6 requisições para extrair 64 chars). Mas quebra a premissa de constant-time.
Evidênciasrc/api/auth/token.rs:131-138: if a.len() != b.len() { return false; }
RecomendaçãoUsar crate subtle ou constant_time_eq para comparação de bytes. Hash tokens armazenados como [u8; 32] em vez de hex string.
ValidaçãoTeste: validate_token com tokens de diferentes tamanhos deve levar o mesmo tempo (±5%).
PrioridadeMédia

M-04: Backup sem Criptografia

CampoValor
ProblemaBackupScheduler::backup_now() copia snapshots para diretório de backup sem qualquer criptografia. Dados sensíveis ficam em texto puro no disco.
ImpactoSe 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ênciasrc/infra/backup_scheduler.rs:170-208: nenhuma chamada a encrypt_block ou similar. Backup é cópia literal dos arquivos SSTable.
RecomendaçãoIntegrar Encryptor no backup. Usar AES-256-GCM com chave separada (rotação periódica).
ValidaçãoTeste: backup → arquivos .encrypted. Tentar ler sem chave → dados ininteligíveis.
PrioridadeMédia

M-05: Compactação Usa std::thread::sleep Dentro de Lock

CampoValor
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.
ImpactoThread pool bloqueada durante sleep de até 5s (max_delay_ms). Redução de throughput.
Evidênciasrc/infra/retry.rs:102: std::thread::sleep(Duration::from_millis(actual_delay_ms))
RecomendaçãoUsar tokio::time::sleep para async contexts. Separar retry de blocking IO.
ValidaçãoTeste de estresse: 1000 writes concorrentes durante compactação → sem starvation.
PrioridadeMédia

M-06: CDC Publisher sem Timeout

CampoValor
ProblemaWebhookPublisher::publish não especifica timeout na requisição HTTP. Se o endpoint CDC travar, a goroutine fica bloqueada indefinidamente.
ImpactoEscrita no engine fica bloqueada aguardando CDC. Degeneração para completa indisponibilidade.
Evidênciasrc/infra/cdc.rs: reqwest post sem .timeout().
RecomendaçãoAdicionar reqwest::Client::builder().timeout(Duration::from_secs(5)). Usar circuit breaker para CDC.
ValidaçãoTeste: configurar CDC endpoint que não responde → timeout após 5s.
PrioridadeMédia

M-07: Falta de Auditoria (Access Log)

CampoValor
ProblemaO 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.
ImpactoImpossível fazer auditoria forense: quem deletou qual key, quando.
Evidênciasrc/api/mod.rs:574: .wrap(actix_web::middleware::Logger::default()) — formato de log não customizado.
RecomendaçãoCustomizar Logger para incluir X-User-Id (do token), X-Request-Id, key do path, response status. Adicionar log estruturado em formato JSON.
ValidaçãoVerificar logs: {"method":"DELETE","path":"/keys/secret","user":"alice","status":200}
PrioridadeMédia

M-08: Degradation Manager Não Integrado com API

CampoValor
ProblemaDegradationManager existe mas não é verificado nos handlers da API. Writes continuam mesmo quando o disco está crítico.
ImpactoEscrita em disco cheio causa corrupção de SSTable e perda de dados.
Evidênciasrc/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çãoIntegrar DegradationManager::check_write_allowed() em todos os handlers de mutação. Conectar DiskMonitor::on_critical para setar ReadOnly.
ValidaçãoTeste: encher disco → POST /keys → retorna 503 Service Unavailable.
PrioridadeMédia

M-09: Sem Limite de Conexões por IP

CampoValor
ProblemaRate limiter é baseado em requisições/minuto, não em conexões simultâneas. max_connections=10000 é global, não por IP.
ImpactoUm único IP pode abrir 10000 conexões simultâneas e exaurir o file descriptor pool.
Evidênciasrc/api/rate_limiter.rs: rastreia requisições em janela de 60s, mas não limita conexões simultâneas por IP.
RecomendaçãoAdicionar max_connections_per_ip: usize (default 100). Usar HashMap<IpAddr, AtomicUsize> para tracking de conexões ativas.
ValidaçãoTeste: 200 conexões simultâneas do mesmo IP → 100 aceitas, 100 rejeitadas com 429.
PrioridadeMédia

M-10: Dependência Bincode UNMAINTAINED

CampoValor
Problemabincode 1.3.3 é marcado como UNMAINTAINED (RUSTSEC-2025-0141), mas está como dependência (aparentemente removida — verificar Cargo.toml atual).
ImpactoSe presente, bugs de segurança não serão corrigidos.
EvidênciaSECURITY_REPORT.md:64 — mas não aparece no Cargo.toml atual (postcard substituiu?). Verificar Cargo.lock.
RecomendaçãoConfirmar que bincode não está em nenhuma dependência transitiva. Executar cargo audit regularmente.
Validaçãocargo audit não deve reportar bincode.
PrioridadeMédia

🔵 Achados Baixos

L-01: CLI sem Gestão de Tokens

CampoValor
ProblemaCLI (apexstore-cli) não tem comandos para criar, listar, revogar tokens de API.
ImpactoAdministradores precisam criar tokens manualmente via API POST /admin/tokens (que nem existe como endpoint documentado).
Evidênciasrc/bin/cli.rs: comandos get/put/delete/scan — sem subcomando token.
RecomendaçãoAdicionar apexstore-cli token create/list/revoke com persistência no engine.
Validaçãoapexstore-cli token create --name "ci-user" --permission read → retorna token.
PrioridadeBaixa

L-02: Admin Dashboard Auto-Refresh sem Cache Bust

CampoValor
ProblemaDashboard HTML auto-refresh a cada 5s via location.reload(), não via fetch(). Causa flash visual e perde estado.
ImpactoExperiência de monitoração ruim. Pequena sobrecarga de CPU/rendering.
Evidênciasrc/api/admin/dashboard.rs:216: setInterval(updateTime, 1000); setTimeout(function() { location.reload(); }, 5000);
RecomendaçãoSubstituir por fetch('/stats/all') com atualização parcial do DOM.
ValidaçãoDashboard atualiza sem flash visual.
PrioridadeBaixa

L-03: Sem cargo audit no CI

CampoValor
ProblemaWorkflow CI (ci.yml) não executa cargo audit para detectar vulnerabilidades em dependências.
ImpactoVulnerabilidades em dependências só são descobertas manualmente.
EvidênciaSECURITY_REPORT.md:105: #183 — No cargo audit in CI. Workflow não tem step de audit.
RecomendaçãoAdicionar cargo audit ao CI. Usar cargo-audit com --deny warnings.
ValidaçãoCI passa com cargo audit.
PrioridadeBaixa

L-04: Endpoints Frontend Duplicados

CampoValor
ProblemaPOST /keys (frontend) e PUT /keys/{key} fazem a mesma coisa com APIs diferentes. GET /stats/all e GET /stats são redundantes.
ImpactoSuperfície de ataque maior sem necessidade. Manutenção duplicada.
Evidênciasrc/api/mod.rs:345-369 (post_key) vs 73-99 (put_key). 319-342 (get_stats_all) vs 193-217 (get_stats).
RecomendaçãoConsolidar: remover endpoints duplicados ou fazê-los redirecionar. Versionar API (/v1/keys).
ValidaçãoTestes existentes continuam passando após remoção dos duplicados.
PrioridadeBaixa

L-05: Sem Health Check de Dependências Externas

CampoValor
ProblemaHealth checks (/health/liveness, /health/readiness) verificam apenas o engine local, não dependências externas (CDC endpoint, Webhook, OTLP collector).
ImpactoReadiness retorna 200 mesmo quando todas as dependências externas estão down. K8s não mata pod.
Evidênciasrc/api/health.rs: liveness e readiness só verificam engine stats.
RecomendaçãoAdicionar health checks para dependências: CDC endpoint (ping), OTLP (gRPC health check), disk space.
ValidaçãoCDC endpoint retornando 503 → /health/readiness retorna 503.
PrioridadeBaixa

🗄️ Riscos do Banco de Dados (LSM-tree)

DB-01: Write Amplification sem Monitoramento (Médio)

ProblemaO 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.
ImpactoSem monitorar write amplification, usuários podem configurar tamanhos de nível errados e ter 20-50x write amplification, reduzindo vida de SSD.
RecomendaçãoAdicionar 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)

ProblemaSe 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.
ImpactoLatência P99 pode disparar de 1ms para 50ms em bancos com muitos níveis e sem bloom filter efetivo.
RecomendaçãoExigir Bloom Filter (default 1% false positive). Monitorar bloom_filter_negatives_total para detectar filtros ineficazes.

DB-03: Compaction Pode Causar Write Stalls (Baixo)

ProblemaSe 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.
ImpactoWrites bloqueados por segundos. Picos de latência.
RecomendaçãoIntegrar CompactionBackpressure com RateLimiterState da API. Quando backpressure > threshold, reduzir rate limit da API dinamicamente.

DB-04: Sem Range Deletions Otimizadas (Baixo)

Problemadelete_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.
ImpactoDeletar 1M keys com prefixo requer 1M operações. Write stall.
RecomendaçãoImplementar delete_range() no engine com tombstone de range (já há range_start/range_end no LogRecord).

DB-05: Block Cache Tamanho Fixo (Baixo)

ProblemaGlobalBlockCache::new(64, 4096) — tamanho fixo de 64MB. Sem resize dinâmico ou adaptive cache.
ImpactoCache pode estar superdimensionado (desperdício de memória) ou subdimensionado (cache miss rate alto).
RecomendaçãoMonitorar cache_hits_total / (cache_hits_total + cache_misses_total). Adicionar resize via API admin.

📋 Plano de Correção

Fase 1 — Imediata (Semanas 1-2)

PrioridadeIDAçãoEsforço
🔴 P0C-01Mudar default auth para true. Adicionar middleware obrigatório.2h
🔴 P0C-02Remover Cors::permissive(). Exigir origens explícitas.1h
🔴 P0C-03Reduzir payload max para 1MB default. Adicionar json_payload middleware.1h
🔴 P0C-04Adicionar suporte TLS (rustls) ou documentar reverse proxy obrigatório.8h
🟠 P1H-01Refatorar /scan para usar engine.scan() em vez de N+1 queries.3h
🟠 P1H-02Adicionar max_batch_size limit (default 1000).1h

Fase 2 — Curto Prazo (Semanas 3-4)

PrioridadeIDAçãoEsforço
🟠 P1H-03Desabilitar GraphQL playground em produção.1h
🟠 P1H-04Adicionar auth no WebSocket sync.4h
🟠 P1H-05Substituir Mutex<HashMap> por sharded ou lock-free rate limiter.6h
🟠 P1H-06Integrar IdempotencyMiddleware na cadeia de middleware.3h
🟠 P1H-07Adicionar validação de env vars com logging de warning.2h
🟠 P1H-08Implementar keys_with_limit() para evitar OOM em scans.4h

Fase 3 — Médio Prazo (Semanas 5-6)

PrioridadeIDAçãoEsforço
🔴 P0C-05Adicionar auth + retry + timeout no CDC Webhook.4h
🟡 P2M-01Fixar default workers=4. Documentar engine lock-bound.1h
🟡 P2M-02Adicionar CSRF protection middleware.3h
🟡 P2M-03Usar subtle::ConstantTimeEq para token comparison.1h
🟡 P2M-04Criptografar backups com AES-256-GCM.4h
🟡 P2M-06Adicionar timeout no CDC HTTP client.1h
🟡 P2M-07Customizar Logger para auditoria (principal, path, status).2h
🟡 P2M-08Integrar DegradationManager nos handlers de mutação.3h
🟡 P2M-09Adicionar max_connections_per_ip.3h

Fase 4 — Contínuo (Sprints)

PrioridadeIDAçãoEsforço
🔵 P3L-01..L-05Melhorias de CLI, dashboard, CI audit, consolidar endpoints, health checks12h
🟡 P2M-05Refatorar retry para async com tokio::time::sleep3h
🟡 P2M-10Confirmar remoção de bincode, adicionar cargo audit ao CI1h

🧪 Plano de Testes

Testes de Segurança

TesteFerramentaCritério
Auth bypasscurl / httpxGET /keys sem token → 401
CORS reflectioncurl -H "Origin: https://evil.com"Response não deve refletir Origin
Payload oversizedcurl -X PUT -d @50MB.json413 Payload Too Large
Path traversalGET /keys/../../../etc/passwd404 (não 200 com conteúdo)
Rate limit bypass101 req/min de mesmo IP429 na 101ª
Token fuzzing1000 tokens aleatórios401 para todos
WebSocket authws sem tokenConexão rejeitada
GraphQL iDquery {__schema{types{name}}} com profundidade 10Limitada a 3 níveis
Batch DoSPOST /keys/batch com 10001 registros413 ou 429
CDC injectionConfigurar CDC_ENDPOINT para servidor do atacanteDados não devem vazar
TLS checkcurl sem -kHandshake TLS bem-sucedido

Testes de Resiliência

TesteCenárioCritério
Kill + recoveryMatar processo, reiniciarWAL recovery, dados íntegros
Disk fillPreencher disco até thresholdEngine entra em ReadOnly
Conexões em massa2000 conexões simultâneas2000 processadas, demais rejeitadas ordeiramente
Compactação + writes1000 writes/s durante compactaçãoWrites não bloqueiam > 1s
CDC offlineEndpoint CDC fora do arEngine continua operacional
Panic em workerForçar panic em thread de compactaçãoThread reinicia, engine continua

Testes de Performance

TesteMétricaAlvo
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 workloadmixed_bench> 5000 ops/s
Write amplificationwrite_amplification< 10x
Concurrent connectionsstress_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_ORIGINS configurado com origens específicas (nunca vazio)
  • MAX_JSON_PAYLOAD_SIZE reduzido para 1MB
  • Deploy atrás de TLS (nginx, caddy, ou TLS nativo)
  • REQUEST_TIMEOUT_SECONDS configurado (30s default)
  • RATE_LIMIT_REQUESTS_PER_MINUTE configurado (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=true com WAL_MAX_SIZE=67108864 (64MB)
  • BACKUP_SCHEDULER configurado com retention_count >= 10

Monitoramento

  • Prometheus /metrics integrado ao scraping
  • OTLP export configurado (OTEL_EXPORTER_OTLP_ENDPOINT)
  • Dashboard de latency P50/P99/P95 configurado
  • Alerta de apexstore_errors_total > 0 em 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 audit executado em cada PR
  • cargo clippy -- -D warnings passa
  • cargo test --all-features passa
  • cargo bench sem regressão > 10%
  • cargo fmt --check passa

Documentação

  • docs/SECURITY.md atualizado com procedimentos de incidentes
  • docs/OPS.md com runbooks de recovery
  • .env.example com valores seguros (auth=true, CORS configurado)
  • Variáveis de produção documentadas

Suposições Explicitas

  1. Auth stateless: Usei tokens Bearer armazenados no engine como única fonte de verdade. Não há OAuth2, OIDC, SAML ou provedor externo.
  2. Deployment: Assumo deploy em container (Docker/K8s) com reverse proxy (nginx). Recomendo fortemente TLS no proxy.
  3. Monitoração: Assumo Prometheus + Grafana para métricas, e OTLP collector opcional para tracing.
  4. Backup: Assumo backup periódico via BackupScheduler para diretório local ou volume montado (NFS/S3 via CSI).
  5. Dados sensíveis: Considerei notas, tags e values como dados sensíveis que precisam de criptografia em repouso e em trânsito.
  6. Escala: Análise considera até 10M keys, 1000 writes/s, 10000 conexões simultâneas.
  7. 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 Encryptor com AES-256-GCM está implementado corretamente (nonces aleatórios de 12 bytes, autenticação via GCM), mas EncryptionConfig::default() retorna enabled: false. Nenhum código de inicialização do servidor (bin/server.rs) chama from_key_path().
  • Evidência: src/storage/encryption.rs:27-33 — enabled: false no default. src/bin/server.rs:61-72 — LsmConfig::builder() não chama .encryption_key_path().
  • Como reproduzir: Executar servidor, inspecionar .lsm_data/sstables/*.sst com xxd — dados são texto puro (LZ4 comprimido, sem criptografia).
  • Correção recomendada: Configuração deve exigir chave em produção (panic se enabled=false em release build). Adicionar LsmConfig::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/*.sst e wal.log têm permissão -rw-rw-r--. O Rust cria arquivos com a umask do processo, sem chamada explícita a set_permissions().
  • Correção recomendada: Usar std::fs::set_permissions() para 0o600 (owner-only) em todos os arquivos de dados criados. Adicionar FILE_CREATION_MASK configurá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 como lsm_{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::Hasher usado para checksum de cada frame. Trailing partial checksum detectado em 425.
  • 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 → CorruptedData error.
  • 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ção put_cf_internal aceita key e value como Vec<u8> sem verificação de tamanho máximo. src/api/mod.rs nã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:
    #![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())));
    }
    }
    Validar tanto no engine quanto no middleware HTTP.
  • 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 value individualmente.
  • 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) e String::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 é para Mmap::map() do crate memmap2, que é uma operação padrão e segura na prática. O fallback para pread existe 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 causa panic! 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 ao catch_unwind do actix), mas corrompe estado compartilhado se o Mutex estiver 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 ? ou expect("context").
    • Fase 2: Usar cargo clippy -- -D clippy::unwrap_used para prevenir novos unwrap().
    • Fase 3: Adicionar #[deny(clippy::unwrap_used)] no crate.
  • 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 que unwrap() por dar contexto, mas ainda causa panic. Alguns expect() em engine/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 ? com thiserror ou anyhow context.
  • 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 por parking_lot::Mutex no 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 usa Mutex como ú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/flush e /admin/compact podem 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-|AKIA não encontrou ocorrências. .secrets.example conté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_INTERVAL registros (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_INTERVAL definido como constante; batched sync implementado.
  • Correção recomendada: Tornar WAL_SYNC_INTERVAL configurável. Para máxima durabilidade, permitir WAL_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_VERSION verifica 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ência add_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() retorna Err(IoError). O erro propaga para a API, que retorna 500. O engine não entra em modo ReadOnly automaticamente — o DegradationManager existe mas não é integrado com o DiskMonitor.
  • Evidência: src/storage/wal.rs:214-221: erro de sync_all() propaga via ?. src/infra/degradation.rs: implementado mas não chamado nos handlers. src/infra/disk_monitor.rs: on_critical callback não conectado ao engine.
  • Como reproduzir: Preencher o disco (dd if=/dev/zero of=./disk_fill bs=1M count=...), depois PUT /keys/test → 500 Internal Server Error.
  • Correção recomendada:
    1. Conectar DiskMonitor::on_critical → DegradationManager::set_mode(ReadOnly)
    2. Nos handlers da API, chamar degradation_manager.check_write_allowed() antes de escrever
    3. Retornar 503 Service Unavailable em vez de 500
  • 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 CompactionBackpressure calcula 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 com RateLimiterState.
  • Correção recomendada: Quando should_backpressure() retorna true, reduzir dinamicamente max_requests_per_minute via 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::Mutex não envenena, diferentemente de std::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 de parking_lot::Mutex consistente.
  • 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 Mutex para coordenar WAL + MemTable + VersionSet. Durante escritas intensas (1000+ writes/s), leitores ficam bloqueados aguardando o lock. Com parking_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 adquirem core.lock().
  • Correção recomendada:
    1. Usar RwLock para separar leitores (get) de escritores (put).
    2. Implementar MVCC (multi-version concurrency control) com VersionSet snapshot para leituras sem lock.
    3. Como passo intermediário, usar parking_lot::RwLock no lugar de Mutex.
  • 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. OtelInstruments exporta 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_ms ao EngineMetrics.
  • 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-id tracking 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, configurar WAL_SYNC_INTERVAL=1.
  • Evidência: WAL_SYNC_INTERVAL = 4 (hardcoded em wal.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 com WAL_SYNC_INTERVAL=4 amortiza 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 Mutex do 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 por table_id.
  • Observação: A lru crate 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ção get_cf itera níveis.
  • Correção recomendada: Manter Bloom Filter obrigatório (default enabled). Adicionar métrica read_amplification exposta.
  • 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: LazyLevelingCompaction implementa switch.

[COMP-WRITE-AMP-001] Write amplification não é monitorada em produção

  • Severidade: Média
  • Área: Performance
  • Componente: Compaction/Metrics
  • Impacto: Bench write_amplification existe, mas a métrica real compaction_bytes_written / user_bytes_written nã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.rs existe. src/infra/metrics.rs: não inclui write_amplification_ratio.
  • Correção recomendada: Adicionar métrica apexstore_write_amplification_ratio calculada a partir de compaction_bytes_total e user_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 criterion comparison feature com baseline para 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-skiplist ou dashmap para 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: MergeIterator e StorageIterator usam pattern de streaming.

4. Matriz de Risco do LSM-Tree

ComponenteSegurançaResiliênciaPerformanceRisco Geral
WAL🟢 CRC32 + AES-256-GCM (opt)🟡 Batch fsync (RPO não-zero)🟡 Group commit não implementadoMédio
MemTable🟢 BTreeMap + Mutex seguro🟡 Lock único pode causar starvation🟡 BTreeMap O(log n), sem skip listMédio
SSTable🟢 CRC32 + Bloom + Cache LRU🟡 Sem auto-repair de corrupção🟢 Blocos cacheados, bloom filterBaixo
Compaction🟢 Write-then-rename atômico🟢 Crash-safe🟢 LazyLeveling híbridoBaixo
API/HTTP🔴 Auth+CORS+Payload+No TLS🟡 Sem degradation integrado🟡 N+1 scan, batch sem limiteCrítico
CDC🔴 Sem auth, sem retry🟡 Sem timeout, sem circuit breaker🟢 Boa estrutura de eventosAlto

5. Plano de Correção Priorizado

Quick Wins (24h)

IDAçãoEsforçoIssues
C-01Mudar AuthConfig::default() para enabled: true15min#324
C-02Substituir Cors::permissive() por deny-by-default30min#325
C-03Reduzir MAX_JSON_PAYLOAD_SIZE para 1MB15min#326
INPUT-VAL-001Adicionar MAX_KEY_SIZE e MAX_VALUE_SIZE no engine1h(nova issue)
H-03Desabilitar GraphQL playground em release30min#331
M-10Adicionar cargo audit ao CI30min#346
RATE-LIMITAdicionar endpoint limits para /admin/*15min(nova issue)
COMP-WRITE-AMPAdicionar métrica write amplification no Prometheus1h#352

Correções para 7 Dias

IDAçãoEsforçoIssues
C-04Adicionar suporte TLS nativo (rustls)8h#327
C-05Adicionar auth + retry + timeout no CDC Webhook4h#328
H-01Refatorar /scan para usar iterator scan (N+1 fix)3h#329
H-02Adicionar max_batch_size no batch endpoint1h#330
H-04Adicionar auth no WebSocket sync4h#332
H-05Substituir Mutex<HashMap> por sharded rate limiter6h#333
H-06Integrar IdempotencyMiddleware na cadeia3h#334
H-07Adicionar validação de env vars com logging2h#335
H-08Implementar keys_with_limit()4h#336
INPUT-VAL-002Validar UTF-8 nas chaves da API1h(nova issue)
M-01Fixar default workers=430min#337
M-08Integrar DegradationManager nos handlers3h#344
M-09Adicionar max_connections_per_ip3h#345

Melhorias Estruturais (30 Dias)

IDAçãoEsforço
UNWRAP-001Erradicar 918 unwrap() em produção40h (pode ser automatizado parcialmente)
STARVATION-001Migrar de Mutex para RwLock no engine16h
WRITE-WAL-001Implementar group commit no WAL12h
WRITE-SERIAL-001Separar WAL lock do MemTable lock20h
IO-DISK-FULL-001Integrar Degradation + DiskMonitor + API handlers8h
IO-READ-ERROR-001Implementar quarantine de SSTables corrompidos8h
CRASH-SST-001Implementar auto-repair parcial de SSTables16h
WAL-FSYNC-001Tornar WAL_SYNC_INTERVAL configurável2h
BACKPRESSURE-001Integrar CompactionBackpressure com RateLimiter6h
MEMTABLE-CONCAvaliar skip list lock-free (crossbeam)16h

6. Plano de Testes Recomendado

Testes Unitários por Componente

ComponenteO que testarStatus atual
WALCRC32 detecção, versões V0-V3, replay, truncation✅ Bom
MemTableInsert/Get/Delete/Scan, TTL expiry, overflow✅ Bom
SSTableBuild/Read, CRC32, bloom filter, compressão✅ Bom
CompactionEstratégias size-tiered/leveled, atomicidade✅ Bom
AuthToken CRUD, expiry, permissions, timing✅ Bom
Rate LimiterSliding window, per-endpoint, X-Forwarded-For✅ Bom
RetryBackoff, jitter, exhaustion✅ Bom
Circuit BreakerOpen/HalfOpen/Closed, thresholds✅ Bom
BackupSnapshot/restore, retention, erro✅ Bom
EncryptionAES-256-GCM roundtrip, wrong key, disabled✅ Bom
ScrubberCRC32 valid/invalid, orphan detection✅ Bom
DegradationMode switching, write block✅ Bom
IdempotencyCache 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 ?, configurar clippy::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_size default 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_ORIGINS configurado 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-Key middleware integrado
  • CSRF protection middleware implementado

Resiliência

  • DiskMonitor configurado e conectado ao DegradationManager
  • WAL_SYNC_INTERVAL configurado conforme RPO desejado
  • CompactionBackpressure integrado ao rate limiter
  • CDC webhook com retry + timeout + circuit breaker
  • PanicRecovery registrado com callback de alerta
  • Backup automático configurado com criptografia
  • Health checks incluem dependências externas

Performance

  • WORKERS configurado (recomendado: 4)
  • BLOCK_CACHE_SIZE_MB configurado conforme workload
  • BLOOM_FALSE_POSITIVE_RATE definido (default 1%)
  • Benchmarks executados contra hardware alvo
  • cargo criterion sem regressão > 5% vs baseline

CI/CD

  • cargo audit executando em cada PR
  • cargo clippy -- -D warnings passando
  • cargo test --all-features passando
  • cargo fmt --check passando
  • Fuzz tests integrados (cargo-fuzz)

Dependências

  • lru upgrade para ≥ 0.16.3 (RUSTSEC-2026-0002)
  • paste UNMAINTAINED — avaliar substituto (transitivo via ratatui)
  • atomic-polyfill UNMAINTAINED — avaliar portable-atomic

Issues Criadas

Todas as issues estão no GitHub:

IDIssueLink
C-01Auth desabilitado por padrão#324
C-02CORS permissivo#325
C-03Payload 50MB#326
C-04Sem TLS#327
C-05CDC sem auth/retry#328
H-01N+1 /scan#329
H-02Batch sem limite#330
H-03GraphQL playground#331
H-04WebSocket sem auth#332
H-05Rate limiter Mutex bottleneck#333
H-06Idempotency não integrado#334
H-07Env vars sem validação#335
H-08engine.keys() OOM#336
M-01Workers ilimitados#337
M-02Sem CSRF#338
M-03Token timing attack#339
M-04Backup sem criptografia#340
M-05Retry blocking sleep#341
M-06CDC sem timeout#342
M-07Falta auditoria logs#343
M-08Degradation não integrado#344
M-09Sem limite conexões/IP#345
M-10Sem cargo audit no CI#346
DB-04Range delete ausente#347
L-01CLI sem token mgmt#348
L-02Dashboard reload#349
L-03Endpoints duplicados#350
L-04Health checks incompletos#351
L-05Mé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.