#pragma once #include "../document.hpp" #include "../memory_store.hpp" #include #include #include #include #include namespace smartbotic::database { /** * Snapshot file format: * * Header (64 bytes): * - Magic: "CALSNAP1" (8 bytes) * - Version: uint32 (4 bytes) * - Timestamp: uint64 (8 bytes) * - WAL Sequence: uint64 (8 bytes) - Sequence at snapshot time * - Document Count: uint64 (8 bytes) * - Collection Count: uint32 (4 bytes) * - Uncompressed Size: uint64 (8 bytes) * - Compressed Size: uint64 (8 bytes) * - Compression Type: uint32 (4 bytes) - 0=none, 1=lz4 * - Header Checksum: uint32 (4 bytes) * * Body layout (v4, compressed): * Sequence of LZ4-compressed chunks, each prefixed with length: * - uint32_t uncompressed_size (<= 16 MB per chunk) * - uint32_t compressed_size * - uint8_t[compressed_size] (LZ4 block) * Terminated by an end marker (uncompressed_size=0, compressed_size=0). * header.compressedSize = total body bytes including length prefixes and end marker. * header.uncompressedSize = sum of all chunks' uncompressed sizes (original payload size). * * Body layout (v3, compressed): * Single LZ4 block of header.compressedSize bytes, decompressing to header.uncompressedSize bytes. * * Body payload (after decompression, same in v3 and v4): * For each collection: * - Collection name length: uint16 * - Collection name: bytes * - Collection options JSON length: uint32 * - Collection options JSON: bytes * - Document count: uint64 * For each document: * - Document JSON length: uint32 * - Document JSON: bytes * (v2+) Version history: * - History entry count: uint64 (number of doc IDs with history) * For each doc ID with history: * - Doc ID length: uint16 * - Doc ID: bytes * - Version count: uint32 * For each version: * - Version JSON length: uint32 * - Version JSON: bytes * (v3+) Vector data: * - Vector count: uint64 (number of vectors in this collection) * For each vector: * - Doc ID length: uint16 * - Doc ID: bytes * - Vector dimension: uint32 * - Vector data: float32[dimension] (raw bytes) * * Footer: * - Body checksum: uint32 */ struct SnapshotHeader { char magic[8] = {'C', 'A', 'L', 'S', 'N', 'A', 'P', '1'}; uint32_t version = 4; // v4 = streaming/chunked body uint64_t timestamp = 0; uint64_t walSequence = 0; uint64_t documentCount = 0; uint32_t collectionCount = 0; uint64_t uncompressedSize = 0; uint64_t compressedSize = 0; uint32_t compressionType = 0; // 0=none, 1=lz4 uint32_t headerChecksum = 0; }; /** * Snapshot manager for creating and loading snapshots. */ class SnapshotManager { public: struct Config { std::filesystem::path snapshotDir; bool compressionEnabled = true; uint32_t maxSnapshots = 5; // Keep last N snapshots // NEW in v1.6.1: durability bool validateAfterWrite = true; bool cleanupOnlyIfVerified = true; }; explicit SnapshotManager(Config config); ~SnapshotManager() = default; // Non-copyable SnapshotManager(const SnapshotManager&) = delete; SnapshotManager& operator=(const SnapshotManager&) = delete; /** * Create a snapshot from the current state of the memory store. * @param store The memory store to snapshot * @param walSequence Current WAL sequence number * @return Path to the created snapshot file */ std::filesystem::path createSnapshot(const MemoryStore& store, uint64_t walSequence); /** * Load the most recent snapshot into the memory store. * @param store The memory store to load into * @return The WAL sequence at which the snapshot was taken (or 0 if no snapshot) */ uint64_t loadLatestSnapshot(MemoryStore& store); /** * Load a specific snapshot into the memory store. * @param path Path to the snapshot file * @param store The memory store to load into * @return The WAL sequence at which the snapshot was taken */ uint64_t loadSnapshot(const std::filesystem::path& path, MemoryStore& store); /** * Attempt to load snapshots in order, trying newest first and falling * back to older ones if the newer ones are corrupt. Used by recovery * mode SnapshotFallback and auto-escalation from Normal. * * @param store The store to load into * @param outUsed If non-null, set to the path of the snapshot that loaded * @param outAttempted If non-null, set to how many snapshots were tried * @return WAL sequence from the loaded snapshot * @throws std::runtime_error if all snapshots fail to load */ uint64_t loadWithFallback(MemoryStore& store, std::filesystem::path* outUsed = nullptr, size_t* outAttempted = nullptr); /** * Get list of available snapshots sorted by timestamp (newest first). */ [[nodiscard]] std::vector listSnapshots() const; /** * Get info about a snapshot file. */ [[nodiscard]] std::optional getSnapshotInfo(const std::filesystem::path& path) const; /** * Delete old snapshots, keeping only the most recent ones. */ void cleanupOldSnapshots(); /** * Verify a snapshot file's integrity. */ [[nodiscard]] bool verifySnapshot(const std::filesystem::path& path) const; /// v2.17.0 - delete every snapshot except `keep` (the at-rest seal). size_t removeAllExcept(const std::filesystem::path& keep); private: /** * Generate a filename for a new snapshot. */ [[nodiscard]] std::string generateFilename() const; /** * Compress data using LZ4. */ [[nodiscard]] std::vector compress(const std::vector& data) const; /** * Decompress data using LZ4. */ [[nodiscard]] std::vector decompress(const std::vector& data, uint64_t uncompressedSize) const; /** * Serialize store data to bytes. */ [[nodiscard]] std::vector serializeStore(const MemoryStore& store, uint64_t& docCount, uint32_t& collCount) const; /** * Deserialize bytes into store. * @param snapshotVersion Snapshot format version (for backward compatibility) */ void deserializeStore(const std::vector& data, MemoryStore& store, uint32_t snapshotVersion = 3) const; Config config_; }; } // namespace smartbotic::database