turndb 0.1.2

A content-addressed columnar store for AI traces: byte-exact, embedded, and readable by the CLI and the npm package over the same directory.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! Segment files: the append-only containers holding block frames.

use super::block::{self, BLOCK_HDR_LEN, BLOCK_XSUM_LEN};
use crate::readat::ReadAt;
use anyhow::{bail, Context, Result};
use std::fs::{File, OpenOptions};
use std::io::Read;
use std::path::{Path, PathBuf};

/// Segment header length. The first block begins here, so a `Loc.block_off` below it is invalid.
pub const SEG_HDR_LEN: u64 = 48;

/// Identity assertion, not a version. A mismatch refuses — there is no negotiation anywhere.
pub const MAGIC: &[u8; 8] = b"TURNFOLD";

/// Segment flag: this segment's block payloads are ENCRYPTED.
///
/// RESERVED AND REFUSED. Nothing writes it and nothing reads it — the bit is claimed so that if
/// encryption is ever built, every reader shipped before it already refuses rather than serving
/// ciphertext as content. A reject-forward lever protects only the readers that already refuse,
/// so claiming the bit early costs four bytes of documentation and buys that guarantee; the
/// refusal names encryption so an operator is not sent hunting corruption that is not there.
pub const SEG_FLAG_ENCRYPTED: u32 = 1 << 0;

/// Default roll threshold. Bounded so a crash-time tail scan stays short and mmap granularity stays sane.
pub const SEG_MAX_DEFAULT: u32 = 1 << 30;

/// Format bound. `Loc.block_off` is a `u32`, so a block start must fit in one.
pub const SEG_MAX_LIMIT: u64 = 1 << 32;

/// Block id and byte offset entries reconstructed for one segment.
pub type BlockDirectory = Vec<(u32, u32)>;

/// A sidecar's committed segment tail and its block directory.
pub type DirectorySidecar = (u32, BlockDirectory);

pub fn seg_name(n: u32) -> String {
    format!("seg-{n:08}.fold")
}

/// Parse a segment file name **numerically**. Lexicographic ordering breaks once the `%08` width is
/// exceeded, and a mis-ordered segment list corrupts recovery.
pub fn parse_seg_name(name: &str) -> Option<u32> {
    let rest = name.strip_prefix("seg-")?.strip_suffix(".fold")?;
    if rest.is_empty() || !rest.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    rest.parse::<u32>().ok()
}

/// The 48-byte segment header.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SegHeader {
    pub seg: u32,
    /// See [`SEG_FLAG_ENCRYPTED`]. Zero for a plaintext segment.
    pub flags: u32,
    /// BLAKE3 of this segment's trained dictionary, or all-zero for "no dictionary".
    pub dict_id: [u8; 32],
}

impl SegHeader {
    pub fn has_dict(&self) -> bool {
        self.dict_id != [0u8; 32]
    }

    pub fn encode(&self) -> [u8; SEG_HDR_LEN as usize] {
        let mut b = [0u8; SEG_HDR_LEN as usize];
        b[0..8].copy_from_slice(MAGIC);
        b[8..12].copy_from_slice(&self.seg.to_le_bytes());
        b[12..16].copy_from_slice(&self.flags.to_le_bytes());
        b[16..48].copy_from_slice(&self.dict_id);
        b
    }

    /// Decode + validate. `expect_seg` is the number parsed from the filename; the header must agree,
    /// which catches a renamed, copied, or cross-wired segment.
    pub fn decode(b: &[u8], expect_seg: u32) -> Result<SegHeader> {
        if b.len() < SEG_HDR_LEN as usize {
            bail!("segment header truncated: {} bytes", b.len());
        }
        if &b[0..8] != MAGIC {
            bail!("not a turndb fold segment (bad magic)");
        }
        let seg = u32::from_le_bytes(b[8..12].try_into().unwrap());
        if seg != expect_seg {
            bail!("segment header says seg {seg} but the file is named for {expect_seg}");
        }
        let flags = u32::from_le_bytes(b[12..16].try_into().unwrap());
        // The reject-forward lever: unknown means stop, not adapt. The encryption bit is named
        // in its own refusal because "this is encrypted and this build cannot read it" and
        // "unknown flags" send an operator to very different places.
        if flags & SEG_FLAG_ENCRYPTED != 0 {
            bail!(
                "segment {expect_seg} is ENCRYPTED and this build has no decryption path — \
                 refusing rather than serving ciphertext as content"
            );
        }
        if flags != 0 {
            bail!("segment flags {flags:#x} unknown — refusing (no compatibility negotiation)");
        }
        let mut dict_id = [0u8; 32];
        dict_id.copy_from_slice(&b[16..48]);
        Ok(SegHeader { seg, flags, dict_id })
    }
}

