zipatch-rs 1.5.0

Parser for FFXIV ZiPatch patch files
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//! Apply-time progress checkpoints — the data the library emits while a patch
//! is being written so a consumer can persist enough state to resume a
//! crashed/interrupted apply later.
//!
//! # Shape
//!
//! Every checkpoint is a small, owned, serialisable value. The library hands
//! one to the consumer-installed [`CheckpointSink`] at each natural recovery
//! boundary the apply driver walks past:
//!
//! - **Sequential apply** ([`crate::ZiPatchReader::apply_to`]) — one
//!   [`Checkpoint::Sequential`] per top-level chunk, plus one per DEFLATE
//!   block inside the [`crate::chunk::sqpk::SqpkFile`] `AddFile` loop
//!   (the only chunk type that can carry hundreds of MB of payload). The
//!   in-flight `AddFile` state rides inside the same record so a resume can
//!   pick up the file mid-stream rather than restarting the chunk.
//! - **Indexed apply** ([`crate::index::IndexApplier`]) — one
//!   [`Checkpoint::Indexed`] per target boundary, plus an interior poll every
//!   64 regions inside a long target. Same cadence as the existing
//!   cancellation poll, so the cost of opting in is one extra struct
//!   construction per 64 regions and one [`CheckpointSink::record`] call.
//!
//! Nothing here consumes a checkpoint — the read side is part of the resume
//! work that follows. This module is the emit side only: the library writes
//! checkpoints, the consumer persists them, and a later resume entry point
//! will load the most recent one and pick up from there.
//!
//! # Sink ownership
//!
//! [`ApplyContext::with_checkpoint_sink`](crate::ApplyContext::with_checkpoint_sink)
//! installs a [`CheckpointSink`] for the sequential driver; the indexed
//! driver picks it up off the same [`crate::ApplyContext`]. The default is
//! [`NoopCheckpointSink`] — consumers that never opt in pay nothing.
//!
//! # Serde
//!
//! Every type here derives `serde::Serialize` / `serde::Deserialize` under
//! the existing `serde` feature so consumers can persist checkpoints
//! alongside the rest of the indexed-apply data model. The format on disk is
//! the consumer's choice; the crate does not pin one.
//!
//! [`ApplyContext`]: crate::ApplyContext

use std::io;
use std::path::PathBuf;

/// Persistence policy a [`CheckpointSink`] requests from the apply driver.
///
/// After a checkpoint is recorded, the apply driver inspects this value to
/// decide how aggressively to push pending writes through the operating
/// system. Cheap sinks (in-memory test capture) ask for [`Self::Flush`];
/// durability-sensitive sinks (persist-to-disk so a crash recovers cleanly)
/// ask for [`Self::Fsync`] or [`Self::FsyncEveryN`].
///
/// The driver calls [`crate::ApplyContext::sync_all`] when the policy
/// demands it, which both flushes every cached `BufWriter` and calls
/// `File::sync_all` on the underlying handle. Honouring this on every
/// record would gut throughput on patches with millions of regions — hence
/// [`Self::FsyncEveryN`] for the typical "fsync every N records" cadence
/// downstream consumers want.
///
/// **Mid-block checkpoints** — the per-DEFLATE-block emissions inside
/// [`crate::chunk::sqpk::SqpkFile`] `AddFile` — never flush and never
/// fsync regardless of policy. Those emissions fire often enough on a
/// multi-GB file that interleaving a sync syscall would gut throughput.
/// The driver guarantees the next chunk-boundary checkpoint flushes the
/// bytes the mid-block run accumulated in its `BufWriter`, so a resume
/// from an in-flight checkpoint can never miss data that a later
/// chunk-boundary checkpoint already covered.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CheckpointPolicy {
    /// Flush `BufWriter` buffers to the OS only; no `fsync`. Survives a
    /// process crash but not an OS crash or power loss between checkpoint
    /// and recovery.
    Flush,
    /// Flush and `fsync` every cached file handle on every recorded
    /// checkpoint. Strongest durability; pay the syscall cost on every
    /// record.
    Fsync,
    /// Flush every record; `fsync` once every `N` records. `N == 0` is
    /// rejected at sink-installation time
    /// ([`crate::ApplyContext::with_checkpoint_sink`] and
    /// [`crate::IndexApplier::with_checkpoint_sink`] both panic) — use
    /// [`Self::Fsync`] for "fsync every record" instead.
    ///
    /// In-flight mid-block checkpoints (the per-DEFLATE-block emissions
    /// inside [`crate::chunk::sqpk::SqpkFile`] `AddFile`) **never** fsync
    /// regardless of policy: those emissions are too frequent to interleave
    /// with a sync syscall, and the apply driver guarantees that a resume
    /// from an in-flight checkpoint can never miss data that a later
    /// chunk-boundary checkpoint already covered.
    FsyncEveryN(u32),
}

