interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-store / src / lib.rs

4225 lines · 172429 bytes Raw Blame History
1//! Durable single-writer changeset storage engine (`synapse-store`, Gate 1).
2//!
3//! Provides:
4//! - Append-only WAL (`SWAL` v1, 88-byte header) with Castagnoli CRC-32C, SHA-256 hash chain,
5//! monotonic `WalSeq` validation, and explicit `FsyncPolicy`.
6//! - Content-addressed immutable blobs with atomic visibility tied strictly to committed
7//! `WalSeq` watermarks (preventing phantom visibility after crashes): one file each
8//! (`blobs/<2-hex>/<64-hex>`) in v1 stores, inside the append-only segment files in
9//! group-commit stores (ADR 0003 A2, [`segment`]).
10//! - Idempotent ingest (`IdempotencyKey`), snapshot reads (`snapshot_seq`), read-your-writes
11//! enforcement (`min_visible_seq`), deterministic replay, and admission backpressure.
12//! - Atomic checkpointing, WAL compaction, and root-based garbage collection (`GarbageRoot`).
13//! - Deterministic fault injection for torn headers, torn payloads, CRC corruption, broken
14//! chains, sequence gaps, pre-WAL crash recovery, and child-process `SIGABRT` crash recovery.
15
16use serde::{Deserialize, Serialize};
17use sha2::{Digest, Sha256};
18use std::collections::{BTreeMap, BTreeSet};
19use std::fs::{self, File, OpenOptions};
20use std::io::{Read, Seek, SeekFrom, Write};
21use std::path::{Path, PathBuf};
22pub use synapse_auth::{SignedStateMove, StateMoveFault};
23use synapse_core::{
24 BlobDigest, ChainPath, ChangesetEnvelope, ChangesetEnvelopeV2, ChangesetId, DerivedRevision,
25 EvidenceAttachment, GitHubPullRequestProjection, IdempotencyKey, MutationOp,
26 ObsolescenceMarker, RadicleCanonicalHead, RefusalCode, RepoId, RevisionState, SynapseError,
27 SynapseResult, WalSeq,
28};
29
30#[cfg(test)]
31mod a1_tests;
32pub mod blockdev;
33#[cfg(test)]
34mod blockdev_a2_suite;
35#[cfg(test)]
36mod blockdev_tests;
37pub mod chunk;
38pub mod codec;
39#[cfg(test)]
40mod g2_tests;
41pub mod git_bridge;
42#[cfg(test)]
43mod group_tests;
44#[cfg(test)]
45mod j1_corpus;
46mod revision;
47pub mod seal;
48pub mod segment;
49#[cfg(test)]
50mod segment_tests;
51mod shared;
52pub mod wal2;
53
54use blockdev::Medium;
55pub use blockdev::{BlockDeviceConfig, FormatPolicy};
56pub use chunk::{ChunkDigest, ChunkManifest, ChunkParams};
57pub use codec::{CheckpointChain, CheckpointState, CodecRefusal, RecordCodec};
58pub use revision::{
59 verify_revision_log, AdmissionAuthority, ChangeStatus, RecordedMarker, RevisionOutcome,
60 SealReplayReport, StateMoveReplayReport, StoredRevision, DOMAIN_STATE_ROOT_REVISIONS_V1,
61};
62pub use seal::{RevisionSeal, RevisionSealKey};
63pub use shared::{GroupCommitStats, SharedStore};
64
65/// Magic bytes for a Synapse WAL frame (`b"SWAL"`).
66pub const WAL_MAGIC: [u8; 4] = *b"SWAL";
67
68/// Supported WAL frame format version.
69pub const WAL_VERSION: u16 = 1;
70
71/// Fixed byte length of a WAL frame header.
72pub const WAL_HEADER_LEN: usize = 88;
73
74/// Domain tag for WAL frame SHA-256 chain computation.
75pub const DOMAIN_WAL_FRAME_V1: &[u8] = b"SYNAPSE_WAL_FRAME_V1\0";
76
77/// Supported checkpoint manifest format version.
78pub const CHECKPOINT_VERSION: u16 = 1;
79
80/// Castagnoli CRC-32C (`0x82F63B78` reflected polynomial).
81///
82/// Uses the Arm `crc` instructions when the CPU has them (detected at run time) and the
83/// portable bitwise loop otherwise. Both produce identical values (tested).
84pub fn crc32c(bytes: &[u8]) -> u32 {
85 #[cfg(target_arch = "aarch64")]
86 {
87 if std::arch::is_aarch64_feature_detected!("crc") {
88 // SAFETY: the `crc` target feature was detected at run time.
89 return unsafe { crc32c_aarch64(bytes) };
90 }
91 }
92 crc32c_portable(bytes)
93}
94
95#[cfg(target_arch = "aarch64")]
96#[target_feature(enable = "crc")]
97unsafe fn crc32c_aarch64(bytes: &[u8]) -> u32 {
98 use std::arch::aarch64::{__crc32cb, __crc32cd};
99 let mut crc: u32 = !0;
100 let (chunks, rest) = bytes.as_chunks::<8>();
101 for c in chunks {
102 crc = __crc32cd(crc, u64::from_le_bytes(*c));
103 }
104 for &b in rest {
105 crc = __crc32cb(crc, b);
106 }
107 !crc
108}
109
110/// Portable bitwise CRC-32C (reference implementation).
111pub fn crc32c_portable(bytes: &[u8]) -> u32 {
112 let mut crc: u32 = !0;
113 for &b in bytes {
114 crc ^= u32::from(b);
115 for _ in 0..8 {
116 let mask = (crc & 1).wrapping_neg();
117 crc = (crc >> 1) ^ (0x82F6_3B78 & mask);
118 }
119 }
120 !crc
121}
122
123/// Explicit fsync durability policy for the single-writer engine.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
125pub enum FsyncPolicy {
126 /// Synchronize blob files, shard directories, and `wal.log` via `sync_all()` before
127 /// advancing `committed_seq` or acknowledging any commit.
128 EveryCommit,
129 /// Flush to OS kernel buffers on each commit and call `sync_all()` every `max_records`
130 /// commits (or on explicit `sync()`). Survives user-space process crashes once written
131 /// to the kernel page cache, but does not claim physical power-loss durability until synced.
132 BatchWindow { max_records: u32 },
133 /// Group commit with the same guarantee as `EveryCommit` (`FsyncBeforeAck`): records
134 /// go to WAL v2 (`wal.v2.log`, blobs stored inline), and every batch of up to
135 /// `max_batch_records` records is made durable with one write and one `fdatasync`
136 /// into pre-written log space before any record in it is acknowledged. Concurrent
137 /// submitters batch through [`SharedStore`]; the leader waits at most
138 /// `max_batch_delay_us` microseconds for a batch to fill (0 = natural batching only:
139 /// whatever queued while the previous batch was syncing). Opening a store with this
140 /// policy switches it to WAL v2 permanently (a marker frame in `wal.log` makes older
141 /// binaries refuse the store instead of missing commits).
142 GroupCommit {
143 max_batch_records: u32,
144 max_batch_delay_us: u32,
145 },
146}
147
148impl FsyncPolicy {
149 /// Group commit with natural batching and at most 256 records per batch.
150 pub const GROUP_COMMIT_DEFAULT: Self = Self::GroupCommit {
151 max_batch_records: 256,
152 max_batch_delay_us: 0,
153 };
154
155 fn is_group_commit(&self) -> bool {
156 matches!(self, Self::GroupCommit { .. })
157 }
158}
159
160/// Tested vs hardware durability classification attached to commit receipts.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
162pub enum DurabilityGuarantee {
163 /// `fsync` (`sync_all`) completed on blob files, directory metadata, and `wal.log`
164 /// prior to commit acknowledgment. Verified against user-space process crash and torn writes;
165 /// physical power-loss durability additionally depends on storage hardware FUA/PLP.
166 FsyncBeforeAck,
167 /// Written to OS kernel page cache without immediate `fsync`; durable against user-space
168 /// process termination (`SIGKILL`/`SIGABRT`) but not host kernel panic or power loss until flushed.
169 ProcessCrashPageCacheOnly,
170}
171
172/// Policy governing how `SynapseStore::open` handles a torn frame at the EOF tail of `wal.log`.
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
174pub enum RecoveryPolicy {
175 /// Refuse to open if any frame (including the EOF tail frame) is torn or corrupt.
176 StrictFailClosed,
177 /// If all committed frames up to `N` have valid CRC32C and SHA-256 chain links, and only
178 /// frame `N + 1` at the very end of `wal.log` is truncated/torn (from an unacknowledged write
179 /// interrupted by a crash), truncate `wal.log` back to the end of frame `N` and recover cleanly.
180 /// Any corruption before the final frame still fails closed.
181 TruncateTornTail,
182}
183
184/// Capacity, payload size, and backpressure limits for `SynapseStore`.
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186pub struct StoreLimits {
187 pub max_blob_bytes: u64,
188 pub max_paths_per_changeset: usize,
189 pub max_total_changeset_bytes: u64,
190 pub max_inflight_admissions: usize,
191 pub default_retention_window_ms: u64,
192 /// WAL v2 only: bytes of zero-filled, synced log space kept ahead of the write
193 /// position. Extending it costs one `sync_all` (journal commit) per extension, so a
194 /// larger value moves that cost out of more commits.
195 #[serde(default = "default_wal_prealloc_bytes")]
196 pub wal_prealloc_bytes: u64,
197 /// Largest WAL record payload the store writes or reads (the frame length cap). A
198 /// frame declaring a longer payload is refused before anything is allocated for it,
199 /// and the writer refuses a record above it, so every written frame stays readable.
200 /// Must exceed `max_total_changeset_bytes` plus envelope metadata (WAL v2 frames carry
201 /// their blobs inline).
202 #[serde(default = "default_max_wal_record_bytes")]
203 pub max_wal_record_bytes: u64,
204 /// Segment store (ADR 0003 A2): a new segment file is started when the active one
205 /// holds data and the next batch would end past this many bytes. A larger batch
206 /// still goes into one segment on its own.
207 #[serde(default = "default_segment_bytes")]
208 pub segment_bytes: u64,
209 /// Content-defined chunking of large blobs (ADR 0003 G2): blobs above
210 /// `chunking.threshold_bytes` are stored as chunks, each once per `ChunkDigest`.
211 /// Applies to segment stores (group commit) only; the default is the X6 outcome.
212 #[serde(default)]
213 pub chunking: ChunkParams,
214}
215
216fn default_segment_bytes() -> u64 {
217 256 * 1024 * 1024
218}
219
220fn default_wal_prealloc_bytes() -> u64 {
221 64 * 1024 * 1024
222}
223
224fn default_max_wal_record_bytes() -> u64 {
225 128 * 1024 * 1024
226}
227
228impl Default for StoreLimits {
229 fn default() -> Self {
230 Self {
231 max_blob_bytes: 16 * 1024 * 1024, // 16 MiB per blob
232 max_paths_per_changeset: 2_048,
233 max_total_changeset_bytes: 64 * 1024 * 1024, // 64 MiB per changeset
234 max_inflight_admissions: 64,
235 default_retention_window_ms: 3_600_000, // 1 hour default speculative retention
236 wal_prealloc_bytes: default_wal_prealloc_bytes(),
237 max_wal_record_bytes: default_max_wal_record_bytes(),
238 segment_bytes: default_segment_bytes(),
239 chunking: ChunkParams::default(),
240 }
241 }
242}
243
244/// Deterministic fault injection hooks for Gate 1 crash and torn-write qualification.
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246pub enum FaultInjection {
247 /// No fault injected.
248 None,
249 /// Abort WAL append after writing blobs to disk, simulating a crash before WAL frame write.
250 CrashAfterBlobWriteBeforeWalAppend,
251 /// Write only the first `bytes_written` bytes (`< 88`) of the WAL header, simulating a torn header.
252 TornWalHeaderWrite { bytes_written: usize },
253 /// Write the full 88-byte WAL header but only `bytes_written` bytes of the payload.
254 TornWalPayloadWrite { bytes_written: usize },
255 /// Flip a bit in `payload_crc32c` when writing the next WAL frame.
256 CorruptNextWalCrc,
257 /// Corrupt `prev_frame_sha256` when writing the next WAL frame.
258 CorruptNextWalChain,
259 /// Write the next WAL frame with `seq + 1` (creating a sequence gap).
260 InjectNextWalSequenceGap,
261 /// Write the next WAL frame with duplicate `seq` (reusing the current `committed_seq`).
262 InjectDuplicateWalSequence,
263 /// WAL v2: write only the first `bytes_written` bytes of the next batch, then fail the
264 /// write. The batch extent is rolled back (zeroed and synced); nothing is acknowledged.
265 FailNextBatchWrite { bytes_written: usize },
266 /// WAL v2: write the next batch completely, then report an `fdatasync` failure. The
267 /// batch is rolled back; nothing is acknowledged.
268 FailNextBatchSync,
269 /// WAL v2: as `FailNextBatchSync`, and the rollback fails too. The store refuses all
270 /// further writes until it is reopened (poisoned).
271 FailNextBatchSyncAndRollback,
272 /// WAL v2: write the first `bytes_written` bytes of the next batch, then terminate the
273 /// process with exit code [`FAULT_CRASH_EXIT_CODE`] (crash in the middle of a batch).
274 CrashMidBatchWrite { bytes_written: usize },
275 /// WAL v2: write the whole next batch without syncing, then terminate the process with
276 /// exit code [`FAULT_CRASH_EXIT_CODE`].
277 CrashBeforeBatchSync,
278 /// Segment store: write and `fdatasync` the next batch, then terminate the process
279 /// with exit code [`FAULT_CRASH_EXIT_CODE`] before the blob index is updated or
280 /// anything is acknowledged (crash between payload and index).
281 CrashAfterBatchSyncBeforeIndex,
282 /// Segment store: if the next batch rotates to a new segment, create and pre-write
283 /// the new file, then terminate the process with exit code
284 /// [`FAULT_CRASH_EXIT_CODE`] before the directory flush.
285 CrashAfterSegmentCreateBeforeDirSync,
286 /// Segment store: if the next batch rotates to a new segment, report a failure of
287 /// the directory flush. Nothing is written into the log; nothing is acknowledged.
288 FailNextSegmentDirSync,
289 /// Segment store: in the next `checkpoint_and_compact`, write the segment index
290 /// file, then terminate the process with exit code [`FAULT_CRASH_EXIT_CODE`] before
291 /// the checkpoint replaces the previous one.
292 CrashAfterSegmentIndexBeforeCheckpoint,
293}
294
295/// Exit code used by the process-terminating fault injections.
296pub const FAULT_CRASH_EXIT_CODE: i32 = 42;
297
298/// Review verdict attached to a committed changeset.
299#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
300pub struct ReviewRecord {
301 pub reviewer_did: String,
302 pub approved: bool,
303 pub comment: String,
304 pub recorded_at_ms: u64,
305}
306
307/// Record variants persisted inside WAL frames.
308#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
309pub enum WalRecord {
310 ChangesetIngest {
311 envelope: ChangesetEnvelope,
312 changeset_id: ChangesetId,
313 new_blobs: Vec<BlobDigest>,
314 },
315 EvaluationAttached {
316 changeset_id: ChangesetId,
317 attachment: EvidenceAttachment,
318 },
319 ReviewRecorded {
320 changeset_id: ChangesetId,
321 review: ReviewRecord,
322 },
323 GitProjected {
324 projection: GitHubPullRequestProjection,
325 },
326 CanonicalPromoted {
327 canonical: RadicleCanonicalHead,
328 },
329 LeaseUpdated {
330 changeset_id: ChangesetId,
331 lease_expires_at_ms: u64,
332 },
333 /// Admission of an envelope v2 revision under `chain` at server time `admitted_at_ms`
334 /// (ADR 0003 B1). Binary codec only: it has no v1 JSON form.
335 #[serde(skip)]
336 RevisionAdmitted {
337 envelope: ChangesetEnvelopeV2,
338 chain: ChainPath,
339 admitted_at_ms: u64,
340 new_blobs: Vec<BlobDigest>,
341 /// The server's keyed seal (issue #101); `None` in a store opened without a seal key.
342 seal: Option<RevisionSeal>,
343 },
344 /// An obsolescence marker recorded under `chain` at server time `recorded_at_ms`
345 /// (ADR 0003 B1). Binary codec only.
346 #[serde(skip)]
347 ObsolescenceRecorded {
348 marker: ObsolescenceMarker,
349 chain: ChainPath,
350 recorded_at_ms: u64,
351 seal: Option<RevisionSeal>,
352 },
353 /// A move of a revision to another state, signed by its mover (the audience of the
354 /// chain's leaf link) and recorded at server time `moved_at_ms` (ADR 0003 B4, issue
355 /// #89). Binary codec only.
356 #[serde(skip)]
357 RevisionStateMoved {
358 state_move: SignedStateMove,
359 moved_at_ms: u64,
360 seal: Option<RevisionSeal>,
361 },
362 /// Admission of a server-derived revision under `chain` at server time `admitted_at_ms`
363 /// (ADR 0003 B5). It references only blobs already visible, so it carries none. Binary
364 /// codec only.
365 #[serde(skip)]
366 DerivedRevisionAdmitted {
367 derived: DerivedRevision,
368 chain: ChainPath,
369 admitted_at_ms: u64,
370 seal: Option<RevisionSeal>,
371 },
372 /// One Git bridge entry of an import into `repo_id` (ADR 0003 section 5.10, step H1 cut 2;
373 /// `git_bridge`). Binary codec only. Sealed like the other revision records (issue #101).
374 #[serde(skip)]
375 GitBridgeImported {
376 repo_id: RepoId,
377 entry: git_bridge::GitBridgeEntry,
378 seal: Option<RevisionSeal>,
379 },
380}
381
382impl WalRecord {
383 pub fn kind_byte(&self) -> u8 {
384 match self {
385 Self::ChangesetIngest { .. } => 1,
386 Self::EvaluationAttached { .. } => 2,
387 Self::ReviewRecorded { .. } => 3,
388 Self::GitProjected { .. } => 4,
389 Self::CanonicalPromoted { .. } => 5,
390 Self::LeaseUpdated { .. } => 6,
391 Self::RevisionAdmitted { .. } => 7,
392 Self::ObsolescenceRecorded { .. } => 8,
393 Self::RevisionStateMoved { .. } => 9,
394 Self::GitBridgeImported { .. } => 10,
395 Self::DerivedRevisionAdmitted { .. } => 11,
396 }
397 }
398
399 /// True for the revision records a seal covers (kinds 7 to 11).
400 pub fn is_revision_record(&self) -> bool {
401 matches!(
402 self,
403 Self::RevisionAdmitted { .. }
404 | Self::ObsolescenceRecorded { .. }
405 | Self::RevisionStateMoved { .. }
406 | Self::GitBridgeImported { .. }
407 | Self::DerivedRevisionAdmitted { .. }
408 )
409 }
410
411 /// The keyed seal of a revision record (issue #101), if it carries one.
412 pub fn seal(&self) -> Option<&RevisionSeal> {
413 match self {
414 Self::RevisionAdmitted { seal, .. }
415 | Self::ObsolescenceRecorded { seal, .. }
416 | Self::RevisionStateMoved { seal, .. }
417 | Self::GitBridgeImported { seal, .. }
418 | Self::DerivedRevisionAdmitted { seal, .. } => seal.as_ref(),
419 _ => None,
420 }
421 }
422
423 fn set_seal(&mut self, value: RevisionSeal) {
424 if let Self::RevisionAdmitted { seal, .. }
425 | Self::ObsolescenceRecorded { seal, .. }
426 | Self::RevisionStateMoved { seal, .. }
427 | Self::GitBridgeImported { seal, .. }
428 | Self::DerivedRevisionAdmitted { seal, .. } = self
429 {
430 *seal = Some(value);
431 }
432 }
433
434 /// Blob digests the upserts of this record reference (ingest and revision records), and the
435 /// blobs a Git bridge objects entry maps.
436 pub fn upsert_blobs(&self) -> Vec<BlobDigest> {
437 let mutations = match self {
438 Self::GitBridgeImported { entry, .. } => return entry.blobs(),
439 Self::ChangesetIngest { envelope, .. } => &envelope.mutations,
440 Self::RevisionAdmitted { envelope, .. } => &envelope.content.mutations,
441 Self::DerivedRevisionAdmitted { derived, .. } => &derived.content.mutations,
442 _ => return Vec::new(),
443 };
444 mutations
445 .iter()
446 .filter_map(|m| match &m.op {
447 MutationOp::Upsert { blob_digest, .. } => Some(*blob_digest),
448 MutationOp::Delete => None,
449 })
450 .collect()
451 }
452}
453
454/// Stored metadata for a committed changeset in `SynapseStore`.
455#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
456pub struct StoredChangeset {
457 pub changeset_id: ChangesetId,
458 pub committed_seq: WalSeq,
459 pub envelope: ChangesetEnvelope,
460 pub evaluations: Vec<EvidenceAttachment>,
461 pub reviews: Vec<ReviewRecord>,
462 pub lease_expires_at_ms: u64,
463}
464
465/// Outcome of submitting a changeset to `SynapseStore`.
466#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
467pub enum IngestOutcome {
468 /// Newly committed at `wal_seq`.
469 Committed {
470 wal_seq: WalSeq,
471 changeset_id: ChangesetId,
472 frame_sha256: [u8; 32],
473 durability: DurabilityGuarantee,
474 },
475 /// Already committed under the same `(repo_id, idempotency_key)` with identical `ChangesetId`.
476 IdempotentDuplicate {
477 wal_seq: WalSeq,
478 changeset_id: ChangesetId,
479 },
480}
481
482/// Persisted checkpoint manifest (`checkpoint.v1`) enabling WAL compaction and GC.
483#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
484pub struct CheckpointManifest {
485 pub version: u16,
486 pub checkpoint_seq: WalSeq,
487 pub anchor_frame_sha256: [u8; 32],
488 pub changesets: BTreeMap<String, StoredChangeset>,
489 pub idempotency_index: BTreeMap<String, (WalSeq, ChangesetId)>,
490 pub blob_first_visible_seq: BTreeMap<String, WalSeq>,
491 pub github_projections: BTreeMap<u64, GitHubPullRequestProjection>,
492 pub canonical_heads: BTreeMap<String, RadicleCanonicalHead>,
493}
494
495impl Default for CheckpointManifest {
496 fn default() -> Self {
497 Self {
498 version: CHECKPOINT_VERSION,
499 checkpoint_seq: WalSeq::ZERO,
500 anchor_frame_sha256: [0u8; 32],
501 changesets: BTreeMap::new(),
502 idempotency_index: BTreeMap::new(),
503 blob_first_visible_seq: BTreeMap::new(),
504 github_projections: BTreeMap::new(),
505 canonical_heads: BTreeMap::new(),
506 }
507 }
508}
509
510/// Summary returned after running `checkpoint_and_compact`.
511#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
512pub struct CompactionReport {
513 pub checkpoint_seq: WalSeq,
514 pub anchor_frame_sha256: [u8; 32],
515 pub retained_changesets: usize,
516 pub evicted_changesets: usize,
517 pub retained_blobs: usize,
518 pub swept_blob_files: usize,
519}
520
521/// Single-writer durable changeset and content-addressed blob engine.
522pub struct SynapseStore {
523 root_dir: PathBuf,
524 blobs_dir: PathBuf,
525 wal_path: PathBuf,
526 fsync_policy: FsyncPolicy,
527 limits: StoreLimits,
528 committed_seq: WalSeq,
529 last_frame_sha256: [u8; 32],
530 unflushed_frames: u32,
531 inflight_admissions: usize,
532 fault_injection: FaultInjection,
533 changesets: BTreeMap<ChangesetId, StoredChangeset>,
534 idempotency_index: BTreeMap<(RepoId, IdempotencyKey), (WalSeq, ChangesetId)>,
535 blob_first_visible_seq: BTreeMap<BlobDigest, WalSeq>,
536 github_projections: BTreeMap<u64, GitHubPullRequestProjection>,
537 canonical_heads: BTreeMap<RepoId, RadicleCanonicalHead>,
538 torn_frames_truncated_on_open: usize,
539 /// True once `wal.log` ends with the WAL v2 marker: all new frames go to `wal.v2.log`.
540 v2_mode: bool,
541 /// Layout of the log after `wal.log`, from the marker recovery found.
542 log_layout: LogLayout,
543 /// Segment writer (taken out by the group-commit leader while it writes a batch).
544 wal_v2: Option<segment::SegmentLog>,
545 /// Read handles on the segment files, by segment id, for inline blob reads.
546 segment_readers: BTreeMap<u64, segment::SegReader>,
547 /// Where the segments and the small metadata objects live: the store directory (A2)
548 /// or a raw block device (R1).
549 medium: Medium,
550 /// End of the valid log found by recovery: (segment, byte offset).
551 wal_v2_recovered_end: (u64, u64),
552 /// The blob index: digest to its location inside a segment.
553 blob_locations: BTreeMap<BlobDigest, segment::BlobLoc>,
554 /// The chunk index (ADR 0003 G2): chunk digest to its location inside a segment.
555 chunk_locations: BTreeMap<ChunkDigest, segment::BlobLoc>,
556 /// Chunked blobs: blob digest to its manifest (chunks in order).
557 blob_chunks: BTreeMap<BlobDigest, ChunkManifest>,
558 /// Bytes of batches this store appended to its segments since it was opened.
559 log_bytes_written: u64,
560 /// Set when a failed batch could not be rolled back: every write is refused until reopen.
561 poisoned: Option<String>,
562 /// Codec new WAL records are written with (ADR 0003 A1).
563 codec: RecordCodec,
564 /// Chain of the binary checkpoint (`checkpoint.v2`) this store holds.
565 checkpoint_chain: Option<CheckpointChain>,
566 /// The store holds v1 history: a v1 checkpoint or replayed v1 JSON frames.
567 v1_history: bool,
568 /// A binary checkpoint or a binary frame was replayed: v1 JSON frames are refused.
569 binary_seen: bool,
570 /// `checkpoint.v1` is not yet the tombstone although `checkpoint.v2` exists.
571 /// Envelope v2 revisions, changes, witnesses, and markers (ADR 0003 B1).
572 revisions: revision::RevisionLedger,
573 /// The Git bridge map (step H1 cut 2), derived from the kind 10 records in `revisions`.
574 git_bridge: git_bridge::GitBridgeLedger,
575 /// The server key revision records are sealed with and checked against (issue #101).
576 revision_seal: Option<RevisionSealKey>,
577 tombstone_pending: bool,
578}
579
580/// What follows the v1 frames of `wal.log`.
581#[derive(Debug, Clone, Copy, PartialEq, Eq)]
582enum LogLayout {
583 /// No marker: a v1 store (or a new one).
584 V1,
585 /// WAL v2 marker (version 2): `wal.v2.log` alone, checkpoints emptied it and moved
586 /// retained blobs to blob files (the layout before ADR 0003 A2).
587 SingleFileV2,
588 /// Segment marker (version 3): segments `wal.v2.log`, `wal.v2.000002.log`, ... with
589 /// a segment index bound to the checkpoint (ADR 0003 A2).
590 Segments,
591}
592
593/// One upsert check from ingest step 7, evaluated in mutation order.
594#[derive(Debug, Clone)]
595enum UpsertCheck {
596 /// The provided blob has a different size than the mutation declares.
597 SizeMismatch(SynapseError),
598 /// The blob was not provided, so it must already be committed.
599 MustBeVisible { digest: BlobDigest, path: String },
600}
601
602/// Stateless half of an ingest, computed without any store lock (signature check,
603/// blob digests, limits, and for WAL v2 the encoded payload with its SHA-256 and CRC-32C).
604/// Errors from these checks are deferred so that the stateful half reports refusals in
605/// exactly the same order as [`SynapseStore::ingest_changeset`] always has.
606#[derive(Debug, Clone)]
607pub struct PreparedIngest {
608 envelope: ChangesetEnvelope,
609 changeset_id: ChangesetId,
610 path_count_error: Option<SynapseError>,
611 blob_error: Option<SynapseError>,
612 upsert_checks: Vec<UpsertCheck>,
613 new_blobs: Vec<BlobDigest>,
614 /// Provided blobs, unique and in digest order (v1 writes all of them as files).
615 provided: Vec<(BlobDigest, Vec<u8>)>,
616 encoded: Option<wal2::EncodedRecord>,
617}
618
619impl PreparedIngest {
620 /// Changeset id computed from the validated envelope.
621 pub fn changeset_id(&self) -> ChangesetId {
622 self.changeset_id
623 }
624
625 /// The validated envelope.
626 pub fn envelope(&self) -> &ChangesetEnvelope {
627 &self.envelope
628 }
629
630 fn record(&self) -> WalRecord {
631 WalRecord::ChangesetIngest {
632 envelope: self.envelope.clone(),
633 changeset_id: self.changeset_id,
634 new_blobs: self.new_blobs.clone(),
635 }
636 }
637}
638
639/// Pending (not yet durable) effects of earlier records in the same batch.
640#[derive(Debug, Default)]
641struct BatchOverlay {
642 idempotency: BTreeMap<(RepoId, IdempotencyKey), (WalSeq, ChangesetId)>,
643 changesets: BTreeMap<ChangesetId, RepoId>,
644 blobs: BTreeSet<BlobDigest>,
645 /// Chunks carried by records accepted earlier in this batch (ADR 0003 G2).
646 chunks: BTreeSet<ChunkDigest>,
647 /// Blobs stored as chunks by records accepted earlier in this batch.
648 chunked_blobs: BTreeSet<BlobDigest>,
649}
650
651/// Result of the stateful half of an ingest.
652#[derive(Debug)]
653enum Planned {
654 /// Already committed (or pending in this batch when `depends_on_batch`).
655 Duplicate {
656 wal_seq: WalSeq,
657 changeset_id: ChangesetId,
658 depends_on_batch: bool,
659 },
660 /// Refused (because of a pending record in this batch when `depends_on_batch`).
661 Refused {
662 error: SynapseError,
663 depends_on_batch: bool,
664 },
665 /// Accepted: becomes the next frame.
666 Accept,
667}
668
669/// A WAL v2 batch in flight: the writer and fault taken out of the store, plus the
670/// chain position the batch starts from.
671pub(crate) struct V2Ticket {
672 writer: segment::SegmentLog,
673 fault: FaultInjection,
674 base_seq: WalSeq,
675 prev_sha: [u8; 32],
676 /// Length of the batch written (set by `v2_write`).
677 batch_len: u64,
678}
679
680impl SynapseStore {
681 /// Open or initialize a `SynapseStore` at `root_dir`, verifying checkpoint + WAL chain.
682 /// Revision records are neither sealed nor checked for a seal: whoever can rewrite the
683 /// whole log can rewrite them too (issue #101). Use [`Self::open_sealed`] to close that.
684 pub fn open(
685 root_dir: impl AsRef<Path>,
686 fsync_policy: FsyncPolicy,
687 recovery_policy: RecoveryPolicy,
688 limits: StoreLimits,
689 ) -> SynapseResult<Self> {
690 Self::open_with(root_dir, fsync_policy, recovery_policy, limits, None)
691 }
692
693 /// [`Self::open`] with the server's machine key as the revision seal key (issue #101).
694 /// Every revision record written (kinds 7, 8, 9, 10, and 11) is sealed by `seal`, chained
695 /// to the previous one; on replay a revision record whose seal does not verify against that
696 /// chain changes nothing. `StrictFailClosed` refuses such a store with
697 /// `RevisionRecordUnsealed` (including one with revision records written before it was
698 /// sealed); `TruncateTornTail` opens it, reports them in [`Self::seal_replay_report`],
699 /// and `checkpoint_and_compact` then leaves them out.
700 pub fn open_sealed(
701 root_dir: impl AsRef<Path>,
702 fsync_policy: FsyncPolicy,
703 recovery_policy: RecoveryPolicy,
704 limits: StoreLimits,
705 seal: RevisionSealKey,
706 ) -> SynapseResult<Self> {
707 Self::open_with(root_dir, fsync_policy, recovery_policy, limits, Some(seal))
708 }
709
710 fn open_with(
711 root_dir: impl AsRef<Path>,
712 fsync_policy: FsyncPolicy,
713 recovery_policy: RecoveryPolicy,
714 limits: StoreLimits,
715 revision_seal: Option<RevisionSealKey>,
716 ) -> SynapseResult<Self> {
717 let root_dir = root_dir.as_ref().to_path_buf();
718 #[cfg(test)]
719 if let Some(cfg) = blockdev_tests::redirect(&root_dir) {
720 // Test hook: a directory holding `raw.device` is a raw block store (the A2
721 // crash suite runs unchanged against R1; crash children reopen through here).
722 return Self::open_block_device_with(
723 &cfg,
724 fsync_policy,
725 recovery_policy,
726 limits,
727 revision_seal,
728 );
729 }
730 fs::create_dir_all(root_dir.join("blobs")).map_err(io_err)?;
731 let medium = Medium::Dir(root_dir.clone());
732 Self::open_on(
733 root_dir,
734 medium,
735 fsync_policy,
736 recovery_policy,
737 limits,
738 revision_seal,
739 )
740 }
741
742 /// Open or initialize a store on a raw block device with no filesystem (ADR 0003
743 /// R1, `docs/R1_RAW_BLOCK_STORE.md`). Opens exactly `cfg.path` with `O_DIRECT`;
744 /// refuses a device carrying a filesystem or partition signature unless
745 /// `cfg.allow_foreign_signature` is set. Requires `FsyncPolicy::GroupCommit` (the
746 /// segment layout is the only layout on a device).
747 pub fn open_block_device(
748 cfg: &BlockDeviceConfig,
749 fsync_policy: FsyncPolicy,
750 recovery_policy: RecoveryPolicy,
751 limits: StoreLimits,
752 ) -> SynapseResult<Self> {
753 Self::open_block_device_with(cfg, fsync_policy, recovery_policy, limits, None)
754 }
755
756 /// `open_block_device` with an optional revision seal (#101): the test redirect in
757 /// `open_with` keeps a sealed store sealed when it runs on a raw block device.
758 fn open_block_device_with(
759 cfg: &BlockDeviceConfig,
760 fsync_policy: FsyncPolicy,
761 recovery_policy: RecoveryPolicy,
762 limits: StoreLimits,
763 revision_seal: Option<RevisionSealKey>,
764 ) -> SynapseResult<Self> {
765 if !fsync_policy.is_group_commit() {
766 return Err(SynapseError::new(
767 RefusalCode::IoFailure,
768 "a raw block store needs FsyncPolicy::GroupCommit",
769 ));
770 }
771 let dev = blockdev::BlockDevice::open_path(cfg, limits.segment_bytes)?;
772 // `root_dir` is the device path: any filesystem path derived from it (blob files
773 // of the v1 layout) fails with ENOTDIR instead of landing somewhere else.
774 Self::open_on(
775 cfg.path.clone(),
776 Medium::Block(dev),
777 fsync_policy,
778 recovery_policy,
779 limits,
780 revision_seal,
781 )
782 }
783
784 /// Open a store on an already opened device (tests: in-memory power-cut images).
785 #[cfg(test)]
786 pub(crate) fn open_on_device(
787 dev: std::sync::Arc<blockdev::BlockDevice>,
788 label: PathBuf,
789 recovery_policy: RecoveryPolicy,
790 limits: StoreLimits,
791 ) -> SynapseResult<Self> {
792 Self::open_on(
793 label,
794 Medium::Block(dev),
795 FsyncPolicy::GROUP_COMMIT_DEFAULT,
796 recovery_policy,
797 limits,
798 None,
799 )
800 }
801
802 fn open_on(
803 root_dir: PathBuf,
804 medium: Medium,
805 fsync_policy: FsyncPolicy,
806 recovery_policy: RecoveryPolicy,
807 limits: StoreLimits,
808 revision_seal: Option<RevisionSealKey>,
809 ) -> SynapseResult<Self> {
810 let blobs_dir = root_dir.join("blobs");
811 let wal_path = root_dir.join("wal.log");
812 // ADR 0003 G2: chunk parameters the chunker cannot use are refused, never guessed.
813 limits
814 .chunking
815 .validate()
816 .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e))?;
817
818 let mut store = Self {
819 medium,
820 root_dir,
821 blobs_dir,
822 wal_path,
823 fsync_policy,
824 limits,
825 committed_seq: WalSeq::ZERO,
826 last_frame_sha256: [0u8; 32],
827 unflushed_frames: 0,
828 inflight_admissions: 0,
829 fault_injection: FaultInjection::None,
830 changesets: BTreeMap::new(),
831 idempotency_index: BTreeMap::new(),
832 blob_first_visible_seq: BTreeMap::new(),
833 github_projections: BTreeMap::new(),
834 canonical_heads: BTreeMap::new(),
835 torn_frames_truncated_on_open: 0,
836 v2_mode: false,
837 log_layout: LogLayout::V1,
838 wal_v2: None,
839 segment_readers: BTreeMap::new(),
840 wal_v2_recovered_end: (1, 0),
841 blob_locations: BTreeMap::new(),
842 chunk_locations: BTreeMap::new(),
843 blob_chunks: BTreeMap::new(),
844 log_bytes_written: 0,
845 poisoned: None,
846 codec: RecordCodec::BinaryV2,
847 checkpoint_chain: None,
848 v1_history: false,
849 binary_seen: false,
850 tombstone_pending: false,
851 revisions: revision::RevisionLedger::new(
852 revision_seal.as_ref().map(RevisionSealKey::public_key),
853 ),
854 git_bridge: git_bridge::GitBridgeLedger::default(),
855 revision_seal,
856 };
857
858 store.recover(recovery_policy)?;
859 if store.tombstone_pending {
860 store.write_v1_tombstone()?;
861 }
862 if fsync_policy.is_group_commit() {
863 if store.log_layout != LogLayout::Segments {
864 store.upgrade_to_segments()?;
865 }
866 let (active, end) = store.wal_v2_recovered_end;
867 let writer = segment::SegmentLog::open(
868 &store.medium,
869 active,
870 end,
871 store.limits.segment_bytes,
872 store.limits.wal_prealloc_bytes,
873 )?;
874 store.wal_v2 = Some(writer);
875 store.open_segment_readers()?;
876 } else if store.v2_mode {
877 return Err(SynapseError::new(
878 RefusalCode::WalVersionUnsupported,
879 "store uses WAL v2 (wal.log ends with the v2 marker); open it with FsyncPolicy::GroupCommit",
880 ));
881 }
882 Ok(store)
883 }
884
885 /// Codec this store writes new WAL records with (ADR 0003 A1).
886 pub fn record_codec(&self) -> RecordCodec {
887 self.codec
888 }
889
890 /// Chain fields of the binary checkpoint this store holds, if it has one.
891 pub fn checkpoint_chain(&self) -> Option<CheckpointChain> {
892 self.checkpoint_chain
893 }
894
895 /// Manifest of `blob` when the store holds it as chunks (ADR 0003 G2).
896 pub fn blob_manifest(&self, blob: &BlobDigest) -> Option<&ChunkManifest> {
897 self.blob_chunks.get(blob)
898 }
899
900 /// Chunk storage of the store: (indexed chunks, their total content bytes).
901 pub fn chunk_storage(&self) -> (usize, u64) {
902 let bytes = self
903 .chunk_locations
904 .values()
905 .map(|l| u64::from(l.len))
906 .sum();
907 (self.chunk_locations.len(), bytes)
908 }
909
910 /// Total content bytes of the whole blobs stored inline in segments.
911 pub fn inline_blob_bytes(&self) -> u64 {
912 self.blob_locations.values().map(|l| u64::from(l.len)).sum()
913 }
914
915 /// Bytes of batches this store appended to its segments since it was opened.
916 pub fn log_bytes_written(&self) -> u64 {
917 self.log_bytes_written
918 }
919
920 /// The chunk parameters in force (invalid parameters were refused at open).
921 pub fn chunk_params(&self) -> ChunkParams {
922 self.limits.chunking
923 }
924
925 /// True when this store writes WAL v2 (group commit).
926 pub fn is_wal_v2(&self) -> bool {
927 self.v2_mode
928 }
929
930 /// The fsync policy this store was opened with.
931 pub fn fsync_policy(&self) -> FsyncPolicy {
932 self.fsync_policy
933 }
934
935 /// Admission limits.
936 pub fn limits(&self) -> &StoreLimits {
937 &self.limits
938 }
939
940 /// `Some(reason)` when a failed batch could not be rolled back; writes are refused.
941 pub fn poisoned(&self) -> Option<&str> {
942 self.poisoned.as_deref()
943 }
944
945 /// Return the current committed WAL sequence watermark.
946 pub fn committed_seq(&self) -> WalSeq {
947 self.committed_seq
948 }
949
950 /// Return the SHA-256 digest of the most recently committed WAL frame.
951 pub fn last_frame_sha256(&self) -> [u8; 32] {
952 self.last_frame_sha256
953 }
954
955 /// Return the number of torn tail frames truncated during `open()`.
956 pub fn torn_frames_truncated_on_open(&self) -> usize {
957 self.torn_frames_truncated_on_open
958 }
959
960 /// Configure fault injection for the next write operation (used in Gate 1 fault tests).
961 pub fn set_fault_injection(&mut self, fault: FaultInjection) {
962 self.fault_injection = fault;
963 }
964
965 /// Simulate in-flight queue saturation for testing admission backpressure.
966 pub fn set_simulated_inflight(&mut self, inflight: usize) {
967 self.inflight_admissions = inflight;
968 }
969
970 /// Explicitly `fsync` (`sync_all`) the WAL file and reset the batch counter.
971 pub fn sync_wal(&mut self) -> SynapseResult<()> {
972 if let Some(w) = &self.wal_v2 {
973 // Every v2 batch is already synced before acknowledgment; this is a no-op
974 // apart from the system call.
975 w.sync()?;
976 } else if self.wal_path.exists() {
977 let f = OpenOptions::new()
978 .read(true)
979 .write(true)
980 .open(&self.wal_path)
981 .map_err(io_err)?;
982 f.sync_all().map_err(io_err)?;
983 }
984 self.unflushed_frames = 0;
985 Ok(())
986 }
987
988 /// Ingest a signed `ChangesetEnvelope` along with its referenced `(BlobDigest, Vec<u8>)` blobs.
989 pub fn ingest_changeset(
990 &mut self,
991 envelope: ChangesetEnvelope,
992 blobs: &[(BlobDigest, Vec<u8>)],
993 ) -> SynapseResult<IngestOutcome> {
994 // 1. Check admission backpressure
995 if self.inflight_admissions >= self.limits.max_inflight_admissions {
996 return Err(SynapseError::new(
997 RefusalCode::BackpressureOverCapacity,
998 format!(
999 "admission queue at capacity ({}/{})",
1000 self.inflight_admissions, self.limits.max_inflight_admissions
1001 ),
1002 ));
1003 }
1004
1005 // 2. Validate canonical envelope and Ed25519 signature (the stateless halves of
1006 // steps 4, 6 and 7 are computed here too; their errors are reported in order).
1007 let prepared = Self::prepare_ingest(
1008 &self.limits,
1009 envelope,
1010 blobs,
1011 self.v2_mode.then_some(self.codec),
1012 )?;
1013 self.ingest_prepared(prepared)
1014 }
1015
1016 /// Stateless half of [`Self::ingest_changeset`]: validates the envelope and signature,
1017 /// checks limits and blob digests, and (when `wal_v2_codec` is set) encodes the WAL v2
1018 /// payload with that record codec, its SHA-256 and CRC-32C. A store re-encodes it at
1019 /// commit if its codec changed in between (migration checkpoint). Needs no store lock, so concurrent submitters run it
1020 /// in parallel. Only a validation failure (step 2) is returned here; refusals from
1021 /// steps 4, 6 and 7 are deferred to the stateful half so their order is unchanged.
1022 pub fn prepare_ingest(
1023 limits: &StoreLimits,
1024 envelope: ChangesetEnvelope,
1025 blobs: &[(BlobDigest, Vec<u8>)],
1026 wal_v2_codec: Option<RecordCodec>,
1027 ) -> SynapseResult<PreparedIngest> {
1028 let changeset_id = envelope.validate()?;
1029
1030 // 4. Path count limit (deferred).
1031 let path_count_error =
1032 (envelope.mutations.len() > limits.max_paths_per_changeset).then(|| {
1033 SynapseError::new(
1034 RefusalCode::QuotaTooManyPaths,
1035 format!(
1036 "changeset touches {} paths, exceeding limit {}",
1037 envelope.mutations.len(),
1038 limits.max_paths_per_changeset
1039 ),
1040 )
1041 });
1042
1043 // 6. Index provided blobs and verify digests and size limits (deferred).
1044 let mut provided_map: BTreeMap<BlobDigest, &[u8]> = BTreeMap::new();
1045 let mut total_bytes = 0u64;
1046 let mut blob_error = None;
1047 for (declared_digest, bytes) in blobs {
1048 let len = bytes.len() as u64;
1049 if len > limits.max_blob_bytes {
1050 blob_error = Some(SynapseError::new(
1051 RefusalCode::QuotaPayloadTooLarge,
1052 format!(
1053 "blob size {len} exceeds max_blob_bytes {}",
1054 limits.max_blob_bytes
1055 ),
1056 ));
1057 break;
1058 }
1059 total_bytes = total_bytes.saturating_add(len);
1060 if total_bytes > limits.max_total_changeset_bytes {
1061 blob_error = Some(SynapseError::new(
1062 RefusalCode::QuotaPayloadTooLarge,
1063 format!(
1064 "total blob payload {total_bytes} exceeds max_total_changeset_bytes {}",
1065 limits.max_total_changeset_bytes
1066 ),
1067 ));
1068 break;
1069 }
1070 let actual_digest = BlobDigest::compute(bytes);
1071 if actual_digest != *declared_digest {
1072 blob_error = Some(SynapseError::new(
1073 RefusalCode::BlobDigestMismatch,
1074 format!(
1075 "declared blob digest {} does not match computed {}",
1076 declared_digest, actual_digest
1077 ),
1078 ));
1079 break;
1080 }
1081 provided_map.insert(*declared_digest, bytes.as_slice());
1082 }
1083
1084 // 7. Upsert checks in mutation order (size mismatches and blobs that must already
1085 // be committed; the latter needs store state and is checked later).
1086 let mut upsert_checks = Vec::new();
1087 let mut new_blobs = Vec::new();
1088 if blob_error.is_none() {
1089 for m in &envelope.mutations {
1090 if let MutationOp::Upsert {
1091 blob_digest,
1092 size_bytes,
1093 ..
1094 } = &m.op
1095 {
1096 if let Some(raw) = provided_map.get(blob_digest) {
1097 if raw.len() as u64 != *size_bytes {
1098 upsert_checks.push(UpsertCheck::SizeMismatch(SynapseError::new(
1099 RefusalCode::BlobDigestMismatch,
1100 format!(
1101 "mutation path {} declared size {} but blob is {} bytes",
1102 m.path,
1103 size_bytes,
1104 raw.len()
1105 ),
1106 )));
1107 } else {
1108 new_blobs.push(*blob_digest);
1109 }
1110 } else {
1111 upsert_checks.push(UpsertCheck::MustBeVisible {
1112 digest: *blob_digest,
1113 path: m.path.clone(),
1114 });
1115 }
1116 }
1117 }
1118 }
1119
1120 let clean = path_count_error.is_none()
1121 && blob_error.is_none()
1122 && !upsert_checks
1123 .iter()
1124 .any(|c| matches!(c, UpsertCheck::SizeMismatch(_)));
1125 let mut prepared = PreparedIngest {
1126 envelope,
1127 changeset_id,
1128 path_count_error,
1129 blob_error,
1130 upsert_checks,
1131 new_blobs,
1132 provided: Vec::new(),
1133 encoded: None,
1134 };
1135 if let Some(codec) = wal_v2_codec {
1136 if clean {
1137 // ADR 0003 G2: a blob above the chunk threshold is cut into chunks; each
1138 // distinct chunk is carried once per record (the store drops the chunks it
1139 // already holds at commit, `conform_v2`).
1140 let params = if limits.chunking.validate().is_ok() {
1141 limits.chunking
1142 } else {
1143 ChunkParams::OFF
1144 };
1145 let mut inline: Vec<(BlobDigest, &[u8])> = Vec::new();
1146 let mut manifests: Vec<ChunkManifest> = Vec::new();
1147 let mut chunks: Vec<(ChunkDigest, &[u8])> = Vec::new();
1148 let mut seen_chunks = BTreeSet::new();
1149 for d in &prepared.new_blobs {
1150 if inline.iter().any(|(x, _)| x == d) || manifests.iter().any(|m| m.blob == *d)
1151 {
1152 continue;
1153 }
1154 let bytes = provided_map[d];
1155 if params.is_chunked(bytes.len()) {
1156 let cb = chunk::chunk_blob(*d, bytes, &params);
1157 for (cd, r) in cb.distinct {
1158 if seen_chunks.insert(cd) {
1159 chunks.push((cd, &bytes[r]));
1160 }
1161 }
1162 manifests.push(cb.manifest);
1163 } else {
1164 inline.push((*d, bytes));
1165 }
1166 }
1167 let record = prepared.record();
1168 prepared.encoded = Some(if manifests.is_empty() {
1169 wal2::encode_record(&record, &inline, codec)?
1170 } else {
1171 let meta = codec::encode_record_with(&record, codec)?;
1172 wal2::encode_parts(
1173 record.kind_byte(),
1174 codec,
1175 &meta,
1176 &inline,
1177 &manifests,
1178 &chunks,
1179 )?
1180 });
1181 }
1182 } else {
1183 prepared.provided = provided_map
1184 .into_iter()
1185 .map(|(d, b)| (d, b.to_vec()))
1186 .collect();
1187 }
1188 Ok(prepared)
1189 }
1190
1191 /// Stateful half of [`Self::ingest_changeset`], committing one prepared changeset
1192 /// on its own (one record, one sync).
1193 pub fn ingest_prepared(
1194 &mut self,
1195 mut prepared: PreparedIngest,
1196 ) -> SynapseResult<IngestOutcome> {
1197 self.check_writable()?;
1198 match self.plan_ingest(&prepared, &BatchOverlay::default()) {
1199 Planned::Duplicate {
1200 wal_seq,
1201 changeset_id,
1202 ..
1203 } => {
1204 return Ok(IngestOutcome::IdempotentDuplicate {
1205 wal_seq,
1206 changeset_id,
1207 })
1208 }
1209 Planned::Refused { error, .. } => return Err(error),
1210 Planned::Accept => {}
1211 }
1212 let changeset_id = prepared.changeset_id;
1213 let record = prepared.record();
1214
1215 if self.v2_mode {
1216 self.conform_v2(&mut prepared, &mut BatchOverlay::default())?;
1217 let encoded = prepared.encoded.expect("conform_v2 checked it");
1218 let mut ticket = self.v2_begin()?;
1219 let result = Self::v2_write(&mut ticket, &[&encoded]);
1220 let placed = self.v2_finish(ticket, result)?;
1221 self.apply_v2_ingest(&placed[0], record, &encoded);
1222 return Ok(IngestOutcome::Committed {
1223 wal_seq: placed[0].seq,
1224 changeset_id,
1225 frame_sha256: placed[0].frame_sha256,
1226 durability: DurabilityGuarantee::FsyncBeforeAck,
1227 });
1228 }
1229
1230 // The frame payload is encoded (and checked against the frame cap) before any
1231 // blob is written.
1232 let payload = self.encode_v1_payload(&record)?;
1233
1234 // 8. Write all provided blobs to the content-addressed store BEFORE appending the WAL frame
1235 for (digest, raw) in &prepared.provided {
1236 self.write_blob_file(*digest, raw)?;
1237 }
1238
1239 if self.fault_injection == FaultInjection::CrashAfterBlobWriteBeforeWalAppend {
1240 self.fault_injection = FaultInjection::None;
1241 return Err(SynapseError::new(
1242 RefusalCode::IoFailure,
1243 "injected fault: crash after blob write before WAL append",
1244 ));
1245 }
1246
1247 // 9. Append the WAL frame
1248 let (wal_seq, frame_sha256, durability) =
1249 self.append_v1_payload(record.kind_byte(), &payload)?;
1250
1251 // 10. Advance in-memory visibility atomically with `wal_seq`
1252 self.apply_record(wal_seq, record);
1253
1254 Ok(IngestOutcome::Committed {
1255 wal_seq,
1256 changeset_id,
1257 frame_sha256,
1258 durability,
1259 })
1260 }
1261
1262 /// Stateful checks of an ingest (steps 3, 4, 5, 6, 7 in the original order) against
1263 /// committed state plus the not-yet-durable records earlier in the same batch.
1264 fn plan_ingest(&self, p: &PreparedIngest, overlay: &BatchOverlay) -> Planned {
1265 // 3. Idempotency
1266 let idem_key = (p.envelope.repo_id.clone(), p.envelope.idempotency_key);
1267 let (existing, mut dep) = match self.idempotency_index.get(&idem_key) {
1268 Some(v) => (Some(*v), false),
1269 None => (overlay.idempotency.get(&idem_key).copied(), true),
1270 };
1271 if let Some((existing_seq, existing_cs_id)) = existing {
1272 if existing_cs_id == p.changeset_id {
1273 return Planned::Duplicate {
1274 wal_seq: existing_seq,
1275 changeset_id: existing_cs_id,
1276 depends_on_batch: dep,
1277 };
1278 }
1279 return Planned::Refused {
1280 error: SynapseError::new(
1281 RefusalCode::IdempotencyKeyConflict,
1282 format!(
1283 "idempotency key {} already bound to changeset {}, cannot rebind to {}",
1284 p.envelope.idempotency_key.to_hex(),
1285 existing_cs_id,
1286 p.changeset_id
1287 ),
1288 ),
1289 depends_on_batch: dep,
1290 };
1291 }
1292 dep = false;
1293 let refuse = |error: SynapseError, dep: bool| Planned::Refused {
1294 error,
1295 depends_on_batch: dep,
1296 };
1297
1298 // 4. Path count
1299 if let Some(e) = &p.path_count_error {
1300 return refuse(e.clone(), dep);
1301 }
1302
1303 // 5. Parents must be committed (or earlier in this batch)
1304 for parent_id in &p.envelope.parent_changesets {
1305 let parent_repo = if let Some(parent) = self.changesets.get(parent_id) {
1306 &parent.envelope.repo_id
1307 } else if let Some(repo) = overlay.changesets.get(parent_id) {
1308 dep = true;
1309 repo
1310 } else {
1311 return refuse(
1312 SynapseError::new(
1313 RefusalCode::ParentChangesetNotFound,
1314 format!("parent changeset {parent_id} not found"),
1315 ),
1316 dep,
1317 );
1318 };
1319 if parent_repo != &p.envelope.repo_id {
1320 return refuse(
1321 SynapseError::new(
1322 RefusalCode::AuthCrossRepoDenied,
1323 "parent changeset belongs to a different repository",
1324 ),
1325 dep,
1326 );
1327 }
1328 }
1329
1330 // 6. Blob sizes and digests
1331 if let Some(e) = &p.blob_error {
1332 return refuse(e.clone(), dep);
1333 }
1334
1335 // 7. Upserts: provided with the right size, or already committed
1336 for c in &p.upsert_checks {
1337 match c {
1338 UpsertCheck::SizeMismatch(e) => return refuse(e.clone(), dep),
1339 UpsertCheck::MustBeVisible { digest, path } => {
1340 if self.blob_first_visible_seq.contains_key(digest) {
1341 continue;
1342 }
1343 if overlay.blobs.contains(digest) {
1344 dep = true;
1345 continue;
1346 }
1347 return refuse(
1348 SynapseError::new(
1349 RefusalCode::BlobNotFound,
1350 format!("mutation path {path} references missing blob {digest}"),
1351 ),
1352 dep,
1353 );
1354 }
1355 }
1356 }
1357 Planned::Accept
1358 }
1359
1360 fn check_writable(&self) -> SynapseResult<()> {
1361 match &self.poisoned {
1362 Some(reason) => Err(SynapseError::new(
1363 RefusalCode::IoFailure,
1364 format!("store refuses writes until it is reopened: {reason}"),
1365 )),
1366 None => Ok(()),
1367 }
1368 }
1369
1370 /// Take the WAL v2 writer and the pending fault for one batch.
1371 pub(crate) fn v2_begin(&mut self) -> SynapseResult<V2Ticket> {
1372 self.check_writable()?;
1373 let writer = self.wal_v2.take().ok_or_else(|| {
1374 SynapseError::new(RefusalCode::IoFailure, "WAL v2 writer is not available")
1375 })?;
1376 Ok(V2Ticket {
1377 writer,
1378 fault: std::mem::replace(&mut self.fault_injection, FaultInjection::None),
1379 base_seq: self.committed_seq,
1380 prev_sha: self.last_frame_sha256,
1381 batch_len: 0,
1382 })
1383 }
1384
1385 /// Build one batch from `records` and make it durable (one write, one `fdatasync`).
1386 /// Needs no store lock: the ticket owns the writer and the chain position.
1387 pub(crate) fn v2_write(
1388 ticket: &mut V2Ticket,
1389 records: &[&wal2::EncodedRecord],
1390 ) -> Result<Vec<wal2::PlacedFrame>, wal2::BatchFailure> {
1391 use segment::RotationFault as Rot;
1392 use wal2::{BatchIoFault as Io, FrameFault as Fr};
1393 let first_len = records.first().map_or(0, |r| r.payload.len());
1394 let rotation_fault = match ticket.fault {
1395 FaultInjection::CrashAfterSegmentCreateBeforeDirSync => Rot::CrashBeforeDirSync {
1396 code: FAULT_CRASH_EXIT_CODE,
1397 },
1398 FaultInjection::FailNextSegmentDirSync => Rot::FailDirSync,
1399 _ => Rot::None,
1400 };
1401 let (frame_fault, io_fault) = match ticket.fault {
1402 FaultInjection::None => (Fr::None, Io::None),
1403 FaultInjection::CrashAfterBlobWriteBeforeWalAppend => {
1404 return Err(wal2::BatchFailure::RolledBack(SynapseError::new(
1405 RefusalCode::IoFailure,
1406 "injected fault: crash before WAL v2 batch write",
1407 )))
1408 }
1409 FaultInjection::TornWalHeaderWrite { bytes_written } => (
1410 Fr::None,
1411 Io::TornThenStop {
1412 bytes_written: wal2::WAL_V2_BATCH_HEADER_LEN
1413 + bytes_written.min(WAL_HEADER_LEN - 1),
1414 },
1415 ),
1416 FaultInjection::TornWalPayloadWrite { bytes_written } => (
1417 Fr::None,
1418 Io::TornThenStop {
1419 bytes_written: wal2::WAL_V2_BATCH_HEADER_LEN
1420 + WAL_HEADER_LEN
1421 + bytes_written.min(first_len.saturating_sub(1)),
1422 },
1423 ),
1424 FaultInjection::CorruptNextWalCrc => (Fr::CorruptCrc, Io::None),
1425 FaultInjection::CorruptNextWalChain => (Fr::CorruptChain, Io::None),
1426 FaultInjection::InjectNextWalSequenceGap => (Fr::SequenceGap, Io::None),
1427 FaultInjection::InjectDuplicateWalSequence => (Fr::DuplicateSequence, Io::None),
1428 FaultInjection::FailNextBatchWrite { bytes_written } => {
1429 (Fr::None, Io::FailWrite { bytes_written })
1430 }
1431 FaultInjection::FailNextBatchSync => (Fr::None, Io::FailSync),
1432 FaultInjection::FailNextBatchSyncAndRollback => (Fr::None, Io::FailSyncAndRollback),
1433 FaultInjection::CrashMidBatchWrite { bytes_written } => (
1434 Fr::None,
1435 Io::CrashAfterBytes {
1436 bytes_written,
1437 code: FAULT_CRASH_EXIT_CODE,
1438 },
1439 ),
1440 FaultInjection::CrashBeforeBatchSync => (
1441 Fr::None,
1442 Io::CrashBeforeSync {
1443 code: FAULT_CRASH_EXIT_CODE,
1444 },
1445 ),
1446 FaultInjection::CrashAfterBatchSyncBeforeIndex => (
1447 Fr::None,
1448 Io::CrashAfterSync {
1449 code: FAULT_CRASH_EXIT_CODE,
1450 },
1451 ),
1452 FaultInjection::CrashAfterSegmentCreateBeforeDirSync
1453 | FaultInjection::FailNextSegmentDirSync
1454 | FaultInjection::CrashAfterSegmentIndexBeforeCheckpoint => (Fr::None, Io::None),
1455 };
1456 let capacity = wal2::WAL_V2_BATCH_HEADER_LEN
1457 + records
1458 .iter()
1459 .map(|r| WAL_HEADER_LEN + r.payload.len())
1460 .sum::<usize>();
1461 // The finished batch is padded to the next 4 KiB after its 8-byte trailer.
1462 let batch_len = wal2::align_up((capacity + wal2::WAL_V2_BATCH_TRAILER.len()) as u64);
1463 let (segment, base) = ticket.writer.reserve(batch_len, rotation_fault)?;
1464 ticket.batch_len = batch_len;
1465 let mut builder = wal2::BatchBuilder::new(segment, base, capacity);
1466 let mut seq = ticket.base_seq;
1467 let mut prev = ticket.prev_sha;
1468 let mut placed = Vec::with_capacity(records.len());
1469 for (i, r) in records.iter().enumerate() {
1470 seq = seq.next();
1471 let fault = if i == 0 { frame_fault } else { Fr::None };
1472 let p = builder.push(seq, prev, r, fault);
1473 prev = p.frame_sha256;
1474 placed.push(p);
1475 }
1476 let buf = builder.finish();
1477 ticket.writer.write_batch(&buf, io_fault)?;
1478 Ok(placed)
1479 }
1480
1481 /// Return the writer to the store and advance the chain after a durable batch.
1482 /// On failure nothing advances; an unrecoverable failure poisons the store.
1483 pub(crate) fn v2_finish(
1484 &mut self,
1485 ticket: V2Ticket,
1486 result: Result<Vec<wal2::PlacedFrame>, wal2::BatchFailure>,
1487 ) -> SynapseResult<Vec<wal2::PlacedFrame>> {
1488 let active = ticket.writer.active();
1489 self.wal_v2 = Some(ticket.writer);
1490 if !self.segment_readers.contains_key(&active) {
1491 // A new segment (its directory entry is already flushed). Without a read
1492 // handle its blobs could not be served, so a failure here poisons the store.
1493 match self.medium.open_reader(active) {
1494 Ok(r) => {
1495 self.segment_readers.insert(active, r);
1496 }
1497 Err(e) => {
1498 let msg = format!("open segment {active} for reads: {e}");
1499 self.poisoned = Some(msg.clone());
1500 return Err(SynapseError::new(RefusalCode::IoFailure, msg));
1501 }
1502 }
1503 }
1504 match result {
1505 Ok(placed) => {
1506 if let Some(last) = placed.last() {
1507 self.committed_seq = last.seq;
1508 self.last_frame_sha256 = last.frame_sha256;
1509 }
1510 self.log_bytes_written += ticket.batch_len;
1511 Ok(placed)
1512 }
1513 Err(wal2::BatchFailure::RolledBack(e)) => Err(e),
1514 Err(wal2::BatchFailure::Poisoned(e)) => {
1515 self.poisoned = Some(e.message.clone());
1516 Err(e)
1517 }
1518 }
1519 }
1520
1521 /// Make a durable WAL v2 ingest frame visible: inline blob locations, then state.
1522 pub(crate) fn apply_v2_ingest(
1523 &mut self,
1524 placed: &wal2::PlacedFrame,
1525 record: WalRecord,
1526 enc: &wal2::EncodedRecord,
1527 ) {
1528 let loc = |off: u32, len: u32| segment::BlobLoc {
1529 segment: placed.segment,
1530 offset: placed.payload_offset + u64::from(off),
1531 len,
1532 };
1533 for &(digest, off, len) in &enc.inline {
1534 self.blob_locations.entry(digest).or_insert(loc(off, len));
1535 }
1536 for &(digest, off, len) in &enc.chunks {
1537 self.chunk_locations.entry(digest).or_insert(loc(off, len));
1538 }
1539 for m in &enc.manifests {
1540 self.blob_chunks.entry(m.blob).or_insert_with(|| m.clone());
1541 }
1542 self.apply_record(placed.seq, record);
1543 }
1544
1545 /// Read a chunked blob (ADR 0003 G2): its chunks in manifest order, contiguous chunk
1546 /// runs of one segment in one read, then the `BlobDigest` over the whole content.
1547 fn read_chunked_blob(&self, m: &ChunkManifest) -> SynapseResult<Vec<u8>> {
1548 let digest = m.blob;
1549 let len = usize::try_from(m.len).map_err(|_| {
1550 SynapseError::new(RefusalCode::QuotaPayloadTooLarge, "chunked blob too large")
1551 })?;
1552 let mut out = vec![0u8; len];
1553 let mut at = 0usize;
1554 // Pending run: (segment, file offset, start in `out`, length).
1555 let mut run: Option<(u64, u64, usize, usize)> = None;
1556 let flush = |run: (u64, u64, usize, usize), out: &mut [u8]| -> SynapseResult<()> {
1557 let (seg, off, start, n) = run;
1558 let f = self.segment_readers.get(&seg).ok_or_else(|| {
1559 SynapseError::new(
1560 RefusalCode::BlobNotFound,
1561 format!("segment {seg} is not open for reads"),
1562 )
1563 })?;
1564 f.read_into(off, &mut out[start..start + n]).map_err(|e| {
1565 SynapseError::new(
1566 RefusalCode::BlobNotFound,
1567 format!("read chunks of blob {digest} from segment {seg}: {e}"),
1568 )
1569 })
1570 };
1571 for (cd, clen) in &m.chunks {
1572 let loc = self.chunk_locations.get(cd).copied().ok_or_else(|| {
1573 SynapseError::new(
1574 RefusalCode::BlobNotFound,
1575 format!("chunk {cd} of blob {digest} is not indexed"),
1576 )
1577 })?;
1578 let n = *clen as usize;
1579 if loc.len != *clen || at + n > len {
1580 return Err(SynapseError::new(
1581 RefusalCode::BlobDigestMismatch,
1582 format!("chunk {cd} of blob {digest} has inconsistent length"),
1583 ));
1584 }
1585 run = match run {
1586 Some((seg, off, start, rn))
1587 if seg == loc.segment && off + rn as u64 == loc.offset =>
1588 {
1589 Some((seg, off, start, rn + n))
1590 }
1591 Some(r) => {
1592 flush(r, &mut out)?;
1593 Some((loc.segment, loc.offset, at, n))
1594 }
1595 None => Some((loc.segment, loc.offset, at, n)),
1596 };
1597 at += n;
1598 }
1599 if let Some(r) = run {
1600 flush(r, &mut out)?;
1601 }
1602 let computed = BlobDigest::compute(&out);
1603 if at != len || computed != digest {
1604 return Err(SynapseError::new(
1605 RefusalCode::BlobDigestMismatch,
1606 format!("on-disk chunked blob corruption for {digest}: computed {computed}"),
1607 ));
1608 }
1609 Ok(out)
1610 }
1611
1612 fn read_inline_blob(
1613 &self,
1614 digest: BlobDigest,
1615 loc: segment::BlobLoc,
1616 ) -> SynapseResult<Vec<u8>> {
1617 let f = self.segment_readers.get(&loc.segment).ok_or_else(|| {
1618 SynapseError::new(
1619 RefusalCode::BlobNotFound,
1620 format!("segment {} is not open for reads", loc.segment),
1621 )
1622 })?;
1623 let bytes = f.read_at(loc.offset, loc.len).map_err(|e| {
1624 SynapseError::new(
1625 RefusalCode::BlobNotFound,
1626 format!("read blob {digest} from segment {}: {e}", loc.segment),
1627 )
1628 })?;
1629 let computed = BlobDigest::compute(&bytes);
1630 if computed != digest {
1631 return Err(SynapseError::new(
1632 RefusalCode::BlobDigestMismatch,
1633 format!("on-disk inline blob corruption for {digest}: computed {computed}"),
1634 ));
1635 }
1636 Ok(bytes)
1637 }
1638
1639 /// Switch the store to the segment layout for good (ADR 0003 A2). Runs on open with
1640 /// `GroupCommit` for a v1 store, a new store, or a single-file WAL v2 store.
1641 ///
1642 /// First the segment index for the checkpoint on disk is written (replay from the
1643 /// start of segment 1, no entries: such checkpoints keep their blobs as files), then
1644 /// `wal.log` gets the segment marker, atomically: the current log (without a WAL v2
1645 /// marker at its end) plus the marker is written to `wal.log.tmp`, synced, and
1646 /// renamed over `wal.log`, then the directory is synced. A crash before the rename
1647 /// leaves the old store untouched (the stray files are overwritten next time); after
1648 /// it, the complete marker is in place. An in-place append could leave a torn
1649 /// 88-byte tail that strict recovery refuses.
1650 fn upgrade_to_segments(&mut self) -> SynapseResult<()> {
1651 for id in self.medium.list_segments()? {
1652 if id >= 2 && self.segment_has_data(id)? {
1653 return Err(SynapseError::new(
1654 RefusalCode::WalVersionUnsupported,
1655 format!("segment {id} holds data but wal.log has no segment marker"),
1656 ));
1657 }
1658 }
1659 let index = segment::SegmentIndex {
1660 binding: segment::checkpoint_binding_on(&self.medium)?,
1661 replay_segment: 1,
1662 replay_offset: 0,
1663 entries: BTreeMap::new(),
1664 chunks: BTreeMap::new(),
1665 manifests: BTreeMap::new(),
1666 };
1667 let keep = index.write(&self.medium)?;
1668 if let Medium::Block(_) = &self.medium {
1669 // A raw block store is created with the segment layout: `wal.log` is absent
1670 // (new store, or a crash before this commit) and gets only the marker.
1671 if self.medium.exists("wal.log") || self.log_layout != LogLayout::V1 {
1672 return Err(SynapseError::new(
1673 RefusalCode::WalVersionUnsupported,
1674 "raw block store holds a wal.log without the segment marker",
1675 ));
1676 }
1677 let header = marker_header(
1678 segment::WAL_SEGMENT_MARKER_VERSION,
1679 self.committed_seq,
1680 self.last_frame_sha256,
1681 );
1682 self.medium.write_atomic("wal.log", &header)?;
1683 segment::remove_other_indexes(&self.medium, &keep)?;
1684 self.v2_mode = true;
1685 self.log_layout = LogLayout::Segments;
1686 return Ok(());
1687 }
1688 let (keep_len, seq, prev) = match self.log_layout {
1689 LogLayout::SingleFileV2 => {
1690 // Replace the WAL v2 marker (the last 88 bytes) with the segment marker
1691 // at the same chain position.
1692 let old = fs::read(&self.wal_path).map_err(io_err)?;
1693 let at = old.len() - WAL_HEADER_LEN;
1694 let seq = WalSeq(u64::from_le_bytes(old[at + 8..at + 16].try_into().unwrap()));
1695 let prev: [u8; 32] = old[at + 16..at + 48].try_into().unwrap();
1696 (at as u64, seq, prev)
1697 }
1698 _ => {
1699 let len = match fs::metadata(&self.wal_path) {
1700 Ok(m) => m.len(),
1701 Err(_) => 0,
1702 };
1703 (len, self.committed_seq, self.last_frame_sha256)
1704 }
1705 };
1706 let header = marker_header(segment::WAL_SEGMENT_MARKER_VERSION, seq, prev);
1707 let tmp = self.root_dir.join("wal.log.tmp");
1708 {
1709 let mut f = File::create(&tmp).map_err(io_err)?;
1710 if keep_len > 0 {
1711 let src = File::open(&self.wal_path).map_err(io_err)?;
1712 std::io::copy(&mut src.take(keep_len), &mut f).map_err(io_err)?;
1713 }
1714 f.write_all(&header).map_err(io_err)?;
1715 f.sync_all().map_err(io_err)?;
1716 }
1717 fs::rename(&tmp, &self.wal_path).map_err(io_err)?;
1718 sync_dir(&self.root_dir)?;
1719 segment::remove_other_indexes(&self.medium, &keep)?;
1720 self.v2_mode = true;
1721 self.log_layout = LogLayout::Segments;
1722 Ok(())
1723 }
1724
1725 /// True when segment `id` exists and holds a non-zero byte.
1726 fn segment_has_data(&self, id: u64) -> SynapseResult<bool> {
1727 self.medium.segment_has_data(id)
1728 }
1729
1730 /// Open a read handle on every segment file up to the active one.
1731 fn open_segment_readers(&mut self) -> SynapseResult<()> {
1732 let last = self.wal_v2.as_ref().map_or(0, |w| w.active());
1733 for id in 1..=last {
1734 if self.segment_readers.contains_key(&id) {
1735 continue;
1736 }
1737 match self.medium.open_reader(id) {
1738 Ok(r) => {
1739 self.segment_readers.insert(id, r);
1740 }
1741 // Segments before the replay start may hold no retained blob; a missing
1742 // one only fails the reads that need it (BlobNotFound).
1743 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1744 Err(e) => return Err(io_err(e)),
1745 }
1746 }
1747 Ok(())
1748 }
1749
1750 /// Atomically replace `wal.log` with a file holding only the segment marker.
1751 fn replace_wal_log_with_segment_marker(&self) -> SynapseResult<()> {
1752 let header = marker_header(
1753 segment::WAL_SEGMENT_MARKER_VERSION,
1754 self.committed_seq,
1755 self.last_frame_sha256,
1756 );
1757 self.medium.write_atomic("wal.log", &header)
1758 }
1759
1760 /// Attach a machine evaluation receipt to an existing changeset.
1761 pub fn attach_evaluation(
1762 &mut self,
1763 changeset_id: ChangesetId,
1764 attachment: EvidenceAttachment,
1765 ) -> SynapseResult<WalSeq> {
1766 if !self.changesets.contains_key(&changeset_id) {
1767 return Err(SynapseError::new(
1768 RefusalCode::ChangesetNotFound,
1769 format!("changeset {changeset_id} not found"),
1770 ));
1771 }
1772 let record = WalRecord::EvaluationAttached {
1773 changeset_id,
1774 attachment,
1775 };
1776 let (seq, _, _) = self.append_wal_record(&record)?;
1777 self.apply_record(seq, record);
1778 Ok(seq)
1779 }
1780
1781 /// Record a review verdict on an existing changeset.
1782 pub fn record_review(
1783 &mut self,
1784 changeset_id: ChangesetId,
1785 review: ReviewRecord,
1786 ) -> SynapseResult<WalSeq> {
1787 let cs = self.changesets.get(&changeset_id).ok_or_else(|| {
1788 SynapseError::new(
1789 RefusalCode::ChangesetNotFound,
1790 format!("changeset {changeset_id} not found"),
1791 )
1792 })?;
1793 if cs.envelope.author_did == review.reviewer_did {
1794 return Err(SynapseError::new(
1795 RefusalCode::AuthSelfReviewRefused,
1796 "author cannot review their own changeset",
1797 ));
1798 }
1799 let record = WalRecord::ReviewRecorded {
1800 changeset_id,
1801 review,
1802 };
1803 let (seq, _, _) = self.append_wal_record(&record)?;
1804 self.apply_record(seq, record);
1805 Ok(seq)
1806 }
1807
1808 /// Record a human-facing GitHub Pull Request projection.
1809 pub fn record_github_projection(
1810 &mut self,
1811 projection: GitHubPullRequestProjection,
1812 ) -> SynapseResult<WalSeq> {
1813 if !self.changesets.contains_key(&projection.changeset_id) {
1814 return Err(SynapseError::new(
1815 RefusalCode::ChangesetNotFound,
1816 format!("changeset {} not found", projection.changeset_id),
1817 ));
1818 }
1819 let record = WalRecord::GitProjected { projection };
1820 let (seq, _, _) = self.append_wal_record(&record)?;
1821 self.apply_record(seq, record);
1822 Ok(seq)
1823 }
1824
1825 /// Record a verified `RadicleCanonicalHead` receipt.
1826 pub fn record_canonical_promotion(
1827 &mut self,
1828 canonical: RadicleCanonicalHead,
1829 ) -> SynapseResult<WalSeq> {
1830 if let Some(cs_id) = canonical.promoted_changeset_id {
1831 if !self.changesets.contains_key(&cs_id) {
1832 return Err(SynapseError::new(
1833 RefusalCode::ChangesetNotFound,
1834 format!("promoted changeset {cs_id} not found"),
1835 ));
1836 }
1837 }
1838 let record = WalRecord::CanonicalPromoted { canonical };
1839 let (seq, _, _) = self.append_wal_record(&record)?;
1840 self.apply_record(seq, record);
1841 Ok(seq)
1842 }
1843
1844 /// Update the active evaluation/integration lease timestamp on a changeset.
1845 pub fn update_lease(
1846 &mut self,
1847 changeset_id: ChangesetId,
1848 lease_expires_at_ms: u64,
1849 ) -> SynapseResult<WalSeq> {
1850 if !self.changesets.contains_key(&changeset_id) {
1851 return Err(SynapseError::new(
1852 RefusalCode::ChangesetNotFound,
1853 format!("changeset {changeset_id} not found"),
1854 ));
1855 }
1856 let record = WalRecord::LeaseUpdated {
1857 changeset_id,
1858 lease_expires_at_ms,
1859 };
1860 let (seq, _, _) = self.append_wal_record(&record)?;
1861 self.apply_record(seq, record);
1862 Ok(seq)
1863 }
1864
1865 /// Read a committed changeset respecting `min_visible_seq` (read-your-writes) and `snapshot_seq`.
1866 pub fn get_changeset(
1867 &self,
1868 changeset_id: ChangesetId,
1869 min_visible_seq: Option<WalSeq>,
1870 snapshot_seq: Option<WalSeq>,
1871 ) -> SynapseResult<StoredChangeset> {
1872 let effective_snapshot = self.resolve_snapshot_seq(min_visible_seq, snapshot_seq)?;
1873 let stored = self.changesets.get(&changeset_id).ok_or_else(|| {
1874 SynapseError::new(
1875 RefusalCode::ChangesetNotFound,
1876 format!("changeset {changeset_id} not found"),
1877 )
1878 })?;
1879 if stored.committed_seq > effective_snapshot {
1880 return Err(SynapseError::new(
1881 RefusalCode::ChangesetNotFound,
1882 format!(
1883 "changeset {changeset_id} committed at {} is not visible at snapshot {}",
1884 stored.committed_seq, effective_snapshot
1885 ),
1886 ));
1887 }
1888 Ok(stored.clone())
1889 }
1890
1891 /// Read a changeset for a repository-scoped caller. A foreign ID is indistinguishable
1892 /// from an unknown ID, even when the shared store contains it.
1893 pub fn get_changeset_in_repo(
1894 &self,
1895 repo_id: &RepoId,
1896 changeset_id: ChangesetId,
1897 min_visible_seq: Option<WalSeq>,
1898 snapshot_seq: Option<WalSeq>,
1899 ) -> SynapseResult<StoredChangeset> {
1900 let effective_snapshot = self.resolve_snapshot_seq(min_visible_seq, snapshot_seq)?;
1901 let stored = self
1902 .changesets
1903 .get(&changeset_id)
1904 .filter(|cs| &cs.envelope.repo_id == repo_id)
1905 .ok_or_else(|| {
1906 SynapseError::new(
1907 RefusalCode::ChangesetNotFound,
1908 format!("changeset {changeset_id} not found"),
1909 )
1910 })?;
1911 if stored.committed_seq > effective_snapshot {
1912 return Err(SynapseError::new(
1913 RefusalCode::ChangesetNotFound,
1914 format!(
1915 "changeset {changeset_id} committed at {} is not visible at snapshot {}",
1916 stored.committed_seq, effective_snapshot
1917 ),
1918 ));
1919 }
1920 Ok(stored.clone())
1921 }
1922
1923 /// Read an immutable blob ONLY if it is associated with a WAL commit at `<= snapshot_seq`,
1924 /// recomputing its `BlobDigest` on read to detect disk corruption.
1925 pub fn get_blob_visible(
1926 &self,
1927 digest: BlobDigest,
1928 min_visible_seq: Option<WalSeq>,
1929 snapshot_seq: Option<WalSeq>,
1930 ) -> SynapseResult<Vec<u8>> {
1931 let effective_snapshot = self.resolve_snapshot_seq(min_visible_seq, snapshot_seq)?;
1932 let visible_at = self
1933 .blob_first_visible_seq
1934 .get(&digest)
1935 .copied()
1936 .ok_or_else(|| {
1937 SynapseError::new(
1938 RefusalCode::BlobNotFound,
1939 format!("blob {digest} is not committed in the WAL"),
1940 )
1941 })?;
1942 if visible_at > effective_snapshot {
1943 return Err(SynapseError::new(
1944 RefusalCode::BlobNotFound,
1945 format!(
1946 "blob {digest} committed at {visible_at} not visible at {effective_snapshot}"
1947 ),
1948 ));
1949 }
1950 if let Some(&loc) = self.blob_locations.get(&digest) {
1951 return self.read_inline_blob(digest, loc);
1952 }
1953 if let Some(m) = self.blob_chunks.get(&digest) {
1954 return self.read_chunked_blob(m);
1955 }
1956 let path = self.blob_path(digest);
1957 let bytes = fs::read(&path).map_err(|_| {
1958 SynapseError::new(
1959 RefusalCode::BlobNotFound,
1960 format!("blob file missing on disk for {digest}"),
1961 )
1962 })?;
1963 let computed = BlobDigest::compute(&bytes);
1964 if computed != digest {
1965 return Err(SynapseError::new(
1966 RefusalCode::BlobDigestMismatch,
1967 format!("on-disk blob corruption for {digest}: computed {computed}"),
1968 ));
1969 }
1970 Ok(bytes)
1971 }
1972
1973 /// List all committed changesets visible at `snapshot_seq`, ordered by `committed_seq`.
1974 pub fn list_changesets(
1975 &self,
1976 repo_id: Option<&RepoId>,
1977 min_visible_seq: Option<WalSeq>,
1978 snapshot_seq: Option<WalSeq>,
1979 ) -> SynapseResult<Vec<StoredChangeset>> {
1980 let effective_snapshot = self.resolve_snapshot_seq(min_visible_seq, snapshot_seq)?;
1981 let mut list: Vec<StoredChangeset> = self
1982 .changesets
1983 .values()
1984 .filter(|cs| {
1985 cs.committed_seq <= effective_snapshot
1986 && repo_id.is_none_or(|r| &cs.envelope.repo_id == r)
1987 })
1988 .cloned()
1989 .collect();
1990 list.sort_by_key(|cs| cs.committed_seq);
1991 Ok(list)
1992 }
1993
1994 /// Return the current verified `RadicleCanonicalHead` for `repo_id`, if any.
1995 pub fn canonical_head(&self, repo_id: &RepoId) -> Option<&RadicleCanonicalHead> {
1996 self.canonical_heads.get(repo_id)
1997 }
1998
1999 /// Return all recorded `GitHubPullRequestProjection` entries.
2000 pub fn github_projections(&self) -> &BTreeMap<u64, GitHubPullRequestProjection> {
2001 &self.github_projections
2002 }
2003
2004 /// Compute a deterministic SHA-256 digest of all visible state up to `snapshot_seq`.
2005 pub fn state_root_digest(&self, snapshot_seq: Option<WalSeq>) -> SynapseResult<[u8; 32]> {
2006 let snap = self.resolve_snapshot_seq(None, snapshot_seq)?;
2007 Ok(codec::state_root_of(
2008 &self.changesets,
2009 self.revisions.log(),
2010 snap,
2011 ))
2012 }
2013
2014 /// Write an atomic checkpoint, compact `wal.log`, and sweep unreferenced speculative blobs
2015 /// outside active `GarbageRoot`s.
2016 pub fn checkpoint_and_compact(&mut self, now_ms: u64) -> SynapseResult<CompactionReport> {
2017 self.check_writable()?;
2018 // The last v1 state root, taken before eviction changes the state (used only by a
2019 // v1 store's migration checkpoint).
2020 let v1_state_root_at_entry = self.state_root_digest(None)?;
2021 // 1. Identify garbage roots:
2022 // - Canonical head changeset lineages
2023 // - Open (non-merged) or merged GitHub PR projection changeset lineages
2024 // - Changesets with active lease `lease_expires_at_ms > now_ms`
2025 // - Changesets within `default_retention_window_ms`
2026 let mut retained_cs: BTreeSet<ChangesetId> = BTreeSet::new();
2027 let mut worklist: Vec<ChangesetId> = Vec::new();
2028
2029 for canon in self.canonical_heads.values() {
2030 if let Some(cs_id) = canon.promoted_changeset_id {
2031 worklist.push(cs_id);
2032 }
2033 }
2034 for proj in self.github_projections.values() {
2035 worklist.push(proj.changeset_id);
2036 }
2037 for (cs_id, stored) in &self.changesets {
2038 let within_window = now_ms.saturating_sub(stored.envelope.created_at_ms)
2039 <= self.limits.default_retention_window_ms;
2040 let active_lease = stored.lease_expires_at_ms > now_ms;
2041 if within_window || active_lease {
2042 worklist.push(*cs_id);
2043 }
2044 }
2045
2046 // Revisions are never evicted (no sweep before K1), so their v1 parents stay too.
2047 for rev in self.revisions.revisions() {
2048 worklist.extend(rev.content.parents.iter().copied());
2049 }
2050
2051 // Compute transitive ancestor closure over `parent_changesets`
2052 while let Some(cs_id) = worklist.pop() {
2053 if retained_cs.insert(cs_id) {
2054 if let Some(stored) = self.changesets.get(&cs_id) {
2055 for parent in &stored.envelope.parent_changesets {
2056 worklist.push(*parent);
2057 }
2058 }
2059 }
2060 }
2061
2062 let total_before = self.changesets.len();
2063 self.changesets.retain(|id, _| retained_cs.contains(id));
2064 let evicted_changesets = total_before.saturating_sub(self.changesets.len());
2065
2066 self.idempotency_index
2067 .retain(|_, (_, cs_id)| retained_cs.contains(cs_id));
2068
2069 // 2. Compute retained blob closure from retained changesets
2070 let mut retained_blobs: BTreeSet<BlobDigest> = BTreeSet::new();
2071 for rev in self.revisions.revisions() {
2072 for m in &rev.content.mutations {
2073 if let MutationOp::Upsert { blob_digest, .. } = &m.op {
2074 retained_blobs.insert(*blob_digest);
2075 }
2076 }
2077 }
2078 retained_blobs.extend(self.git_bridge.blob_digests());
2079 for stored in self.changesets.values() {
2080 for m in &stored.envelope.mutations {
2081 if let MutationOp::Upsert { blob_digest, .. } = &m.op {
2082 retained_blobs.insert(*blob_digest);
2083 }
2084 }
2085 }
2086 self.blob_first_visible_seq
2087 .retain(|digest, _| retained_blobs.contains(digest));
2088
2089 // 2b. Segment store (ADR 0003 A2): retained blobs stay where they are, inside
2090 // the segments; the segment index written below records their locations.
2091 // No blob file is written and no segment byte is removed (no garbage
2092 // collection of segment data before step K1).
2093
2094 // 3. Persist the atomic binary checkpoint `checkpoint.v2`. Every logged frame is
2095 // made durable first, so frames the checkpoint covers are never torn if the
2096 // process dies before `wal.log` is replaced (recovery verifies and skips them;
2097 // in the segment layout the segment index vouches for the covered prefix).
2098 // The first binary checkpoint records the last v1 state root (or the empty
2099 // root for a store that never wrote v1) and chains its own root to it; every
2100 // later one chains to the previous checkpoint root.
2101 // Unverified kind 9 records (kept as no-ops only under `TruncateTornTail`) are left
2102 // out (review of PR #100): they change no state, and carrying them would make
2103 // strict recovery refuse the store forever. The ledger is rebuilt without them
2104 // only once the checkpoint is durable; the replay report counts them. In a sealed
2105 // store (issue #101) the same holds for revision records whose seal does not
2106 // verify; sealed records always stay, so the seal chain stays whole.
2107 self.sync_wal()?;
2108 let revision::CompactedRevisionLog {
2109 log: revision_log,
2110 dropped_moves,
2111 dropped_unsealed,
2112 } = self.revisions.compacted_log();
2113 let (v1_state_root, prev_checkpoint_root) = match self.checkpoint_chain {
2114 Some(c) => (c.v1_state_root, c.checkpoint_root),
2115 None if self.v1_history => (v1_state_root_at_entry, v1_state_root_at_entry),
2116 None => (codec::empty_state_root(), codec::empty_state_root()),
2117 };
2118 let state = CheckpointState {
2119 checkpoint_seq: self.committed_seq,
2120 anchor_frame_sha256: self.last_frame_sha256,
2121 changesets: std::mem::take(&mut self.changesets),
2122 idempotency_index: std::mem::take(&mut self.idempotency_index),
2123 blob_first_visible_seq: std::mem::take(&mut self.blob_first_visible_seq),
2124 github_projections: std::mem::take(&mut self.github_projections),
2125 canonical_heads: std::mem::take(&mut self.canonical_heads),
2126 revision_log,
2127 };
2128 let encoded = codec::encode_checkpoint_v2(&state, v1_state_root, prev_checkpoint_root);
2129 self.changesets = state.changesets;
2130 self.idempotency_index = state.idempotency_index;
2131 self.blob_first_visible_seq = state.blob_first_visible_seq;
2132 self.github_projections = state.github_projections;
2133 self.canonical_heads = state.canonical_heads;
2134 let revision_log = state.revision_log;
2135 let (bytes, chain) = encoded?;
2136 // Read back what will be written: it must decode to the same chain and root (the
2137 // live state, less any unverified kind 9 records left out above).
2138 let snap = self.resolve_snapshot_seq(None, None)?;
2139 let expected_root = codec::state_root_of(&self.changesets, &revision_log, snap);
2140 let (_, check) = codec::decode_checkpoint_v2(&bytes)?;
2141 if check != chain || chain.state_root != expected_root {
2142 return Err(SynapseError::new(
2143 RefusalCode::CheckpointCorrupt,
2144 "checkpoint.v2 does not decode back to the state it was written from",
2145 ));
2146 }
2147 // Segment store: the index bound to this checkpoint's exact bytes goes first. A
2148 // crash before the checkpoint rename leaves the previous checkpoint and its own
2149 // index (removed only below, after this checkpoint is durable).
2150 let segment_index = if self.v2_mode {
2151 let log = self.wal_v2.as_ref().ok_or_else(|| {
2152 SynapseError::new(RefusalCode::IoFailure, "WAL v2 writer is not available")
2153 })?;
2154 let index = segment::SegmentIndex {
2155 binding: segment::binding_of(Some((codec::CHECKPOINT_V2_FILE, &bytes))),
2156 replay_segment: log.active(),
2157 replay_offset: log.write_offset(),
2158 entries: self
2159 .blob_locations
2160 .iter()
2161 .filter(|(d, _)| retained_blobs.contains(d))
2162 .map(|(d, l)| (*d, *l))
2163 .collect(),
2164 chunks: BTreeMap::new(),
2165 manifests: self
2166 .blob_chunks
2167 .iter()
2168 .filter(|(d, _)| retained_blobs.contains(d))
2169 .map(|(d, m)| (*d, m.clone()))
2170 .collect(),
2171 };
2172 // ADR 0003 G2: the chunks the retained chunked blobs name.
2173 let mut index = index;
2174 for m in index.manifests.values() {
2175 for (cd, _) in &m.chunks {
2176 let loc = self.chunk_locations.get(cd).copied().ok_or_else(|| {
2177 SynapseError::new(
2178 RefusalCode::CheckpointCorrupt,
2179 format!("chunk {cd} of retained blob {} is not indexed", m.blob),
2180 )
2181 })?;
2182 index.chunks.insert(*cd, loc);
2183 }
2184 }
2185 let name = index.write(&self.medium)?;
2186 if self.fault_injection == FaultInjection::CrashAfterSegmentIndexBeforeCheckpoint {
2187 std::process::exit(FAULT_CRASH_EXIT_CODE);
2188 }
2189 Some((name, index))
2190 } else {
2191 None
2192 };
2193 self.medium
2194 .write_atomic(codec::CHECKPOINT_V2_FILE, &bytes)?;
2195 self.checkpoint_chain = Some(chain);
2196 if dropped_moves + dropped_unsealed > 0 {
2197 self.revisions
2198 .rebuild_after_compaction(revision::CompactedRevisionLog {
2199 log: revision_log,
2200 dropped_moves,
2201 dropped_unsealed,
2202 });
2203 }
2204 self.codec = RecordCodec::BinaryV2;
2205 self.binary_seen = true;
2206 // checkpoint.v1 becomes the tombstone only after checkpoint.v2 is durable.
2207 self.write_v1_tombstone()?;
2208
2209 // 4. Compact `wal.log` (truncate to empty since all state up to `checkpoint_seq` is in `checkpoint.v2`)
2210 if let Some((name, index)) = segment_index {
2211 // Segment store: `wal.log` keeps only the segment marker (so older binaries
2212 // still refuse the store); the segments are kept whole, replay starts at the
2213 // index's position, and older index files are removed.
2214 self.replace_wal_log_with_segment_marker()?;
2215 segment::remove_other_indexes(&self.medium, &name)?;
2216 self.blob_locations = index.entries;
2217 self.chunk_locations = index.chunks;
2218 self.blob_chunks = index.manifests;
2219 } else {
2220 let f = OpenOptions::new()
2221 .create(true)
2222 .write(true)
2223 .truncate(true)
2224 .open(&self.wal_path)
2225 .map_err(io_err)?;
2226 f.sync_all().map_err(io_err)?;
2227 }
2228 self.medium.sync_namespace()?;
2229 self.unflushed_frames = 0;
2230
2231 // 5. Sweep unreferenced blobs on disk (including orphan blobs from pre-WAL crashes)
2232 let swept_blob_files = self.sweep_unreferenced_blobs(&retained_blobs)?;
2233
2234 Ok(CompactionReport {
2235 checkpoint_seq: self.committed_seq,
2236 anchor_frame_sha256: self.last_frame_sha256,
2237 retained_changesets: self.changesets.len(),
2238 evicted_changesets,
2239 retained_blobs: retained_blobs.len(),
2240 swept_blob_files,
2241 })
2242 }
2243
2244 fn resolve_snapshot_seq(
2245 &self,
2246 min_visible_seq: Option<WalSeq>,
2247 snapshot_seq: Option<WalSeq>,
2248 ) -> SynapseResult<WalSeq> {
2249 if let Some(min_seq) = min_visible_seq {
2250 if min_seq > self.committed_seq {
2251 return Err(SynapseError::new(
2252 RefusalCode::VisibilitySeqAhead,
2253 format!(
2254 "requested min_visible_seq {} exceeds committed_seq {}",
2255 min_seq, self.committed_seq
2256 ),
2257 ));
2258 }
2259 }
2260 if let Some(snap) = snapshot_seq {
2261 if snap > self.committed_seq {
2262 return Err(SynapseError::new(
2263 RefusalCode::VisibilitySeqAhead,
2264 format!(
2265 "requested snapshot_seq {} exceeds committed_seq {}",
2266 snap, self.committed_seq
2267 ),
2268 ));
2269 }
2270 if let Some(min_seq) = min_visible_seq {
2271 if snap < min_seq {
2272 return Err(SynapseError::new(
2273 RefusalCode::VisibilitySeqAhead,
2274 format!("snapshot_seq {snap} is older than min_visible_seq {min_seq}"),
2275 ));
2276 }
2277 }
2278 Ok(snap)
2279 } else {
2280 Ok(self.committed_seq)
2281 }
2282 }
2283
2284 fn blob_path(&self, digest: BlobDigest) -> PathBuf {
2285 let hex = digest.to_hex();
2286 self.blobs_dir.join(&hex[0..2]).join(&hex)
2287 }
2288
2289 fn write_blob_file(&self, digest: BlobDigest, bytes: &[u8]) -> SynapseResult<()> {
2290 let final_path = self.blob_path(digest);
2291 if final_path.exists() {
2292 let existing = fs::read(&final_path).map_err(io_err)?;
2293 let existing_digest = BlobDigest::compute(&existing);
2294 if existing_digest != digest || existing.as_slice() != bytes {
2295 return Err(SynapseError::new(
2296 RefusalCode::BlobImmutableConflict,
2297 format!("on-disk blob {digest} conflicts with immutable content"),
2298 ));
2299 }
2300 if self.syncs_blob_files() {
2301 // The file may be left over from a crash before its WAL frame (never
2302 // synced); make it durable before a frame that references it is.
2303 File::open(&final_path)
2304 .and_then(|f| f.sync_all())
2305 .map_err(io_err)?;
2306 sync_dir(final_path.parent().expect("blob shard parent"))?;
2307 }
2308 return Ok(());
2309 }
2310 let shard_dir = final_path.parent().expect("blob shard parent");
2311 if !shard_dir.exists() {
2312 fs::create_dir_all(shard_dir).map_err(io_err)?;
2313 if self.syncs_blob_files() {
2314 sync_dir(&self.blobs_dir)?;
2315 }
2316 }
2317 let tmp_path = shard_dir.join(format!("{}.tmp.{}", digest.to_hex(), std::process::id()));
2318 {
2319 let mut f = File::create(&tmp_path).map_err(io_err)?;
2320 f.write_all(bytes).map_err(io_err)?;
2321 if self.syncs_blob_files() {
2322 f.sync_all().map_err(io_err)?;
2323 }
2324 }
2325 fs::rename(&tmp_path, &final_path).map_err(io_err)?;
2326 if self.syncs_blob_files() {
2327 sync_dir(shard_dir)?;
2328 }
2329 Ok(())
2330 }
2331
2332 /// Blob files are synced under `EveryCommit` and when `GroupCommit` compaction moves
2333 /// inline blobs out of the log.
2334 fn syncs_blob_files(&self) -> bool {
2335 matches!(
2336 self.fsync_policy,
2337 FsyncPolicy::EveryCommit | FsyncPolicy::GroupCommit { .. }
2338 )
2339 }
2340
2341 fn sweep_unreferenced_blobs(
2342 &self,
2343 retained_blobs: &BTreeSet<BlobDigest>,
2344 ) -> SynapseResult<usize> {
2345 let mut swept = 0usize;
2346 if !self.blobs_dir.exists() {
2347 return Ok(0);
2348 }
2349 for shard_entry in fs::read_dir(&self.blobs_dir).map_err(io_err)? {
2350 let shard_entry = shard_entry.map_err(io_err)?;
2351 let shard_path = shard_entry.path();
2352 if !shard_path.is_dir() {
2353 continue;
2354 }
2355 for file_entry in fs::read_dir(&shard_path).map_err(io_err)? {
2356 let file_entry = file_entry.map_err(io_err)?;
2357 let file_path = file_entry.path();
2358 let name = file_entry.file_name();
2359 let name_str = name.to_string_lossy();
2360 let should_remove = if name_str.contains(".tmp.") {
2361 true
2362 } else if let Ok(digest) = BlobDigest::from_hex(&name_str) {
2363 !retained_blobs.contains(&digest)
2364 } else {
2365 false
2366 };
2367 if should_remove {
2368 fs::remove_file(&file_path).map_err(io_err)?;
2369 swept += 1;
2370 }
2371 }
2372 }
2373 Ok(swept)
2374 }
2375
2376 /// Refuse a WAL payload above `StoreLimits::max_wal_record_bytes` (replay would refuse it).
2377 fn check_frame_cap(&self, payload_len: usize) -> SynapseResult<()> {
2378 if payload_len as u64 > self.limits.max_wal_record_bytes {
2379 return Err(SynapseError::new(
2380 RefusalCode::QuotaPayloadTooLarge,
2381 format!(
2382 "WAL record of {payload_len} bytes exceeds max_wal_record_bytes {}",
2383 self.limits.max_wal_record_bytes
2384 ),
2385 ));
2386 }
2387 Ok(())
2388 }
2389
2390 /// `record` as a `wal.log` payload in this store's codec, checked against the cap.
2391 fn encode_v1_payload(&self, record: &WalRecord) -> SynapseResult<Vec<u8>> {
2392 let payload = codec::encode_record_with(record, self.codec)?;
2393 self.check_frame_cap(payload.len())?;
2394 Ok(payload)
2395 }
2396
2397 /// Bring a prepared WAL v2 payload to this store's codec (it changes once, at the
2398 /// migration checkpoint, possibly between prepare and commit), drop what the store
2399 /// already holds (ADR 0003 G2: a manifest of a blob already stored, a chunk already
2400 /// indexed, counting the records accepted earlier in this batch), and check the cap.
2401 /// On success the record's chunks and chunked blobs join `overlay`.
2402 pub(crate) fn conform_v2(
2403 &self,
2404 p: &mut PreparedIngest,
2405 overlay: &mut BatchOverlay,
2406 ) -> SynapseResult<()> {
2407 let enc = p.encoded.as_ref().ok_or_else(|| {
2408 SynapseError::new(
2409 RefusalCode::IoFailure,
2410 "changeset was prepared for WAL v1 but the store writes WAL v2",
2411 )
2412 })?;
2413 let blob_held = |d: &BlobDigest| {
2414 self.blob_chunks.contains_key(d)
2415 || self.blob_locations.contains_key(d)
2416 || overlay.blobs.contains(d)
2417 };
2418 let chunk_held =
2419 |d: &ChunkDigest| self.chunk_locations.contains_key(d) || overlay.chunks.contains(d);
2420 let drops = enc.manifests.iter().any(|m| blob_held(&m.blob))
2421 || enc.chunks.iter().any(|(d, _, _)| chunk_held(d));
2422 if drops {
2423 let rebuilt = enc.rebuild(
2424 &p.record(),
2425 self.codec,
2426 |m| !blob_held(&m.blob),
2427 |d| !chunk_held(d),
2428 )?;
2429 p.encoded = Some(rebuilt);
2430 } else if enc.codec() != self.codec {
2431 let recoded = enc.recode(&p.record(), self.codec)?;
2432 p.encoded = Some(recoded);
2433 }
2434 let enc = p.encoded.as_ref().expect("set above");
2435 self.check_frame_cap(enc.payload.len())?;
2436 overlay.chunks.extend(enc.chunks.iter().map(|(d, _, _)| *d));
2437 overlay
2438 .chunked_blobs
2439 .extend(enc.manifests.iter().map(|m| m.blob));
2440 Ok(())
2441 }
2442
2443 fn append_wal_record(
2444 &mut self,
2445 record: &WalRecord,
2446 ) -> SynapseResult<(WalSeq, [u8; 32], DurabilityGuarantee)> {
2447 if self.v2_mode {
2448 let encoded = wal2::encode_record(record, &[], self.codec)?;
2449 self.check_frame_cap(encoded.payload.len())?;
2450 let mut ticket = self.v2_begin()?;
2451 let result = Self::v2_write(&mut ticket, &[&encoded]);
2452 let placed = self.v2_finish(ticket, result)?;
2453 return Ok((
2454 placed[0].seq,
2455 placed[0].frame_sha256,
2456 DurabilityGuarantee::FsyncBeforeAck,
2457 ));
2458 }
2459 let payload = self.encode_v1_payload(record)?;
2460 self.append_v1_payload(record.kind_byte(), &payload)
2461 }
2462
2463 fn append_v1_payload(
2464 &mut self,
2465 kind: u8,
2466 payload: &[u8],
2467 ) -> SynapseResult<(WalSeq, [u8; 32], DurabilityGuarantee)> {
2468 let fault = std::mem::replace(&mut self.fault_injection, FaultInjection::None);
2469
2470 let next_seq = match fault {
2471 FaultInjection::InjectNextWalSequenceGap => self.committed_seq.next().next(),
2472 FaultInjection::InjectDuplicateWalSequence => self.committed_seq,
2473 _ => self.committed_seq.next(),
2474 };
2475
2476 let mut prev_sha = self.last_frame_sha256;
2477 if fault == FaultInjection::CorruptNextWalChain {
2478 prev_sha[0] ^= 0xff;
2479 }
2480
2481 let mut crc = crc32c(payload);
2482 if fault == FaultInjection::CorruptNextWalCrc {
2483 crc ^= 0xdead_beef;
2484 }
2485
2486 let mut header_prefix = [0u8; 56];
2487 header_prefix[0..4].copy_from_slice(&WAL_MAGIC);
2488 header_prefix[4..6].copy_from_slice(&WAL_VERSION.to_le_bytes());
2489 header_prefix[6] = kind;
2490 header_prefix[7] = self.codec.frame_flags();
2491 header_prefix[8..16].copy_from_slice(&next_seq.0.to_le_bytes());
2492 header_prefix[16..48].copy_from_slice(&prev_sha);
2493 header_prefix[48..52].copy_from_slice(&(payload.len() as u32).to_le_bytes());
2494 header_prefix[52..56].copy_from_slice(&crc.to_le_bytes());
2495
2496 let frame_sha256 = compute_wal_frame_sha256(&header_prefix, payload);
2497 let mut header = [0u8; WAL_HEADER_LEN];
2498 header[0..56].copy_from_slice(&header_prefix);
2499 header[56..88].copy_from_slice(&frame_sha256);
2500
2501 let mut f = OpenOptions::new()
2502 .create(true)
2503 .append(true)
2504 .open(&self.wal_path)
2505 .map_err(io_err)?;
2506
2507 match fault {
2508 FaultInjection::TornWalHeaderWrite { bytes_written } => {
2509 let n = bytes_written.min(WAL_HEADER_LEN - 1);
2510 f.write_all(&header[..n]).map_err(io_err)?;
2511 f.sync_all().map_err(io_err)?;
2512 return Err(SynapseError::new(
2513 RefusalCode::WalTornFrame,
2514 "injected fault: torn WAL header write",
2515 ));
2516 }
2517 FaultInjection::TornWalPayloadWrite { bytes_written } => {
2518 let n = bytes_written.min(payload.len().saturating_sub(1));
2519 f.write_all(&header).map_err(io_err)?;
2520 f.write_all(&payload[..n]).map_err(io_err)?;
2521 f.sync_all().map_err(io_err)?;
2522 return Err(SynapseError::new(
2523 RefusalCode::WalTornFrame,
2524 "injected fault: torn WAL payload write",
2525 ));
2526 }
2527 _ => {
2528 f.write_all(&header).map_err(io_err)?;
2529 f.write_all(payload).map_err(io_err)?;
2530 }
2531 }
2532
2533 let durability = match self.fsync_policy {
2534 // GroupCommit stores always write WAL v2 (handled above); syncing here keeps
2535 // the guarantee if that invariant were ever broken.
2536 FsyncPolicy::EveryCommit | FsyncPolicy::GroupCommit { .. } => {
2537 f.sync_all().map_err(io_err)?;
2538 self.unflushed_frames = 0;
2539 DurabilityGuarantee::FsyncBeforeAck
2540 }
2541 FsyncPolicy::BatchWindow { max_records } => {
2542 self.unflushed_frames = self.unflushed_frames.saturating_add(1);
2543 if self.unflushed_frames >= max_records.max(1) {
2544 f.sync_all().map_err(io_err)?;
2545 self.unflushed_frames = 0;
2546 DurabilityGuarantee::FsyncBeforeAck
2547 } else {
2548 f.flush().map_err(io_err)?;
2549 DurabilityGuarantee::ProcessCrashPageCacheOnly
2550 }
2551 }
2552 };
2553
2554 self.committed_seq = next_seq;
2555 self.last_frame_sha256 = frame_sha256;
2556 Ok((next_seq, frame_sha256, durability))
2557 }
2558
2559 fn apply_record(&mut self, seq: WalSeq, record: WalRecord) {
2560 match record {
2561 WalRecord::ChangesetIngest {
2562 envelope,
2563 changeset_id,
2564 new_blobs,
2565 } => {
2566 for digest in new_blobs {
2567 self.blob_first_visible_seq.entry(digest).or_insert(seq);
2568 }
2569 for m in &envelope.mutations {
2570 if let MutationOp::Upsert { blob_digest, .. } = &m.op {
2571 self.blob_first_visible_seq
2572 .entry(*blob_digest)
2573 .or_insert(seq);
2574 }
2575 }
2576 self.idempotency_index.insert(
2577 (envelope.repo_id.clone(), envelope.idempotency_key),
2578 (seq, changeset_id),
2579 );
2580 self.changesets.insert(
2581 changeset_id,
2582 StoredChangeset {
2583 changeset_id,
2584 committed_seq: seq,
2585 envelope,
2586 evaluations: Vec::new(),
2587 reviews: Vec::new(),
2588 lease_expires_at_ms: 0,
2589 },
2590 );
2591 }
2592 WalRecord::EvaluationAttached {
2593 changeset_id,
2594 attachment,
2595 } => {
2596 if let Some(cs) = self.changesets.get_mut(&changeset_id) {
2597 cs.evaluations.push(attachment);
2598 }
2599 }
2600 WalRecord::ReviewRecorded {
2601 changeset_id,
2602 review,
2603 } => {
2604 if let Some(cs) = self.changesets.get_mut(&changeset_id) {
2605 cs.reviews.push(review);
2606 }
2607 }
2608 WalRecord::GitProjected { projection } => {
2609 self.github_projections
2610 .insert(projection.pr_number, projection);
2611 }
2612 WalRecord::CanonicalPromoted { canonical } => {
2613 self.canonical_heads
2614 .insert(canonical.repo_id.clone(), canonical);
2615 }
2616 WalRecord::LeaseUpdated {
2617 changeset_id,
2618 lease_expires_at_ms,
2619 } => {
2620 if let Some(cs) = self.changesets.get_mut(&changeset_id) {
2621 cs.lease_expires_at_ms = lease_expires_at_ms;
2622 }
2623 }
2624 record @ WalRecord::RevisionAdmitted { .. }
2625 if !self.revisions.accepts(seq, &record) =>
2626 {
2627 self.revisions.apply(seq, record);
2628 }
2629 record @ WalRecord::RevisionAdmitted { .. } => {
2630 if let WalRecord::RevisionAdmitted { new_blobs, .. } = &record {
2631 for digest in new_blobs {
2632 self.blob_first_visible_seq.entry(*digest).or_insert(seq);
2633 }
2634 }
2635 for digest in record.upsert_blobs() {
2636 self.blob_first_visible_seq.entry(digest).or_insert(seq);
2637 }
2638 self.revisions.apply(seq, record);
2639 }
2640 record @ (WalRecord::ObsolescenceRecorded { .. }
2641 | WalRecord::RevisionStateMoved { .. }) => self.revisions.apply(seq, record),
2642 record @ (WalRecord::DerivedRevisionAdmitted { .. }
2643 | WalRecord::GitBridgeImported { .. })
2644 if !self.revisions.accepts(seq, &record) =>
2645 {
2646 self.revisions.apply(seq, record);
2647 }
2648 record @ WalRecord::GitBridgeImported { .. } => {
2649 for digest in record.upsert_blobs() {
2650 self.blob_first_visible_seq.entry(digest).or_insert(seq);
2651 }
2652 self.git_bridge.apply(&record);
2653 self.revisions.apply(seq, record);
2654 }
2655 record @ WalRecord::DerivedRevisionAdmitted { .. } => {
2656 for digest in record.upsert_blobs() {
2657 self.blob_first_visible_seq.entry(digest).or_insert(seq);
2658 }
2659 self.revisions.apply(seq, record);
2660 }
2661 }
2662 }
2663
2664 fn recover(&mut self, recovery_policy: RecoveryPolicy) -> SynapseResult<()> {
2665 // 1. Load the checkpoint: checkpoint.v2 (binary, chained) when present, else
2666 // checkpoint.v1 (JSON). Once checkpoint.v2 exists, checkpoint.v1 is the
2667 // tombstone that makes binaries knowing only v1 refuse the store.
2668 if self.medium.exists(codec::CHECKPOINT_V2_FILE) {
2669 let raw = self
2670 .medium
2671 .read(codec::CHECKPOINT_V2_FILE)
2672 .map_err(io_err)?;
2673 let (state, chain) = codec::decode_checkpoint_v2(&raw)?;
2674 if self.medium.exists("checkpoint.v1") {
2675 let v1 = self.medium.read("checkpoint.v1").map_err(io_err)?;
2676 if v1 != codec::v1_tombstone_bytes() {
2677 // A crash between writing checkpoint.v2 and the tombstone leaves the
2678 // older v1 checkpoint; it must not be ahead of checkpoint.v2.
2679 let m: CheckpointManifest = serde_json::from_slice(&v1).map_err(|e| {
2680 SynapseError::new(
2681 RefusalCode::CheckpointCorrupt,
2682 format!("corrupt checkpoint.v1 next to checkpoint.v2: {e}"),
2683 )
2684 })?;
2685 if m.version != CHECKPOINT_VERSION || m.checkpoint_seq > chain.checkpoint_seq {
2686 return Err(SynapseError::new(
2687 RefusalCode::CheckpointCorrupt,
2688 "checkpoint.v1 is neither the tombstone nor older than checkpoint.v2",
2689 ));
2690 }
2691 self.tombstone_pending = true;
2692 }
2693 } else {
2694 self.tombstone_pending = true;
2695 }
2696 self.load_checkpoint_state(state);
2697 self.checkpoint_chain = Some(chain);
2698 self.binary_seen = true;
2699 } else if self.medium.exists("checkpoint.v1") {
2700 let raw = self.medium.read("checkpoint.v1").map_err(io_err)?;
2701 if raw == codec::v1_tombstone_bytes() {
2702 return Err(SynapseError::new(
2703 RefusalCode::CheckpointCorrupt,
2704 "checkpoint.v1 is the v2 tombstone but checkpoint.v2 is missing",
2705 ));
2706 }
2707 let manifest: CheckpointManifest = serde_json::from_slice(&raw).map_err(|e| {
2708 SynapseError::new(
2709 RefusalCode::CheckpointCorrupt,
2710 format!("corrupt checkpoint.v1: {e}"),
2711 )
2712 })?;
2713 self.load_checkpoint_state(CheckpointState::from_v1_manifest(manifest)?);
2714 self.v1_history = true;
2715 }
2716
2717 // 2. Replay wal.log (v1 frames, possibly ending in the WAL v2 marker), then wal.v2.log.
2718 // Frames the checkpoint already covers (a crash after the checkpoint rename and
2719 // before the logs were emptied) are verified and skipped. In the segment layout
2720 // (ADR 0003 A2) replay of the segments starts at the segment index position.
2721 let mut overlap = CheckpointOverlap::default();
2722 if self.medium.exists("wal.log") {
2723 self.recover_v1(recovery_policy, &mut overlap)?;
2724 }
2725 self.recover_v2(recovery_policy, &mut overlap)?;
2726 overlap.close(self.committed_seq, self.last_frame_sha256)?;
2727
2728 // 3. A state move that does not verify was written without the mover's key: the
2729 // unkeyed seal cannot tell a forgery from a store's write, so strict recovery
2730 // refuses the store instead of hiding it as a no-op (issue #89). It checks the
2731 // records themselves, so a forgery inside a resealed checkpoint is refused too.
2732 if recovery_policy == RecoveryPolicy::StrictFailClosed {
2733 // Issue #101: in a sealed store, a revision record whose seal does not verify
2734 // against the chain so far was written, changed, moved, or followed by a removal
2735 // without the server key.
2736 let seals = self.revisions.seal_report();
2737 if let Some(seq) = seals.first_unsealed {
2738 return Err(SynapseError::new(
2739 RefusalCode::RevisionRecordUnsealed,
2740 format!(
2741 "{} revision record(s) are not sealed by the store's seal key (first at {seq}); strict recovery refuses the store (open it with TruncateTornTail and run checkpoint_and_compact to drop them)",
2742 seals.unsealed
2743 ),
2744 ));
2745 }
2746 let report = self.revisions.state_move_report();
2747 if let Some((seq, fault)) = report.first_unverified {
2748 return Err(SynapseError::new(
2749 RefusalCode::RevisionStateMoveUnverified,
2750 format!(
2751 "{} WAL kind 9 state move(s) do not verify (first at {seq}: {fault:?}); strict recovery refuses the store (open it with TruncateTornTail and run checkpoint_and_compact to drop them)",
2752 report.unverified()
2753 ),
2754 ));
2755 }
2756 }
2757
2758 // 4. A store with v1 history keeps writing v1 JSON until its first binary
2759 // checkpoint (the migration checkpoint); every other store writes binary v2.
2760 self.codec = if self.checkpoint_chain.is_some() || !self.v1_history {
2761 RecordCodec::BinaryV2
2762 } else {
2763 RecordCodec::JsonV1
2764 };
2765 Ok(())
2766 }
2767
2768 fn load_checkpoint_state(&mut self, s: CheckpointState) {
2769 self.committed_seq = s.checkpoint_seq;
2770 self.last_frame_sha256 = s.anchor_frame_sha256;
2771 self.changesets = s.changesets;
2772 self.idempotency_index = s.idempotency_index;
2773 self.blob_first_visible_seq = s.blob_first_visible_seq;
2774 self.github_projections = s.github_projections;
2775 self.canonical_heads = s.canonical_heads;
2776 self.revisions = revision::RevisionLedger::from_log(
2777 s.revision_log,
2778 self.revision_seal.as_ref().map(RevisionSealKey::public_key),
2779 );
2780 self.git_bridge = git_bridge::GitBridgeLedger::from_log(self.revisions.applied_log());
2781 }
2782
2783 /// Admit a replayed (not checkpoint-covered) frame written with `codec`: the codec
2784 /// moves from v1 JSON to binary v2 only at the migration checkpoint, never back.
2785 fn admit_replayed_codec(&mut self, codec: RecordCodec, seq: WalSeq) -> SynapseResult<()> {
2786 match codec {
2787 RecordCodec::JsonV1 if self.binary_seen => Err(SynapseError::new(
2788 RefusalCode::WalVersionUnsupported,
2789 format!("v1 JSON WAL record at {seq} after binary v2 records"),
2790 )),
2791 RecordCodec::JsonV1 => {
2792 self.v1_history = true;
2793 Ok(())
2794 }
2795 RecordCodec::BinaryV2 if self.v1_history && self.checkpoint_chain.is_none() => {
2796 Err(SynapseError::new(
2797 RefusalCode::WalVersionUnsupported,
2798 format!(
2799 "binary v2 WAL record at {seq} in a v1 store before its migration checkpoint"
2800 ),
2801 ))
2802 }
2803 RecordCodec::BinaryV2 => {
2804 self.binary_seen = true;
2805 Ok(())
2806 }
2807 }
2808 }
2809
2810 /// Replace `checkpoint.v1` with the tombstone (atomic: temp file, sync, rename, sync).
2811 fn write_v1_tombstone(&mut self) -> SynapseResult<()> {
2812 self.medium
2813 .write_atomic("checkpoint.v1", &codec::v1_tombstone_bytes())?;
2814 self.tombstone_pending = false;
2815 Ok(())
2816 }
2817
2818 fn recover_v1(
2819 &mut self,
2820 recovery_policy: RecoveryPolicy,
2821 overlap: &mut CheckpointOverlap,
2822 ) -> SynapseResult<()> {
2823 let (mut f, file_len) = match &self.medium {
2824 Medium::Dir(_) => {
2825 let f = OpenOptions::new()
2826 .read(true)
2827 .write(true)
2828 .open(&self.wal_path)
2829 .map_err(io_err)?;
2830 let len = f.metadata().map_err(io_err)?.len();
2831 (WalLogSource::File(f), len)
2832 }
2833 Medium::Block(_) => {
2834 let bytes = self.medium.read("wal.log").map_err(io_err)?;
2835 let len = bytes.len() as u64;
2836 (WalLogSource::Object(std::io::Cursor::new(bytes)), len)
2837 }
2838 };
2839 let mut offset = 0u64;
2840
2841 while offset < file_len {
2842 let remaining = file_len - offset;
2843 if remaining < WAL_HEADER_LEN as u64 {
2844 return self.handle_torn_tail(&mut f, offset, recovery_policy, "torn WAL header");
2845 }
2846
2847 let mut header = [0u8; WAL_HEADER_LEN];
2848 f.seek(SeekFrom::Start(offset)).map_err(io_err)?;
2849 f.read_exact(&mut header).map_err(io_err)?;
2850
2851 if header[0..4] != WAL_MAGIC {
2852 return Err(SynapseError::new(
2853 RefusalCode::WalMagicInvalid,
2854 format!("invalid WAL magic at byte offset {offset}"),
2855 ));
2856 }
2857 let version = u16::from_le_bytes(header[4..6].try_into().unwrap());
2858 let marker_version =
2859 version == wal2::WAL_V2_VERSION || version == segment::WAL_SEGMENT_MARKER_VERSION;
2860 if marker_version && header[6] == WAL_V2_MARKER_KIND {
2861 // Log marker: the log continues in wal.v2.log (version 2) or in the
2862 // segments (version 3). It must be the last frame, continue the chain
2863 // without advancing it, and hash correctly.
2864 if offset + WAL_HEADER_LEN as u64 != file_len {
2865 return Err(SynapseError::new(
2866 RefusalCode::WalMagicInvalid,
2867 format!("unexpected bytes after the WAL v2 marker at offset {offset}"),
2868 ));
2869 }
2870 let seq = WalSeq(u64::from_le_bytes(header[8..16].try_into().unwrap()));
2871 let marker_prev: [u8; 32] = header[16..48].try_into().unwrap();
2872 // Inside the checkpoint overlap the marker continues the skipped frames; a
2873 // marker with nothing skipped before it and below the checkpoint is checked
2874 // through the v2 batches that must chain from it up to the anchor.
2875 let covered = overlap.covers(seq, self.committed_seq);
2876 let (expected_seq, expected_prev) = match overlap.cursor {
2877 Some(cursor) if covered => cursor,
2878 None if covered && seq < self.committed_seq => (seq, marker_prev),
2879 _ => (self.committed_seq, self.last_frame_sha256),
2880 };
2881 if seq != expected_seq {
2882 return Err(SynapseError::new(
2883 RefusalCode::WalSequenceGap,
2884 format!("WAL v2 marker at {seq} does not follow {expected_seq}"),
2885 ));
2886 }
2887 if header != marker_header(version, expected_seq, expected_prev) {
2888 return Err(SynapseError::new(
2889 RefusalCode::WalChainMismatch,
2890 format!("WAL v2 marker at offset {offset} does not match the chain"),
2891 ));
2892 }
2893 if covered && (overlap.cursor.is_some() || seq < self.committed_seq) {
2894 overlap.cursor = Some((seq, marker_prev));
2895 }
2896 self.v2_mode = true;
2897 self.log_layout = if version == wal2::WAL_V2_VERSION {
2898 LogLayout::SingleFileV2
2899 } else {
2900 LogLayout::Segments
2901 };
2902 break;
2903 }
2904 if version != WAL_VERSION {
2905 return Err(SynapseError::new(
2906 RefusalCode::WalVersionUnsupported,
2907 format!("unsupported WAL version {version} at offset {offset}"),
2908 ));
2909 }
2910 let flags = header[7];
2911 let frame_codec = RecordCodec::from_frame_flags(flags).ok_or_else(|| {
2912 SynapseError::new(
2913 RefusalCode::WalFlagsNonZero,
2914 format!("unknown WAL flags {flags} at offset {offset}"),
2915 )
2916 })?;
2917
2918 let seq = WalSeq(u64::from_le_bytes(header[8..16].try_into().unwrap()));
2919 let prev_sha: [u8; 32] = header[16..48].try_into().unwrap();
2920 let payload_len = u32::from_le_bytes(header[48..52].try_into().unwrap()) as u64;
2921 let expected_crc = u32::from_le_bytes(header[52..56].try_into().unwrap());
2922 let expected_frame_sha: [u8; 32] = header[56..88].try_into().unwrap();
2923
2924 // The declared length is checked against the cap before it is trusted (so a
2925 // damaged length is never taken for a torn tail) and before any allocation.
2926 if payload_len > self.limits.max_wal_record_bytes {
2927 return Err(SynapseError::new(
2928 RefusalCode::QuotaPayloadTooLarge,
2929 format!(
2930 "WAL frame at offset {offset} declares {payload_len} payload bytes, above max_wal_record_bytes {}",
2931 self.limits.max_wal_record_bytes
2932 ),
2933 ));
2934 }
2935
2936 if remaining < (WAL_HEADER_LEN as u64 + payload_len) {
2937 return self.handle_torn_tail(
2938 &mut f,
2939 offset,
2940 recovery_policy,
2941 "torn WAL payload at EOF",
2942 );
2943 }
2944
2945 let mut payload = vec![0u8; payload_len as usize];
2946 f.read_exact(&mut payload).map_err(io_err)?;
2947
2948 // Frames covered by checkpoint.v1: verify their integrity and their chain,
2949 // then skip them (the checkpoint already holds their effects).
2950 if overlap.covers(seq, self.committed_seq) {
2951 let actual_crc = crc32c(&payload);
2952 if actual_crc != expected_crc {
2953 return Err(SynapseError::new(
2954 RefusalCode::WalCrcMismatch,
2955 format!("WAL payload CRC32C mismatch at {seq} (covered by checkpoint)"),
2956 ));
2957 }
2958 if compute_wal_frame_sha256(&header[0..56], &payload) != expected_frame_sha {
2959 return Err(SynapseError::new(
2960 RefusalCode::WalChainMismatch,
2961 format!("WAL frame_sha256 mismatch at {seq} (covered by checkpoint)"),
2962 ));
2963 }
2964 overlap.skip(seq, prev_sha, expected_frame_sha)?;
2965 offset += WAL_HEADER_LEN as u64 + payload_len;
2966 continue;
2967 }
2968 overlap.close(self.committed_seq, self.last_frame_sha256)?;
2969
2970 // Sequence continuity check
2971 let expected_seq = self.committed_seq.next();
2972 if seq != expected_seq {
2973 return Err(SynapseError::new(
2974 RefusalCode::WalSequenceGap,
2975 format!(
2976 "WAL sequence mismatch at offset {offset}: expected {expected_seq}, found {seq}"
2977 ),
2978 ));
2979 }
2980
2981 // Hash-chain continuity check
2982 if prev_sha != self.last_frame_sha256 {
2983 return Err(SynapseError::new(
2984 RefusalCode::WalChainMismatch,
2985 format!("WAL prev_frame_sha256 mismatch at {seq}"),
2986 ));
2987 }
2988
2989 // CRC32C check
2990 let actual_crc = crc32c(&payload);
2991 if actual_crc != expected_crc {
2992 return Err(SynapseError::new(
2993 RefusalCode::WalCrcMismatch,
2994 format!(
2995 "WAL payload CRC32C mismatch at {seq}: expected {expected_crc:#x}, computed {actual_crc:#x}"
2996 ),
2997 ));
2998 }
2999
3000 // Frame SHA-256 check
3001 let actual_frame_sha = compute_wal_frame_sha256(&header[0..56], &payload);
3002 if actual_frame_sha != expected_frame_sha {
3003 return Err(SynapseError::new(
3004 RefusalCode::WalChainMismatch,
3005 format!("WAL frame_sha256 mismatch at {seq}"),
3006 ));
3007 }
3008
3009 self.admit_replayed_codec(frame_codec, seq)?;
3010 let record =
3011 codec::decode_record_with(&payload, frame_codec, self.limits.max_wal_record_bytes)
3012 .map_err(|e| {
3013 SynapseError::new(e.code, format!("WAL record at {seq}: {}", e.message))
3014 })?;
3015 if frame_codec == RecordCodec::BinaryV2 && record.kind_byte() != header[6] {
3016 return Err(SynapseError::new(
3017 RefusalCode::WalRecordMalformed,
3018 format!("record kind byte does not match payload at {seq}"),
3019 ));
3020 }
3021
3022 // Verify that all blobs referenced by a committed ingest or revision exist and match digest
3023 for blob_digest in &record.upsert_blobs() {
3024 {
3025 {
3026 let bpath = self.blob_path(*blob_digest);
3027 let raw = fs::read(&bpath).map_err(|_| {
3028 SynapseError::new(
3029 RefusalCode::BlobNotFound,
3030 format!("committed blob {blob_digest} missing during WAL replay"),
3031 )
3032 })?;
3033 if BlobDigest::compute(&raw) != *blob_digest {
3034 return Err(SynapseError::new(
3035 RefusalCode::BlobDigestMismatch,
3036 format!("committed blob {blob_digest} corrupt during WAL replay"),
3037 ));
3038 }
3039 }
3040 }
3041 }
3042
3043 self.committed_seq = seq;
3044 self.last_frame_sha256 = expected_frame_sha;
3045 self.apply_record(seq, record);
3046
3047 offset += WAL_HEADER_LEN as u64 + payload_len;
3048 }
3049
3050 Ok(())
3051 }
3052
3053 /// Replay the log after `wal.log`: segment 1 (`wal.v2.log`) and, in the segment
3054 /// layout, the segments after it, whole batches only (all frames valid or none
3055 /// applied). In the segment layout replay starts at the position the segment index
3056 /// of the checkpoint names, and the index supplies the locations of the blobs the
3057 /// checkpoint retains.
3058 fn recover_v2(
3059 &mut self,
3060 recovery_policy: RecoveryPolicy,
3061 overlap: &mut CheckpointOverlap,
3062 ) -> SynapseResult<()> {
3063 let ids = self.medium.list_segments()?;
3064 if !self.v2_mode {
3065 for &id in &ids {
3066 if self.segment_has_data(id)? {
3067 return Err(SynapseError::new(
3068 RefusalCode::WalVersionUnsupported,
3069 format!(
3070 "{} holds data but wal.log does not end with the WAL v2 marker",
3071 segment::segment_file_name(id)
3072 ),
3073 ));
3074 }
3075 }
3076 return Ok(());
3077 }
3078 let (start_seg, start_off) = if self.log_layout == LogLayout::Segments {
3079 let binding = segment::checkpoint_binding_on(&self.medium)?;
3080 let index = segment::SegmentIndex::load_from(&self.medium, &binding)?;
3081 self.blob_locations = index.entries.clone();
3082 self.chunk_locations = index.chunks.clone();
3083 self.blob_chunks = index.manifests.clone();
3084 if (index.replay_segment, index.replay_offset) != (1, 0) {
3085 // The index vouches for every segment byte before its replay position:
3086 // those frames are covered by the checkpoint it is bound to.
3087 if overlap.cursor.is_some() {
3088 overlap.cursor = Some((self.committed_seq, self.last_frame_sha256));
3089 }
3090 overlap.close(self.committed_seq, self.last_frame_sha256)?;
3091 }
3092 (index.replay_segment, index.replay_offset)
3093 } else {
3094 // Single-file WAL v2: segment 1 only.
3095 if let Some(&id) = ids.iter().find(|&&id| id >= 2) {
3096 if self.segment_has_data(id)? {
3097 return Err(SynapseError::new(
3098 RefusalCode::WalVersionUnsupported,
3099 format!(
3100 "segment {id} holds data but wal.log has the single-file WAL v2 marker"
3101 ),
3102 ));
3103 }
3104 }
3105 (1, 0)
3106 };
3107 let last = ids.last().copied().unwrap_or(0).max(start_seg);
3108 let max = if self.log_layout == LogLayout::Segments {
3109 // Segments are never removed (no garbage collection before K1), so every id
3110 // up to the last must be present; only a store that crashed before creating
3111 // its first segment has none.
3112 let never_created = ids.is_empty() && (start_seg, start_off) == (1, 0);
3113 if let Some(missing) = (1..=last).find(|id| !never_created && !ids.contains(id)) {
3114 return Err(SynapseError::new(
3115 RefusalCode::WalSequenceGap,
3116 format!(
3117 "segment file {} is missing",
3118 segment::segment_file_name(missing)
3119 ),
3120 ));
3121 }
3122 last
3123 } else {
3124 1
3125 };
3126 self.wal_v2_recovered_end = (start_seg, start_off);
3127 for id in start_seg..=max {
3128 let base = if id == start_seg { start_off } else { 0 };
3129 let Some(buf) = self.medium.read_segment_from(id, base)? else {
3130 break;
3131 };
3132 let (end, holds_data, truncated) =
3133 self.replay_segment(id, base, &buf, max, recovery_policy, overlap)?;
3134 if holds_data || id == start_seg {
3135 self.wal_v2_recovered_end = (id, end);
3136 }
3137 if truncated {
3138 break;
3139 }
3140 }
3141 Ok(())
3142 }
3143
3144 /// True when every segment after `id` up to `max` is missing or all zero.
3145 fn later_segments_zero(&self, id: u64, max: u64) -> SynapseResult<bool> {
3146 for later in id + 1..=max {
3147 if self.segment_has_data(later)? {
3148 return Ok(false);
3149 }
3150 }
3151 Ok(true)
3152 }
3153
3154 /// Replay the batches of segment `id` held in `buf` (the file from byte `base` on).
3155 /// Returns the absolute end of the valid log in this segment, whether it holds a
3156 /// batch (or a torn tail), and whether a torn tail was truncated.
3157 #[allow(clippy::too_many_arguments)]
3158 fn replay_segment(
3159 &mut self,
3160 id: u64,
3161 base: u64,
3162 buf: &[u8],
3163 max: u64,
3164 recovery_policy: RecoveryPolicy,
3165 overlap: &mut CheckpointOverlap,
3166 ) -> SynapseResult<(u64, bool, bool)> {
3167 let hlen = wal2::WAL_V2_BATCH_HEADER_LEN;
3168 let mut off = 0usize;
3169 let mut holds_data = false;
3170 while off < buf.len() {
3171 let header_end = (off + hlen).min(buf.len());
3172 let header_zero = buf[off..header_end].iter().all(|b| *b == 0);
3173 if header_zero && buf[off..].iter().all(|b| *b == 0) {
3174 break; // clean end of this segment
3175 }
3176 holds_data = true;
3177 // A batch the checkpoint covers: verify it whole (fail closed on any error, it
3178 // was acknowledged before the checkpoint) and skip it.
3179 if let Some((_, _, first)) = buf.get(off..off + hlen).and_then(wal2::parse_batch_header)
3180 {
3181 if overlap.covers(first, self.committed_seq) {
3182 let (expected_seq, expected_prev) = match overlap.cursor {
3183 Some((s, h)) => (s.next(), h),
3184 // Nothing skipped yet: take the chain link the batch states; the
3185 // skipped chain must still end at the checkpoint anchor.
3186 None => (first, wal2::first_frame_prev(buf, off)),
3187 };
3188 let (frames, next) = wal2::validate_batch(
3189 buf,
3190 off,
3191 expected_seq,
3192 expected_prev,
3193 self.limits.max_wal_record_bytes,
3194 )?;
3195 for fr in &frames {
3196 if fr.seq > self.committed_seq {
3197 return Err(SynapseError::new(
3198 RefusalCode::WalSequenceGap,
3199 format!(
3200 "WAL v2 batch at {off} straddles checkpoint {} (frame {})",
3201 self.committed_seq, fr.seq
3202 ),
3203 ));
3204 }
3205 overlap.cursor = Some((fr.seq, fr.frame_sha256));
3206 }
3207 off = next;
3208 continue;
3209 }
3210 }
3211 overlap.close(self.committed_seq, self.last_frame_sha256)?;
3212 let result = if header_zero {
3213 Err(SynapseError::new(
3214 RefusalCode::WalTornFrame,
3215 format!("non-zero bytes after an empty WAL v2 batch header at {off}"),
3216 ))
3217 } else {
3218 wal2::validate_batch(
3219 buf,
3220 off,
3221 self.committed_seq.next(),
3222 self.last_frame_sha256,
3223 self.limits.max_wal_record_bytes,
3224 )
3225 };
3226 match result {
3227 Ok((frames, next)) => {
3228 for fr in frames {
3229 self.admit_replayed_codec(fr.codec, fr.seq)?;
3230 {
3231 for blob_digest in &fr.record.upsert_blobs() {
3232 {
3233 let inline = fr.inline.iter().any(|(d, _, _)| d == blob_digest);
3234 let inline = inline
3235 || fr.manifests.iter().any(|m| m.blob == *blob_digest);
3236 if inline
3237 || self.blob_locations.contains_key(blob_digest)
3238 || self.blob_chunks.contains_key(blob_digest)
3239 {
3240 continue;
3241 }
3242 let raw = fs::read(self.blob_path(*blob_digest)).map_err(|_| {
3243 SynapseError::new(
3244 RefusalCode::BlobNotFound,
3245 format!("committed blob {blob_digest} missing during WAL v2 replay"),
3246 )
3247 })?;
3248 if BlobDigest::compute(&raw) != *blob_digest {
3249 return Err(SynapseError::new(
3250 RefusalCode::BlobDigestMismatch,
3251 format!("committed blob {blob_digest} corrupt during WAL v2 replay"),
3252 ));
3253 }
3254 }
3255 }
3256 }
3257 for &(d, rel, len) in &fr.inline {
3258 self.blob_locations.entry(d).or_insert(segment::BlobLoc {
3259 segment: id,
3260 offset: base + rel,
3261 len,
3262 });
3263 }
3264 // ADR 0003 G2: the frame's chunks join the chunk index; every chunk a
3265 // manifest names must then be indexed (in this frame or earlier).
3266 for &(d, rel, len) in &fr.chunks {
3267 self.chunk_locations.entry(d).or_insert(segment::BlobLoc {
3268 segment: id,
3269 offset: base + rel,
3270 len,
3271 });
3272 }
3273 for m in fr.manifests {
3274 for (cd, clen) in &m.chunks {
3275 match self.chunk_locations.get(cd) {
3276 Some(loc) if loc.len == *clen => {}
3277 _ => {
3278 return Err(SynapseError::new(
3279 RefusalCode::BlobNotFound,
3280 format!(
3281 "chunk {cd} of blob {} missing during WAL v2 replay at {}",
3282 m.blob, fr.seq
3283 ),
3284 ))
3285 }
3286 }
3287 }
3288 self.blob_chunks.entry(m.blob).or_insert(m);
3289 }
3290 self.committed_seq = fr.seq;
3291 self.last_frame_sha256 = fr.frame_sha256;
3292 self.apply_record(fr.seq, fr.record);
3293 }
3294 off = next;
3295 }
3296 Err(e) => {
3297 // A length above the cap is never taken for a torn tail.
3298 if e.code == RefusalCode::QuotaPayloadTooLarge {
3299 return Err(e);
3300 }
3301 // A torn tail is only the last write: nothing valid after it in this
3302 // segment, its lost end reads back as zeros, and every later segment
3303 // is empty (a batch never goes to a new segment before the previous
3304 // one is durable).
3305 let torn = !wal2::valid_batch_after(buf, off + 1)
3306 && wal2::torn_evidence(buf, off)
3307 && self.later_segments_zero(id, max)?;
3308 if !torn {
3309 return Err(e);
3310 }
3311 match recovery_policy {
3312 RecoveryPolicy::StrictFailClosed => {
3313 return Err(SynapseError::new(
3314 RefusalCode::WalTornFrame,
3315 format!(
3316 "torn WAL v2 batch in segment {id} at byte offset {}: {}",
3317 base + off as u64,
3318 e.message
3319 ),
3320 ))
3321 }
3322 RecoveryPolicy::TruncateTornTail => {
3323 let last_nonzero = buf.iter().rposition(|b| *b != 0).unwrap_or(off);
3324 let end = wal2::align_up(last_nonzero as u64 + 1) as usize;
3325 self.medium.zero_segment_range(
3326 id,
3327 base + off as u64,
3328 base + end as u64,
3329 )?;
3330 self.torn_frames_truncated_on_open += 1;
3331 return Ok((base + off as u64, true, true));
3332 }
3333 }
3334 }
3335 }
3336 }
3337 Ok((base + off as u64, holds_data, false))
3338 }
3339
3340 fn handle_torn_tail(
3341 &mut self,
3342 f: &mut WalLogSource,
3343 valid_offset: u64,
3344 recovery_policy: RecoveryPolicy,
3345 reason: &str,
3346 ) -> SynapseResult<()> {
3347 match recovery_policy {
3348 RecoveryPolicy::StrictFailClosed => Err(SynapseError::new(
3349 RefusalCode::WalTornFrame,
3350 format!("{reason} at byte offset {valid_offset}"),
3351 )),
3352 RecoveryPolicy::TruncateTornTail => {
3353 match f {
3354 WalLogSource::File(f) => {
3355 f.set_len(valid_offset).map_err(io_err)?;
3356 f.sync_all().map_err(io_err)?;
3357 }
3358 WalLogSource::Object(c) => {
3359 let keep = c.get_ref()[..valid_offset as usize].to_vec();
3360 self.medium.write_atomic("wal.log", &keep)?;
3361 }
3362 }
3363 self.torn_frames_truncated_on_open += 1;
3364 Ok(())
3365 }
3366 }
3367 }
3368}
3369
3370/// `wal.log` as recovery reads it: the file (A2) or the bytes of the metadata object (R1).
3371enum WalLogSource {
3372 File(File),
3373 Object(std::io::Cursor<Vec<u8>>),
3374}
3375
3376impl Read for WalLogSource {
3377 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
3378 match self {
3379 WalLogSource::File(f) => f.read(buf),
3380 WalLogSource::Object(c) => c.read(buf),
3381 }
3382 }
3383}
3384
3385impl Seek for WalLogSource {
3386 fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
3387 match self {
3388 WalLogSource::File(f) => f.seek(pos),
3389 WalLogSource::Object(c) => c.seek(pos),
3390 }
3391 }
3392}
3393
3394/// Log frames that `checkpoint.v1` already covers, met at the start of replay.
3395///
3396/// A crash after the checkpoint is renamed into place but before `wal.log` (and, in the
3397/// single-file WAL v2 layout before ADR 0003 A2, `wal.v2.log`) is emptied leaves frames with `seq <= checkpoint_seq` in front of the
3398/// log. Recovery verifies them (CRC, frame digest, and one unbroken hash chain among
3399/// them) and skips them; the skipped chain must end exactly at the checkpoint's sequence
3400/// and anchor digest. Skipping is allowed only before the first frame is applied.
3401#[derive(Debug, Default)]
3402struct CheckpointOverlap {
3403 /// Last skipped frame: `(seq, frame_sha256)`.
3404 cursor: Option<(WalSeq, [u8; 32])>,
3405 /// Set once replay moved past the covered frames.
3406 closed: bool,
3407}
3408
3409impl CheckpointOverlap {
3410 fn covers(&self, seq: WalSeq, committed: WalSeq) -> bool {
3411 !self.closed && seq <= committed
3412 }
3413
3414 /// Record a skipped v1 frame; it must extend the skipped chain.
3415 fn skip(&mut self, seq: WalSeq, prev: [u8; 32], frame_sha256: [u8; 32]) -> SynapseResult<()> {
3416 if let Some((s, h)) = self.cursor {
3417 if seq != s.next() {
3418 return Err(SynapseError::new(
3419 RefusalCode::WalSequenceGap,
3420 format!("covered WAL frames jump from {s} to {seq}"),
3421 ));
3422 }
3423 if prev != h {
3424 return Err(SynapseError::new(
3425 RefusalCode::WalChainMismatch,
3426 format!("covered WAL frame {seq} does not chain to {s}"),
3427 ));
3428 }
3429 }
3430 self.cursor = Some((seq, frame_sha256));
3431 Ok(())
3432 }
3433
3434 /// Leave the overlap: the skipped chain, if any, must end at the checkpoint anchor.
3435 fn close(&mut self, checkpoint_seq: WalSeq, anchor: [u8; 32]) -> SynapseResult<()> {
3436 if self.closed {
3437 return Ok(());
3438 }
3439 self.closed = true;
3440 match self.cursor {
3441 Some((s, _)) if s != checkpoint_seq => Err(SynapseError::new(
3442 RefusalCode::WalSequenceGap,
3443 format!(
3444 "frames covered by checkpoint.v1 end at {s}, checkpoint is {checkpoint_seq}"
3445 ),
3446 )),
3447 Some((_, h)) if h != anchor => Err(SynapseError::new(
3448 RefusalCode::WalChainMismatch,
3449 format!(
3450 "frames covered by checkpoint.v1 do not end at its anchor ({checkpoint_seq})"
3451 ),
3452 )),
3453 _ => Ok(()),
3454 }
3455 }
3456}
3457
3458/// Frame kind of the WAL v2 marker written at the end of `wal.log`.
3459const WAL_V2_MARKER_KIND: u8 = 0xFF;
3460
3461/// The 88-byte log marker: v1 header layout with `version` (2: WAL v2 in `wal.v2.log`
3462/// alone; 3: the segment layout of ADR 0003 A2), kind `0xFF`, an empty payload, `seq`
3463/// and `prev_frame_sha256` equal to the last committed frame, and the v2 frame digest.
3464/// Binaries that do not know the version refuse it (`WalVersionUnsupported`) instead of
3465/// missing the commits that follow it.
3466fn marker_header(version: u16, seq: WalSeq, prev: [u8; 32]) -> [u8; WAL_HEADER_LEN] {
3467 let mut h = wal2::frame_header(
3468 seq,
3469 prev,
3470 WAL_V2_MARKER_KIND,
3471 0,
3472 0,
3473 crc32c(&[]),
3474 &wal2::payload_digest(&[]),
3475 )
3476 .0;
3477 h[4..6].copy_from_slice(&version.to_le_bytes());
3478 let sha = wal2::frame_digest(&h[0..56], &wal2::payload_digest(&[]));
3479 h[56..88].copy_from_slice(&sha);
3480 h
3481}
3482
3483fn compute_wal_frame_sha256(header_prefix_56: &[u8], payload: &[u8]) -> [u8; 32] {
3484 let mut hasher = Sha256::new();
3485 hasher.update(DOMAIN_WAL_FRAME_V1);
3486 hasher.update(header_prefix_56);
3487 hasher.update(payload);
3488 hasher.finalize().into()
3489}
3490
3491/// One `wal.log` frame (88-byte header plus payload) decoded and verified on its own:
3492/// header fields, length cap, CRC-32C, frame digest, record codec and kind. Sequence and
3493/// chain continuity are the caller's (recovery checks them against the previous frame).
3494#[derive(Debug, Clone, PartialEq, Eq)]
3495pub struct DecodedFrame {
3496 pub seq: WalSeq,
3497 pub prev_frame_sha256: [u8; 32],
3498 pub frame_sha256: [u8; 32],
3499 pub codec: RecordCodec,
3500 pub record: WalRecord,
3501 /// Bytes the frame occupies (header plus payload).
3502 pub frame_len: usize,
3503}
3504
3505/// Build a `wal.log` frame around `payload` (any bytes) with header `kind` and `flags`.
3506/// Returns the frame and its `frame_sha256`. Used by the writer and by test corpora.
3507pub fn wal_frame_from_payload(
3508 seq: WalSeq,
3509 prev_frame_sha256: [u8; 32],
3510 kind: u8,
3511 flags: u8,
3512 payload: &[u8],
3513) -> (Vec<u8>, [u8; 32]) {
3514 let mut header_prefix = [0u8; 56];
3515 header_prefix[0..4].copy_from_slice(&WAL_MAGIC);
3516 header_prefix[4..6].copy_from_slice(&WAL_VERSION.to_le_bytes());
3517 header_prefix[6] = kind;
3518 header_prefix[7] = flags;
3519 header_prefix[8..16].copy_from_slice(&seq.0.to_le_bytes());
3520 header_prefix[16..48].copy_from_slice(&prev_frame_sha256);
3521 header_prefix[48..52].copy_from_slice(&(payload.len() as u32).to_le_bytes());
3522 header_prefix[52..56].copy_from_slice(&crc32c(payload).to_le_bytes());
3523 let sha = compute_wal_frame_sha256(&header_prefix, payload);
3524 let mut frame = Vec::with_capacity(WAL_HEADER_LEN + payload.len());
3525 frame.extend_from_slice(&header_prefix);
3526 frame.extend_from_slice(&sha);
3527 frame.extend_from_slice(payload);
3528 (frame, sha)
3529}
3530
3531/// Encode `record` with `codec` as one `wal.log` frame. Refuses a payload above `cap`.
3532pub fn encode_wal_frame(
3533 seq: WalSeq,
3534 prev_frame_sha256: [u8; 32],
3535 record: &WalRecord,
3536 codec: RecordCodec,
3537 cap: u64,
3538) -> SynapseResult<(Vec<u8>, [u8; 32])> {
3539 let payload = codec::encode_record_with(record, codec)?;
3540 if payload.len() as u64 > cap {
3541 return Err(SynapseError::new(
3542 RefusalCode::QuotaPayloadTooLarge,
3543 format!(
3544 "WAL record of {} bytes exceeds the cap {cap}",
3545 payload.len()
3546 ),
3547 ));
3548 }
3549 Ok(wal_frame_from_payload(
3550 seq,
3551 prev_frame_sha256,
3552 record.kind_byte(),
3553 codec.frame_flags(),
3554 &payload,
3555 ))
3556}
3557
3558/// Decode and verify the `wal.log` frame at the start of `buf`; `cap` is the largest
3559/// payload length accepted (`StoreLimits::max_wal_record_bytes`).
3560pub fn decode_wal_frame(buf: &[u8], cap: u64) -> SynapseResult<DecodedFrame> {
3561 let header = buf.get(..WAL_HEADER_LEN).ok_or_else(|| {
3562 SynapseError::new(
3563 RefusalCode::WalTornFrame,
3564 format!("{} bytes cannot hold a WAL frame header", buf.len()),
3565 )
3566 })?;
3567 if header[0..4] != WAL_MAGIC {
3568 return Err(SynapseError::new(
3569 RefusalCode::WalMagicInvalid,
3570 "invalid WAL magic",
3571 ));
3572 }
3573 let version = u16::from_le_bytes([header[4], header[5]]);
3574 if version != WAL_VERSION {
3575 return Err(SynapseError::new(
3576 RefusalCode::WalVersionUnsupported,
3577 format!("unsupported WAL version {version}"),
3578 ));
3579 }
3580 let codec = RecordCodec::from_frame_flags(header[7]).ok_or_else(|| {
3581 SynapseError::new(
3582 RefusalCode::WalFlagsNonZero,
3583 format!("unknown WAL flags {}", header[7]),
3584 )
3585 })?;
3586 let seq = WalSeq(u64::from_le_bytes(
3587 header[8..16].try_into().expect("8 bytes"),
3588 ));
3589 let prev_frame_sha256: [u8; 32] = header[16..48].try_into().expect("32 bytes");
3590 let payload_len = u32::from_le_bytes(header[48..52].try_into().expect("4 bytes"));
3591 let crc = u32::from_le_bytes(header[52..56].try_into().expect("4 bytes"));
3592 let frame_sha256: [u8; 32] = header[56..88].try_into().expect("32 bytes");
3593 if u64::from(payload_len) > cap {
3594 return Err(SynapseError::new(
3595 RefusalCode::QuotaPayloadTooLarge,
3596 format!("WAL frame {seq} declares {payload_len} payload bytes, above the cap {cap}"),
3597 ));
3598 }
3599 let frame_len = WAL_HEADER_LEN + payload_len as usize;
3600 let payload = buf.get(WAL_HEADER_LEN..frame_len).ok_or_else(|| {
3601 SynapseError::new(
3602 RefusalCode::WalTornFrame,
3603 format!(
3604 "WAL frame {seq} declares {payload_len} payload bytes, {} present",
3605 buf.len() - WAL_HEADER_LEN
3606 ),
3607 )
3608 })?;
3609 if crc32c(payload) != crc {
3610 return Err(SynapseError::new(
3611 RefusalCode::WalCrcMismatch,
3612 format!("WAL payload CRC32C mismatch at {seq}"),
3613 ));
3614 }
3615 if compute_wal_frame_sha256(&header[0..56], payload) != frame_sha256 {
3616 return Err(SynapseError::new(
3617 RefusalCode::WalChainMismatch,
3618 format!("WAL frame_sha256 mismatch at {seq}"),
3619 ));
3620 }
3621 let record = codec::decode_record_with(payload, codec, cap)?;
3622 if record.kind_byte() != header[6] {
3623 return Err(SynapseError::new(
3624 RefusalCode::WalRecordMalformed,
3625 format!("record kind byte does not match payload at {seq}"),
3626 ));
3627 }
3628 Ok(DecodedFrame {
3629 seq,
3630 prev_frame_sha256,
3631 frame_sha256,
3632 codec,
3633 record,
3634 frame_len,
3635 })
3636}
3637
3638fn sync_dir(dir: &Path) -> SynapseResult<()> {
3639 let f = File::open(dir).map_err(io_err)?;
3640 f.sync_all().map_err(io_err)
3641}
3642
3643/// Write `bytes` to `path` atomically: `tmp` is written and synced, renamed over `path`,
3644/// and `dir` is synced.
3645fn write_file_atomic(dir: &Path, tmp: &Path, path: &Path, bytes: &[u8]) -> SynapseResult<()> {
3646 {
3647 let mut f = File::create(tmp).map_err(io_err)?;
3648 f.write_all(bytes).map_err(io_err)?;
3649 f.sync_all().map_err(io_err)?;
3650 }
3651 fs::rename(tmp, path).map_err(io_err)?;
3652 sync_dir(dir)
3653}
3654
3655fn io_err(e: std::io::Error) -> SynapseError {
3656 SynapseError::new(RefusalCode::IoFailure, e.to_string())
3657}
3658
3659#[cfg(test)]
3660mod tests {
3661 use super::*;
3662 use ed25519_dalek::SigningKey;
3663 use std::process::Command;
3664 use synapse_core::{FileMode, GitOid, PathMutation, SYNAPSE_ENVELOPE_VERSION};
3665
3666 pub(crate) fn temp_store_dir(label: &str) -> PathBuf {
3667 let dir = std::env::temp_dir().join(format!(
3668 "synapse-store-test-{}-{}-{}",
3669 label,
3670 std::process::id(),
3671 std::time::SystemTime::now()
3672 .duration_since(std::time::UNIX_EPOCH)
3673 .unwrap()
3674 .as_nanos()
3675 ));
3676 let _ = fs::remove_dir_all(&dir);
3677 fs::create_dir_all(&dir).unwrap();
3678 dir
3679 }
3680
3681 pub(crate) fn make_signed_changeset(
3682 signing_key: &SigningKey,
3683 idem_label: &str,
3684 path: &str,
3685 content: &[u8],
3686 parents: Vec<ChangesetId>,
3687 created_at_ms: u64,
3688 ) -> (ChangesetEnvelope, Vec<(BlobDigest, Vec<u8>)>) {
3689 let digest = BlobDigest::compute(content);
3690 let mut env = ChangesetEnvelope {
3691 version: SYNAPSE_ENVELOPE_VERSION,
3692 repo_id: RepoId::new("aien-spark/synapse").unwrap(),
3693 base_git_oid: GitOid::compute_blob(b"base"),
3694 parent_changesets: parents,
3695 author_did: String::new(),
3696 idempotency_key: IdempotencyKey::from_label(idem_label),
3697 created_at_ms,
3698 intent_summary: format!("Update {path}"),
3699 mutations: vec![PathMutation {
3700 path: path.to_string(),
3701 op: MutationOp::Upsert {
3702 mode: FileMode::Regular644,
3703 blob_digest: digest,
3704 size_bytes: content.len() as u64,
3705 },
3706 }],
3707 evidence_receipts: vec![],
3708 signature: vec![],
3709 };
3710 env.sign(signing_key);
3711 (env, vec![(digest, content.to_vec())])
3712 }
3713
3714 #[test]
3715 fn test_crc32c_standard_rfc3720_vector() {
3716 assert_eq!(crc32c(b"123456789"), 0xe306_9283);
3717 }
3718
3719 #[test]
3720 fn test_idempotent_ingest_snapshot_reads_and_deterministic_replay() {
3721 let dir = temp_store_dir("idempotent-replay");
3722 let key = SigningKey::from_bytes(&[11u8; 32]);
3723
3724 let (root_before, cs1_id, cs2_id);
3725 {
3726 let mut store = SynapseStore::open(
3727 &dir,
3728 FsyncPolicy::EveryCommit,
3729 RecoveryPolicy::StrictFailClosed,
3730 StoreLimits::default(),
3731 )
3732 .unwrap();
3733
3734 let (env1, blobs1) =
3735 make_signed_changeset(&key, "idem-1", "src/a.rs", b"pub fn a() {}\n", vec![], 1000);
3736 let out1 = store.ingest_changeset(env1.clone(), &blobs1).unwrap();
3737 let seq1 = match out1 {
3738 IngestOutcome::Committed {
3739 wal_seq,
3740 changeset_id,
3741 durability,
3742 ..
3743 } => {
3744 assert_eq!(wal_seq, WalSeq(1));
3745 assert_eq!(durability, DurabilityGuarantee::FsyncBeforeAck);
3746 cs1_id = changeset_id;
3747 wal_seq
3748 }
3749 _ => panic!("expected Committed"),
3750 };
3751
3752 // Re-submitting identical envelope + idempotency key returns IdempotentDuplicate without advancing WAL
3753 let dup = store.ingest_changeset(env1, &blobs1).unwrap();
3754 assert_eq!(
3755 dup,
3756 IngestOutcome::IdempotentDuplicate {
3757 wal_seq: seq1,
3758 changeset_id: cs1_id
3759 }
3760 );
3761 assert_eq!(store.committed_seq(), WalSeq(1));
3762
3763 // Re-submitting the SAME idempotency key with DIFFERENT content fails closed
3764 let (env_conflict, blobs_conflict) = make_signed_changeset(
3765 &key,
3766 "idem-1",
3767 "src/a.rs",
3768 b"pub fn a_modified() {}\n",
3769 vec![],
3770 1001,
3771 );
3772 let err = store
3773 .ingest_changeset(env_conflict, &blobs_conflict)
3774 .unwrap_err();
3775 assert_eq!(err.code, RefusalCode::IdempotencyKeyConflict);
3776
3777 // Submit second changeset stacked on cs1_id
3778 let (env2, blobs2) = make_signed_changeset(
3779 &key,
3780 "idem-2",
3781 "src/b.rs",
3782 b"pub fn b() {}\n",
3783 vec![cs1_id],
3784 2000,
3785 );
3786 let out2 = store.ingest_changeset(env2, &blobs2).unwrap();
3787 match out2 {
3788 IngestOutcome::Committed {
3789 wal_seq,
3790 changeset_id,
3791 ..
3792 } => {
3793 assert_eq!(wal_seq, WalSeq(2));
3794 cs2_id = changeset_id;
3795 }
3796 _ => panic!("expected Committed"),
3797 }
3798
3799 // Snapshot isolation check: at snapshot WalSeq(1), cs1 is visible, cs2 and blob2 are NOT visible
3800 assert!(store
3801 .get_changeset(cs1_id, Some(WalSeq(1)), Some(WalSeq(1)))
3802 .is_ok());
3803 assert_eq!(
3804 store
3805 .get_changeset(cs2_id, None, Some(WalSeq(1)))
3806 .unwrap_err()
3807 .code,
3808 RefusalCode::ChangesetNotFound
3809 );
3810 assert_eq!(
3811 store
3812 .get_blob_visible(blobs2[0].0, None, Some(WalSeq(1)))
3813 .unwrap_err()
3814 .code,
3815 RefusalCode::BlobNotFound
3816 );
3817 // At WalSeq(2), blob2 is visible
3818 assert_eq!(
3819 store
3820 .get_blob_visible(blobs2[0].0, Some(WalSeq(2)), Some(WalSeq(2)))
3821 .unwrap(),
3822 b"pub fn b() {}\n"
3823 );
3824
3825 // Requesting min_visible_seq ahead of committed_seq refuses with VisibilitySeqAhead
3826 assert_eq!(
3827 store
3828 .get_changeset(cs1_id, Some(WalSeq(99)), None)
3829 .unwrap_err()
3830 .code,
3831 RefusalCode::VisibilitySeqAhead
3832 );
3833
3834 root_before = store.state_root_digest(None).unwrap();
3835 }
3836
3837 // Reopen and deterministically replay WAL from disk
3838 let reopened = SynapseStore::open(
3839 &dir,
3840 FsyncPolicy::EveryCommit,
3841 RecoveryPolicy::StrictFailClosed,
3842 StoreLimits::default(),
3843 )
3844 .unwrap();
3845 assert_eq!(reopened.committed_seq(), WalSeq(2));
3846 assert_eq!(reopened.state_root_digest(None).unwrap(), root_before);
3847 let _ = fs::remove_dir_all(&dir);
3848 }
3849
3850 #[test]
3851 fn test_fault_injection_crash_before_wal_and_torn_frames_no_phantom_visibility() {
3852 let dir = temp_store_dir("fault-injection");
3853 let key = SigningKey::from_bytes(&[22u8; 32]);
3854
3855 let mut store = SynapseStore::open(
3856 &dir,
3857 FsyncPolicy::EveryCommit,
3858 RecoveryPolicy::StrictFailClosed,
3859 StoreLimits::default(),
3860 )
3861 .unwrap();
3862
3863 // Commit seq 1 normally
3864 let (env1, blobs1) = make_signed_changeset(
3865 &key,
3866 "k1",
3867 "src/one.rs",
3868 b"const ONE: u32 = 1;\n",
3869 vec![],
3870 100,
3871 );
3872 store.ingest_changeset(env1, &blobs1).unwrap();
3873 assert_eq!(store.committed_seq(), WalSeq(1));
3874
3875 // Fault 1: Crash after writing blob to disk, BEFORE appending WAL frame
3876 store.set_fault_injection(FaultInjection::CrashAfterBlobWriteBeforeWalAppend);
3877 let (env_phantom, blobs_phantom) = make_signed_changeset(
3878 &key,
3879 "k-phantom",
3880 "src/phantom.rs",
3881 b"phantom content\n",
3882 vec![],
3883 200,
3884 );
3885 let phantom_blob_digest = blobs_phantom[0].0;
3886 let phantom_cs_id = env_phantom.compute_id();
3887 assert_eq!(
3888 store
3889 .ingest_changeset(env_phantom, &blobs_phantom)
3890 .unwrap_err()
3891 .code,
3892 RefusalCode::IoFailure
3893 );
3894
3895 // Even though the blob file is on disk, it MUST NOT be visible through the store!
3896 assert_eq!(
3897 store
3898 .get_blob_visible(phantom_blob_digest, None, None)
3899 .unwrap_err()
3900 .code,
3901 RefusalCode::BlobNotFound
3902 );
3903 assert_eq!(
3904 store
3905 .get_changeset(phantom_cs_id, None, None)
3906 .unwrap_err()
3907 .code,
3908 RefusalCode::ChangesetNotFound
3909 );
3910
3911 // Fault 2: Torn WAL payload write on seq 2
3912 store.set_fault_injection(FaultInjection::TornWalPayloadWrite { bytes_written: 12 });
3913 let (env_torn, blobs_torn) = make_signed_changeset(
3914 &key,
3915 "k-torn",
3916 "src/torn.rs",
3917 b"torn payload bytes\n",
3918 vec![],
3919 300,
3920 );
3921 let torn_blob_digest = blobs_torn[0].0;
3922 let torn_cs_id = env_torn.compute_id();
3923 assert_eq!(
3924 store
3925 .ingest_changeset(env_torn, &blobs_torn)
3926 .unwrap_err()
3927 .code,
3928 RefusalCode::WalTornFrame
3929 );
3930 drop(store);
3931
3932 // StrictFailClosed must refuse the torn tail frame
3933 let strict_err = SynapseStore::open(
3934 &dir,
3935 FsyncPolicy::EveryCommit,
3936 RecoveryPolicy::StrictFailClosed,
3937 StoreLimits::default(),
3938 )
3939 .err()
3940 .expect("StrictFailClosed must refuse torn tail");
3941 assert_eq!(strict_err.code, RefusalCode::WalTornFrame);
3942
3943 // TruncateTornTail must truncate the unacknowledged torn frame, preserve seq 1, and expose zero phantom data
3944 let mut recovered = SynapseStore::open(
3945 &dir,
3946 FsyncPolicy::EveryCommit,
3947 RecoveryPolicy::TruncateTornTail,
3948 StoreLimits::default(),
3949 )
3950 .unwrap();
3951 assert_eq!(recovered.torn_frames_truncated_on_open(), 1);
3952 assert_eq!(recovered.committed_seq(), WalSeq(1));
3953 assert_eq!(
3954 recovered
3955 .get_changeset(torn_cs_id, None, None)
3956 .unwrap_err()
3957 .code,
3958 RefusalCode::ChangesetNotFound
3959 );
3960 assert_eq!(
3961 recovered
3962 .get_blob_visible(torn_blob_digest, None, None)
3963 .unwrap_err()
3964 .code,
3965 RefusalCode::BlobNotFound
3966 );
3967
3968 // Subsequent commit seq 2 after recovery must chain cleanly from seq 1!
3969 let (env2, blobs2) = make_signed_changeset(
3970 &key,
3971 "k2",
3972 "src/two.rs",
3973 b"const TWO: u32 = 2;\n",
3974 vec![],
3975 400,
3976 );
3977 let out2 = recovered.ingest_changeset(env2, &blobs2).unwrap();
3978 assert!(matches!(
3979 out2,
3980 IngestOutcome::Committed {
3981 wal_seq: WalSeq(2),
3982 ..
3983 }
3984 ));
3985
3986 let _ = fs::remove_dir_all(&dir);
3987 }
3988
3989 #[test]
3990 fn test_wal_crc_chain_and_sequence_corruption_refusals() {
3991 for (label, fault, expected_code) in [
3992 (
3993 "crc",
3994 FaultInjection::CorruptNextWalCrc,
3995 RefusalCode::WalCrcMismatch,
3996 ),
3997 (
3998 "chain",
3999 FaultInjection::CorruptNextWalChain,
4000 RefusalCode::WalChainMismatch,
4001 ),
4002 (
4003 "seq-gap",
4004 FaultInjection::InjectNextWalSequenceGap,
4005 RefusalCode::WalSequenceGap,
4006 ),
4007 (
4008 "seq-dup",
4009 FaultInjection::InjectDuplicateWalSequence,
4010 RefusalCode::WalSequenceGap,
4011 ),
4012 ] {
4013 let dir = temp_store_dir(label);
4014 let key = SigningKey::from_bytes(&[33u8; 32]);
4015 let mut store = SynapseStore::open(
4016 &dir,
4017 FsyncPolicy::EveryCommit,
4018 RecoveryPolicy::StrictFailClosed,
4019 StoreLimits::default(),
4020 )
4021 .unwrap();
4022 let (env1, blobs1) = make_signed_changeset(&key, "k1", "src/a.rs", b"a\n", vec![], 100);
4023 store.ingest_changeset(env1, &blobs1).unwrap();
4024
4025 store.set_fault_injection(fault);
4026 let (env2, blobs2) = make_signed_changeset(&key, "k2", "src/b.rs", b"b\n", vec![], 200);
4027 store.ingest_changeset(env2, &blobs2).unwrap();
4028 drop(store);
4029
4030 let err = SynapseStore::open(
4031 &dir,
4032 FsyncPolicy::EveryCommit,
4033 RecoveryPolicy::TruncateTornTail,
4034 StoreLimits::default(),
4035 )
4036 .err()
4037 .expect("corrupted WAL must fail closed");
4038 assert_eq!(err.code, expected_code, "case {label} failed");
4039 let _ = fs::remove_dir_all(&dir);
4040 }
4041 }
4042
4043 #[test]
4044 fn test_compaction_checkpoint_and_garbage_collection() {
4045 let dir = temp_store_dir("compaction-gc");
4046 let key = SigningKey::from_bytes(&[44u8; 32]);
4047 let limits = StoreLimits {
4048 default_retention_window_ms: 500,
4049 ..Default::default()
4050 };
4051
4052 let mut store = SynapseStore::open(
4053 &dir,
4054 FsyncPolicy::EveryCommit,
4055 RecoveryPolicy::StrictFailClosed,
4056 limits.clone(),
4057 )
4058 .unwrap();
4059
4060 // 1. Old speculative changeset at t=100 (unpinned, will expire at now_ms=2000)
4061 let (env_ephemeral, blobs_ephemeral) = make_signed_changeset(
4062 &key,
4063 "ephemeral",
4064 "src/speculative.rs",
4065 b"ephemeral work\n",
4066 vec![],
4067 100,
4068 );
4069 let ephemeral_blob = blobs_ephemeral[0].0;
4070 let ephemeral_id = match store
4071 .ingest_changeset(env_ephemeral, &blobs_ephemeral)
4072 .unwrap()
4073 {
4074 IngestOutcome::Committed { changeset_id, .. } => changeset_id,
4075 _ => unreachable!(),
4076 };
4077
4078 // 2. Old changeset at t=150 that IS promoted to RadicleCanonicalHead (GarbageRoot!)
4079 let (env_canon, blobs_canon) = make_signed_changeset(
4080 &key,
4081 "canon",
4082 "src/lib.rs",
4083 b"pub fn canonical() {}\n",
4084 vec![],
4085 150,
4086 );
4087 let canon_blob = blobs_canon[0].0;
4088 let canon_id = match store.ingest_changeset(env_canon, &blobs_canon).unwrap() {
4089 IngestOutcome::Committed { changeset_id, .. } => changeset_id,
4090 _ => unreachable!(),
4091 };
4092 store
4093 .record_canonical_promotion(RadicleCanonicalHead {
4094 repo_id: RepoId::new("aien-spark/synapse").unwrap(),
4095 default_branch: "main".to_string(),
4096 canonical_git_oid: GitOid::compute_blob(b"commit"),
4097 promoted_changeset_id: Some(canon_id),
4098 rad_id_commit_oid: GitOid::compute_blob(b"rad-id"),
4099 threshold: 1,
4100 verified_delegates: vec![
4101 "did:key:z6MkfZDue1TbaNFi3ZzcD9uiTeduPLC52ucdFVuLKZwexxhK".to_string(),
4102 ],
4103 verified_at_ms: 200,
4104 })
4105 .unwrap();
4106
4107 // Compact at now_ms = 2000: ephemeral (t=100) is evicted and its blob swept; canon (t=150) is retained!
4108 let report = store.checkpoint_and_compact(2000).unwrap();
4109 assert_eq!(report.evicted_changesets, 1);
4110 assert_eq!(report.retained_changesets, 1);
4111 assert_eq!(report.swept_blob_files, 1);
4112 assert!(store.get_changeset(canon_id, None, None).is_ok());
4113 assert!(store.get_blob_visible(canon_blob, None, None).is_ok());
4114 assert_eq!(
4115 store
4116 .get_changeset(ephemeral_id, None, None)
4117 .unwrap_err()
4118 .code,
4119 RefusalCode::ChangesetNotFound
4120 );
4121 assert_eq!(
4122 store
4123 .get_blob_visible(ephemeral_blob, None, None)
4124 .unwrap_err()
4125 .code,
4126 RefusalCode::BlobNotFound
4127 );
4128
4129 // Append another changeset after compaction and verify reopen replays checkpoint + new WAL frame
4130 let (env_post, blobs_post) = make_signed_changeset(
4131 &key,
4132 "post-ckpt",
4133 "src/post.rs",
4134 b"pub fn post() {}\n",
4135 vec![canon_id],
4136 2100,
4137 );
4138 let post_id = match store.ingest_changeset(env_post, &blobs_post).unwrap() {
4139 IngestOutcome::Committed { changeset_id, .. } => changeset_id,
4140 _ => unreachable!(),
4141 };
4142 let expected_seq = store.committed_seq();
4143 let expected_root = store.state_root_digest(None).unwrap();
4144 drop(store);
4145
4146 let reopened = SynapseStore::open(
4147 &dir,
4148 FsyncPolicy::EveryCommit,
4149 RecoveryPolicy::StrictFailClosed,
4150 limits,
4151 )
4152 .unwrap();
4153 assert_eq!(reopened.committed_seq(), expected_seq);
4154 assert_eq!(reopened.state_root_digest(None).unwrap(), expected_root);
4155 assert!(reopened.get_changeset(canon_id, None, None).is_ok());
4156 assert!(reopened.get_changeset(post_id, None, None).is_ok());
4157
4158 let _ = fs::remove_dir_all(&dir);
4159 }
4160
4161 #[test]
4162 fn test_subprocess_crash_recovery_no_lost_ack_and_no_phantom_visibility() {
4163 // Child subprocess entry point when invoked with SYNAPSE_CRASH_CHILD_DIR
4164 if let Ok(child_dir) = std::env::var("SYNAPSE_CRASH_CHILD_DIR") {
4165 let key = SigningKey::from_bytes(&[55u8; 32]);
4166 let mut store = SynapseStore::open(
4167 &child_dir,
4168 FsyncPolicy::EveryCommit,
4169 RecoveryPolicy::StrictFailClosed,
4170 StoreLimits::default(),
4171 )
4172 .unwrap();
4173 for i in 1..=5u64 {
4174 let (env, blobs) = make_signed_changeset(
4175 &key,
4176 &format!("child-ack-{i}"),
4177 &format!("src/f{i}.rs"),
4178 format!("pub const V{i}: u64 = {i};\n").as_bytes(),
4179 vec![],
4180 i * 100,
4181 );
4182 store.ingest_changeset(env, &blobs).unwrap();
4183 }
4184 // Start writing 6th changeset with a torn WAL header, then immediately terminate process
4185 store.set_fault_injection(FaultInjection::TornWalHeaderWrite { bytes_written: 24 });
4186 let (env6, blobs6) = make_signed_changeset(
4187 &key,
4188 "child-unacked-6",
4189 "src/f6.rs",
4190 b"unacked 6\n",
4191 vec![],
4192 600,
4193 );
4194 let _ = store.ingest_changeset(env6, &blobs6);
4195 std::process::exit(42);
4196 }
4197
4198 let dir = temp_store_dir("subprocess-crash");
4199 let exe = std::env::current_exe().expect("test binary path");
4200 let status = Command::new(exe)
4201 .arg("--exact")
4202 .arg("tests::test_subprocess_crash_recovery_no_lost_ack_and_no_phantom_visibility")
4203 .arg("--nocapture")
4204 .env("SYNAPSE_CRASH_CHILD_DIR", &dir)
4205 .status()
4206 .expect("spawn child process");
4207 assert_eq!(status.code(), Some(42));
4208
4209 // Parent process recovers the store after child process crash
4210 let recovered = SynapseStore::open(
4211 &dir,
4212 FsyncPolicy::EveryCommit,
4213 RecoveryPolicy::TruncateTornTail,
4214 StoreLimits::default(),
4215 )
4216 .unwrap();
4217 assert_eq!(recovered.committed_seq(), WalSeq(5));
4218 assert_eq!(recovered.torn_frames_truncated_on_open(), 1);
4219 let all = recovered
4220 .list_changesets(None, Some(WalSeq(5)), None)
4221 .unwrap();
4222 assert_eq!(all.len(), 5);
4223 let _ = fs::remove_dir_all(&dir);
4224 }
4225}