/// fsync a directory so a create/rename within it is durable.
pub fn fsync_dir(dir: &Path) -> Result<()> {
    crate::vfs::sync_dir(dir).with_context(|| format!("fsync dir {}", dir.display()))
}

/// Create segment `n` with its header durable before any frame can follow it.
///
/// `O_EXCL`: a leftover file is never appended to. Combined with fsyncing the header before returning,
/// this makes "file exists but is shorter than a header" provably hold no durable frame — which is what
/// lets recovery delete such a file safely.
pub fn create(dir: &Path, n: u32, dict_id: [u8; 32]) -> Result<File> {
    create_flagged(dir, n, dict_id, 0)
}

/// [`create`], with segment flags — how an encrypted segment announces itself.
pub fn create_flagged(dir: &Path, n: u32, dict_id: [u8; 32], flags: u32) -> Result<File> {
    let path = dir.join(seg_name(n));
    let f = crate::vfs::create_new(&path)
        .with_context(|| format!("create segment {}", path.display()))?;
    crate::vfs::write_all_at(&f, &path, &SegHeader { seg: n, flags, dict_id }.encode(), 0)?;
    crate::vfs::sync_file(&f, &path)?;
    fsync_dir(dir)?;
    Ok(f)
}

/// Read-only handle — never opens for write, so a reader cannot damage a store it does not own.
pub fn open_read(dir: &Path, n: u32) -> Result<File> {
    let path = dir.join(seg_name(n));
    File::open(&path).with_context(|| format!("open segment {} read-only", path.display()))
}

pub fn open_rw(dir: &Path, n: u32) -> Result<File> {
    let path = dir.join(seg_name(n));
    OpenOptions::new()
        .read(true)
        .write(true)
        .open(&path)
        .with_context(|| format!("open segment {}", path.display()))
}

/// Deallocate `len` bytes at `off` — the extents are freed and read back as zeros, and the file's
/// length is untouched, so every offset in it still means what it meant.
///
/// This is the one operation that destroys committed fold bytes in place. It is a Linux
/// filesystem feature (ext4, xfs, btrfs, tmpfs...); where the kernel or filesystem declines, the
/// error surfaces and the caller falls back to a re-fold, which reclaims the same space by
/// rewriting rather than by punching.
///
/// **Only a block's PAYLOAD is ever punched, never its header.** The frame chain is walked by
/// reading a header and stepping over `stored` bytes, so a punched header would end the chain and
/// silently orphan every block after it in the segment. Sixteen surviving header bytes carry no
/// content — they carry the length that keeps the chain walkable, and the `block_id` that lets a
/// scan report the erasure by name.
pub fn punch(f: &File, path: &Path, off: u64, len: u64) -> Result<()> {
    // Through the vfs seam, and `path` exists only to feed it: destroying committed bytes in
    // place is precisely the kind of mutation the crash simulator must be able to replay.
    if let Err(e) = crate::vfs::punch_hole(f, path, off, len) {
        bail!("punching {len} bytes at {off} failed ({e}) — this filesystem may not support hole punching; re-fold instead");
    }
    crate::vfs::sync_file(f, path)?;
    Ok(())
}