/// Sink for apply-time checkpoints — installed via
/// [`crate::ApplyContext::with_checkpoint_sink`] on the sequential driver and
/// inherited by the indexed driver.
///
/// Implement on a struct that owns whatever persistence handle the consumer
/// uses (a file, a channel, a key-value store, an in-memory `Vec` for tests).
/// A blanket impl is provided for any
/// `FnMut(&Checkpoint) -> io::Result<()>` closure for the ad-hoc case.
///
/// # Recording semantics
///
/// [`Self::record`] runs synchronously inline with the apply loop. The
/// returned `io::Result` is propagated as a [`crate::ZiPatchError::Io`]; a
/// failing sink aborts the apply at the boundary just past the chunk or
/// region that produced the checkpoint. The library does not retry. Sinks
/// should be cheap — buffering through to an `O_APPEND` write on a small
/// log file is typical; the [`Self::policy`] return then decides whether the
/// driver also issues a flush/fsync.
pub trait CheckpointSink {
    /// Persist or otherwise record `checkpoint`. Called inline with the
    /// apply loop at each emission site.
    fn record(&mut self, checkpoint: &Checkpoint) -> io::Result<()>;

    /// Policy the driver should honour after each successful [`Self::record`].
    /// Default is [`CheckpointPolicy::Flush`] — strongest available without
    /// the per-record `fsync` cost.
    fn policy(&self) -> CheckpointPolicy {
        CheckpointPolicy::Flush
    }
}

/// No-op sink used when no consumer is installed.
///
/// Public because [`ApplyContext::with_checkpoint_sink`](crate::ApplyContext::with_checkpoint_sink)
/// is generic and callers occasionally need to name the default.
#[derive(Debug, Default, Clone, Copy)]
pub struct NoopCheckpointSink;

impl CheckpointSink for NoopCheckpointSink {
    fn record(&mut self, _checkpoint: &Checkpoint) -> io::Result<()> {
        Ok(())
    }
}

impl<F> CheckpointSink for F
where
    F: FnMut(&Checkpoint) -> io::Result<()>,
{
    fn record(&mut self, checkpoint: &Checkpoint) -> io::Result<()> {
        self(checkpoint)
    }
}

/// One apply-time checkpoint, emitted at a natural recovery boundary.
///
/// Two variants, one per apply driver. The `schema_version` field on each
/// inner struct lets a future resume reader refuse to consume a checkpoint
/// from an incompatible build rather than silently misinterpret its fields.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Checkpoint {
    /// Sequential apply driver checkpoint. Emitted per top-level chunk and
    /// per DEFLATE block inside a long `SqpkFile::AddFile`.
    Sequential(SequentialCheckpoint),
    /// Indexed apply driver checkpoint. Emitted per target and every 64
    /// regions inside a long target.
    Indexed(IndexedCheckpoint),
}

