-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextractor.rs
More file actions
2091 lines (1952 loc) · 85.9 KB
/
Copy pathextractor.rs
File metadata and controls
2091 lines (1952 loc) · 85.9 KB
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Drive a [`StreamingDecoder`] forward, fan its output into a [`Sink`],
//! and release source blocks behind the decoder via a [`PunchHole`].
//!
//! The loop is a Rust port of `pyproto/core.py`'s `PunchingExtractor`,
//! with the §8.1 refinement that punching is gated on a *quiescent
//! checkpoint position* rather than just `bytes_consumed`. The
//! checkpoint advances only when the decoder reports a
//! [`StreamingDecoder::frame_boundary`] *and* the sink reports
//! [`Sink::is_quiescent`] in the same step. Anything we punch is
//! irrecoverable; aligning the punch limit with restart-safe positions
//! means a crash here loses at most one frame of work even before the
//! §9 checkpointing layer is in place.
//!
//! # Stats
//!
//! [`ExtractionStats`] records what the extractor saw: bytes consumed
//! from the source, bytes written to the sink, bytes successfully
//! punched, plus a coarse breakdown of where wall-clock time went
//! (decode vs. write vs. punch). Stats are reset on every
//! [`Extractor::extract`] call and represent that single extraction.
//!
//! # Source ownership
//!
//! The extractor borrows the source's file descriptor for hole punching
//! but does not read from it directly — the decoder, constructed by
//! the caller, owns the read side. The accompanying
//! `examples/extract_demo.rs` opens the source twice (one read handle
//! for the decoder, one read-write handle for punching) and passes the
//! latter's [`OsFd`] to [`Extractor::extract`]. The §10
//! coordinator follows the same shape, plumbing the fd through the
//! [`crate::download::SparseFile`] it already owns.
use std::io::Write;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use thiserror::Error;
use crate::checkpoint::SinkState;
use crate::decode::{DecodeError, DecodeStatus, StreamingDecoder};
use crate::os_fd::OsFd;
use crate::progress::ProgressState;
use crate::punch::{align_down, PunchError, PunchHole};
use crate::sink::{Sink, SinkError};
use crate::types::ByteOffset;
/// Default minimum gap, in bytes, between successive punch syscalls.
///
/// Matches the Python prototype's `_PUNCH_THRESHOLD` (4 MiB). Smaller
/// values reduce the in-flight compressed footprint at the cost of more
/// syscalls; larger values amortize the syscall over more decoded
/// bytes.
pub const DEFAULT_PUNCH_THRESHOLD: u64 = 4 * 1024 * 1024;
/// Default duration past which the §2.2 watchdog warns that a single
/// `decode_step` call took unusually long.
///
/// 30 s matches the renderer's stall threshold
/// ([`crate::progress::DEFAULT_STALL_WARN_INTERVAL`]) and the io_uring
/// backend's in-flight watchdog ([`crate::io_backend`] §2.1) so the
/// three signals compose: a freeze surfaces all of them inside the
/// same wall-clock window and the operator can correlate from log
/// alone. Override via `PEEL_DECODE_STEP_WARN_SECS`.
pub const DEFAULT_DECODE_STEP_WARN: Duration = Duration::from_secs(30);
/// Read `PEEL_DECODE_STEP_WARN_SECS` (positive integer seconds) and
/// fall back to [`DEFAULT_DECODE_STEP_WARN`]. `0` or any malformed
/// value uses the default.
fn decode_step_warn_from_env() -> Duration {
std::env::var("PEEL_DECODE_STEP_WARN_SECS")
.ok()
.and_then(|s| s.trim().parse::<u64>().ok())
.filter(|n| *n > 0)
.map(Duration::from_secs)
.unwrap_or(DEFAULT_DECODE_STEP_WARN)
}
/// §2.2 (`PLAN_decoder_freeze.md`): post-hoc watchdog that fires a
/// single `tracing::warn!` line when one `decode_step` call exceeds
/// `threshold`.
///
/// Post-hoc because we run on the same thread as the call we are
/// timing — we cannot preempt it. The point is to localise the wedge
/// after the fact: if the watchdog fires on the freeze and the
/// io_uring §2.1 watchdog also fires, the wedge is inside a
/// kernel-level op the ring is waiting on. If §2.2 fires but §2.1
/// stays silent, the wedge is somewhere `decode_step` reaches that
/// is not the IO backend (sink-side `write_all`, a CPU spin, etc.).
///
/// Rate-limited via `last_warned_at`: a sustained slow window emits
/// one entry per `threshold`-sized interval, not one per loop tick.
struct DecodeStepWatchdog {
threshold: Duration,
last_warned_at: Option<Instant>,
}
impl DecodeStepWatchdog {
fn from_env() -> Self {
Self {
threshold: decode_step_warn_from_env(),
last_warned_at: None,
}
}
/// `true` iff `elapsed` exceeds the threshold *and* the rate-limit
/// window has elapsed since the last warning. Mutates
/// `last_warned_at` to `Some(now)` on a positive return.
fn should_warn(&mut self, elapsed: Duration, now: Instant) -> bool {
if elapsed < self.threshold {
return false;
}
if let Some(prev) = self.last_warned_at {
if now.saturating_duration_since(prev) < self.threshold {
return false;
}
}
self.last_warned_at = Some(now);
true
}
}
/// Errors produced by [`Extractor::extract`].
///
/// The variants distinguish the three responsibilities the extractor
/// fans the work across: the decoder (source byte stream), the sink
/// (output destination), and the puncher (block release on the
/// source). Callers can `match` on the variant to decide what to log
/// vs. retry vs. surface as a hard failure.
#[derive(Debug, Error)]
pub enum ExtractorError {
/// The decoder rejected the source bytes.
#[error("decode failed during extraction")]
Decode(#[source] DecodeError),
/// The sink rejected a write or its terminal close check.
#[error("sink failed during extraction")]
Sink(#[source] SinkError),
/// The puncher returned an unrecoverable error.
/// `PunchError::Unsupported` is *not* surfaced as an error — it is
/// observed once and downgrades the rest of the extraction to a
/// no-op puncher silently.
#[error("hole punch failed at offset {offset} length {length}")]
Punch {
/// Offset passed to the failing punch.
offset: u64,
/// Length passed to the failing punch.
length: u64,
/// The underlying puncher error.
#[source]
source: PunchError,
},
/// Defensive: the decoder reported [`DecodeError::Write`] but the
/// adapter that wraps the sink did not capture the underlying
/// [`SinkError`]. By construction this cannot happen; surfacing it
/// as its own variant keeps the public error surface honest if a
/// future refactor breaks the invariant.
#[error("sink reported failure but the typed error was lost (internal invariant)")]
SinkErrorLost,
/// The checkpoint observer registered via
/// [`Extractor::extract_with_callback`] returned an error. The
/// underlying cause is preserved for the coordinator to surface.
#[error("checkpoint observer aborted extraction")]
Observer(#[source] std::io::Error),
}
/// Tunables for [`Extractor::extract`].
#[derive(Debug, Clone, Copy)]
pub struct ExtractorConfig {
/// Minimum gap, in bytes, between successive punch syscalls. The
/// extractor accumulates progress and only invokes the puncher
/// when the unpunched-but-checkpointed prefix is at least this
/// large.
pub punch_threshold: u64,
/// Minimum source-byte progress between successive
/// [`Extractor::extract_with_callback`] observer invocations.
///
/// The extractor measures progress against the most recently
/// persisted boundary and gates the observer call when *both*
/// this floor *and* [`Self::checkpoint_min_interval`] have not
/// been cleared. Throttled steps skip both the
/// [`StreamingDecoder::decoder_state`] call and the
/// [`CheckpointInfo`] allocation, which is load-bearing for
/// decoders whose `decoder_state()` serializes a non-trivial
/// sliding window (xz_native: ~8 MiB per call).
/// See `internal/old/PLAN_lazy_decoder_state.md`.
///
/// `0` means "no byte-progress floor" — every quiescent advance
/// fires the observer. This is the [`Self::default`] so that
/// library callers using [`Extractor::extract`] /
/// [`Extractor::with_defaults`] get the historical
/// "observer-per-advance" behavior. Production callers (the
/// [`crate::coordinator`]) explicitly set the
/// [`crate::coordinator::CoordinatorConfig::checkpoint_min_bytes`]
/// value here.
///
/// The very first persist-eligible advance always fires
/// regardless of these floors, so a clean cadence config
/// doesn't strand a run with no checkpoints.
pub checkpoint_min_bytes: u64,
/// Minimum wall-clock time between successive observer
/// invocations. Pairs with [`Self::checkpoint_min_bytes`] —
/// throttle gates a call only when *both* the byte floor *and*
/// the time floor have not been cleared.
///
/// `Duration::ZERO` (the [`Self::default`]) means "no
/// time-based floor". As with `checkpoint_min_bytes`, the very
/// first persist-eligible advance always fires.
pub checkpoint_min_interval: Duration,
}
impl Default for ExtractorConfig {
fn default() -> Self {
Self {
punch_threshold: DEFAULT_PUNCH_THRESHOLD,
checkpoint_min_bytes: 0,
checkpoint_min_interval: Duration::ZERO,
}
}
}
// `CheckpointAck` was removed in `PLAN_lazy_decoder_state.md` Phase 1.
//
// The throttle that the coordinator's observer used to apply (returning
// `CheckpointAck::Throttled` to skip a write) now lives inside the
// extractor's run loop, gated by [`ExtractorConfig::checkpoint_min_bytes`]
// and [`ExtractorConfig::checkpoint_min_interval`]. The observer's only
// signal to the extractor is now its `io::Result<()>` return: `Ok` means
// "persisted; advance hole-punching up to this position", `Err` means
// "abort the extraction with this error".
//
// The punch-bounded-by-last-persisted invariant
// (`tests::throttled_observer_does_not_advance_punch_past_persisted_position`)
// continues to hold: the extractor's throttle skips the observer call and
// does *not* update `last_persisted_quiescent_at`, so a crash between a
// throttled step and the next durable write resumes from the most recent
// observer-acknowledged position.
/// Snapshot passed to the [`Extractor::extract_with_callback`]
/// observer on every quiescent advance.
///
/// The observer is the §10 coordinator's hook for writing a checkpoint
/// at exactly the right moment: the decoder has just completed a frame
/// **and** the sink reports it is at a member boundary, so the source
/// position recorded here is a restart-safe point for resume.
///
/// The `'a` lifetime ties the borrowed `decoder` reference to the
/// extractor's run loop — observers cannot outlive a single
/// invocation, which matches the §10 coordinator's "write the
/// checkpoint synchronously, then return" shape.
/// `PLAN_checkpoint_blob_dedup.md` Phase 2.
pub struct CheckpointInfo<'a> {
/// Source byte offset immediately past the most recently completed
/// frame. Resume seeks the decoder back to this offset.
pub source_position: u64,
/// Total bytes consumed from the source by the decoder so far.
pub bytes_in: u64,
/// Total bytes the sink has accepted so far.
pub bytes_out: u64,
/// Running count of quiescent checkpoints observed in this run,
/// inclusive of this one. Useful for throttling cadence.
pub quiescent_index: u64,
/// Borrow of the live decoder so the observer can populate the
/// resume blob with one memcpy via
/// [`StreamingDecoder::decoder_state_into`]. Decoders whose
/// frame boundaries are restartable from the offset alone (the
/// historical contract; everything but lz4 / xz_native / zstd /
/// deflate_native mid-frame boundaries today) leave `out`
/// untouched and return `false`.
/// `PLAN_checkpoint_blob_dedup.md` Phase 2 replaces the prior
/// `decoder_state: Option<Vec<u8>>` field; the old field forced
/// a 4-stage clone-and-copy chain, the borrow lets the observer
/// thread the blob bytes straight into the `Checkpoint` body
/// buffer.
pub decoder: &'a dyn StreamingDecoder,
/// Live sink state captured at the same step. The coordinator
/// persists this verbatim into the checkpoint; the sink's
/// resume constructor consumes it to restart from the exact
/// position the killed run left off.
pub sink_state: SinkState,
}
/// Wall-clock and byte-volume statistics for one extraction.
///
/// The main extraction times overlap inside the decode loop only
/// inasmuch as [`Self::write_time`] is *subtracted out* of
/// [`Self::decode_time`] when the sink write happens inside
/// `decode_step`. `decode_time`, `write_time`, and `punch_time` are
/// therefore disjoint and can be summed for "useful time" without
/// double-counting. The `source_*` fields are lower-level diagnostics
/// from the coordinator's streaming reader and may overlap
/// `decode_time`.
#[derive(Debug, Default, Clone, Copy)]
pub struct ExtractionStats {
/// Total bytes the decoder reported as consumed from the source
/// when the loop ended. For a clean extraction this equals the
/// source's logical length.
pub bytes_in: u64,
/// Total bytes the sink accepted via [`Sink::write`].
pub bytes_out: u64,
/// Total bytes successfully released via [`PunchHole::punch`].
/// Zero when the puncher reported [`PunchError::Unsupported`] on
/// its first call.
pub bytes_punched: u64,
/// Number of successful [`PunchHole::punch`] calls.
pub punch_calls: u64,
/// True if the puncher reported [`PunchError::Unsupported`] at
/// least once. After that point, the extractor stops issuing
/// punches (the source's compressed footprint is held until the
/// caller deletes the file).
pub punch_unsupported: bool,
/// Number of distinct frame-boundary observations. Each transition
/// of [`StreamingDecoder::frame_boundary`] to a new value
/// increments this counter once.
pub frame_boundaries_observed: u64,
/// Number of times the checkpoint position was advanced. A
/// checkpoint advance requires both a new frame boundary *and*
/// [`Sink::is_quiescent`]; these are usually but not always
/// 1:1 with frame boundaries.
pub quiescent_checkpoints: u64,
/// Bytes the streaming source read back from the sparse part
/// file. Only coordinator-driven runs populate this; direct
/// extractor use leaves it at zero.
pub source_sparse_read_bytes: u64,
/// Wall-clock time spent in sparse-file `read_at` calls on the
/// streaming source path.
pub source_sparse_read_time: Duration,
/// Wall-clock time the streaming source spent waiting for the
/// needed chunk bitmap bit to become complete.
pub source_wait_time: Duration,
/// Number of source-read calls that had to wait for at least one
/// missing chunk.
pub source_wait_count: u64,
/// Number of poll sleeps taken by the streaming source while
/// waiting for incomplete chunks.
pub source_poll_sleeps: u64,
/// Wall-clock time spent inside [`StreamingDecoder::decode_step`],
/// minus the time the decoder spent calling the sink.
pub decode_time: Duration,
/// Wall-clock time spent inside [`Sink::write`], cumulated across
/// every call the decoder made into the wrapping adapter.
pub write_time: Duration,
/// Wall-clock time spent inside [`PunchHole::punch`].
pub punch_time: Duration,
/// Wall-clock time spent in `SparseFile::sync_all` from the
/// checkpoint observer (publication-side fsync of `.peel.part`).
/// Populated only by coordinator-driven runs;
/// [`Extractor::extract`] / [`Extractor::extract_with_callback`]
/// leave this at zero. `PLAN_checkpoint_cadence_throughput.md`
/// Phase 0.
pub ckpt_sparse_sync_time: Duration,
/// Number of `SparseFile::sync_all` calls the observer made.
pub ckpt_sparse_sync_calls: u64,
/// Wall-clock time spent constructing the [`crate::checkpoint::Checkpoint`]
/// — bitmap clone, fingerprints clone, sink-state clone, hash-state
/// snapshot, decoder-state clone, plus the binary serialize.
/// Coordinator-only.
pub ckpt_serialize_time: Duration,
/// Wall-clock time from `OpenOptions::open(.tmp)` through the
/// final `write_all` (no fsync). Coordinator-only.
pub ckpt_tmp_write_time: Duration,
/// Wall-clock time spent in `File::sync_all` on the `.tmp` file.
/// Coordinator-only.
pub ckpt_tmp_fsync_time: Duration,
/// Wall-clock time spent in `fs::rename(.tmp, ckpt)`.
/// Coordinator-only.
pub ckpt_rename_time: Duration,
/// Wall-clock time spent in `File::sync_all` on the parent
/// directory. Coordinator-only.
pub ckpt_dir_fsync_time: Duration,
/// Number of parent-directory `sync_all` calls the observer
/// made (one per checkpoint write on platforms that support it).
pub ckpt_dir_fsync_calls: u64,
/// Total wall-clock spent inside the checkpoint observer closure
/// (sum of every observer invocation, success and error). Used
/// to assert that the per-step counters above add up to the
/// observed observer time within noise.
pub ckpt_observer_time: Duration,
/// Wall-clock time spent inside
/// [`StreamingDecoder::decoder_state_into`] during
/// persist-eligible advances — the call that streams the
/// resume blob into the `Checkpoint` body buffer. After
/// `PLAN_checkpoint_blob_dedup.md` Phase 2 this call lives
/// inside the observer's `serialize` phase; the observer
/// times it separately and the merge subtracts it from
/// `ckpt_serialize_time` so the diagnostic columns stay
/// non-overlapping.
pub ckpt_decoder_state_time: Duration,
/// Number of [`StreamingDecoder::decoder_state_into`] calls.
/// Equals `quiescent_checkpoints` exactly (one per
/// persist-eligible advance).
pub ckpt_decoder_state_calls: u64,
}
/// Coordinator that ties decoder, sink, and puncher into one loop.
///
/// `Extractor` is configuration-only; create it once with
/// [`Extractor::with_defaults`] (or [`Extractor::new`] for a custom
/// [`ExtractorConfig`]) and reuse it for as many extractions as the
/// caller has work for. The state for any single extraction lives
/// entirely on the call stack of [`Self::extract`].
///
/// Optionally pairs with a [`ProgressState`] (via
/// [`Self::with_progress`]) so the per-write byte counter feeds the
/// `PLAN_v2.md` §6 progress UI.
#[derive(Clone)]
pub struct Extractor {
config: ExtractorConfig,
progress: Option<Arc<ProgressState>>,
/// Optional run-wide kill switch, polled once per `decode_step`
/// iteration of the inner loop. See [`Self::with_kill_switch`].
kill_switch: Option<Arc<AtomicBool>>,
/// Optional dynamic checkpoint byte-floor provider
/// (`PLAN_checkpoint_cadence_throughput.md` Phase 2). When set,
/// the cadence throttle calls this on each persist-eligible
/// advance and uses the returned value as the byte floor instead
/// of [`ExtractorConfig::checkpoint_min_bytes`]. The provider is
/// expected to return *at least* the configured floor — the
/// coordinator wires it up so the configured value is the lower
/// bound and the rate-aware term is the upper bound.
checkpoint_floor_provider: Option<Arc<dyn Fn() -> u64 + Send + Sync>>,
}
impl std::fmt::Debug for Extractor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Extractor")
.field("config", &self.config)
.field("progress", &self.progress.as_ref().map(|_| "ProgressState"))
.field(
"kill_switch",
&self.kill_switch.as_ref().map(|_| "AtomicBool"),
)
.field(
"checkpoint_floor_provider",
&self
.checkpoint_floor_provider
.as_ref()
.map(|_| "FloorProvider"),
)
.finish()
}
}
impl Extractor {
/// Create an extractor with the given config.
#[must_use]
pub fn new(config: ExtractorConfig) -> Self {
Self {
config,
progress: None,
kill_switch: None,
checkpoint_floor_provider: None,
}
}
/// Create an extractor with [`ExtractorConfig::default`].
#[must_use]
pub fn with_defaults() -> Self {
Self::new(ExtractorConfig::default())
}
/// Attach a [`ProgressState`] to the extractor. Every successful
/// sink write `fetch_add`s its byte length into
/// [`ProgressState::add_extracted`]; the renderer thread reads
/// from there asynchronously.
#[must_use]
pub fn with_progress(mut self, progress: Arc<ProgressState>) -> Self {
self.progress = Some(progress);
self
}
/// Attach the run-wide kill switch (`PLAN_responsiveness.md`
/// §2.3). The inner loop polls the flag once per iteration —
/// before each `decode_step` call — so a CPU-bound decoder that
/// never reads source bytes (e.g., a zstd block whose literals
/// fit entirely in the window) still notices a SIGTERM within one
/// step. Tripping returns
/// [`ExtractorError::Observer`] carrying the
/// `peel:kill-switch-tripped` sentinel; the coordinator's
/// `run_one` matcher recognizes it and surfaces
/// `CoordinatorError::Aborted`.
#[must_use]
pub fn with_kill_switch(mut self, kill: Arc<AtomicBool>) -> Self {
self.kill_switch = Some(kill);
self
}
/// Attach a dynamic byte-floor provider for the checkpoint
/// cadence throttle (`PLAN_checkpoint_cadence_throughput.md`
/// Phase 2).
///
/// On each persist-eligible advance the throttle calls
/// `provider()` and uses the returned value as the byte floor
/// instead of [`ExtractorConfig::checkpoint_min_bytes`]. The
/// coordinator uses this to scale the floor with realized
/// download throughput: at high rates the realized term raises
/// the floor so cadence is paced by the OS's ability to durably
/// publish, not by raw byte progress; at low rates the
/// configured byte floor still wins.
///
/// The contract: the provider returns *at least* the configured
/// `checkpoint_min_bytes` value (the coordinator enforces this
/// via `max(configured, rate * target_interval)`); the throttle
/// does not double-check. The time floor
/// ([`ExtractorConfig::checkpoint_min_interval`]) still bounds
/// resume granularity from above regardless of the dynamic
/// floor.
#[must_use]
pub fn with_checkpoint_floor_provider(
mut self,
provider: Arc<dyn Fn() -> u64 + Send + Sync>,
) -> Self {
self.checkpoint_floor_provider = Some(provider);
self
}
/// Borrow the configured tunables.
#[must_use]
pub fn config(&self) -> &ExtractorConfig {
&self.config
}
/// Drive `decoder` to completion, fanning its output into `sink`
/// and punching the source behind quiescent checkpoints.
///
/// `source_fd` must refer to the same file the decoder is reading
/// from and must be open with write permission (the punch syscall
/// requires it). The caller typically opens the source twice — one
/// read-only handle for the decoder and one read-write handle for
/// the puncher — and hands the read-write handle's
/// [`OsFd`] in here.
///
/// # Errors
///
/// Returns the appropriate [`ExtractorError`] variant on failure.
/// `PunchError::Unsupported` is *not* a hard failure: the first
/// such observation flips [`ExtractionStats::punch_unsupported`]
/// and the rest of the extraction proceeds without space
/// reclamation.
pub fn extract<S: Sink>(
&self,
source_fd: OsFd<'_>,
decoder: &mut dyn StreamingDecoder,
sink: S,
puncher: &dyn PunchHole,
) -> Result<ExtractionStats, ExtractorError> {
self.extract_with_callback(source_fd, decoder, sink, puncher, |_| Ok(()))
}
/// Like [`Self::extract`] but invokes `on_checkpoint` whenever the
/// extractor advances its quiescent-checkpoint position *and* the
/// configured cadence floors
/// ([`ExtractorConfig::checkpoint_min_bytes`] /
/// [`ExtractorConfig::checkpoint_min_interval`]) have been cleared.
///
/// Throttled steps skip the observer call entirely — including the
/// [`StreamingDecoder::decoder_state`] invocation that builds the
/// resume blob. This is load-bearing for decoders whose
/// `decoder_state()` is non-trivial (xz_native: ~8 MiB per call); see
/// `internal/old/PLAN_lazy_decoder_state.md` for the diagnosis.
///
/// On a successful observer return (`Ok(())`) the extractor advances
/// hole-punching up to the now-persisted position. On `Err`, the
/// extractor stops and surfaces [`ExtractorError::Observer`]; no
/// further bytes are written and no further punches issued. The
/// punch-bounded-by-last-persisted invariant is preserved:
/// throttled steps do *not* update the persisted-position cursor,
/// so a crash between a throttled step and the next observer call
/// resumes from the most recent observer-acknowledged position.
///
/// # Errors
///
/// Same as [`Self::extract`], plus [`ExtractorError::Observer`] if
/// `on_checkpoint` returns `Err`.
pub fn extract_with_callback<S, F>(
&self,
source_fd: OsFd<'_>,
decoder: &mut dyn StreamingDecoder,
mut sink: S,
puncher: &dyn PunchHole,
on_checkpoint: F,
) -> Result<ExtractionStats, ExtractorError>
where
S: Sink,
F: for<'a> FnMut(CheckpointInfo<'a>) -> std::io::Result<()>,
{
let stats = self.run_loop(source_fd, decoder, &mut sink, puncher, on_checkpoint)?;
sink.close().map_err(ExtractorError::Sink)?;
Ok(stats)
}
/// Inner loop. Borrowing `&mut sink` here (rather than moving) is
/// what lets [`Self::extract`] call `sink.close()` once the loop
/// returns and the borrow is released.
fn run_loop<S, F>(
&self,
source_fd: OsFd<'_>,
decoder: &mut dyn StreamingDecoder,
sink: &mut S,
puncher: &dyn PunchHole,
mut on_checkpoint: F,
) -> Result<ExtractionStats, ExtractorError>
where
S: Sink,
F: for<'a> FnMut(CheckpointInfo<'a>) -> std::io::Result<()>,
{
// Align to the puncher's preferred block boundary or 4 KiB,
// whichever is larger. Misaligned tails are silently retained
// by the kernel rather than treated as an error; aligning here
// keeps the punch effective without surprising the caller.
let block = puncher.block_size_hint().max(4096);
let mut stats = ExtractionStats::default();
let mut last_punched: u64 = 0;
let mut last_quiescent_at: u64 = 0;
// Highest boundary the observer has reported as durably
// persisted. Hole-punching is bounded by this — never by
// `last_quiescent_at` — so a throttled (non-persisted)
// observer call cannot orphan the bytes the still-current
// durable checkpoint references. A crash between a
// throttled write and the next persisted one resumes from
// `last_persisted_quiescent_at` with all bytes from there
// onward intact.
let mut last_persisted_quiescent_at: u64 = 0;
let mut last_observed_boundary: Option<u64> = None;
let mut punch_disabled = false;
// Throttle bookkeeping (Phase 1 of `PLAN_lazy_decoder_state.md`).
// `None` until the first persist-eligible advance — the very
// first call always fires regardless of the cadence floors so
// a clean run produces at least one durable checkpoint even
// when both floors are wide.
let mut last_persist_time: Option<Instant> = None;
let mut adapter = SinkAdapter {
sink,
bytes_out: 0,
write_time: Duration::ZERO,
captured: None,
progress: self.progress.as_deref(),
};
// §2.2 (PLAN_decoder_freeze.md): post-hoc watchdog. Reads the
// env once at loop entry; the threshold is fixed for the run.
let mut step_watchdog = DecodeStepWatchdog::from_env();
loop {
// §2.3: poll the kill switch at the top of every loop
// iteration — independent of the source-read poll, since a
// CPU-bound decoder may not read source bytes between work
// units. Tripping surfaces as `Observer` carrying the
// shared `peel:kill-switch-tripped` sentinel so the
// coordinator's `run_one` matcher maps it to `Aborted`.
if let Some(flag) = self.kill_switch.as_ref() {
if flag.load(Ordering::Acquire) {
return Err(ExtractorError::Observer(std::io::Error::other(
"peel:kill-switch-tripped",
)));
}
}
// Time the decode_step call as a whole, then subtract out
// any time the inner sink.write spent — that becomes
// stats.write_time, and the rest is decode-only time.
let pre_write = adapter.write_time;
let t_decode = Instant::now();
// §1.3: span carries the decoder's source cursor so a wedge
// here (e.g., a decoder spinning without producing) is
// visible under `RUST_LOG=peel=debug`.
let bytes_consumed = decoder.bytes_consumed().get();
// §2.2: capture the sink's bytes_out before the call so the
// watchdog can report whether the slow step *produced*
// output or merely *read* source. The two deltas, taken
// together with `write_delta`, distinguish a
// sink-blocked step from a source-blocked step.
let bytes_out_before = adapter.bytes_out;
// §2.4b: publish the entry timestamp so the renderer-side
// peer watchdog ([`crate::progress::DecodeStepStallDetector`])
// can fire even when this thread is parked inside a
// blocking syscall — the §2.2 post-hoc check below cannot
// run while the call is still in flight. The
// `mark_decode_step_exited` pair-call sits right after the
// return below; on a panic from the decoder, the renderer
// would briefly continue to see a non-zero `started_ns`,
// but the surrounding `extract_with_callback` unwinds and
// tears down the extractor before the next renderer tick.
if let Some(p) = self.progress.as_deref() {
p.mark_decode_step_entered();
}
let step = {
let span = tracing::debug_span!(
target: "peel::extractor",
"decode_step",
bytes_consumed,
bytes_out = adapter.bytes_out,
);
let _enter = span.enter();
decoder.decode_step(&mut adapter)
};
if let Some(p) = self.progress.as_deref() {
p.mark_decode_step_exited();
}
let total = t_decode.elapsed();
let write_delta = adapter.write_time.saturating_sub(pre_write);
stats.decode_time = stats
.decode_time
.saturating_add(total.saturating_sub(write_delta));
stats.write_time = stats.write_time.saturating_add(write_delta);
// §2.2 watchdog firing site. Runs *after* the call returns
// (post-hoc — we cannot preempt a step we are running on
// the same thread as). On a true wedge the call never
// returns; on a slow-but-finite call the warning surfaces
// exactly which step took the time and what it produced.
if step_watchdog.should_warn(total, Instant::now()) {
let after_consumed = decoder.bytes_consumed().get();
let consumed_delta = after_consumed.saturating_sub(bytes_consumed);
let bytes_out_delta = adapter.bytes_out.saturating_sub(bytes_out_before);
tracing::warn!(
target: "peel::extractor",
elapsed_secs = total.as_secs(),
write_time_secs = write_delta.as_secs(),
bytes_consumed = after_consumed,
consumed_delta,
bytes_out = adapter.bytes_out,
bytes_out_delta,
"decode_step took {}s (consumed +{} src bytes, wrote +{} out bytes, sink time {}s)",
total.as_secs(),
consumed_delta,
bytes_out_delta,
write_delta.as_secs(),
);
}
let status = match step {
Ok(s) => s,
Err(DecodeError::Write(_)) => {
// The decoder surfaces a write failure as an
// io::Error; the adapter captured the typed
// SinkError before returning that io::Error.
return Err(adapter
.captured
.take()
.map_or(ExtractorError::SinkErrorLost, ExtractorError::Sink));
}
Err(other) => return Err(ExtractorError::Decode(other)),
};
stats.bytes_in = decoder.bytes_consumed().get();
// Checkpoint discipline: only fire when the boundary
// *just* advanced AND the sink is quiescent in the same
// step. If we instead allowed firing on a later iteration
// (after the boundary changed), the sink might have
// already consumed bytes from frame N+1 — pairing an old
// `source_position` with a newer `bytes_out` and breaking
// resume's byte-identical guarantee.
let boundary = decoder.frame_boundary().map(ByteOffset::get);
let boundary_advanced = boundary != last_observed_boundary && boundary.is_some();
if boundary_advanced {
stats.frame_boundaries_observed = stats.frame_boundaries_observed.saturating_add(1);
last_observed_boundary = boundary;
}
if boundary_advanced {
if let Some(b) = boundary {
if adapter.sink.is_quiescent() && b > last_quiescent_at {
last_quiescent_at = b;
// Throttle gate (Phase 1 of
// `PLAN_lazy_decoder_state.md`). The gate
// sits *before* both `decoder.decoder_state()`
// and the `CheckpointInfo` allocation so a
// throttled step pays neither cost. The very
// first persist-eligible advance bypasses the
// gate (`last_persist_time == None`); after
// that, a step is throttled iff *both* the
// byte floor and the time floor are
// un-cleared.
let throttled = if let Some(prev) = last_persist_time {
let bytes_progressed = b.saturating_sub(last_persisted_quiescent_at);
let time_progressed = prev.elapsed();
// Phase 2: sample the dynamic floor when
// a provider is attached; otherwise use
// the static configured floor. The
// provider's contract is to return at
// least the configured floor, so the
// throttle never relaxes below the
// user-set lower bound.
let bytes_floor = self
.checkpoint_floor_provider
.as_ref()
.map_or(self.config.checkpoint_min_bytes, |p| p());
bytes_progressed < bytes_floor
&& time_progressed < self.config.checkpoint_min_interval
} else {
false
};
if !throttled {
stats.quiescent_checkpoints =
stats.quiescent_checkpoints.saturating_add(1);
// Drain any sink-side write buffer
// *before* snapshotting `sink_state`, so
// the `bytes_written` count published in
// the checkpoint reflects bytes that
// have actually reached the kernel. Pairs
// with `PLAN_raw_row_throughput.md` Phase
// 1's `RawSink` BufWriter: without this
// call, a kill-9 between the durable
// checkpoint write and the next natural
// buffer flush would leave the on-disk
// file shorter than the checkpoint's
// recorded length, and `RawSink::resume`
// (which `set_len`s up to the recorded
// length) would grow the file with zero
// bytes rather than truncating — a bug.
// Default impl is a no-op for sinks
// whose `write` already hits the page
// cache verbatim (every sink other than
// `RawSink`).
adapter.sink.flush_durable().map_err(ExtractorError::Sink)?;
// Phase 2 of
// `PLAN_checkpoint_blob_dedup.md`: the
// observer (the §10 coordinator) calls
// `decoder_state_into(&mut body)` directly
// through the borrowed decoder ref, so
// the resume blob bytes flow into the
// `Checkpoint` body buffer with one
// memcpy. Per-call cost is timed inside
// the observer and merged into
// `ckpt_decoder_state_time` /
// `ckpt_decoder_state_calls` via the
// observer-stats merge.
let info = CheckpointInfo {
source_position: b,
bytes_in: stats.bytes_in,
bytes_out: adapter.bytes_out,
quiescent_index: stats.quiescent_checkpoints,
decoder,
sink_state: adapter.sink.sink_state(),
};
on_checkpoint(info).map_err(ExtractorError::Observer)?;
last_persist_time = Some(Instant::now());
last_persisted_quiescent_at = b;
}
}
}
}
// Punch behind the last *persisted* boundary, aligned to
// filesystem blocks. Bounding by the persisted (rather
// than the latest-observed) position is what guarantees
// that a crash before the next persisted write resumes
// cleanly: the durable checkpoint's `decoder_position`
// always points at bytes the punch has not touched.
if !punch_disabled {
self.maybe_punch(
source_fd,
puncher,
block,
last_persisted_quiescent_at,
&mut last_punched,
&mut stats,
&mut punch_disabled,
/*final_sweep=*/ false,
)?;
}
if status == DecodeStatus::Eof {
break;
}
}
// Final sweep: release every block up to the last persisted
// checkpoint, ignoring the punch_threshold so even a small
// tail gets freed. The successful EOF path means the
// extraction is complete and no resume will be attempted, so
// bounding by `last_persisted_quiescent_at` here is purely
// defensive — but it preserves the `maybe_punch` contract
// ("never punch past a position the observer hasn't
// acknowledged as durable") in one place.
if !punch_disabled {
self.maybe_punch(
source_fd,
puncher,
block,
last_persisted_quiescent_at,
&mut last_punched,
&mut stats,
&mut punch_disabled,
/*final_sweep=*/ true,
)?;
}
stats.bytes_in = decoder.bytes_consumed().get();
stats.bytes_out = adapter.bytes_out;
Ok(stats)
}
/// Issue a punch covering `[last_punched, align_down(quiescent_at))`
/// when the gap meets the configured threshold (or unconditionally
/// during the final sweep).
#[allow(clippy::too_many_arguments)]
fn maybe_punch(
&self,
source_fd: OsFd<'_>,
puncher: &dyn PunchHole,
block: u64,
quiescent_at: u64,
last_punched: &mut u64,
stats: &mut ExtractionStats,
punch_disabled: &mut bool,
final_sweep: bool,
) -> Result<(), ExtractorError> {
// INVARIANT: `block >= 4096 > 0`, so `align_down` returns Some.
let aligned = align_down(quiescent_at, block).unwrap_or(0);
let gap = aligned.saturating_sub(*last_punched);
let should_punch = if final_sweep {
gap > 0
} else {
gap >= self.config.punch_threshold
};
if !should_punch {
return Ok(());
}
// §1.3: span around the punch syscall — slow filesystems
// (network mounts, congested NVMe) sometimes show up here.
let span = tracing::debug_span!(
target: "peel::punch",
"maybe_punch",
offset = *last_punched,
length = gap,
final_sweep,
);
let _enter = span.enter();
let t = Instant::now();
let result = puncher.punch(source_fd, ByteOffset::new(*last_punched), gap);
stats.punch_time = stats.punch_time.saturating_add(t.elapsed());
match result {
Ok(()) => {
stats.bytes_punched = stats.bytes_punched.saturating_add(gap);
stats.punch_calls = stats.punch_calls.saturating_add(1);
*last_punched = aligned;
Ok(())
}
Err(PunchError::Unsupported { .. }) => {
stats.punch_unsupported = true;
*punch_disabled = true;
Ok(())
}
Err(other) => Err(ExtractorError::Punch {
offset: *last_punched,
length: gap,
source: other,
}),
}
}
}
/// `Write` adapter that forwards into a [`Sink`], counts bytes, and
/// times the call so the extractor can split decode time from sink
/// write time. Captures the typed [`SinkError`] on failure so the
/// extractor can recover it after `decode_step` collapses it to an
/// `io::Error`.
struct SinkAdapter<'a, S: Sink> {
sink: &'a mut S,
bytes_out: u64,
write_time: Duration,
captured: Option<SinkError>,
progress: Option<&'a ProgressState>,
}
impl<S: Sink> Write for SinkAdapter<'_, S> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
// §1.3: span around the sink write — when extract progress is
// flat, this span (vs the surrounding decode_step span) shows
// whether the wedge is in the decoder or the sink.
let span = tracing::debug_span!(
target: "peel::sink",
"sink_write",
buf_len = buf.len(),
bytes_out = self.bytes_out,
);
let _enter = span.enter();
let t = Instant::now();
let result = self.sink.write(buf);
self.write_time = self.write_time.saturating_add(t.elapsed());
match result {
Ok(()) => {
// u64 can address every byte we'll ever care about; an
// `as` cast is fine because `buf.len() <= isize::MAX`.
let n = buf.len() as u64;
self.bytes_out = self.bytes_out.saturating_add(n);
if let Some(p) = self.progress {
p.add_extracted(n);
}
Ok(buf.len())