/// Walk the block chain to the last **complete, checksum-valid** block. Returns the offset just past
/// it plus every `(block_id, offset)` seen, which is how the block directory is rebuilt at open.
///
/// This is how the fold finds its own last good byte with no external length authority. It never
/// decompresses: read 12 bytes, hash `12 + stored`, advance. The first failure of any kind is the end
/// of good data — during a tail scan a bad frame is a boundary, not an error — except a frame the
/// manifest declares PUNCHED, which the `punched` parameter of the `_with_limits` variants lets the
/// walk step over. This convenience wrapper has no manifest in hand and passes no declaration.
pub fn scan_tail(f: &dyn ReadAt, file_len: u64, has_dict: bool) -> Result<(u64, Vec<(u32, u32)>)> {
    scan_tail_with_limits(f, file_len, has_dict, &[], crate::read_limits::ReadLimits::default())
}

/// [`scan_tail`] with explicit admission before its reusable frame buffer grows, and with the
/// manifest's declared-punched block ranges (inclusive `[lo, hi]`) — empty when the caller holds
/// no manifest.
pub fn scan_tail_with_limits(
    f: &dyn ReadAt,
    file_len: u64,
    has_dict: bool,
    punched: &[(u32, u32)],
    read_limits: crate::read_limits::ReadLimits,
) -> Result<(u64, Vec<(u32, u32)>)> {
    scan_tail_controlled_with_limits(
        f,
        file_len,
        has_dict,
        punched,
        &crate::control::OperationControl::default(),
        "fold scan",
        read_limits,
    )
}

/// [`scan_tail`] with cooperative checks between complete frames. No manifest in hand, so no
/// punched declaration reaches the walk.
pub fn scan_tail_controlled(
    f: &dyn ReadAt,
    file_len: u64,
    has_dict: bool,
    control: &crate::control::OperationControl,
    operation: &'static str,
) -> Result<(u64, Vec<(u32, u32)>)> {
    scan_tail_controlled_with_limits(
        f,
        file_len,
        has_dict,
        &[],
        control,
        operation,
        crate::read_limits::ReadLimits::default(),
    )
}

/// Controlled tail scan with explicit frame-byte and block-count admission. `punched` carries the
/// manifest's declared-erased block-id ranges so the walk can step over a punched frame whatever
/// residue a crash left in its payload.
pub fn scan_tail_controlled_with_limits(
    f: &dyn ReadAt,
    file_len: u64,
    has_dict: bool,
    punched: &[(u32, u32)],
    control: &crate::control::OperationControl,
    operation: &'static str,
    read_limits: crate::read_limits::ReadLimits,
) -> Result<(u64, Vec<(u32, u32)>)> {
    let read_limits = read_limits.validate()?;
    let mut off = SEG_HDR_LEN;
    let mut hdr = [0u8; BLOCK_HDR_LEN];
    let mut payload = Vec::new();
    // Blocks land in COMPLETION order, so position no longer implies identity — the directory is
    // rebuilt from the ids the frames carry.
    let mut dir: Vec<(u32, u32)> = Vec::new();
    loop {
        control.check(operation)?;
        if off + (block::BLOCK_OVERHEAD as u64) > file_len {
            break; // cannot hold even an empty block
        }
        if f.read_exact_at(&mut hdr, off).is_err() {
            break;
        }
        let h = match block::parse_hdr(&hdr, has_dict) {
            Ok(h) => h,
            Err(_) => break,
        };
        // Unlike checksum damage, a valid header outside runtime policy is not a crash-tail
        // boundary. Surface the typed refusal so writer recovery never truncates a valid committed
        // block merely because this process was opened with a smaller budget.
        read_limits.admit(
            format!("fold block {}", h.block_id),
            u64::from(h.stored),
            u64::from(h.raw),
        )?;
        let end =
            match off.checked_add(BLOCK_HDR_LEN as u64 + h.stored as u64 + BLOCK_XSUM_LEN as u64) {
                Some(e) => e,
                None => break,
            };
        if end > file_len {
            break; // the promised payload/checksum never fully reached disk
        }
        // verify the whole block frame's bytes
        let span = (BLOCK_HDR_LEN + h.stored as usize + BLOCK_XSUM_LEN) as usize;
        payload.resize(span, 0);
        if f.read_exact_at(&mut payload[..span], off).is_err() {
            break;
        }
        control.check(operation)?;
        if block::verify_frame_bytes(&payload[..span], has_dict).is_err() {
            // A PUNCHED block: header intact (punch never touches it — that is what keeps the
            // chain walkable), payload deallocated. The deallocation is volatile until its fsync,
            // so a crash can leave the payload in any of THREE residues: fully readable (the
            // fallocate never landed — the frame still verifies and never reaches this branch),
            // fully zeroed (it completed), or PARTIALLY zeroed (fallocate is per-extent, so power
            // loss mid-punch genuinely half-zeroes a range). The manifest's punched declaration is
            // the erasure AUTHORITY — it is committed before any byte is destroyed — so a declared
            // frame is stepped over whatever its payload holds, and its location is retained so a
            // later read reports ERASED by name instead of resolving into damage.
            //
            // The all-zero test survives beside the declaration because a historical committed
            // prefix can predate the declaration reaching this open. It is deliberately not
            // widened: an UNDECLARED checksum-failing frame with nonzero payload bytes is damage,
            // and damage still ends the walk — the skip is authorized by the declaration, never
            // guessed from the payload.
            let declared = punched.iter().any(|&(lo, hi)| (lo..=hi).contains(&h.block_id));
            let body = &payload[BLOCK_HDR_LEN..span - BLOCK_XSUM_LEN];
            if declared || (h.stored > 0 && body.iter().all(|&b| b == 0)) {
                read_limits.admit_fold_blocks(dir.len() as u64 + 1)?;
                read_limits.admit_fold_blocks(u64::from(h.block_id) + 1)?;
                dir.push((h.block_id, off as u32));
                off = end;
                continue;
            }
            break;
        }
        read_limits.admit_fold_blocks(dir.len() as u64 + 1)?;
        read_limits.admit_fold_blocks(u64::from(h.block_id) + 1)?;
        dir.push((h.block_id, off as u32));
        off = end;
    }
    Ok((off, dir))
}