/// Sequential-apply checkpoint payload.
///
/// Captures "how far into the patch stream the driver has gotten" using two
/// independent measures so a resume can pick the right one:
///
/// - `next_chunk_index` — the zero-based index of the **next** chunk the
///   driver is about to apply. Equal to the count of chunks that have been
///   fully applied.
/// - `bytes_read` — the cumulative byte offset within the patch stream the
///   driver has read up to. Equivalent to the [`crate::ChunkEvent::bytes_read`]
///   field at the same emission point.
///
/// `in_flight` is `Some` only between DEFLATE block boundaries inside an
/// `SqpkFile::AddFile`; per-chunk emissions carry `None`. Resuming a sequential
/// apply that crashed mid-AddFile picks up at `in_flight.block_idx`, seeking
/// to `in_flight.bytes_into_target` within the target file before resuming the
/// chunk's block loop.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SequentialCheckpoint {
    /// Layout version of this checkpoint struct. See [`Self::CURRENT_SCHEMA_VERSION`].
    pub schema_version: u32,
    /// Index of the next chunk to apply. Equal to the number of chunks that
    /// have been fully applied as of this checkpoint.
    pub next_chunk_index: u64,
    /// Cumulative byte offset within the patch stream the driver has read.
    ///
    /// Informational metadata. Resume is positional on `next_chunk_index`,
    /// not on this counter: the fast-forward re-parses `next_chunk_index`
    /// chunks and surfaces a `warn!` (but does not error) if the resulting
    /// `bytes_read` differs from the value recorded here.
    pub bytes_read: u64,
    /// Identifier the driver was told to associate with the patch source —
    /// typically the patch filename. `None` when no identifier was supplied
    /// via [`crate::ZiPatchReader::with_patch_name`]. Used at resume time
    /// to detect a checkpoint that was persisted for a different patch.
    pub patch_name: Option<String>,
    /// Total byte length of the patch stream, when the driver could measure
    /// it (i.e. the underlying reader is [`std::io::Seek`]). `None` for the
    /// sequential `apply_to` path which only requires
    /// [`std::io::Read`]; populated by `resume_apply_to`. Used together with
    /// `patch_name` to detect a checkpoint persisted for a patch that has
    /// since been replaced.
    ///
    /// `None` means the recording driver did not know the size (e.g.
    /// checkpoints captured via [`crate::ZiPatchReader::apply_to`] with a
    /// `Read`-only source); the resume path will not use it for stale
    /// detection in that case — the `patch_name` check alone governs.
    /// Stale-detection mismatch only fires when both the checkpoint and the
    /// resume side carry a `Some` and the two values disagree.
    pub patch_size: Option<u64>,
    /// Mid-chunk state for an in-flight [`crate::chunk::sqpk::SqpkFile`]
    /// `AddFile`. Present only at per-block emissions; `None` at per-chunk
    /// emissions.
    pub in_flight: Option<InFlightAddFile>,
}

impl SequentialCheckpoint {
    /// Current schema-version constant for [`SequentialCheckpoint`].
    pub const CURRENT_SCHEMA_VERSION: u32 = 1;

    /// Construct a [`SequentialCheckpoint`] with the given fields.
    ///
    /// Exists because the struct is `#[non_exhaustive]`, which forbids
    /// external code from using the struct-literal syntax. Consumers
    /// hand-rolling a synthetic checkpoint (typically in tests, or when
    /// migrating a persisted checkpoint from an older schema) construct
    /// one via this method instead.
    ///
    /// # Notes
    ///
    /// The constructor is intentionally permissive: it accepts any
    /// combination of fields, including pairings the apply driver itself
    /// would never emit. Resume re-validates against the patch stream and
    /// the on-disk state before honouring a checkpoint, so contradictory
    /// inputs are detected at resume time and either trigger a
    /// warn-and-restart (stale-detection paths) or surface as a typed
    /// error — never silent corruption.
    #[must_use]
    pub fn new(
        next_chunk_index: u64,
        bytes_read: u64,
        patch_name: Option<String>,
        patch_size: Option<u64>,
        in_flight: Option<InFlightAddFile>,
    ) -> Self {
        Self {
            schema_version: Self::CURRENT_SCHEMA_VERSION,
            next_chunk_index,
            bytes_read,
            patch_name,
            patch_size,
            in_flight,
        }
    }

    /// Return a clone of `self` with `in_flight` overwritten.
    ///
    /// Convenience for resume tests / persistence-layer code that needs
    /// to splice an in-flight payload into an otherwise-untouched
    /// chunk-boundary checkpoint without re-naming every field.
    ///
    /// # Notes
    ///
    /// Like [`Self::new`], this is permissive — any
    /// [`InFlightAddFile`] payload is accepted regardless of whether it
    /// pairs sensibly with the chunk index or byte offset on `self`. Resume
    /// re-validates before acting on the in-flight state, so a mismatch
    /// surfaces as a warn-and-restart rather than silent corruption.
    #[must_use]
    pub fn with_in_flight(mut self, in_flight: Option<InFlightAddFile>) -> Self {
        self.in_flight = in_flight;
        self
    }
}

