nmr 0.1.3

NMR data tools for Rust
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
//! Numeric replay belongs to execution, separate from immutable history values.

use crate::execution::ExecutionContext;
use crate::processed::{DerivedRawOrigin, ProcessedDataset, ProcessedOrigin, ProcessedProvenance};
use crate::processing::contracts::{
    error::*, history::*, operation::*, options::*, prepared_step::*, state::*,
};
use crate::processing::engine::execution::*;
use crate::processing::kernels::buffer::*;
use crate::processing::prepare::plan::*;
use crate::processing::prepare::resources::*;
use crate::raw::{RawDataset, SourceDigest};

use crate::processing::contracts::history::replay_record;

impl ProcessingHistory {
    /// Strictly replays from ordered aggregate starting points and retains their
    /// reading context. Current replay rejects any input count other than one.
    pub fn replay(
        &self,
        inputs: &[&crate::Dataset],
        options: ProcessingOptions,
    ) -> Result<crate::Dataset, ProcessingError> {
        self.replay_with_context(inputs, options, &mut ExecutionContext::default())
    }
    /// Replays using shared cancellation, progress and work accounting.
    pub fn replay_with_context(
        &self,
        inputs: &[&crate::Dataset],
        options: ProcessingOptions,
        control: &mut ExecutionContext<'_>,
    ) -> Result<crate::Dataset, ProcessingError> {
        control.check_cancelled()?;
        if self.inputs().len() != 1 {
            return Err(ProcessingError::MissingCapability {
                capability: "single external replay input",
                axis: None,
            });
        }
        if inputs.len() != 1 {
            return Err(ProcessingError::InputCountMismatch {
                expected: 1,
                actual: inputs.len(),
            });
        }
        let input = inputs[0];
        let options =
            crate::processing::prepare::resources::reserve_context(input.metadata(), options)?;
        let output = match self.input() {
            HistoryInput::Raw { .. } => self.replay_raw_with_context(
                input
                    .as_raw()
                    .ok_or(ProcessingError::InputIdentityMismatch)?,
                options,
                control,
            )?,
            HistoryInput::Processed { .. } => self.replay_processed_with_context(
                input
                    .as_processed()
                    .ok_or(ProcessingError::InputIdentityMismatch)?,
                options,
                control,
            )?,
        };
        Ok(input.derived_processed(output))
    }

    /// Replays all resolved operations against the exact bound raw input.
    ///
    /// Opaque source metadata is not consulted. Automatic operations use their
    /// recorded resolved parameters rather than running inference again.
    pub fn replay_raw(
        &self,
        raw: &RawDataset,
        options: ProcessingOptions,
    ) -> Result<crate::processed::ProcessedDataset, ProcessingError> {
        self.replay_raw_with_context(raw, options, &mut ExecutionContext::default())
    }
    /// Replays using shared cancellation, progress and work accounting.
    pub fn replay_raw_with_context(
        &self,
        raw: &RawDataset,
        options: ProcessingOptions,
        control: &mut ExecutionContext<'_>,
    ) -> Result<crate::processed::ProcessedDataset, ProcessingError> {
        control.check_cancelled()?;
        self.validate_input_structure()?;
        replay_raw_history(self, raw, options, control)
    }

    /// Strictly replays from the original processed starting point.
    /// Success confirms identity checks and execution, not numerical comparison.
    pub fn replay_processed(
        &self,
        input: &crate::processed::ProcessedDataset,
        options: ProcessingOptions,
    ) -> Result<crate::processed::ProcessedDataset, ProcessingError> {
        self.replay_processed_with_context(input, options, &mut ExecutionContext::default())
    }
    /// Replays using shared cancellation, progress and work accounting.
    pub fn replay_processed_with_context(
        &self,
        input: &crate::processed::ProcessedDataset,
        options: ProcessingOptions,
        control: &mut ExecutionContext<'_>,
    ) -> Result<crate::processed::ProcessedDataset, ProcessingError> {
        control.check_cancelled()?;
        self.validate_input_structure()?;
        replay_processed_history(self, input, options, control)
    }
}