/// The durable end of the fold: everything strictly before this is committed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Default)]
pub struct FoldTail {
    pub seg: u32,
    pub off: u32,
}

// ---------------------------------------------------------------------------------------------
// The directory sidecar — advisory, derived, and the answer to O(store) opens
// ---------------------------------------------------------------------------------------------

/// Sidecar magic. `seg-NNNNNNNN.dir` beside a SEALED segment carries what `scan_tail` would
/// recompute: the block ids and offsets, and the scan end.
pub const DIR_MAGIC: &[u8; 8] = b"TURNSDIR";

/// ```text
/// offset  size  field
///      0     8  MAGIC = "TURNSDIR"
///      8     4  seg          must match the filename AND the segment beside it
///     12     4  tail         scan end; for a sealed segment this IS the file length
///     16     4  n_entries
///     20   n*8  (block_id u32, offset u32) per block
///  20+n*8    4  crc32 over everything before it
/// ```
pub fn dir_path(dir: &Path, n: u32) -> PathBuf {
    dir.join(format!("seg-{n:08}.dir"))
}

/// Write the sidecar for a sealed segment. ADVISORY, so tmp + rename but no fsync anywhere: a
/// sidecar lost to a crash costs one rescan at the next open, and a torn one fails its checksum
/// and costs the same. Nothing durable depends on it.
pub fn write_dir_sidecar(dir: &Path, n: u32, tail: u32, entries: &[(u32, u32)]) -> Result<()> {
    let mut b = Vec::with_capacity(24 + entries.len() * 8);
    b.extend_from_slice(DIR_MAGIC);
    b.extend_from_slice(&n.to_le_bytes());
    b.extend_from_slice(&tail.to_le_bytes());
    b.extend_from_slice(&(entries.len() as u32).to_le_bytes());
    for (id, off) in entries {
        b.extend_from_slice(&id.to_le_bytes());
        b.extend_from_slice(&off.to_le_bytes());
    }
    let crc = crc32fast::hash(&b);
    b.extend_from_slice(&crc.to_le_bytes());
    let tmp = dir.join(format!("seg-{n:08}.dir.tmp"));
    crate::vfs::write_file(&tmp, &b)?;
    crate::vfs::rename(&tmp, &dir_path(dir, n))?;
    Ok(())
}