/// Mid-AddFile state — the DEFLATE block boundary the driver is between.
///
/// Resume reads this back, opens `target_path`, seeks to
/// `file_offset + bytes_into_target`, and re-feeds the chunk's remaining
/// blocks starting from `block_idx`. The chunk's `path` and `file_offset`
/// are echoed in full to make the resume self-contained — callers shouldn't
/// have to cross-reference the original patch stream to interpret the
/// checkpoint.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct InFlightAddFile {
    /// Absolute filesystem path of the target file the `AddFile` writes into.
    pub target_path: PathBuf,
    /// The chunk's wire-format `file_offset` — the byte offset within the
    /// target file at which block 0 starts.
    pub file_offset: u64,
    /// Zero-based index of the **next** block to write. Equal to the count
    /// of blocks already written for this `AddFile`.
    pub block_idx: u32,
    /// Total decompressed bytes written into the target file so far for
    /// this `AddFile`. The current writer position is
    /// `file_offset + bytes_into_target`.
    pub bytes_into_target: u64,
}

impl InFlightAddFile {
    /// Construct an [`InFlightAddFile`] with the given fields.
    ///
    /// Exists because the struct is `#[non_exhaustive]`, which forbids
    /// external code from using the struct-literal syntax.
    ///
    /// # Notes
    ///
    /// Permissive by design: any combination of fields is accepted,
    /// including ones the apply driver would never produce (e.g.
    /// `block_idx = u32::MAX`, or a `bytes_into_target` that does not
    /// correspond to any real block boundary). Resume re-validates the
    /// in-flight state against the patch stream and the on-disk file
    /// before acting on it; contradictory inputs trigger a warn-and-restart
    /// path rather than silent corruption.
    #[must_use]
    pub fn new(
        target_path: PathBuf,
        file_offset: u64,
        block_idx: u32,
        bytes_into_target: u64,
    ) -> Self {
        Self {
            target_path,
            file_offset,
            block_idx,
            bytes_into_target,
        }
    }
}

/// Indexed-apply checkpoint payload.
///
/// Emitted by the [`crate::index::IndexApplier::execute`] driver at the same
/// per-target / per-64-regions cadence as the existing cancellation poll.
///
/// - `plan_crc32` — identity of the [`crate::index::Plan`] the checkpoint was
///   produced against, computed via [`crate::index::Plan::crc32`].
///   [`crate::index::IndexApplier::resume_execute`] re-computes the CRC at
///   resume time and warns-and-restarts on mismatch (same precedent as the
///   sequential resume's `patch_name` / `patch_size` check).
/// - `next_target_idx` — zero-based index of the **next** target the driver
///   will write into. Equal to the count of fully-written targets.
/// - `next_region_idx` — zero-based index of the **next** region within
///   `next_target_idx`'s timeline. Zero at the target boundary; advances by
///   64 for each mid-target poll.
/// - `bytes_written` — cumulative bytes written across all targets and
///   regions completed so far. Mirrors the same counter the indexed driver
///   carries internally.
/// - `fs_ops_done` — `true` once every [`crate::index::FilesystemOp`] in
///   [`crate::index::Plan::fs_ops`] has been applied. A resume that sees
///   this `true` skips the `fs_ops` pass; otherwise it re-runs every op
///   (each op is idempotent w.r.t. the install state the prior partial run
///   would have left behind).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct IndexedCheckpoint {
    /// Layout version of this checkpoint struct. See [`Self::CURRENT_SCHEMA_VERSION`].
    pub schema_version: u32,
    /// CRC32 of the [`crate::index::Plan`] this checkpoint was produced
    /// against. See [`crate::index::Plan::crc32`].
    ///
    /// `0` is a legitimate CRC32 output — the hash space is uniform over
    /// `u32` and a real plan can hash to zero. Consumers must represent
    /// "no checkpoint yet" via `Option<IndexedCheckpoint>` (i.e. pass
    /// `None` to [`crate::index::IndexApplier::resume_execute`]); a
    /// sentinel `plan_crc32: 0` would collide with that legitimate output
    /// and either trigger a spurious warn-and-restart against a plan that
    /// happens to hash to zero, or silently accept a stale checkpoint
    /// from a plan that does.
    pub plan_crc32: u32,
    /// `true` once every [`crate::index::FilesystemOp`] in
    /// [`crate::index::Plan::fs_ops`] has been applied.
    pub fs_ops_done: bool,
    /// Index of the next target to apply. Equal to the number of targets
    /// fully written at this checkpoint.
    pub next_target_idx: u64,
    /// Index of the next region within `next_target_idx`'s timeline.
    pub next_region_idx: u64,
    /// Cumulative bytes written across all targets and regions completed.
    pub bytes_written: u64,
}

