Repository navigation
Releases
Releases · vubon/kachedb
v0.5.0 — Production Hardening, Bounded Durability & Crash Recovery
[v0.5.0] — 2026-11-21
⚠️ Upgrade & Compatibility Notes
- Upgrading from
v0.4.0(KDB\x05): Snapshots where all KV entries carry full key names load automatically and upgrade to Snapshot Format V7 (KDB\x07) on the next save. - Upgrading from
v0.3.xor older (KDB\x02–KDB\x04): Legacy snapshots containing KV entries (kv_count > 0) are intentionally rejected at startup (SnapshotError::MissingKeyBytes) because pre-v0.4.0snapshots persisted only one-way 64-bit hash digests without original key bytes. To enforce full key identity and eliminate silent hash-collision aliasing, migrate from a complete source or back up and start fresh (vector-only V2–V4 snapshots with0KV entries still load directly). - Legacy Snapshot + Non-Empty AOF: Pairing an uncheckpointed legacy snapshot with a non-empty AOF whose recovery base cannot be proven now fails fast with a migration error instead of risking silent state divergence.
- Strict Protocol Bounds: Client commands exceeding 64 MiB total frame size, 2 MiB per bulk argument, or 65,536 arguments are now rejected upfront.
🛡️ Production Hardening, Bounded Durability & Crash Recovery (ADR 6)
-
Coordinated AOF Background Rewrite Engine (
BGREWRITEAOF):- Implemented live, concurrent append-only log compaction via
BGREWRITEAOFwithout stalling foreground client command processing. - Snapshot base capture under unified commit fence (
durability::with_commit_fence) freezing KV entries, expiration deadlines, and vector graphs (HNSW and Flat). - Bounded in-memory delta buffer (64 MiB / 65,536 journal records) tracking mutating client operations during snapshot capture; cleanly cancels background rewrite if delta capacity exhausts.
- Writer thread atomic cutover: flushes delta records, fsyncs replacement file, performs atomic rename over active journal, swaps file descriptors retaining write locks, and synchronizes parent directory (
sync_directory). - Standalone log recovery through
scan_baseand streamingChecksummedReadervalidating IEEE 802.3 CRC32 checksums before hydrating in-memory state.
- Implemented live, concurrent append-only log compaction via
-
Full Key Byte Identity & Snapshot Formats V6 / V7 (
KDB\x06/KDB\x07):- Enforced full byte-for-byte equality verification (
entry.key() == key) during SwissTable probing, eliminating false-positive key hits across colliding hash fingerprints. - Slot-scoped overflow storage (
slot_overflow_keys) mapping unique slot indices to heap-allocated key bytes for keys exceeding 40 bytes, preventing hash collisions from overwriting neighboring entries. - Snapshot Formats V6 (
KDB\x06) & V7 (KDB\x07): Persists explicit key lengths and full key bytes for every KV entry alongside journal checkpoints and HNSW vector graphs (KDB\x07is the canonical active format). Automatically upgrades named V5 snapshots while rejecting anonymous V2–V4 KV entries (MissingKeyBytes) to prevent silent key aliasing.
- Enforced full byte-for-byte equality verification (
-
Bounded Connection Ingress & Frame Parser Caps:
- Enforced strict 64 MiB ingress buffer capacity limits across epoll, io_uring, and TLS plaintext byte streams, proactively mitigating memory-exhaustion denial of service.
- Introduced
CommandFrameDecoderenforcing upfront protocol constraints: 64 MiB total command frame length, 2 MiB bulk argument cap, and 65,536 maximum argument count. - All parser pointer offsets and size computations use checked integer arithmetic (
checked_add,checked_mul) preventing integer overflow exploits. - Frame boundary parser reset prevents deserialization state leakage across pipelined commands; isolated historical AOF replay via
parse_command_frame_for_replay.
-
Atomic Two-Phase MSET (
MSET):- Implemented strict two-phase commit (2PC) reservation and write execution across SwissTable shards.
- Pre-allocates and reserves slots before mutation; rolls back cleanly upon arena exhaustion or validation failure, guaranteeing all-or-nothing atomicity with zero partial writes.
-
Bounded Durability Queue & Safe Checkpoint Recovery:
- Dedicated background AOF writer thread consuming mutations over a bounded, lock-free ring channel.
- Graceful server shutdown barrier draining pending write records prior to process exit.
- Crash recovery guarantees: replays strictly the log suffix past the proven checkpoint sequence number, validating IEEE 802.3 CRC32 record checksums.
-
Slot Lifetime Synchronization & Cross-Worker Deallocation:
- Expiration re-check in
advance_expired_entriesensures live keys updated concurrently are never evicted prematurely. - Cross-worker deallocation inboxes prevent memory leaks and slot corruption during cross-thread frees.
- Bounded timing wheel bucket sweeps prevent latency spikes during large forward clock jumps.
- Expiration re-check in
v0.4.0 — Keyspace Cursor & Pattern Scanning (SCAN, HSCAN)
[v0.4.0] — 2026-11-08
🔍 Keyspace Cursor & Pattern Scanning (SCAN, HSCAN)
-
Stateless Bit-Reversed Cursor Over SwissTable Shards:
- Implemented
SCAN <cursor> [MATCH pattern] [COUNT count] [TYPE type]across 256 independent SwissTable shards. - Implemented home-bucket bit-reversed iteration (
next_bit_reversed_cursor) over probe chains originating ath1(key_hash, cap) == home_bucket, mathematically guaranteeing zero skipped keys across open-addressing table growth (grow), shrink-on-delete (shrink), and tombstone back-shift compaction (compact_one_group). - Bit-packed 53-bit cursor
((local_cursor << 8) | shard_idx)guarantees lossless roundtrips in JavaScript/JSON runtimes (< Number.MAX_SAFE_INTEGER). - Amortized shard lock acquisition: batches up to 256 home buckets per read lock acquisition, with bounded per-call step (
MAX_BUCKETS_PER_STEP = 4096). - Empty database fast-path: checks
shard.is_empty()across all 256 shards in$\mathcal{O}(1)$ and returns cursor"0"in a single network round-trip.
- Implemented
-
Single-Pass Hash Scanning (
HSCAN):- Implemented
HSCAN <key> <cursor> [MATCH pattern] [COUNT count]reading bounded in-slot Megaslab frames ($\le 4\text{ KB}$ ,$\le 128$ field-value pairs) in a single pass.
- Implemented
-
40-Byte Inline SSO & Zero-Bloat Key Storage:
- Replaced 42 bytes of unused padding in
HashEntry(_pad: [u8; 42]) withkey_len: u16andinline_key: [u8; 40]. - Preserved exact 64-byte L1 CPU cache-line alignment (
size_of::<HashEntry>() == 64) andsize_of::<TableEntry>() <= 24, resulting in 0 bytes of memory bloat per slot across all 256 shards. - Keys
$\le 40$ bytes are stored 100% inline with zero heap allocations on the write hot-path. - Keys
$> 40$ bytes store their 40-byte prefix inline in L1 cache and full key bytes in shard-localSwissTable::overflow_keys: HashMap<u64, Box<[u8]>>, leaving Megaslab value slots 100% unmodified.
- Replaced 42 bytes of unused padding in
-
Zero-Allocation Glob Pattern Matching Engine:
- Fast iterative byte-level glob matcher supporting wildcards (
*,?), character classes ([abc],[a-z]), negation ([^abc],[!abc]), and escape sequences (\x). - Single-star backtrack anchor preventing exponential ReDoS backtrack vulnerabilities (CVE-2022-36021).
-
CompiledPatternliteral-prefix fast-path evaluates and rejects non-matching keys directly from the 40-byte L1 prefix before ever accessingoverflow_keys.
- Fast iterative byte-level glob matcher supporting wildcards (
-
Snapshot Format V5 (
KDB\x05):- Introduced Snapshot V5 format persisting
[key_len: u16][key_bytes]alongside each KV payload. - Full backward compatibility: seamlessly loads legacy V2, V3, and V4 snapshots without keys (
key_len = 0), logging a warning and lazily upgrading them on write (SET,HSET,EXPIRE,PERSIST) or AOF recovery. - Added
anonymous_keys:<count>metric toINFOcommand.
- Introduced Snapshot V5 format persisting
-
Protocol Error Handling & Wire Framing Decoupling:
- Added
parse_command_frameto cleanly decouple wire transport framing from command argument validation. - Semantic command errors (
InvalidCursor,SyntaxError,WrongArgumentCount,PatternTooLong) consume the frame, return-ERR ...\r\nto the client, and keep the TCP connection alive.
- Added
-
Compaction & AOF Rewrite Integrity:
- Fixed
BGREWRITEAOFinkachedb-serverto serializeVALUE_TYPE_HASHentries usingHashSlotFrame::encode_pairsasAofOp::HSet(rather than stringSet), and emit follow-upAofOp::Expireframes whenexpire_at > 0.
- Fixed
-
CLI & Benchmarking Tools:
- Updated
kachedb-cli snapshot-infoforensic inspector to recognize and validateKDB\x05plaintext and encrypted snapshots. - Added
--command SCANsupport to the nativekachedb-benchharness.
- Updated
-
Python Client SDK (
kachedb):- Added native
scan()andhscan()methods withMATCH,COUNT, andTYPEfiltering toKacheClient. - Added Pythonic generators
scan_iter()andhscan_iter()for seamless multi-page iteration. - Added unit test suite covering mock wire payloads and live client round-trips against KacheDB daemon.
- Added native
v0.3.2 — Container Restart Persistence Fix & Deterministic XXH3 Hasher
[v0.3.2] — 2026-11-07
🐛 Bug Fixes & Persistence Reliability
- Zero KV Data Loss on Container Restarts (
dump.kdb):- Fixed a shutdown ordering race where worker threads dropped their thread-local
SlabPoolarenas upon exiting their event loop before the snapshot worker could capture state. Dropping pools unregisteredMegaslabArenas fromGLOBAL_ARENAS, causingresolve_slot_ptr()to returnNoneand overwritingdump.kdbwith 0 KV keys. - Introduced
ShutdownBarrierinkachedb-net, ensuring worker threads pause after halting network event loops while keeping their memory pools fully allocated and registered. - The main server thread now deterministically halts connection dispatch, signals background workers, performs the final shutdown snapshot, and only then releases worker threads for orderly memory reclamation.
- Fixed a shutdown ordering race where worker threads dropped their thread-local
- Cross-Process Deterministic Key Hashing (
kachedb-hash):- Switched
hash_keyinSwissTablefrom per-process randomizedAHasher::default()toxxhash_rust::xxh3::xxh3_64. - Guarantees that key hashes saved in
dump.kdbremain 100% deterministic and reachable across server and container restarts across all CPU architectures. - Added deterministic hash stability regression tests in
crates/kachedb-hash.
- Switched
- Dynamic Version Metadata & Python Bindings:
- Synchronized
HELLO,INFO, and daemon startup logs to compile-timeenv!("CARGO_PKG_VERSION"). - Bumped Python bindings in
bindings/pythonto0.3.2.
- Synchronized
v0.3.1 — Python SDK Redis Hash Methods & Array Support
[v0.3.1] — 2026-10-05
🐍 Python SDK Redis Hash Methods & Array Parsing
- Redis Hash Commands in
KacheClient(bindings/python):- Added native hash methods:
hset(with single-pair and dict mapping support),hget,hdel,hexists,hlen, andhgetall. - Implemented recursive RESP array (
*) decoding in_read_response(). - Added mock socket unit tests and live hash roundtrip tests in
test_client.py.
- Added native hash methods:
⚙️ CI & CLI Enhancements
- Toolchain Determinism: Pinned workspace and CI Rust toolchain to
1.97.1viarust-toolchain.tomland GitHub Actions workflows. - One-Shot CLI Execution: Added
kachedb-cli -p <PORT> <COMMAND> [ARGS...]for one-shot command execution and Docker healthchecks.
v0.3.0 — Redis Hash Primitives & Sub-25ns In-Slot Directory
📦 Redis Hash Primitives (HSET, HGET, HDEL, HEXISTS, HLEN, HGETALL)
-
Strict O(1) In-Slot Open-Addressing Directory:
- Implemented in-slot open-addressing directory packed directly inside pre-allocated 64-byte aligned Megaslab slots, eliminating pointer fragmentation and cache misses.
- Achieved sub-25 ns point lookups (
HGET,HEXISTS) resolving within a single L1 CPU cache line. - Zero heap allocation on the hot path for requests with
$\le 8$ field-value pairs (SmallVecstack buffer).
-
Megaslab App-Cache Slot Isolation:
- Hashes strictly reside in
AppSmall(128 B),AppMedium(512 B), orAppLarge(4 KB) slots, completely isolated from tensor slab pools. - Automatic slot resizing and pair relocation as fields grow, capped at 4096 bytes per hash key.
- Hashes strictly reside in
-
Strict Type Guards & SwissTable Type Tag:
- Added
value_typetag (VALUE_TYPE_HASH = 1,VALUE_TYPE_STRING = 0) toHashEntrySwissTable metadata. - Added type guards across all string commands (
GET,APPEND,STRLEN,INCR,DECR,INCRBY,DECRBY) returning-WRONGTYPE Operation against a key holding the wrong kind of value. - Updated
TYPEcommand to returnhash,string,vector, ornone.MGETreturnsnilfor non-string keys.
- Added
-
ACID Persistence & Snapshot Format V4 (
KDB\x04):-
AOF Logging: Hash mutations logged as logical pairs with opcodes
0x07(HSet) and0x08(HDel), ensuring deterministic append-only journal replay. -
Snapshot Format V4: Introduced
KDB\x04format with typed record headers (RecordType = 0x01for Hash) supporting both plaintext and hardware-accelerated encrypted snapshots (AES-256-GCM / ChaCha20-Poly1305) with seamless backward-compatibility for legacyKDB\x02andKDB\x03formats.
-
AOF Logging: Hash mutations logged as logical pairs with opcodes
🛠️ Architecture & Tooling Modularization
- Modularization of
kachedb-net/src/connection/:- Refactored monolithic 3,300-line
connection.rsinto domain-specific command handler submodules:strings.rs,hashes.rs,vectors.rs,expiry.rs,admin.rs,mod.rs, and isolatedtests.rs.
- Refactored monolithic 3,300-line
- Modularization of
kachedb-cli:- Restructured CLI into dedicated submodules:
repl.rs(interactive terminal, quoted tokenizer, pretty-printer),snapshot.rs(forensic inspector supporting V2, V3, and V4 snapshots with CRC32 verification),bench.rs(pipelined throughput benchmark), andmain.rs(clean CLI argument parsing with one-shot execution support likekachedb-cli -p 6379 ping). - Documented Hash, Admin, and Vector Index commands in interactive
helpreference card.
- Restructured CLI into dedicated submodules:
- Benchmarking Engine (
kachedb-bench&run_benchmark.sh):- Expanded native
kachedb-benchharness with--command hset,hget, andhmixoperations, pipelining, and high-resolution latency histograms. - Updated
docker/run_benchmark.shwith automated versioned report generation (benchmark_comparison_results_<version>_hash.md).
- Expanded native
- CI & Toolchain Determinism:
- Pinned repository and CI Rust toolchain to
1.97.1viarust-toolchain.tomland GitHub Actions workflows.
- Pinned repository and CI Rust toolchain to
v0.2.0: Snapshot Encryption-at-Rest & Hybrid Context Engine
🔐 Snapshot Encryption-at-Rest (dump.kdb)
-
Hardware-Accelerated Streaming AEAD Encryption:
- Implemented zero-overhead snapshot encryption using AES-256-GCM (AES-NI / ARMv8 Crypto Extensions) and ChaCha20-Poly1305 streaming AEAD fallback.
- Zero hot-path overhead: in-memory SwissTable lookups and SIMD vector dot products operate on plaintext in memory; encryption and decryption stream through 64 KiB buffers out-of-band during background snapshot disk writes and boot hydration.
- Per-chunk 96-bit nonces (
$Nonce_i = MasterNonce \oplus i$ ) and index-bound AAD ($AAD = i$ ) prevent chunk reordering, substitution, or truncation.
-
Wire Format
KDB\x03& Seamless Backward Compatibility:- Added
KDB\x03wire format containing 32-byte HKDF salt, 12-byte master nonce, encrypted 64 KiB chunks, and EOF sentinel0u32before the IEEE 802.3 CRC32 trailer. - Automatically loads unencrypted legacy
KDB\x02and unencryptedKDB\x03snapshots with zero key prompts or configuration.
- Added
-
Key Ingestion & Zeroization:
- Supports 32-byte raw binary master key files (
snapshot-encryption-key-file), 64-character hex keys, or passphrases derived with HKDF-SHA256 (snapshot-encryption-key). - Volatile memory zeroization upon drop (
std::ptr::write_volatile).
- Supports 32-byte raw binary master key files (
-
Offline Snapshot Diagnostics (
kachedb-cli):- Added
kachedb-cli snapshot-info <FILE.kdb>subcommand to inspect format version, timestamp, encryption status, cipher suite, salt, master nonce, and verify full CRC32 checksum integrity.
- Added
🧠 Hybrid Context Engine & Vector Upgrades
- 64-Bit Tag Bitmask Pre-Filtering:
- High-speed bitwise pre-filtering skipping irrelevant vectors before SIMD dot product computation.
- Hierarchical Document Chunking & Parent Pointers:
- Added
parent_keylinkage in vector entries to seamlessly retrieve full parent context documents from SwissTable.
- Added
- Automatic Multi-Core Auto-Parallelism:
- Setting
workers 0inkachedb.confautomatically detects available physical/logical CPU cores.
- Setting
- Antigravity IDE Integration Guide:
- Added comprehensive guide and production-tested
.agents/AGENTS.mdrule template (docs/guides/agentic-ide-integration.md) for configuring KacheDB as an autonomous persistent memory layer for Antigravity IDE coding agents.
- Added comprehensive guide and production-tested