/// The sidecar's entries, or `None` — absent, damaged, or not describing this file's bytes. The
/// caller rescans on `None`; it must never trust a sidecar this refused.
///
/// `tail == file_len` is the staleness gate, not a nicety: recovery can truncate a once-sealed
/// segment back into being the active one, and its leftover sidecar then describes blocks past
/// the committed tail. A sealed segment ends exactly at its last block, so any length mismatch
/// means the sidecar and the segment parted ways.
pub fn read_dir_sidecar(dir: &Path, n: u32, file_len: u64) -> Option<DirectorySidecar> {
    read_dir_sidecar_with_limits(dir, n, file_len, crate::read_limits::ReadLimits::default())
        .ok()
        .flatten()
}

/// Read and parse advisory directory metadata with explicit byte and object admission.
pub fn read_dir_sidecar_with_limits(
    dir: &Path,
    n: u32,
    file_len: u64,
    read_limits: crate::read_limits::ReadLimits,
) -> Result<Option<DirectorySidecar>> {
    let Some(bytes) = read_dir_sidecar_bytes_with_limits(dir, n, file_len, read_limits)? else {
        return Ok(None);
    };
    parse_dir_sidecar_with_limits(&bytes, n, file_len, read_limits)
}

/// Largest structurally possible sidecar for a segment extent. Every indexed block consumes at
/// least one frame overhead in the segment, so advisory metadata cannot legitimately outgrow this.
pub fn max_dir_sidecar_bytes(file_len: u64) -> u64 {
    let frames = file_len.saturating_sub(SEG_HDR_LEN).div_ceil(super::block::BLOCK_OVERHEAD as u64);
    24u64.saturating_add(frames.saturating_mul(8))
}

/// Read advisory bytes only after their filesystem length fits what the segment could describe.
/// `None` is intentionally the only failure: callers rescan the authoritative segment.
pub fn read_dir_sidecar_bytes(dir: &Path, n: u32, file_len: u64) -> Option<Vec<u8>> {
    read_dir_sidecar_bytes_with_limits(dir, n, file_len, crate::read_limits::ReadLimits::default())
        .ok()
        .flatten()
}

/// Read advisory sidecar bytes after both structural and runtime byte admission.
pub fn read_dir_sidecar_bytes_with_limits(
    dir: &Path,
    n: u32,
    file_len: u64,
    read_limits: crate::read_limits::ReadLimits,
) -> Result<Option<Vec<u8>>> {
    let file = match File::open(dir_path(dir, n)) {
        Ok(file) => file,
        Err(_) => return Ok(None),
    };
    let max = max_dir_sidecar_bytes(file_len);
    let len = match file.metadata() {
        Ok(metadata) => metadata.len(),
        Err(_) => return Ok(None),
    };
    if len > max {
        return Ok(None);
    }
    read_limits.admit_stored(format!("fold segment {n} directory sidecar"), len)?;
    let capacity = match usize::try_from(len) {
        Ok(capacity) => capacity,
        Err(_) => return Ok(None),
    };
    let mut bytes = Vec::new();
    if bytes.try_reserve_exact(capacity).is_err()
        || file.take(max.saturating_add(1)).read_to_end(&mut bytes).is_err()
    {
        return Ok(None);
    }
    Ok((bytes.len() as u64 <= max).then_some(bytes))
}

/// [`read_dir_sidecar`]'s validation core, over bytes from ANY source — a directory or a pack.
pub fn parse_dir_sidecar(b: &[u8], n: u32, file_len: u64) -> Option<DirectorySidecar> {
    parse_dir_sidecar_with_limits(b, n, file_len, crate::read_limits::ReadLimits::default())
        .ok()
        .flatten()
}