impl IndexedCheckpoint {
    /// Current schema-version constant for [`IndexedCheckpoint`].
    ///
    /// Bumped to `2` alongside the addition of `plan_crc32` and
    /// `fs_ops_done`; a `1`-vintage persisted checkpoint will fail
    /// `check_schema_version`-style validation at resume time.
    pub const CURRENT_SCHEMA_VERSION: u32 = 2;

    /// Construct an [`IndexedCheckpoint`] with the given fields.
    ///
    /// Exists because the struct is `#[non_exhaustive]`, which forbids
    /// external code from using the struct-literal syntax. Consumers
    /// hand-rolling a synthetic checkpoint (typically in tests, or when
    /// migrating a persisted checkpoint from an older schema) construct
    /// one via this method instead.
    ///
    /// # Notes
    ///
    /// Permissive by design: any combination of fields is accepted,
    /// including pairings the indexed driver would never emit (e.g.
    /// `fs_ops_done: false` with `next_target_idx > 0`).
    /// [`crate::index::IndexApplier::resume_execute`] re-validates the
    /// checkpoint's `plan_crc32` against the plan it is handed, and
    /// re-runs every step that has not been confirmed durable; a
    /// contradictory checkpoint either matches a re-derivable resume
    /// state or triggers the warn-and-restart path on CRC mismatch.
    #[must_use]
    pub fn new(
        plan_crc32: u32,
        fs_ops_done: bool,
        next_target_idx: u64,
        next_region_idx: u64,
        bytes_written: u64,
    ) -> Self {
        Self {
            schema_version: Self::CURRENT_SCHEMA_VERSION,
            plan_crc32,
            fs_ops_done,
            next_target_idx,
            next_region_idx,
            bytes_written,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::sync::Mutex;

    // --- NoopCheckpointSink ---

    #[test]
    fn noop_sink_records_succeed_for_every_variant() {
        let mut sink = NoopCheckpointSink;
        let seq = Checkpoint::Sequential(SequentialCheckpoint {
            schema_version: SequentialCheckpoint::CURRENT_SCHEMA_VERSION,
            next_chunk_index: 3,
            bytes_read: 1024,
            patch_name: None,
            patch_size: None,
            in_flight: None,
        });
        let indexed = Checkpoint::Indexed(IndexedCheckpoint {
            schema_version: IndexedCheckpoint::CURRENT_SCHEMA_VERSION,
            plan_crc32: 0xDEAD_BEEF,
            fs_ops_done: true,
            next_target_idx: 7,
            next_region_idx: 128,
            bytes_written: 65536,
        });

        sink.record(&seq).expect("Noop must succeed");
        sink.record(&indexed).expect("Noop must succeed");
    }

    #[test]
    fn noop_sink_default_policy_is_flush() {
        let sink = NoopCheckpointSink;
        assert_eq!(sink.policy(), CheckpointPolicy::Flush);
    }

    // --- Closure blanket impl ---

    #[test]
    fn closure_sink_captures_records_in_order() {
        let captured: Arc<Mutex<Vec<Checkpoint>>> = Arc::new(Mutex::new(Vec::new()));
        let captured_clone = captured.clone();
        let mut sink = move |c: &Checkpoint| -> io::Result<()> {
            captured_clone.lock().unwrap().push(c.clone());
            Ok(())
        };

        let a = Checkpoint::Sequential(SequentialCheckpoint {
            schema_version: SequentialCheckpoint::CURRENT_SCHEMA_VERSION,
            next_chunk_index: 1,
            bytes_read: 32,
            patch_name: None,
            patch_size: None,
            in_flight: None,
        });
        let b = Checkpoint::Sequential(SequentialCheckpoint {
            schema_version: SequentialCheckpoint::CURRENT_SCHEMA_VERSION,
            next_chunk_index: 2,
            bytes_read: 64,
            patch_name: None,
            patch_size: None,
            in_flight: None,
        });

        sink.record(&a).unwrap();
        sink.record(&b).unwrap();

        let got = captured.lock().unwrap();
        assert_eq!(got.len(), 2);
        assert_eq!(got[0], a);
        assert_eq!(got[1], b);
    }

    #[test]
    fn closure_sink_propagates_io_error_unchanged() {
        let mut sink = |_: &Checkpoint| -> io::Result<()> { Err(io::Error::other("synthetic")) };
        let c = Checkpoint::Indexed(IndexedCheckpoint {
            schema_version: IndexedCheckpoint::CURRENT_SCHEMA_VERSION,
            plan_crc32: 0,
            fs_ops_done: false,
            next_target_idx: 0,
            next_region_idx: 0,
            bytes_written: 0,
        });
        let err = sink.record(&c).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::Other);
        assert_eq!(err.to_string(), "synthetic");
    }

    // --- Schema-version constants ---

    #[test]
    fn schema_version_constants_have_expected_values() {
        assert_eq!(SequentialCheckpoint::CURRENT_SCHEMA_VERSION, 1);
        assert_eq!(IndexedCheckpoint::CURRENT_SCHEMA_VERSION, 2);
    }

    // --- Serde round-trip (only meaningful under the serde feature) ---

    #[cfg(feature = "serde")]
    #[test]
    fn bincode_round_trips_sequential_checkpoint_without_in_flight() {
        let cp = Checkpoint::Sequential(SequentialCheckpoint {
            schema_version: SequentialCheckpoint::CURRENT_SCHEMA_VERSION,
            next_chunk_index: 42,
            bytes_read: 0x1_0000_0000,
            patch_name: Some("H2017.07.11.0000.0000a.patch".into()),
            patch_size: Some(0x2_0000_0000),
            in_flight: None,
        });

        let cfg = bincode::config::standard();
        let bytes = bincode::serde::encode_to_vec(&cp, cfg).unwrap();
        let (decoded, _): (Checkpoint, _) = bincode::serde::decode_from_slice(&bytes, cfg).unwrap();
        assert_eq!(cp, decoded);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn bincode_round_trips_sequential_checkpoint_with_in_flight() {
        let cp = Checkpoint::Sequential(SequentialCheckpoint {
            schema_version: SequentialCheckpoint::CURRENT_SCHEMA_VERSION,
            next_chunk_index: 9,
            bytes_read: 1_048_576,
            patch_name: Some("patch.patch".into()),
            patch_size: Some(1_048_576 * 4),
            in_flight: Some(InFlightAddFile {
                target_path: PathBuf::from("/install/sqpack/ffxiv/000000.win32.dat0"),
                file_offset: 0,
                block_idx: 17,
                bytes_into_target: 17 * 16_384,
            }),
        });

        let cfg = bincode::config::standard();
        let bytes = bincode::serde::encode_to_vec(&cp, cfg).unwrap();
        let (decoded, _): (Checkpoint, _) = bincode::serde::decode_from_slice(&bytes, cfg).unwrap();
        assert_eq!(cp, decoded);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn bincode_round_trips_indexed_checkpoint() {
        let cp = Checkpoint::Indexed(IndexedCheckpoint {
            schema_version: IndexedCheckpoint::CURRENT_SCHEMA_VERSION,
            plan_crc32: 0xA5A5_5A5A,
            fs_ops_done: true,
            next_target_idx: 12,
            next_region_idx: 64,
            bytes_written: 12345,
        });

        let cfg = bincode::config::standard();
        let bytes = bincode::serde::encode_to_vec(&cp, cfg).unwrap();
        let (decoded, _): (Checkpoint, _) = bincode::serde::decode_from_slice(&bytes, cfg).unwrap();
        assert_eq!(cp, decoded);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn bincode_round_trips_checkpoint_policy_variants() {
        for policy in [
            CheckpointPolicy::Flush,
            CheckpointPolicy::Fsync,
            CheckpointPolicy::FsyncEveryN(64),
            CheckpointPolicy::FsyncEveryN(1),
        ] {
            let cfg = bincode::config::standard();
            let bytes = bincode::serde::encode_to_vec(&policy, cfg).unwrap();
            let (decoded, _): (CheckpointPolicy, _) =
                bincode::serde::decode_from_slice(&bytes, cfg).unwrap();
            assert_eq!(policy, decoded);
        }
    }
}