snapshot.hpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. // 2.20.1: uncompressed bytes per LZ4 chunk. The writer streams one
  92. // chunk at a time to disk, so this (plus its compressed copy) is the
  93. // writer's buffer, not the store's size. Tests lower it.
  94. size_t chunkBytes = 16 * 1024 * 1024;
  95. };
  96. /// 2.20.1 - a snapshot that started and never finished (the process was
  97. /// killed while writing it: OOM, SIGKILL, power). Read at boot from the
  98. /// marker createSnapshot leaves while it runs.
  99. struct InterruptedSnapshot {
  100. uint64_t startedMs = 0; // wall clock, ms since epoch
  101. uint64_t walSequence = 0; // the WAL sequence it was taken at
  102. };
  103. explicit SnapshotManager(Config config);
  104. ~SnapshotManager() = default;
  105. // Non-copyable
  106. SnapshotManager(const SnapshotManager&) = delete;
  107. SnapshotManager& operator=(const SnapshotManager&) = delete;
  108. /**
  109. * Create a snapshot from the current state of the memory store.
  110. * @param store The memory store to snapshot
  111. * @param walSequence Current WAL sequence number
  112. * @return Path to the created snapshot file
  113. */
  114. std::filesystem::path createSnapshot(const MemoryStore& store, uint64_t walSequence);
  115. /**
  116. * Load the most recent snapshot into the memory store.
  117. * @param store The memory store to load into
  118. * @return The WAL sequence at which the snapshot was taken (or 0 if no snapshot)
  119. */
  120. uint64_t loadLatestSnapshot(MemoryStore& store);
  121. /**
  122. * Load a specific snapshot into the memory store.
  123. * @param path Path to the snapshot file
  124. * @param store The memory store to load into
  125. * @return The WAL sequence at which the snapshot was taken
  126. */
  127. uint64_t loadSnapshot(const std::filesystem::path& path, MemoryStore& store);
  128. /**
  129. * Attempt to load snapshots in order, trying newest first and falling
  130. * back to older ones if the newer ones are corrupt. Used by recovery
  131. * mode SnapshotFallback and auto-escalation from Normal.
  132. *
  133. * @param store The store to load into
  134. * @param outUsed If non-null, set to the path of the snapshot that loaded
  135. * @param outAttempted If non-null, set to how many snapshots were tried
  136. * @return WAL sequence from the loaded snapshot
  137. * @throws std::runtime_error if all snapshots fail to load
  138. */
  139. uint64_t loadWithFallback(MemoryStore& store,
  140. std::filesystem::path* outUsed = nullptr,
  141. size_t* outAttempted = nullptr);
  142. /**
  143. * Get list of available snapshots sorted by timestamp (newest first).
  144. */
  145. [[nodiscard]] std::vector<std::filesystem::path> listSnapshots() const;
  146. /** Remove snapshot .tmp files a killed process left. Boot only: a snapshot
  147. * in progress owns its .tmp. */
  148. void removeOrphanedTmpFiles() const;
  149. /**
  150. * Get info about a snapshot file.
  151. */
  152. [[nodiscard]] std::optional<SnapshotHeader> getSnapshotInfo(const std::filesystem::path& path) const;
  153. /**
  154. * Delete old snapshots, keeping only the most recent ones.
  155. */
  156. void cleanupOldSnapshots();
  157. /**
  158. * Verify a snapshot file's integrity.
  159. */
  160. [[nodiscard]] bool verifySnapshot(const std::filesystem::path& path) const;
  161. /// v2.17.0 - delete every snapshot except `keep` (the at-rest seal).
  162. size_t removeAllExcept(const std::filesystem::path& keep);
  163. /// 2.20.1 - the snapshot that was in progress when the process last died,
  164. /// if any. A process killed by the kernel cannot log its own death, so
  165. /// this is how the NEXT boot learns that snapshots are not completing
  166. /// (the marker stays until a snapshot completes, so every boot of a crash
  167. /// loop reports it).
  168. [[nodiscard]] std::optional<InterruptedSnapshot> interruptedSnapshot() const;
  169. /// Path of the in-progress marker (for tests and the CLI).
  170. [[nodiscard]] std::filesystem::path inProgressMarkerPath() const;
  171. private:
  172. /**
  173. * Generate a filename for a new snapshot.
  174. */
  175. [[nodiscard]] std::string generateFilename() const;
  176. /**
  177. * Compress data using LZ4.
  178. */
  179. [[nodiscard]] std::vector<uint8_t> compress(const std::vector<uint8_t>& data) const;
  180. /**
  181. * Decompress data using LZ4.
  182. */
  183. [[nodiscard]] std::vector<uint8_t> decompress(const std::vector<uint8_t>& data,
  184. uint64_t uncompressedSize) const;
  185. /**
  186. * Serialize store data into `sink`, a piece at a time (2.20.1: before,
  187. * this returned the whole body as one buffer).
  188. */
  189. template <typename Sink>
  190. void serializeStore(const MemoryStore& store, Sink& sink,
  191. uint64_t& docCount, uint32_t& collCount) const;
  192. /**
  193. * Deserialize bytes into store.
  194. * @param snapshotVersion Snapshot format version (for backward compatibility)
  195. */
  196. void deserializeStore(const std::vector<uint8_t>& data, MemoryStore& store,
  197. uint32_t snapshotVersion = 3) const;
  198. Config config_;
  199. };
  200. } // namespace smartbotic::database