/// Parse advisory directory bytes with object admission before allocating the entry vector.
pub fn parse_dir_sidecar_with_limits(
    b: &[u8],
    n: u32,
    file_len: u64,
    read_limits: crate::read_limits::ReadLimits,
) -> Result<Option<DirectorySidecar>> {
    if b.len() < 24 || &b[0..8] != DIR_MAGIC {
        return Ok(None);
    }
    let crc = u32::from_le_bytes(b[b.len() - 4..].try_into().unwrap());
    if crc32fast::hash(&b[..b.len() - 4]) != crc {
        return Ok(None);
    }
    let seg = u32::from_le_bytes(b[8..12].try_into().unwrap());
    let tail = u32::from_le_bytes(b[12..16].try_into().unwrap());
    let n_entries = u32::from_le_bytes(b[16..20].try_into().unwrap()) as usize;
    let expected_len = n_entries.checked_mul(8).and_then(|bytes| 24usize.checked_add(bytes));
    if seg != n || tail as u64 != file_len || expected_len != Some(b.len()) {
        return Ok(None);
    }
    read_limits.admit_fold_blocks(n_entries as u64)?;
    let mut entries = Vec::with_capacity(n_entries);
    for i in 0..n_entries {
        let at = 20 + i * 8;
        entries.push((
            u32::from_le_bytes(b[at..at + 4].try_into().unwrap()),
            u32::from_le_bytes(b[at + 4..at + 8].try_into().unwrap()),
        ));
    }
    Ok(Some((tail, entries)))
}

/// The full path of a segment, for callers that need it (tests, introspection).
pub fn seg_path(dir: &Path, n: u32) -> PathBuf {
    dir.join(seg_name(n))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn seg_names_parse_numerically() {
        assert_eq!(seg_name(0), "seg-00000000.fold");
        assert_eq!(parse_seg_name("seg-00000000.fold"), Some(0));
        assert_eq!(parse_seg_name("seg-00000042.fold"), Some(42));
        // past the %08 width, numeric parsing still works where lexicographic ordering would fail
        assert_eq!(parse_seg_name("seg-123456789.fold"), Some(123_456_789));
        assert_eq!(parse_seg_name("seg-.fold"), None);
        assert_eq!(parse_seg_name("seg-00x0.fold"), None);
        assert_eq!(parse_seg_name("nope.fold"), None);
    }

    #[test]
    fn header_roundtrips_and_validates() {
        let h = SegHeader { seg: 5, flags: 0, dict_id: [0u8; 32] };
        let b = h.encode();
        assert_eq!(b.len(), SEG_HDR_LEN as usize);
        assert_eq!(SegHeader::decode(&b, 5).unwrap(), h);
        assert!(!h.has_dict());

        // header/filename disagreement is caught
        assert!(SegHeader::decode(&b, 6).is_err());

        // bad magic is caught
        let mut bad = b;
        bad[0] = b'X';
        assert!(SegHeader::decode(&bad, 5).is_err());

        // Both the reserved encryption bit and any unknown bit refuse rather than negotiate.
        let mut flagged = b;
        flagged[12] = SEG_FLAG_ENCRYPTED as u8;
        assert!(SegHeader::decode(&flagged, 5).is_err(), "the reserved encryption bit must refuse");
        let mut future = b;
        future[13] = 0x04;
        assert!(SegHeader::decode(&future, 5).is_err(), "unknown flags must refuse");
    }

    #[test]
    fn advisory_sidecar_size_is_bounded_by_the_segment_it_describes() {
        let dir = std::env::temp_dir().join(format!("turndb-sidecar-limit-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file_len = SEG_HDR_LEN + crate::fold::block::BLOCK_OVERHEAD as u64;
        let max = max_dir_sidecar_bytes(file_len);
        std::fs::File::create(dir_path(&dir, 0)).unwrap().set_len(max + 1).unwrap();
        let got = read_dir_sidecar_bytes(&dir, 0, file_len);
        std::fs::remove_dir_all(dir).ok();
        assert!(got.is_none(), "an impossible sparse sidecar must be ignored before allocation");
    }
}