pub(crate) fn replay_raw_history(
    history: &ProcessingHistory,
    raw: &RawDataset,
    options: ProcessingOptions,
    control: &mut ExecutionContext<'_>,
) -> Result<ProcessedDataset, ProcessingError> {
    let options = reserve_prepared(
        history.initial_descriptor().axes().len(),
        history.records().len(),
        false,
        options,
    )?;
    let options = reserve_axes(
        checked_times(
            axis_reservation(
                raw_axis_storage(raw.descriptor().axes())?,
                std::iter::empty(),
                true,
            )?,
            3,
        )?
        .checked_add(checked_times(history_axis_bytes(history)?, 2)?)
        .ok_or(ProcessingError::SizeOverflow)?,
        options,
    )?;
    let options = reserve_states(raw.descriptor().axes().len(), raw_map_points(raw), options)?;
    let options = reserve_containers(
        crate::processing::prepare::memory::raw_replay(raw, history)?,
        options,
    )?;
    let input = ProcessingInput::from_dataset_with_context(raw, control)?;
    if history.raw_input_digests() != Some(input.digests()) {
        return Err(ProcessingError::InputIdentityMismatch);
    }
    if history.raw_input_normalization() != Some(raw.provenance().sample_normalization()) {
        return Err(ProcessingError::InputIdentityMismatch);
    }
    let HistoryInput::Raw {
        format, sources, ..
    } = history.input()
    else {
        return Err(ProcessingError::InputIdentityMismatch);
    };
    if *format != raw.provenance().format()
        || sources.len() != raw.provenance().sources().len()
        || sources
            .iter()
            .zip(raw.provenance().sources())
            .any(|(a, b)| !a.same_content(b))
    {
        return Err(ProcessingError::InputIdentityMismatch);
    }
    if format.is_some() && sources.is_empty()
        || sources
            .iter()
            .any(|source| matches!(source.digest(), SourceDigest::NotComputed))
    {
        return Err(ProcessingError::MissingCapability {
            capability: "complete raw source identity",
            axis: None,
        });
    }
    if !(1..=3).contains(&raw.descriptor().axes().len()) || !input.dense {
        return Err(ProcessingError::Mapping(
            "history replay requires dense rank-1 through rank-3 raw input",
        ));
    }
    if !input.strong_source_identity {
        return Err(ProcessingError::MissingCapability {
            capability: "complete source-data digest",
            axis: None,
        });
    }

    // Resolve and check the entire history before allocating expanded samples.
    let mut baseline = expand_raw_descriptor(raw.descriptor().axes())?;
    check_sample_peak(descriptor_bytes(&baseline)?, 0, options)?;
    if !baseline.same_axes_except_labels(history.initial_descriptor()) {
        return Err(ProcessingError::InputIdentityMismatch);
    }
    baseline = history.initial_descriptor().clone();
    let mut state = PlanState::from_raw(
        &baseline,
        raw.descriptor().axes(),
        raw.sampling_schedule(),
        raw.data().layout().absolute_origin(),
    )?;
    let mut steps = Vec::new();
    steps
        .try_reserve_exact(history.records().len())
        .map_err(|_| ProcessingError::AllocationFailure)?;
    for (step_index, record) in history.records().iter().enumerate() {
        control.check_cancelled()?;
        if let Some(version) = record.algorithm_version() {
            if version
                != crate::processing::contracts::history::algorithm_version(record.requested())
            {
                return Err(
                    ProcessingError::UnsupportedHistoryVersion(version.into()).located(
                        Some(step_index),
                        Some(record.target()),
                        ProcessingPhase::Replay,
                    ),
                );
            }
        }
        replay_record(&mut state, record).map_err(|e| {
            ProcessingError::from(e).located(
                Some(step_index),
                Some(record.target()),
                ProcessingPhase::Replay,
            )
        })?;
        if let ProcessingRecord::Applied {
            requested,
            resolved,
            input_descriptor,
            output_descriptor,
            ..
        } = record
        {
            check_working_limit(
                input_descriptor,
                output_descriptor,
                match requested.target() {
                    OperationTarget::Axis(axis) => Some(axis),
                    _ => None,
                },
                resolved,
                options,
            )?;
            check_transform_work(
                input_descriptor,
                match requested.target() {
                    OperationTarget::Axis(axis) => Some(axis),
                    _ => None,
                },
                resolved,
                options,
            )?;
            steps.push(PreparedStep {
                step_index,
                axis: match requested.target() {
                    OperationTarget::Axis(axis) => Some(axis),
                    _ => None,
                },
                before: input_descriptor.clone(),
                after: output_descriptor.clone(),
                resolved: (**resolved).clone(),
            });
        }
    }
    let descriptor = state.descriptor()?;
    check_resource(
        crate::resource::ResourceKind::OutputBytes,
        descriptor_bytes(&descriptor)?,
        options.max_output_bytes,
    )?;
    let prepared = PreparedRawPlan {
        phase: ProcessingPhase::Replay,
        resources: estimate_resources(&descriptor, &steps, options)?,
        descriptor: descriptor.clone(),
        steps,
        operations: Vec::new(),
        options,
        input_digest: input.digests().dataset(),
    };
    control.ensure_work(prepared.estimated_work()?)?;
    let (_, samples) = expand_raw(control, raw)?;
    let data = execute(control, samples, baseline, &prepared, options)?;
    let provenance = ProcessedProvenance::derived(
        ProcessedOrigin::DerivedRaw(DerivedRawOrigin::new(
            raw.snapshot_with_digests(input.digests()),
            raw.descriptor().axes().len(),
        )),
        raw.provenance().sources().to_vec(),
        history.clone(),
    );
    ProcessedDataset::new_derived_with_context(control, descriptor, data, provenance)
}

