Skip to main content

scientific_workflow/persistence/local/
stored_state_series_reader.rs

1//! All-in-one reconstruction of persisted streams into `StateSeries`.
2//!
3//! [`StoredStateSeriesReader`] is the complete public read boundary. It owns a recording
4//! directory, one validated snapshot of its sole `metadata.json`, and a
5//! caller-configured [`JsonPayloadDecoderRegistry`] registry. [`StoredStateSeriesReader::read_stream_as_state_series`] verifies a
6//! selected stream's immutable chunks, dispatches each raw payload to the
7//! decoder registered for its key, assembles complete `SystemState` values, and
8//! returns one fully validated `StateSeries`.
9//!
10//! # Transactional result
11//!
12//! A read returns either the complete series or one [`PersistenceError`]. States
13//! accumulated before a later checksum, record, decoder, or series failure are
14//! dropped internally and never exposed as a partial success.
15//!
16//! # Memory behavior
17//!
18//! Chunk files are processed one buffered line at a time. Record structure is
19//! deserialized with borrowed `serde_json::value::RawValue` field slices, so a
20//! payload decoder reads directly from the line buffer into its final concrete
21//! allocation. The reader does not construct an intermediate JSON value tree
22//! for tensor elements and does not retain encoded chunk bytes after a record
23//! has been reconstructed.
24//!
25//! The requested result is intentionally eager: `StateSeries` owns every
26//! reconstructed state. A future out-of-core method may be added on this same
27//! reader without exposing the private raw-record machinery.
28
29use std::fmt;
30use std::fs;
31use std::io::{BufRead, BufReader, Read};
32use std::path::{Path, PathBuf};
33
34use serde::de::{SeqAccess, Visitor};
35use serde::{Deserialize, Deserializer};
36use serde_json::value::RawValue;
37use sha2::{Digest, Sha256};
38
39use crate::state::{StateSeries, StateTime, SystemState, SystemStateSchema, schema_from_fields};
40
41use super::RecordingTiming;
42use super::error::PersistenceError;
43use super::json_payload_decoder::JsonPayloadDecoderRegistry;
44use super::jsonl_format::{ChunkMetadata, RecordingMetadata, RecordingStatus, StateStreamMetadata};
45
46/// Name of the only metadata document in one recording directory.
47const METADATA_FILE: &str = "metadata.json";
48
49/// Reader that reconstructs complete in-memory series from one completed recording.
50///
51/// Construction consumes the decoder registry so decoder configuration and
52/// metadata remain one coherent read authority. The type is intentionally
53/// non-Clone because registered decoders may not have meaningful clone
54/// semantics.
55pub struct StoredStateSeriesReader {
56    artifacts: Option<crate::artifact::ArtifactSet>,
57    root: PathBuf,
58    metadata_path: PathBuf,
59    metadata: RecordingMetadata,
60    timing: RecordingTiming,
61    decoders: JsonPayloadDecoderRegistry,
62}
63
64impl StoredStateSeriesReader {
65    /// Opens one recording directory and validates its authoritative metadata.
66    ///
67    /// The metadata snapshot must declare successful completion. Reading an
68    /// active or failed recording is deliberately rejected because its chunk
69    /// inventory is not a complete analysis result.
70    ///
71    /// Decoder coverage is checked per selected stream by
72    /// [`StoredStateSeriesReader::read_stream_as_state_series`], allowing one registry to serve only the streams
73    /// an analysis intends to load.
74    ///
75    /// # Errors
76    ///
77    /// Returns [`PersistenceError::Io`] when `metadata.json` cannot be read,
78    /// [`PersistenceError::Json`] when it is not syntactically valid JSON, semantic
79    /// metadata errors from internal `RecordingMetadata::validate`, or
80    /// [`PersistenceError::RecordingNotComplete`] unless status is complete.
81    pub fn open_completed_recording(
82        root: &Path,
83        decoders: JsonPayloadDecoderRegistry,
84    ) -> Result<Self, PersistenceError> {
85        let root = root.to_path_buf();
86        let metadata_path = root.join(METADATA_FILE);
87        let bytes = fs::read(&metadata_path).map_err(|source| PersistenceError::Io {
88            operation: "read metadata",
89            path: metadata_path.clone(),
90            source,
91        })?;
92        let metadata: RecordingMetadata =
93            serde_json::from_slice(&bytes).map_err(|source| PersistenceError::Json {
94                operation: "parse metadata",
95                path: metadata_path.clone(),
96                source,
97            })?;
98        metadata.validate(&metadata_path)?;
99        if !matches!(metadata.status, RecordingStatus::Complete) {
100            return Err(PersistenceError::RecordingNotComplete {
101                path: metadata_path,
102            });
103        }
104        let timing = RecordingTiming::from_stored(&metadata.timing, &metadata_path)?;
105        Ok(Self {
106            artifacts: None,
107            root,
108            metadata_path,
109            metadata,
110            timing,
111            decoders,
112        })
113    }
114
115    /// Opens a recording directly through verified artifacts without a local copy.
116    pub fn from_artifacts(
117        artifacts: crate::artifact::ArtifactSet,
118        decoders: JsonPayloadDecoderRegistry,
119    ) -> Result<Self, PersistenceError> {
120        let root = PathBuf::from(artifacts.prefix());
121        let metadata_path = root.join(METADATA_FILE);
122        let input = artifacts
123            .reader(METADATA_FILE)
124            .map_err(|source| PersistenceError::Io {
125                operation: "open artifact metadata",
126                path: metadata_path.clone(),
127                source,
128            })?;
129        let metadata: RecordingMetadata =
130            serde_json::from_reader(input).map_err(|source| PersistenceError::Json {
131                operation: "parse artifact metadata",
132                path: metadata_path.clone(),
133                source,
134            })?;
135        metadata.validate(&metadata_path)?;
136        if !matches!(metadata.status, RecordingStatus::Complete) {
137            return Err(PersistenceError::RecordingNotComplete {
138                path: metadata_path,
139            });
140        }
141        let timing = RecordingTiming::from_stored(&metadata.timing, &metadata_path)?;
142        Ok(Self {
143            artifacts: Some(artifacts),
144            root,
145            metadata_path,
146            metadata,
147            timing,
148            decoders,
149        })
150    }
151    /// Returns a local recording path, or None for an artifact-backed reader.
152    pub fn recording_directory(&self) -> Option<&Path> {
153        self.artifacts.is_none().then_some(self.root.as_path())
154    }
155
156    /// Iterates declared stream names in deterministic metadata order.
157    pub fn stream_names(&self) -> impl ExactSizeIterator<Item = &str> {
158        self.metadata
159            .streams
160            .iter()
161            .map(|stream| stream.name.as_str())
162    }
163
164    /// Returns the validated persistence format version.
165    pub fn format_version(&self) -> u32 {
166        self.metadata.version
167    }
168
169    /// Borrows immutable metadata supplied when recording began.
170    pub fn user_metadata(&self) -> &serde_json::Map<String, serde_json::Value> {
171        &self.metadata.user_metadata
172    }
173
174    /// Borrows values committed only at successful completion.
175    pub fn terminal_metadata(&self) -> &serde_json::Map<String, serde_json::Value> {
176        &self.metadata.terminal_metadata
177    }
178
179    /// Borrows automatic operational timing for the completed recording.
180    pub fn recording_timing(&self) -> &RecordingTiming {
181        &self.timing
182    }
183
184    /// Returns the metadata-declared record count for one completed stream.
185    pub fn stream_record_count(&self, stream: &str) -> Result<u64, PersistenceError> {
186        let declaration =
187            self.metadata
188                .stream(stream)
189                .ok_or_else(|| PersistenceError::UnknownStateStream {
190                    stream: stream.to_owned(),
191                })?;
192        declaration
193            .chunks
194            .iter()
195            .try_fold(0_u64, |total, chunk| total.checked_add(chunk.records))
196            .ok_or_else(|| PersistenceError::ByteCountOverflow {
197                stream: declaration.name.clone(),
198            })
199    }
200
201    /// Returns the exact metadata-declared encoded bytes for one stream.
202    pub fn stream_encoded_bytes(&self, stream: &str) -> Result<u64, PersistenceError> {
203        let declaration =
204            self.metadata
205                .stream(stream)
206                .ok_or_else(|| PersistenceError::UnknownStateStream {
207                    stream: stream.to_owned(),
208                })?;
209        declaration
210            .chunks
211            .iter()
212            .try_fold(0_u64, |total, chunk| total.checked_add(chunk.bytes))
213            .ok_or_else(|| PersistenceError::ByteCountOverflow {
214                stream: declaration.name.clone(),
215            })
216    }
217
218    /// Reconstructs one named logical stream as a complete `StateSeries`.
219    ///
220    /// The method validates decoder coverage before opening chunk files. It
221    /// then checks every chunk's filesystem length, processes its complete
222    /// JSONL records in order, verifies descriptor record/index facts and
223    /// SHA-256, and appends only fully decoded states to the private series.
224    ///
225    /// # Errors
226    ///
227    /// Returns precise stream-selection, decoder, filesystem, integrity,
228    /// record, payload-conversion, or series-invariant errors. No partially
229    /// reconstructed series is returned on failure.
230    pub fn read_stream_as_state_series(
231        &self,
232        stream: &str,
233    ) -> Result<StateSeries, PersistenceError> {
234        let declaration =
235            self.metadata
236                .stream(stream)
237                .ok_or_else(|| PersistenceError::UnknownStateStream {
238                    stream: stream.to_owned(),
239                })?;
240        self.decoders
241            .require(declaration.fields.iter().map(|field| field.name.as_str()))?;
242
243        let spec = stream_spec(&self.metadata_path, declaration)?;
244        let total_records = self.stream_record_count(stream)?;
245        let capacity =
246            usize::try_from(total_records).map_err(|_| PersistenceError::ByteCountOverflow {
247                stream: declaration.name.clone(),
248            })?;
249        let mut series = StateSeries::with_capacity(spec, capacity);
250        let mut previous_iteration = None;
251
252        for chunk in &declaration.chunks {
253            self.read_chunk(declaration, chunk, &mut previous_iteration, &mut series)?;
254        }
255        Ok(series)
256    }
257
258    /// Reconstructs every declared stream in metadata order.
259    ///
260    /// Distinct stream schemas and sampling intervals remain distinct series. If any
261    /// stream fails, already reconstructed series are dropped and no partial
262    /// vector is returned.
263    pub fn read_all_streams_as_state_series(
264        &self,
265    ) -> Result<Vec<(String, StateSeries)>, PersistenceError> {
266        self.metadata
267            .streams
268            .iter()
269            .map(|stream| {
270                self.read_stream_as_state_series(&stream.name)
271                    .map(|series| (stream.name.clone(), series))
272            })
273            .collect()
274    }
275
276    /// Reconstructs only the latest state in one completed stream.
277    ///
278    /// Earlier chunks are not opened. The newest chunk's length, checksum,
279    /// framing, record count, positional widths, iteration order, and declared
280    /// first/final iterations are verified before its final record is decoded
281    /// into the stream's partial schema. This is suitable for final-value
282    /// analysis; the returned partial state is not an append/resume handle.
283    pub fn read_latest_state_from_stream(
284        &self,
285        stream: &str,
286    ) -> Result<SystemState, PersistenceError> {
287        let declaration =
288            self.metadata
289                .stream(stream)
290                .ok_or_else(|| PersistenceError::UnknownStateStream {
291                    stream: stream.to_owned(),
292                })?;
293        self.decoders
294            .require(declaration.fields.iter().map(|field| field.name.as_str()))?;
295        let chunk = declaration
296            .chunks
297            .last()
298            .ok_or_else(|| PersistenceError::NoRecordedState {
299                stream: declaration.name.clone(),
300            })?;
301        let path = self.root.join(&declaration.directory).join(&chunk.file);
302        let bytes = if let Some(artifacts) = &self.artifacts {
303            let relative = format!("{}/{}", declaration.directory, chunk.file);
304            let mut bytes = Vec::new();
305            artifacts
306                .reader(&relative)
307                .and_then(|r| {
308                    r.take(chunk.bytes.saturating_add(1))
309                        .read_to_end(&mut bytes)
310                })
311                .map_err(|source| PersistenceError::Io {
312                    operation: "read artifact chunk",
313                    path: path.clone(),
314                    source,
315                })?;
316            if bytes.len() as u64 != chunk.bytes {
317                return Err(PersistenceError::ChunkSizeMismatch {
318                    path: path.clone(),
319                    expected: chunk.bytes,
320                    actual: bytes.len() as u64,
321                });
322            }
323            verify_checksum(
324                &self.metadata_path,
325                &path,
326                &chunk.checksum,
327                Sha256::digest(&bytes),
328            )?;
329            bytes
330        } else {
331            read_verified_chunk(&self.metadata_path, &path, chunk)?
332        };
333        let record =
334            verified_final_jsonl_record(&self.metadata_path, &path, declaration, chunk, &bytes)?;
335        let spec = stream_spec(&self.metadata_path, declaration)?;
336        let state =
337            decode_state_record_with_decoders(record, &path, declaration, &spec, &self.decoders)?;
338        if state.time().iteration() != chunk.last_iteration {
339            return Err(invalid_record(
340                &path,
341                chunk.records,
342                format!(
343                    "latest record iteration {} differs from chunk descriptor {}",
344                    state.time().iteration(),
345                    chunk.last_iteration
346                ),
347            ));
348        }
349        Ok(state)
350    }
351
352    /// Verifies and reconstructs one immutable committed chunk.
353    fn read_chunk(
354        &self,
355        stream: &StateStreamMetadata,
356        chunk: &ChunkMetadata,
357        previous_iteration: &mut Option<u64>,
358        series: &mut StateSeries,
359    ) -> Result<(), PersistenceError> {
360        let path = self.root.join(&stream.directory).join(&chunk.file);
361        let relative = format!("{}/{}", stream.directory, chunk.file);
362        let file = if let Some(artifacts) = &self.artifacts {
363            let reference =
364                artifacts
365                    .reference(&relative)
366                    .map_err(|source| PersistenceError::Io {
367                        operation: "inspect artifact chunk",
368                        path: path.clone(),
369                        source,
370                    })?;
371            if reference.bytes != chunk.bytes {
372                return Err(PersistenceError::ChunkSizeMismatch {
373                    path: path.clone(),
374                    expected: chunk.bytes,
375                    actual: reference.bytes,
376                });
377            }
378            artifacts.reader(&relative)
379        } else {
380            verify_file_size(&path, chunk.bytes)?;
381            crate::workspace::open_file(&path)
382        }
383        .map_err(|source| {
384            if source.kind() == std::io::ErrorKind::NotFound {
385                PersistenceError::MissingChunk { path: path.clone() }
386            } else {
387                PersistenceError::Io {
388                    operation: "open chunk",
389                    path: path.clone(),
390                    source,
391                }
392            }
393        })?;
394        let mut input = BufReader::new(file);
395        let mut line = Vec::new();
396        let mut line_number = 0_u64;
397        let mut records = 0_u64;
398        let mut first_iteration = None;
399        let mut last_iteration = None;
400        let mut hasher = Sha256::new();
401
402        loop {
403            line.clear();
404            let bytes_read =
405                input
406                    .read_until(b'\n', &mut line)
407                    .map_err(|source| PersistenceError::Io {
408                        operation: "read chunk",
409                        path: path.clone(),
410                        source,
411                    })?;
412            if bytes_read == 0 {
413                break;
414            }
415            line_number =
416                line_number
417                    .checked_add(1)
418                    .ok_or_else(|| PersistenceError::ByteCountOverflow {
419                        stream: stream.name.clone(),
420                    })?;
421            hasher.update(&line);
422            if line.last() != Some(&b'\n') {
423                return Err(invalid_record(
424                    &path,
425                    line_number,
426                    "record is not terminated by a newline",
427                ));
428            }
429            line.pop();
430            if line.is_empty() {
431                return Err(invalid_record(
432                    &path,
433                    line_number,
434                    "record line must not be empty",
435                ));
436            }
437
438            let record: BorrowedRecord<'_> = serde_json::from_slice(&line).map_err(|source| {
439                invalid_record(&path, line_number, format!("invalid JSON record: {source}"))
440            })?;
441            validate_iteration(&path, line_number, record.iteration, *previous_iteration)?;
442            let iteration = record.iteration;
443            first_iteration.get_or_insert(iteration);
444            last_iteration = Some(iteration);
445            *previous_iteration = Some(iteration);
446
447            let time = match record.physical_time {
448                Some(physical_time) => {
449                    StateTime::from_iteration_and_physical_time(iteration, physical_time)
450                        .ok_or_else(|| {
451                            invalid_record(&path, line_number, "physical time must be finite")
452                        })?
453                }
454                None => StateTime::from_iteration(iteration),
455            };
456            let mut state = series.schema().create_empty_state(time);
457            decode_values(
458                &self.decoders,
459                stream,
460                &path,
461                line_number,
462                record.values,
463                &mut state,
464            )?;
465            series.push_state(state).map_err(|rejection| {
466                let (source, state) = rejection.into_parts();
467                let index = state.time().iteration();
468                drop(state);
469                PersistenceError::StateSeriesInvariant {
470                    stream: stream.name.clone(),
471                    iteration: index,
472                    source,
473                }
474            })?;
475            records =
476                records
477                    .checked_add(1)
478                    .ok_or_else(|| PersistenceError::ByteCountOverflow {
479                        stream: stream.name.clone(),
480                    })?;
481        }
482
483        validate_chunk_facts(
484            &self.metadata_path,
485            stream,
486            chunk,
487            records,
488            first_iteration,
489            last_iteration,
490        )?;
491        verify_checksum(
492            &self.metadata_path,
493            &path,
494            &chunk.checksum,
495            hasher.finalize(),
496        )
497    }
498}
499
500/// Verifies one complete latest chunk while retaining only its final record.
501fn verified_final_jsonl_record<'a>(
502    metadata_path: &Path,
503    path: &Path,
504    stream: &StateStreamMetadata,
505    chunk: &ChunkMetadata,
506    bytes: &'a [u8],
507) -> Result<&'a [u8], PersistenceError> {
508    let mut records = 0_u64;
509    let mut first_iteration = None;
510    let mut last_iteration = None;
511    let mut previous_iteration = None;
512    let mut final_record = None;
513
514    for framed in bytes.split_inclusive(|byte| *byte == b'\n') {
515        records = records
516            .checked_add(1)
517            .ok_or_else(|| PersistenceError::ByteCountOverflow {
518                stream: stream.name.clone(),
519            })?;
520        if !framed.ends_with(b"\n") {
521            return Err(invalid_record(
522                path,
523                records,
524                "record is not terminated by a newline",
525            ));
526        }
527        let record_bytes = &framed[..framed.len() - 1];
528        if record_bytes.is_empty() {
529            return Err(invalid_record(
530                path,
531                records,
532                "record line must not be empty",
533            ));
534        }
535        let record: BorrowedRecord<'_> =
536            serde_json::from_slice(record_bytes).map_err(|source| {
537                invalid_record(path, records, format!("invalid JSON record: {source}"))
538            })?;
539        if record.values.entries.len() != stream.fields.len() {
540            return Err(invalid_record(
541                path,
542                records,
543                format!(
544                    "record contains {} payload values but stream `{}` declares {} fields",
545                    record.values.entries.len(),
546                    stream.name,
547                    stream.fields.len()
548                ),
549            ));
550        }
551        if record.physical_time.is_some_and(|time| !time.is_finite()) {
552            return Err(invalid_record(
553                path,
554                records,
555                "physical time must be finite",
556            ));
557        }
558        validate_iteration(path, records, record.iteration, previous_iteration)?;
559        first_iteration.get_or_insert(record.iteration);
560        last_iteration = Some(record.iteration);
561        previous_iteration = Some(record.iteration);
562        final_record = Some(record_bytes);
563    }
564
565    validate_chunk_facts(
566        metadata_path,
567        stream,
568        chunk,
569        records,
570        first_iteration,
571        last_iteration,
572    )?;
573    final_record.ok_or_else(|| invalid_record(path, 1, "latest chunk contains no record"))
574}
575
576impl fmt::Debug for StoredStateSeriesReader {
577    /// Formats bounded configuration without decoder internals or payloads.
578    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
579        formatter
580            .debug_struct("StoredStateSeriesReader")
581            .field("root", &self.root)
582            .field("streams", &self.metadata.streams.len())
583            .field("decoders", &self.decoders)
584            .finish_non_exhaustive()
585    }
586}
587
588/// Parses one record and dispatches each raw field into its owned final type.
589fn decode_state_record_with_decoders(
590    record: &[u8],
591    path: &Path,
592    stream: &StateStreamMetadata,
593    full_spec: &SystemStateSchema,
594    decoders: &JsonPayloadDecoderRegistry,
595) -> Result<SystemState, PersistenceError> {
596    let record: BorrowedRecord<'_> = serde_json::from_slice(record)
597        .map_err(|source| invalid_record(path, 1, format!("invalid JSON record: {source}")))?;
598    let time = match record.physical_time {
599        Some(physical_time) => {
600            StateTime::from_iteration_and_physical_time(record.iteration, physical_time)
601                .ok_or_else(|| invalid_record(path, 1, "physical time must be finite"))?
602        }
603        None => StateTime::from_iteration(record.iteration),
604    };
605    let mut state = full_spec.create_empty_state(time);
606    decode_values(decoders, stream, path, 1, record.values, &mut state)?;
607    Ok(state)
608}
609
610/// Borrowed JSONL record whose payload values point into one line buffer.
611#[derive(Deserialize)]
612#[serde(deny_unknown_fields)]
613struct BorrowedRecord<'a> {
614    iteration: u64,
615    #[serde(default)]
616    physical_time: Option<f64>,
617    #[serde(borrow)]
618    values: BorrowedValues<'a>,
619}
620
621/// Positional field collection backed by borrowed raw JSON slices.
622struct BorrowedValues<'a> {
623    entries: Vec<&'a RawValue>,
624}
625
626impl<'de: 'a, 'a> Deserialize<'de> for BorrowedValues<'a> {
627    /// Retains each positional raw value boundary without decoding its payload.
628    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
629    where
630        D: Deserializer<'de>,
631    {
632        deserializer.deserialize_seq(BorrowedValuesVisitor {
633            output: std::marker::PhantomData,
634        })
635    }
636}
637
638/// Serde visitor for one record's positional `values` array.
639struct BorrowedValuesVisitor<'a> {
640    /// Selects the shorter lifetime exposed by the containing record.
641    output: std::marker::PhantomData<&'a RawValue>,
642}
643
644impl<'de: 'a, 'a> Visitor<'de> for BorrowedValuesVisitor<'a> {
645    type Value = BorrowedValues<'a>;
646
647    /// Describes the required JSON representation.
648    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
649        formatter.write_str("an array of raw JSON payload values")
650    }
651
652    /// Collects each potentially large value as a borrow into the input line.
653    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
654    where
655        A: SeqAccess<'de>,
656    {
657        let mut entries = Vec::with_capacity(sequence.size_hint().unwrap_or(0));
658        while let Some(value) = sequence.next_element::<&'de RawValue>()? {
659            let value: &'a RawValue = value;
660            entries.push(value);
661        }
662        Ok(BorrowedValues { entries })
663    }
664}
665
666/// Reconstructs one stream's immutable key/description specification.
667fn stream_spec(
668    metadata_path: &Path,
669    stream: &StateStreamMetadata,
670) -> Result<SystemStateSchema, PersistenceError> {
671    schema_from_fields(
672        metadata_path,
673        stream
674            .fields
675            .iter()
676            .map(|field| (field.name.as_str(), field.description.as_deref())),
677    )
678    .map_err(|source| PersistenceError::InvalidMetadata {
679        path: metadata_path.to_path_buf(),
680        reason: format!(
681            "stream `{}` has an invalid state schema: {source}",
682            stream.name
683        ),
684    })
685}
686
687/// Verifies filesystem length before allocating decoded payloads.
688fn verify_file_size(path: &Path, expected: u64) -> Result<(), PersistenceError> {
689    let actual = match crate::workspace::file_size(path) {
690        Ok(bytes) => bytes,
691        Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
692            return Err(PersistenceError::MissingChunk {
693                path: path.to_path_buf(),
694            });
695        }
696        Err(source) => {
697            return Err(PersistenceError::Io {
698                operation: "inspect chunk",
699                path: path.to_path_buf(),
700                source,
701            });
702        }
703    };
704    if actual != expected {
705        return Err(PersistenceError::ChunkSizeMismatch {
706            path: path.to_path_buf(),
707            expected,
708            actual,
709        });
710    }
711    Ok(())
712}
713
714/// Reads one immutable chunk only after enforcing its authoritative descriptor.
715pub(crate) fn read_verified_chunk(
716    metadata_path: &Path,
717    path: &Path,
718    chunk: &ChunkMetadata,
719) -> Result<Vec<u8>, PersistenceError> {
720    verify_file_size(path, chunk.bytes)?;
721    let bytes = crate::workspace::open_file(path)
722        .and_then(|r| {
723            let mut bytes = Vec::new();
724            r.take(chunk.bytes.saturating_add(1))
725                .read_to_end(&mut bytes)?;
726            Ok(bytes)
727        })
728        .map_err(|source| {
729            if source.kind() == std::io::ErrorKind::NotFound {
730                PersistenceError::MissingChunk {
731                    path: path.to_path_buf(),
732                }
733            } else {
734                PersistenceError::Io {
735                    operation: "read verified chunk",
736                    path: path.to_path_buf(),
737                    source,
738                }
739            }
740        })?;
741    verify_checksum(metadata_path, path, &chunk.checksum, Sha256::digest(&bytes))?;
742    Ok(bytes)
743}
744
745/// Enforces strict iteration order across chunk boundaries.
746fn validate_iteration(
747    path: &Path,
748    line: u64,
749    iteration: u64,
750    previous: Option<u64>,
751) -> Result<(), PersistenceError> {
752    if let Some(previous) = previous
753        && iteration <= previous
754    {
755        return Err(invalid_record(
756            path,
757            line,
758            format!("iteration {iteration} is not greater than previous iteration {previous}"),
759        ));
760    }
761    Ok(())
762}
763
764/// Validates positional width, dispatches canonical decoders, and fills one state.
765fn decode_values(
766    decoders: &JsonPayloadDecoderRegistry,
767    stream: &StateStreamMetadata,
768    path: &Path,
769    line: u64,
770    values: BorrowedValues<'_>,
771    state: &mut crate::state::SystemState,
772) -> Result<(), PersistenceError> {
773    if values.entries.len() != stream.fields.len() {
774        return Err(invalid_record(
775            path,
776            line,
777            format!(
778                "record contains {} payload values but stream `{}` declares {} fields",
779                values.entries.len(),
780                stream.name,
781                stream.fields.len()
782            ),
783        ));
784    }
785    for (field, raw) in stream.fields.iter().zip(values.entries) {
786        decoders.decode_into(
787            &stream.name,
788            state.time().iteration(),
789            &field.name,
790            raw.get(),
791            state,
792        )?;
793    }
794    Ok(())
795}
796
797/// Compares parsed chunk facts with the authoritative metadata descriptor.
798fn validate_chunk_facts(
799    metadata_path: &Path,
800    stream: &StateStreamMetadata,
801    chunk: &ChunkMetadata,
802    records: u64,
803    first_iteration: Option<u64>,
804    last_iteration: Option<u64>,
805) -> Result<(), PersistenceError> {
806    if records != chunk.records
807        || first_iteration != Some(chunk.first_iteration)
808        || last_iteration != Some(chunk.last_iteration)
809    {
810        return Err(PersistenceError::InvalidMetadata {
811            path: metadata_path.to_path_buf(),
812            reason: format!(
813                "stream `{}` chunk {} declares {} records at {}..={}, but contains {} records at {:?}..={:?}",
814                stream.name,
815                chunk.ordinal,
816                chunk.records,
817                chunk.first_iteration,
818                chunk.last_iteration,
819                records,
820                first_iteration,
821                last_iteration
822            ),
823        });
824    }
825    Ok(())
826}
827
828/// Compares the streamed SHA-256 digest with the descriptor checksum.
829fn verify_checksum(
830    metadata_path: &Path,
831    path: &Path,
832    expected: &str,
833    digest: impl AsRef<[u8]>,
834) -> Result<(), PersistenceError> {
835    let Some(expected_digest) = expected.strip_prefix("sha256:") else {
836        return Err(PersistenceError::InvalidMetadata {
837            path: metadata_path.to_path_buf(),
838            reason: format!("unsupported chunk checksum algorithm in `{expected}`"),
839        });
840    };
841    let actual_digest = lowercase_hex(digest.as_ref());
842    if actual_digest != expected_digest {
843        return Err(PersistenceError::ChecksumMismatch {
844            path: path.to_path_buf(),
845            expected: expected.to_owned(),
846            actual: format!("sha256:{actual_digest}"),
847        });
848    }
849    Ok(())
850}
851
852/// Encodes digest bytes in the persisted lowercase hexadecimal notation.
853fn lowercase_hex(bytes: &[u8]) -> String {
854    use std::fmt::Write as _;
855
856    let mut encoded = String::with_capacity(bytes.len() * 2);
857    for byte in bytes {
858        write!(&mut encoded, "{byte:02x}").expect("writing to String cannot fail");
859    }
860    encoded
861}
862
863/// Constructs one line-aware record error without retaining payload bytes.
864fn invalid_record(path: &Path, line: u64, reason: impl Into<String>) -> PersistenceError {
865    PersistenceError::InvalidRecord {
866        path: path.to_path_buf(),
867        line,
868        reason: reason.into(),
869    }
870}