snapshot.hpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. #pragma once
  2. #include "../document.hpp"
  3. #include "../memory_store.hpp"
  4. #include <filesystem>
  5. #include <functional>
  6. #include <optional>
  7. #include <string>
  8. #include <vector>
  9. namespace smartbotic::database {
  10. /**
  11. * Snapshot file format:
  12. *
  13. * Header (64 bytes):
  14. * - Magic: "CALSNAP1" (8 bytes)
  15. * - Version: uint32 (4 bytes)
  16. * - Timestamp: uint64 (8 bytes)
  17. * - WAL Sequence: uint64 (8 bytes) - Sequence at snapshot time
  18. * - Document Count: uint64 (8 bytes)
  19. * - Collection Count: uint32 (4 bytes)
  20. * - Uncompressed Size: uint64 (8 bytes)
  21. * - Compressed Size: uint64 (8 bytes)
  22. * - Compression Type: uint32 (4 bytes) - 0=none, 1=lz4
  23. * - Header Checksum: uint32 (4 bytes)
  24. *
  25. * Body layout (v4, compressed):
  26. * Sequence of LZ4-compressed chunks, each prefixed with length:
  27. * - uint32_t uncompressed_size (<= 16 MB per chunk)
  28. * - uint32_t compressed_size
  29. * - uint8_t[compressed_size] (LZ4 block)
  30. * Terminated by an end marker (uncompressed_size=0, compressed_size=0).
  31. * header.compressedSize = total body bytes including length prefixes and end marker.
  32. * header.uncompressedSize = sum of all chunks' uncompressed sizes (original payload size).
  33. *
  34. * Body layout (v3, compressed):
  35. * Single LZ4 block of header.compressedSize bytes, decompressing to header.uncompressedSize bytes.
  36. *
  37. * Body payload (after decompression, same in v3 and v4):
  38. * For each collection:
  39. * - Collection name length: uint16
  40. * - Collection name: bytes
  41. * - Collection options JSON length: uint32
  42. * - Collection options JSON: bytes
  43. * - Document count: uint64
  44. * For each document:
  45. * - Document JSON length: uint32
  46. * - Document JSON: bytes
  47. * (v2+) Version history:
  48. * - History entry count: uint64 (number of doc IDs with history)
  49. * For each doc ID with history:
  50. * - Doc ID length: uint16
  51. * - Doc ID: bytes
  52. * - Version count: uint32
  53. * For each version:
  54. * - Version JSON length: uint32
  55. * - Version JSON: bytes
  56. * (v3+) Vector data:
  57. * - Vector count: uint64 (number of vectors in this collection)
  58. * For each vector:
  59. * - Doc ID length: uint16
  60. * - Doc ID: bytes
  61. * - Vector dimension: uint32
  62. * - Vector data: float32[dimension] (raw bytes)
  63. *
  64. * Footer:
  65. * - Body checksum: uint32
  66. */
  67. struct SnapshotHeader {
  68. char magic[8] = {'C', 'A', 'L', 'S', 'N', 'A', 'P', '1'};
  69. uint32_t version = 4; // v4 = streaming/chunked body
  70. uint64_t timestamp = 0;
  71. uint64_t walSequence = 0;
  72. uint64_t documentCount = 0;
  73. uint32_t collectionCount = 0;
  74. uint64_t uncompressedSize = 0;
  75. uint64_t compressedSize = 0;
  76. uint32_t compressionType = 0; // 0=none, 1=lz4
  77. uint32_t headerChecksum = 0;
  78. };
  79. /**
  80. * Snapshot manager for creating and loading snapshots.
  81. */
  82. class SnapshotManager {
  83. public:
  84. struct Config {
  85. std::filesystem::path snapshotDir;
  86. bool compressionEnabled = true;
  87. uint32_t maxSnapshots = 5; // Keep last N snapshots
  88. // NEW in v1.6.1: durability
  89. bool validateAfterWrite = true;
  90. bool cleanupOnlyIfVerified = true;
  91. };
  92. explicit SnapshotManager(Config config);
  93. ~SnapshotManager() = default;
  94. // Non-copyable
  95. SnapshotManager(const SnapshotManager&) = delete;
  96. SnapshotManager& operator=(const SnapshotManager&) = delete;
  97. /**
  98. * Create a snapshot from the current state of the memory store.
  99. * @param store The memory store to snapshot
  100. * @param walSequence Current WAL sequence number
  101. * @return Path to the created snapshot file
  102. */
  103. std::filesystem::path createSnapshot(const MemoryStore& store, uint64_t walSequence);
  104. /**
  105. * Load the most recent snapshot into the memory store.
  106. * @param store The memory store to load into
  107. * @return The WAL sequence at which the snapshot was taken (or 0 if no snapshot)
  108. */
  109. uint64_t loadLatestSnapshot(MemoryStore& store);
  110. /**
  111. * Load a specific snapshot into the memory store.
  112. * @param path Path to the snapshot file
  113. * @param store The memory store to load into
  114. * @return The WAL sequence at which the snapshot was taken
  115. */
  116. uint64_t loadSnapshot(const std::filesystem::path& path, MemoryStore& store);
  117. /**
  118. * Attempt to load snapshots in order, trying newest first and falling
  119. * back to older ones if the newer ones are corrupt. Used by recovery
  120. * mode SnapshotFallback and auto-escalation from Normal.
  121. *
  122. * @param store The store to load into
  123. * @param outUsed If non-null, set to the path of the snapshot that loaded
  124. * @param outAttempted If non-null, set to how many snapshots were tried
  125. * @return WAL sequence from the loaded snapshot
  126. * @throws std::runtime_error if all snapshots fail to load
  127. */
  128. uint64_t loadWithFallback(MemoryStore& store,
  129. std::filesystem::path* outUsed = nullptr,
  130. size_t* outAttempted = nullptr);
  131. /**
  132. * Get list of available snapshots sorted by timestamp (newest first).
  133. */
  134. [[nodiscard]] std::vector<std::filesystem::path> listSnapshots() const;
  135. /**
  136. * Get info about a snapshot file.
  137. */
  138. [[nodiscard]] std::optional<SnapshotHeader> getSnapshotInfo(const std::filesystem::path& path) const;
  139. /**
  140. * Delete old snapshots, keeping only the most recent ones.
  141. */
  142. void cleanupOldSnapshots();
  143. /**
  144. * Verify a snapshot file's integrity.
  145. */
  146. [[nodiscard]] bool verifySnapshot(const std::filesystem::path& path) const;
  147. /// v2.17.0 - delete every snapshot except `keep` (the at-rest seal).
  148. size_t removeAllExcept(const std::filesystem::path& keep);
  149. private:
  150. /**
  151. * Generate a filename for a new snapshot.
  152. */
  153. [[nodiscard]] std::string generateFilename() const;
  154. /**
  155. * Compress data using LZ4.
  156. */
  157. [[nodiscard]] std::vector<uint8_t> compress(const std::vector<uint8_t>& data) const;
  158. /**
  159. * Decompress data using LZ4.
  160. */
  161. [[nodiscard]] std::vector<uint8_t> decompress(const std::vector<uint8_t>& data,
  162. uint64_t uncompressedSize) const;
  163. /**
  164. * Serialize store data to bytes.
  165. */
  166. [[nodiscard]] std::vector<uint8_t> serializeStore(const MemoryStore& store,
  167. uint64_t& docCount,
  168. uint32_t& collCount) const;
  169. /**
  170. * Deserialize bytes into store.
  171. * @param snapshotVersion Snapshot format version (for backward compatibility)
  172. */
  173. void deserializeStore(const std::vector<uint8_t>& data, MemoryStore& store,
  174. uint32_t snapshotVersion = 3) const;
  175. Config config_;
  176. };
  177. } // namespace smartbotic::database