pub(crate) fn replay_processed_history(
    history: &ProcessingHistory,
    input: &ProcessedDataset,
    options: ProcessingOptions,
    control: &mut ExecutionContext<'_>,
) -> Result<ProcessedDataset, ProcessingError> {
    let options = reserve_prepared(
        history.initial_descriptor().axes().len(),
        history.records().len(),
        false,
        options,
    )?;
    let options = reserve_axes(checked_times(history_axis_bytes(history)?, 3)?, options)?;
    let options = reserve_states(history.initial_descriptor().axes().len(), 0, options)?;
    let options = reserve_containers(
        crate::processing::prepare::memory::processed_replay(input, history)?,
        options,
    )?;
    let HistoryInput::Processed {
        digests,
        sources,
        read_record,
    } = history.input()
    else {
        return Err(ProcessingError::InputIdentityMismatch);
    };
    if input.provenance().history().is_some()
        || *digests != input.canonical_digests()
        || read_record.as_ref() != input.provenance().read_record()
        || sources.len() != input.provenance().sources().len()
        || sources
            .iter()
            .zip(input.provenance().sources())
            .any(|(a, b)| {
                a.kind() != b.kind()
                    || a.role() != b.role()
                    || a.id() != b.id()
                    || a.digest() != b.digest()
            })
    {
        return Err(ProcessingError::InputIdentityMismatch);
    }
    if matches!(input.provenance().origin(), ProcessedOrigin::Imported) && read_record.is_none()
        || !matches!(
            input.provenance().origin(),
            ProcessedOrigin::External(_) | ProcessedOrigin::Library(_)
        ) && !sources.is_empty()
            && (read_record.is_none()
                || sources.iter().any(|source| {
                    source.id().is_none()
                        || matches!(
                            source.digest(),
                            crate::provenance::SourceDigest::NotComputed
                        )
                }))
    {
        return Err(ProcessingError::MissingCapability {
            capability: "complete processed reading record",
            axis: None,
        });
    }
    validate_processing_axes(input)?;
    let mut state = input.processing_state().clone();
    if !input
        .descriptor()
        .same_axes_except_labels(history.initial_descriptor())
    {
        return Err(ProcessingError::InputIdentityMismatch);
    }
    // Labels are presentation metadata, excluded from the scientific binding.
    for (axis, recorded) in state
        .axes
        .iter_mut()
        .zip(history.initial_descriptor().axes())
    {
        axis.axis = recorded.clone();
    }
    let mut steps = Vec::new();
    steps
        .try_reserve_exact(history.records().len())
        .map_err(|_| ProcessingError::AllocationFailure)?;
    for (step_index, record) in history.records().iter().enumerate() {
        control.check_cancelled()?;
        if let Some(version) = record.algorithm_version() {
            if version
                != crate::processing::contracts::history::algorithm_version(record.requested())
            {
                return Err(
                    ProcessingError::UnsupportedHistoryVersion(version.into()).located(
                        Some(step_index),
                        Some(record.target()),
                        ProcessingPhase::Replay,
                    ),
                );
            }
        }
        replay_record(&mut state, record).map_err(|e| {
            ProcessingError::from(e).located(
                Some(step_index),
                Some(record.target()),
                ProcessingPhase::Replay,
            )
        })?;
        if let ProcessingRecord::Applied {
            requested,
            resolved,
            input_descriptor,
            output_descriptor,
            ..
        } = record
        {
            check_working_limit(
                input_descriptor,
                output_descriptor,
                match requested.target() {
                    OperationTarget::Axis(axis) => Some(axis),
                    _ => None,
                },
                resolved,
                options,
            )?;
            check_transform_work(
                input_descriptor,
                match requested.target() {
                    OperationTarget::Axis(axis) => Some(axis),
                    _ => None,
                },
                resolved,
                options,
            )?;
            steps.push(PreparedStep {
                step_index,
                axis: match requested.target() {
                    OperationTarget::Axis(axis) => Some(axis),
                    _ => None,
                },
                before: input_descriptor.clone(),
                after: output_descriptor.clone(),
                resolved: (**resolved).clone(),
            });
        }
    }
    let descriptor = state.descriptor()?;
    check_resource(
        crate::resource::ResourceKind::OutputBytes,
        descriptor_bytes(&descriptor)?,
        options.max_output_bytes,
    )?;
    if history
        .segments()
        .last()
        .map(|segment| segment.end_record())
        != Some(history.records().len())
    {
        return Err(ProcessingError::Mapping("incomplete execution segments"));
    }
    // A completed intermediate segment remains owned by this call while the
    // next segment clones and transforms its samples. It is not borrowed input.
    let mut begin = 0;
    let mut source_descriptor = history.initial_descriptor();
    for (index, segment) in history.segments().iter().enumerate() {
        let end = segment.end_record();
        if end < begin || end > history.records().len() {
            return Err(ProcessingError::Mapping(
                "invalid execution segment boundary",
            ));
        }
        let source_bytes = descriptor_bytes(source_descriptor)?;
        let retained = if index == 0 { 0 } else { source_bytes };
        check_sample_peak(source_bytes, retained, options)?;
        for record in &history.records()[begin..end] {
            if let ProcessingRecord::Applied {
                requested,
                resolved,
                input_descriptor,
                output_descriptor,
                ..
            } = record
            {
                check_sample_peak(
                    numerical_working_bytes(
                        input_descriptor,
                        output_descriptor,
                        match requested.target() {
                            OperationTarget::Axis(axis) => Some(axis),
                            _ => None,
                        },
                        resolved,
                    )?,
                    retained,
                    options,
                )?;
                source_descriptor = output_descriptor;
            }
        }
        begin = end;
    }
    let mut current: Option<ProcessedDataset> = None;
    let mut step_iter = steps.into_iter();
    let mut begin = 0;
    for segment in history.segments() {
        let end = segment.end_record();
        if end < begin || end > history.records().len() {
            return Err(ProcessingError::Mapping(
                "invalid execution segment boundary",
            ));
        }
        let count = history.records()[begin..end]
            .iter()
            .filter(|record| matches!(record, ProcessingRecord::Applied { .. }))
            .count();
        let mut steps = try_vec_capacity(count)?;
        steps.extend(step_iter.by_ref().take(count));
        let source = current.as_ref().unwrap_or(input);
        let descriptor = steps
            .last()
            .map_or_else(|| source.descriptor().clone(), |step| step.after.clone());
        let prepared = PreparedRawPlan {
            phase: ProcessingPhase::Replay,
            resources: estimate_resources(&descriptor, &steps, options)?,
            descriptor: descriptor.clone(),
            steps,
            operations: Vec::new(),
            options,
            input_digest: source.canonical_digests().dataset(),
        };
        control.ensure_work(prepared.estimated_work()?)?;
        let samples = clone_samples(source.data().samples(), control)?;
        let data = execute(
            control,
            samples,
            if begin == 0 {
                history.initial_descriptor().clone()
            } else {
                source.descriptor().clone()
            },
            &prepared,
            options,
        )?;
        let provenance =
            ProcessedProvenance::derived_from(source.provenance(), history.prefix(end));
        current = Some(ProcessedDataset::new_derived_with_context(
            control, descriptor, data, provenance,
        )?);
        begin = end;
    }
    current.ok_or(ProcessingError::Mapping("missing execution segment"))
}