Skip to main content

gammaloop_api/
state.rs

1#[cfg(test)]
2use gammalooprs::integrands::process::EvaluationTarget;
3use std::{
4    collections::{BTreeMap, BTreeSet, HashSet},
5    fs::{self},
6    io::{self, IsTerminal},
7    ops::ControlFlow,
8    path::{Path, PathBuf},
9    str::FromStr,
10    sync::{
11        atomic::{AtomicBool, AtomicU64, Ordering},
12        Arc, Mutex,
13    },
14    thread,
15    time::Duration,
16};
17
18use clap::Args;
19use color_eyre::{Result, Section};
20use colored::Colorize;
21use eyre::{eyre, Context};
22use feynkit_generator::GenerationType;
23use gammalooprs::{
24    processes::{Amplitude, CrossSection},
25    utils::serde_utils::IsDefault,
26};
27use linnet::half_edge::subgraph::{SuBitGraph, SubGraphLike, SubSetLike};
28use schemars::{schema_for, JsonSchema, Schema};
29use serde::{Deserialize, Serialize};
30use spenso::algebra::complex::Complex;
31#[cfg(not(target_os = "linux"))]
32use sysinfo::{get_current_pid, ProcessRefreshKind, ProcessesToUpdate, System};
33use toml::Value as TomlValue;
34use tracing::{debug, info, info_span, Span};
35use tracing_indicatif::span_ext::IndicatifSpanExt;
36
37use gammalooprs::{
38    clear_interrupt_request,
39    graph::Graph,
40    initialisation::initialise,
41    integrands::process::ProcessIntegrand,
42    is_interrupt_requested,
43    model::{
44        InputParamCard, Model, ModelGammaLoopExt, ParameterNature, SerializableInputParamCard,
45        UFOSymbol,
46    },
47    momentum::ExternalMomenta,
48    processes::{
49        begin_phase, merge_generated_graph_reports, DotExportSettings, GeneratedGraphReport,
50        GenerationProcessKind, GenerationProgressMode, GenerationProgressModeGuard,
51        GenerationProgressObserver, GenerationProgressObserverGuard, GenerationProgressPhase,
52        GraphGenerationStats, GraphGroupSelectionMode, GraphGroupSelectionPlan,
53        GraphGroupSelectionReport, GraphGroupSelectionSpec, NamedGraphGenerationReport, Process,
54        ProcessCollection, ProcessDefinition, ProcessList, ProcessLoadSelection,
55    },
56    settings::{
57        global::GenerationSettings,
58        runtime::{
59            kinematic::{Externals, KinematicsSettings},
60            LockedRuntimeSettings,
61        },
62        GlobalSettings, RuntimeSettings,
63    },
64    utils::{
65        serde_utils::{get_schema_folder, SmartSerde},
66        tracing::{init_bench_tracing, init_test_tracing},
67        F,
68    },
69    GammaLoopContextContainer,
70};
71
72use crate::{
73    command_parser::{normalize_clap_args, split_command_line},
74    command_template::{contains_placeholder, placeholder_specs, PlaceholderSpec},
75    commands::{save::SaveState, Commands},
76    integrand_info::{collect_integrand_info, IntegrandInfo},
77    model_parameters::{external_model_parameter_type, validate_model_parameter_type},
78    render_smart_toml,
79    tracing::{set_file_log_filter, set_log_style, set_stderr_log_filter},
80    CLISettings,
81};
82
83#[derive(Debug, Clone, Copy, Default)]
84pub struct GenerationResourceSummary {
85    pub peak_ram_bytes: u64,
86    pub generation_cores: usize,
87}
88
89#[derive(Debug, Clone, Default)]
90pub struct GenerationReports {
91    pub reports: Vec<GeneratedGraphReport>,
92    pub resources: GenerationResourceSummary,
93}
94
95#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
96pub struct IntegrandGenerationSummaryKey {
97    pub process_id: usize,
98    pub integrand_name: String,
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
102pub struct IntegrandGenerationSummary {
103    pub peak_ram_bytes: u64,
104    pub reports: Vec<GeneratedGraphReport>,
105    /// The point this generation ran at. Absent in summaries saved before it
106    /// was recorded.
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub generation_point: Option<GenerationPoint>,
109}
110
111/// The model values and kinematics a generated integrand was generated at.
112///
113/// Generation with `generation.threshold_subtraction.check_esurface_at_generation`
114/// classifies threshold existence with these values and omits the counterterms
115/// proven absent, so such an integrand stays valid only at exactly this point.
116/// Whether it did is recorded with the integrand, so the record travels with
117/// copies into other processes.
118///
119/// The values are the integrand's effective numeric inputs: every parameter
120/// of the model it evaluates with (the session model with the session card
121/// and the integrand's settings overlay applied) that is not derived from
122/// others, i.e. every external parameter and every internal parameter
123/// without an expression (a numeric constant), so values from the card, from
124/// the overlay and from the model's own defaults all count. Parameters with
125/// an expression and all couplings (whose expression is mandatory) are not
126/// recorded: they follow from the inputs through expressions that belong to
127/// the structure fingerprint every held graph is checked against.
128///
129/// Every `f64` is stored as its bit pattern (`0x` and 16 hex digits), so the
130/// record survives saving bit-exactly and comparison is exact. Signed zeros
131/// are distinct inputs: comparing bits can only refuse a change, never accept
132/// one, so treating `-0.0` and `+0.0` as different is the conservative rule.
133#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
134pub struct GenerationPoint {
135    /// Whether the generation decided on these values, in which case the
136    /// integrand must stay at this point.
137    pub depends_on_model_values: bool,
138    /// Effective input parameter values (real, imaginary); `None` for an
139    /// input parameter without a value.
140    pub input_parameters: BTreeMap<String, Option<[String; 2]>>,
141    /// The physical point of the integrand's stored kinematic settings right
142    /// after generation.
143    pub kinematics: GenerationKinematics,
144}
145
146impl GenerationPoint {
147    /// The point of an integrand evaluating with `effective_model` and `settings`.
148    fn new(
149        effective_model: &Model,
150        settings: &RuntimeSettings,
151        depends_on_model_values: bool,
152    ) -> Result<Self> {
153        Ok(Self {
154            depends_on_model_values,
155            input_parameters: effective_model
156                .parameters()
157                .iter()
158                .filter(|parameter| {
159                    parameter.nature == ParameterNature::External || parameter.expression.is_none()
160                })
161                .map(|parameter| {
162                    (
163                        parameter.name.clone(),
164                        parameter
165                            .value
166                            .map(|value| [exact_f64(value.re), exact_f64(value.im)]),
167                    )
168                })
169                .collect(),
170            kinematics: GenerationKinematics::new(&settings.kinematics),
171        })
172    }
173
174    /// The first exact difference in values or kinematics from `other`, if any.
175    fn difference(&self, other: &Self) -> Option<String> {
176        if self
177            .input_parameters
178            .keys()
179            .ne(other.input_parameters.keys())
180        {
181            return Some("the set of input model parameters".to_owned());
182        }
183        for ((name, value), other_value) in self
184            .input_parameters
185            .iter()
186            .zip(other.input_parameters.values())
187        {
188            if value != other_value {
189                return Some(format!(
190                    "model parameter '{name}' ({} at generation, now {})",
191                    display_exact_value(value.as_ref()),
192                    display_exact_value(other_value.as_ref())
193                ));
194            }
195        }
196        (self.kinematics != other.kinematics).then(|| "the kinematic settings".to_owned())
197    }
198}
199
200/// The exact, persistable form of `value`: its bit pattern in hexadecimal.
201fn exact_f64(value: f64) -> String {
202    format!("{:#018x}", value.to_bits())
203}
204
205fn display_exact_value(value: Option<&[String; 2]>) -> String {
206    let decode = |bits: &str| {
207        u64::from_str_radix(bits.trim_start_matches("0x"), 16)
208            .map(|bits| format!("{:?}", f64::from_bits(bits)))
209            .unwrap_or_else(|_| bits.to_owned())
210    };
211    value.map_or_else(
212        || "no value".to_owned(),
213        |value| format!("{} + {}i", decode(&value[0]), decode(&value[1])),
214    )
215}
216
217/// The generation-relevant kinematics of an integrand, encoded field by field.
218///
219/// Threshold classification reads the centre-of-mass energy and the external
220/// momenta; generation also reads the helicities (polarization sums), and the
221/// phase-space improvement settings change the evaluated momenta. Each field
222/// is encoded explicitly, floats as [`exact_f64`] bit patterns, so the
223/// encoding does not depend on display-default serialization flags or on the
224/// transient momentum caches. Non-finite floats are encoded like any other
225/// bit pattern and so round-trip exactly; distinct NaN payloads are distinct.
226#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
227pub struct GenerationKinematics {
228    /// `kinematics.e_cm`.
229    pub e_cm: String,
230    /// Each external momentum's components (E, px, py, pz), or `None` for the
231    /// dependent one, in process order.
232    pub momenta: Vec<Option<[String; 4]>>,
233    /// Each external helicity (`Debug` form), in process order.
234    pub helicities: Vec<String>,
235    /// The phase-space improvement mode (`Debug` form).
236    pub improvement_mode: String,
237    /// The maximal deformation of an improved point, if checked.
238    pub large_deformation_check: Option<String>,
239    /// Whether a large deformation only warns.
240    pub only_warn_on_large_deformation: bool,
241}
242
243impl GenerationKinematics {
244    fn new(kinematics: &KinematicsSettings) -> Self {
245        let Externals::Constant {
246            momenta,
247            helicities,
248            improvement_settings,
249            ..
250        } = &kinematics.externals;
251        Self {
252            e_cm: exact_f64(kinematics.e_cm),
253            momenta: momenta
254                .iter()
255                .map(|momentum| match momentum {
256                    ExternalMomenta::Dependent(_) => None,
257                    ExternalMomenta::Independent(components) => {
258                        Some(components.map(|component| exact_f64(component.0)))
259                    }
260                })
261                .collect(),
262            helicities: helicities
263                .iter()
264                .map(|helicity| format!("{helicity:?}"))
265                .collect(),
266            improvement_mode: format!("{:?}", improvement_settings.mode),
267            large_deformation_check: improvement_settings
268                .large_deformation_check
269                .map(|bound| exact_f64(bound.0)),
270            only_warn_on_large_deformation: improvement_settings.only_warn_on_large_deformation,
271        }
272    }
273}
274
275#[derive(Debug, Clone, PartialEq, Eq)]
276pub struct SelectedGraphGroups {
277    pub source_process_id: usize,
278    pub source_process_name: String,
279    pub source_integrand_name: String,
280    pub process_id: usize,
281    pub process_name: String,
282    pub integrand_name: String,
283    pub report: GraphGroupSelectionReport,
284    pub copied_to_output: bool,
285    pub replaced_existing_target: bool,
286    pub removed_target_artifacts: bool,
287    pub discarded_generated_integrand: bool,
288    pub removed_generated_artifacts: bool,
289    pub removed_generation_summary: bool,
290}
291
292#[derive(Debug, Clone, Default, PartialEq, Eq)]
293pub struct GraphGroupSelectionTarget {
294    pub output_process_name: Option<String>,
295    pub output_integrand_name: Option<String>,
296    pub clear_existing_processes: bool,
297}
298
299impl GraphGroupSelectionTarget {
300    pub fn in_place() -> Self {
301        Self::default()
302    }
303
304    pub fn copy(
305        output_process_name: Option<String>,
306        output_integrand_name: Option<String>,
307        clear_existing_processes: bool,
308    ) -> Self {
309        Self {
310            output_process_name,
311            output_integrand_name,
312            clear_existing_processes,
313        }
314    }
315
316    fn is_copy_mode(&self) -> bool {
317        self.output_process_name.is_some() || self.output_integrand_name.is_some()
318    }
319}
320
321#[derive(Debug, Clone, Copy)]
322pub struct GraphGroupSelectionContext<'a> {
323    pub generation_settings: &'a GenerationSettings,
324    pub state_folder: &'a Path,
325    pub read_only_state: bool,
326}
327
328impl<'a> GraphGroupSelectionContext<'a> {
329    pub fn new(
330        generation_settings: &'a GenerationSettings,
331        state_folder: &'a Path,
332        read_only_state: bool,
333    ) -> Self {
334        Self {
335            generation_settings,
336            state_folder,
337            read_only_state,
338        }
339    }
340}
341
342struct IntegrandCopyInsertion {
343    process_id: usize,
344    process_name: String,
345    integrand_name: String,
346    replaced_existing_target: bool,
347    removed_target_artifacts: bool,
348}
349
350struct SelectionSource {
351    process_id: usize,
352    process_name: String,
353    integrand_name: String,
354}
355
356enum IntegrandCopyPayload {
357    Amplitude(Amplitude),
358    CrossSection(CrossSection),
359}
360
361impl IntegrandCopyPayload {
362    fn is_generated(&self) -> bool {
363        match self {
364            Self::Amplitude(amplitude) => amplitude.integrand.is_some(),
365            Self::CrossSection(cross_section) => cross_section.integrand.is_some(),
366        }
367    }
368
369    fn rename(&mut self, new_name: &str) {
370        match self {
371            Self::Amplitude(amplitude) => {
372                amplitude.name = new_name.to_string();
373                rename_process_integrand(amplitude.integrand.as_mut(), new_name);
374            }
375            Self::CrossSection(cross_section) => {
376                cross_section.name = new_name.to_string();
377                rename_process_integrand(cross_section.integrand.as_mut(), new_name);
378            }
379        }
380    }
381
382    fn apply_graph_group_selection(&mut self, plan: &GraphGroupSelectionPlan) -> Result<()> {
383        match self {
384            Self::Amplitude(amplitude) => amplitude.apply_graph_group_selection(plan),
385            Self::CrossSection(cross_section) => cross_section.apply_graph_group_selection(plan),
386        }
387    }
388
389    fn is_compatible_with(&self, collection: &ProcessCollection) -> bool {
390        matches!(
391            (self, collection),
392            (Self::Amplitude(_), ProcessCollection::Amplitudes(_))
393                | (Self::CrossSection(_), ProcessCollection::CrossSections(_))
394        )
395    }
396
397    fn kind_name(&self) -> &'static str {
398        match self {
399            Self::Amplitude(_) => "amplitudes",
400            Self::CrossSection(_) => "cross sections",
401        }
402    }
403
404    fn into_collection(self) -> ProcessCollection {
405        match self {
406            Self::Amplitude(amplitude) => {
407                let mut collection = ProcessCollection::Amplitudes(BTreeMap::new());
408                collection.add_amplitude(amplitude);
409                collection
410            }
411            Self::CrossSection(cross_section) => {
412                let mut collection = ProcessCollection::CrossSections(BTreeMap::new());
413                collection.add_cross_section(cross_section);
414                collection
415            }
416        }
417    }
418
419    fn insert_into_process(self, process: &mut Process, process_name: &str) -> Result<()> {
420        match (self, &mut process.collection) {
421            (Self::Amplitude(amplitude), ProcessCollection::Amplitudes(amplitudes)) => {
422                amplitudes.insert(amplitude.name.clone(), amplitude);
423                Ok(())
424            }
425            (
426                Self::CrossSection(cross_section),
427                ProcessCollection::CrossSections(cross_sections),
428            ) => {
429                cross_sections.insert(cross_section.name.clone(), cross_section);
430                Ok(())
431            }
432            (payload, _) => Err(eyre!(
433                "Destination process '{}' exists but does not contain {}",
434                process_name,
435                payload.kind_name()
436            )),
437        }
438    }
439}
440
441struct GenerationMonitor {
442    peak_ram_bytes: Arc<AtomicU64>,
443    current_ram_bytes: Arc<AtomicU64>,
444    stop_requested: Arc<AtomicBool>,
445    handle: Option<thread::JoinHandle<()>>,
446}
447
448struct AggregateGenerationProgressReporter {
449    progress_span: Span,
450    current_ram_bytes: Arc<AtomicU64>,
451    peak_ram_bytes: Arc<AtomicU64>,
452    state: Mutex<AggregateGenerationProgressState>,
453}
454
455#[derive(Default)]
456struct AggregateGenerationProgressState {
457    phase: Option<GenerationProgressPhase>,
458    kind: Option<GenerationProcessKind>,
459    process: String,
460    integrand: String,
461    total_graphs: usize,
462    done_graphs: usize,
463    total_cuts: Option<usize>,
464    done_cuts: usize,
465    discovered_st_cuts: usize,
466    discovered_valid_cuts: usize,
467    active_graphs: BTreeSet<String>,
468    last_graph: Option<String>,
469    stats: GraphGenerationStats,
470}
471
472impl AggregateGenerationProgressReporter {
473    fn new(
474        current_ram_bytes: Arc<AtomicU64>,
475        peak_ram_bytes: Arc<AtomicU64>,
476        eta_warmup_steps: u64,
477    ) -> Arc<Self> {
478        let span = info_span!(
479            "Integrand generation",
480            indicatif.pb_show = true,
481            indicatif.pb_msg = "Starting integrand generation"
482        );
483        span.pb_set_style(
484            &gammalooprs::utils::long_running_progress_style_with_eta_warmup(eta_warmup_steps),
485        );
486        span.pb_start();
487        span.pb_set_length(0);
488        span.pb_set_position(0);
489        span.pb_tick();
490        Self::new_with_span(current_ram_bytes, peak_ram_bytes, span)
491    }
492
493    #[cfg(test)]
494    fn new_hidden(current_ram_bytes: Arc<AtomicU64>, peak_ram_bytes: Arc<AtomicU64>) -> Arc<Self> {
495        Self::new_with_span(current_ram_bytes, peak_ram_bytes, Span::none())
496    }
497
498    fn new_with_span(
499        current_ram_bytes: Arc<AtomicU64>,
500        peak_ram_bytes: Arc<AtomicU64>,
501        progress_span: Span,
502    ) -> Arc<Self> {
503        Arc::new(Self {
504            progress_span,
505            current_ram_bytes,
506            peak_ram_bytes,
507            state: Mutex::new(AggregateGenerationProgressState::default()),
508        })
509    }
510
511    fn fixed_field(value: &str, width: usize) -> String {
512        let mut chars = value.chars().collect::<Vec<_>>();
513        if chars.len() > width {
514            chars.truncate(width.saturating_sub(1));
515            chars.push('~');
516        }
517        format!("{:<width$}", chars.into_iter().collect::<String>())
518    }
519
520    fn progress_memory(bytes: u64) -> String {
521        const MIB: f64 = 1024.0 * 1024.0;
522        const GIB: f64 = MIB * 1024.0;
523        let value = bytes as f64;
524        if value >= GIB {
525            format!("{:>6.2} GiB", value / GIB)
526        } else {
527            format!("{:>6.0} MiB", value / MIB)
528        }
529    }
530
531    fn progress_percent(percent: f64) -> String {
532        if percent < 0.01 {
533            "0%".to_string()
534        } else if percent < 0.1 {
535            format!("{percent:.3}%")
536        } else if percent < 1.0 {
537            format!("{percent:.2}%")
538        } else if percent < 10.0 {
539            format!("{percent:.1}%")
540        } else {
541            format!("{percent:.0}%")
542        }
543    }
544
545    fn progress_time_share(duration: Duration, total: Duration) -> String {
546        if total.is_zero() {
547            "--".to_string()
548        } else {
549            Self::progress_percent(duration.as_secs_f64() * 100.0 / total.as_secs_f64())
550        }
551    }
552
553    fn progress_units(state: &AggregateGenerationProgressState) -> (u64, u64) {
554        match (state.phase, state.total_cuts) {
555            (Some(GenerationProgressPhase::GraphGeneration), Some(total_cuts)) => {
556                let total = total_cuts.saturating_add(state.total_graphs) as u64;
557                let completed = state
558                    .done_cuts
559                    .saturating_add(state.done_graphs)
560                    .min(total_cuts.saturating_add(state.total_graphs))
561                    as u64;
562                (completed, total)
563            }
564            _ => (state.done_graphs as u64, state.total_graphs as u64),
565        }
566    }
567
568    fn graph_progress_counts(state: &AggregateGenerationProgressState) -> (usize, usize, usize) {
569        let active = state
570            .active_graphs
571            .len()
572            .min(state.total_graphs.saturating_sub(state.done_graphs));
573        (state.done_graphs, active, state.total_graphs)
574    }
575
576    fn refresh(&self, state: &AggregateGenerationProgressState) {
577        let (completed_units, total_units) = Self::progress_units(state);
578        self.progress_span.pb_set_length(total_units);
579        self.progress_span.pb_set_position(completed_units);
580
581        let current_ram = Self::progress_memory(self.current_ram_bytes.load(Ordering::Relaxed));
582        let peak_ram = Self::progress_memory(self.peak_ram_bytes.load(Ordering::Relaxed));
583        let kind = match state.kind {
584            Some(GenerationProcessKind::Amplitude) => "AMP",
585            Some(GenerationProcessKind::CrossSection) => "XS",
586            None => "GEN",
587        };
588        let phase = match state.phase {
589            Some(GenerationProgressPhase::GraphPreprocessing) => "prep",
590            Some(GenerationProgressPhase::GraphGeneration) => "graphs",
591            Some(GenerationProgressPhase::Backend) => "backend",
592            None => "gen",
593        };
594        let last_graph = state.last_graph.as_deref().unwrap_or("-");
595        let cut_context = match (state.phase, state.kind, state.total_cuts) {
596            (
597                Some(GenerationProgressPhase::GraphPreprocessing),
598                Some(GenerationProcessKind::Amplitude),
599                _,
600            ) => None,
601            (Some(GenerationProgressPhase::GraphPreprocessing), _, _) => Some(format!(
602                "{:>4}/{:<4}",
603                state.discovered_valid_cuts, state.discovered_st_cuts
604            )),
605            (_, _, Some(total_cuts)) => Some(format!("{:>4}/{:<4}", state.done_cuts, total_cuts)),
606            _ => Some(format!("{:>4}/{:<4}", "-", "-")),
607        };
608        let phase = Self::fixed_field(phase, 7).bold().blue();
609        let kind = Self::fixed_field(kind, 3).cyan();
610        let identifier = if state.process.is_empty() {
611            state.integrand.clone()
612        } else {
613            format!("{}@{}", state.integrand, state.process)
614        };
615        let identifier = Self::fixed_field(&identifier, 24).yellow();
616        let last_graph = Self::fixed_field(last_graph, 8).green();
617        let (done_graphs, active_graphs, total_graphs) = Self::graph_progress_counts(state);
618        let graph_ratio = format!(
619            "{} {} / {}",
620            format!("{done_graphs:>3}").green(),
621            format!("({active_graphs:>3})").dimmed(),
622            format!("{total_graphs:<3}").green(),
623        );
624        let ram = format!("{current_ram}/{peak_ram}").yellow();
625        let phase_detail = if state.phase == Some(GenerationProgressPhase::GraphPreprocessing) {
626            let steps = match state.kind {
627                Some(GenerationProcessKind::Amplitude) => {
628                    "3D expressions + LMBs + integrands + threshold CTs + tropical samplers"
629                }
630                _ => "cuts + 3D expressions + LMBs + integrands + threshold CTs",
631            };
632            format!("{} {}", "step".bold().blue(), steps.cyan())
633        } else {
634            let total_time = state.stats.timings.total_time;
635            let expression_share =
636                Self::progress_time_share(state.stats.expression_build_time(), total_time);
637            let spenso_share =
638                Self::progress_time_share(state.stats.timings.evaluator_spenso_time, total_time);
639            let symbolica_share =
640                Self::progress_time_share(state.stats.timings.evaluator_symbolica_time, total_time);
641            let compile_share =
642                Self::progress_time_share(state.stats.timings.evaluator_compile_time, total_time);
643            format!(
644                "{} {} {} / {} {} / {} {} / {} {}",
645                "time".bold().blue(),
646                "expr".bold().blue(),
647                expression_share.magenta(),
648                "spenso".bold().blue(),
649                spenso_share.cyan(),
650                "eval".bold().blue(),
651                symbolica_share.green(),
652                "compile".bold().blue(),
653                compile_share.yellow(),
654            )
655        };
656        let mut sections = vec![
657            format!("{} {} {}", phase, kind, identifier),
658            format!("{} {}", "g".bold().blue(), graph_ratio),
659            format!("{} {}", "last".bold().blue(), last_graph),
660        ];
661        if let Some(cut_context) = cut_context {
662            sections.push(format!("{} {}", "cut".bold().blue(), cut_context.green()));
663        }
664        sections.push(format!("{} {}", "ram".bold().blue(), ram));
665        sections.push(phase_detail);
666        self.progress_span.pb_set_message(&sections.join(" | "));
667        self.progress_span.pb_tick();
668    }
669}
670
671impl GenerationProgressObserver for AggregateGenerationProgressReporter {
672    fn begin_phase(
673        &self,
674        phase: GenerationProgressPhase,
675        kind: GenerationProcessKind,
676        process: &str,
677        integrand: &str,
678        total_graphs: usize,
679        total_cuts: Option<usize>,
680    ) {
681        let mut state = self
682            .state
683            .lock()
684            .expect("aggregate generation progress state mutex is poisoned");
685        state.phase = Some(phase);
686        state.kind = Some(kind);
687        state.process.clear();
688        state.process.push_str(process);
689        state.integrand.clear();
690        state.integrand.push_str(integrand);
691        state.total_graphs = total_graphs;
692        state.done_graphs = 0;
693        state.total_cuts = total_cuts;
694        state.done_cuts = 0;
695        state.discovered_st_cuts = 0;
696        state.discovered_valid_cuts = 0;
697        state.active_graphs.clear();
698        state.last_graph = None;
699        state.stats = GraphGenerationStats::default();
700        self.progress_span.pb_reset_elapsed();
701        self.refresh(&state);
702    }
703
704    fn graph_started(
705        &self,
706        _kind: GenerationProcessKind,
707        _integrand: &str,
708        graph: &str,
709        _cut_count: Option<usize>,
710    ) {
711        let mut state = self
712            .state
713            .lock()
714            .expect("aggregate generation progress state mutex is poisoned");
715        state.active_graphs.insert(graph.to_string());
716        state.last_graph = Some(graph.to_string());
717        self.refresh(&state);
718    }
719
720    fn graph_finished(
721        &self,
722        _kind: GenerationProcessKind,
723        _integrand: &str,
724        graph: &str,
725        stats: &GraphGenerationStats,
726        completed_cuts: Option<usize>,
727    ) {
728        let mut state = self
729            .state
730            .lock()
731            .expect("aggregate generation progress state mutex is poisoned");
732        state.done_graphs = state.done_graphs.saturating_add(1).min(state.total_graphs);
733        state.done_cuts += completed_cuts.unwrap_or(0);
734        state.active_graphs.remove(graph);
735        state.last_graph = Some(graph.to_string());
736        state.stats.merge_in_place(stats);
737        self.refresh(&state);
738    }
739
740    fn cuts_discovered(
741        &self,
742        _integrand: &str,
743        graph: &str,
744        st_cut_count: usize,
745        valid_cut_count: usize,
746    ) {
747        let mut state = self
748            .state
749            .lock()
750            .expect("aggregate generation progress state mutex is poisoned");
751        state.discovered_st_cuts += st_cut_count;
752        state.discovered_valid_cuts += valid_cut_count;
753        state.last_graph = Some(graph.to_string());
754        self.refresh(&state);
755    }
756
757    fn cut_finished(&self, _integrand: &str, graph: &str, cut_count: usize) {
758        let mut state = self
759            .state
760            .lock()
761            .expect("aggregate generation progress state mutex is poisoned");
762        state.done_cuts = state.done_cuts.saturating_add(cut_count);
763        if let Some(total_cuts) = state.total_cuts {
764            state.done_cuts = state.done_cuts.min(total_cuts);
765        }
766        state.last_graph = Some(graph.to_string());
767        self.refresh(&state);
768    }
769
770    fn backend_started(&self, kind: GenerationProcessKind, integrand: &str, graph_count: usize) {
771        let mut state = self
772            .state
773            .lock()
774            .expect("aggregate generation progress state mutex is poisoned");
775        state.phase = Some(GenerationProgressPhase::Backend);
776        state.kind = Some(kind);
777        state.integrand.clear();
778        state.integrand.push_str(integrand);
779        state.total_graphs = graph_count;
780        state.done_graphs = 0;
781        state.total_cuts = None;
782        state.done_cuts = 0;
783        state.active_graphs.clear();
784        state.last_graph = None;
785        self.progress_span.pb_reset_elapsed();
786        self.refresh(&state);
787    }
788
789    fn backend_finished(&self, _kind: GenerationProcessKind, _integrand: &str, elapsed: Duration) {
790        let mut state = self
791            .state
792            .lock()
793            .expect("aggregate generation progress state mutex is poisoned");
794        state.done_graphs = state.total_graphs;
795        state.stats.timings.total_time += elapsed;
796        state.stats.timings.evaluator_compile_time += elapsed;
797        self.refresh(&state);
798    }
799}
800
801impl GenerationMonitor {
802    const POLL_INTERVAL: Duration = Duration::from_millis(100);
803
804    #[cfg(target_os = "linux")]
805    fn parse_resident_memory_bytes(status: &str) -> Option<u64> {
806        let mut fields = status
807            .lines()
808            .find_map(|line| line.strip_prefix("VmRSS:"))?
809            .split_ascii_whitespace();
810        let kibibytes = fields.next()?.parse::<u64>().ok()?;
811        if fields.next()? != "kB" || fields.next().is_some() {
812            return None;
813        }
814        kibibytes.checked_mul(1024)
815    }
816
817    #[cfg(target_os = "linux")]
818    fn resident_memory_bytes() -> Option<u64> {
819        // Refreshing one PID with sysinfo also walks the host's processes/tasks.
820        let status = fs::read_to_string("/proc/self/status").ok()?;
821        Self::parse_resident_memory_bytes(&status)
822    }
823
824    fn start() -> Result<Self> {
825        #[cfg(not(target_os = "linux"))]
826        let pid = get_current_pid().map_err(|err| eyre!("Failed to resolve current pid: {err}"))?;
827        #[cfg(target_os = "linux")]
828        let initial_memory = Self::resident_memory_bytes().unwrap_or(0);
829        #[cfg(not(target_os = "linux"))]
830        let initial_memory = 0;
831        let peak_ram_bytes = Arc::new(AtomicU64::new(initial_memory));
832        let current_ram_bytes = Arc::new(AtomicU64::new(initial_memory));
833        let stop_requested = Arc::new(AtomicBool::new(false));
834        let peak_ram_bytes_for_thread = Arc::clone(&peak_ram_bytes);
835        let current_ram_bytes_for_thread = Arc::clone(&current_ram_bytes);
836        let stop_requested_for_thread = Arc::clone(&stop_requested);
837
838        let handle = thread::Builder::new()
839            .name("generation-ram-monitor".to_string())
840            .spawn(move || {
841                #[cfg(not(target_os = "linux"))]
842                let mut system = System::new();
843                loop {
844                    if stop_requested_for_thread.load(Ordering::Relaxed) || is_interrupt_requested()
845                    {
846                        break;
847                    }
848
849                    #[cfg(target_os = "linux")]
850                    let memory = Self::resident_memory_bytes();
851                    #[cfg(not(target_os = "linux"))]
852                    let memory = {
853                        system.refresh_processes_specifics(
854                            ProcessesToUpdate::Some(&[pid]),
855                            true,
856                            ProcessRefreshKind::nothing().with_memory(),
857                        );
858                        system.process(pid).map(|process| process.memory())
859                    };
860                    if let Some(memory) = memory {
861                        current_ram_bytes_for_thread.store(memory, Ordering::Relaxed);
862                        peak_ram_bytes_for_thread.fetch_max(memory, Ordering::Relaxed);
863                    }
864                    thread::park_timeout(Self::POLL_INTERVAL);
865                }
866            })
867            .map_err(|err| eyre!("Failed to spawn generation RAM monitor: {err}"))?;
868
869        Ok(Self {
870            peak_ram_bytes,
871            current_ram_bytes,
872            stop_requested,
873            handle: Some(handle),
874        })
875    }
876
877    fn current_ram_bytes(&self) -> Arc<AtomicU64> {
878        Arc::clone(&self.current_ram_bytes)
879    }
880
881    fn peak_ram_bytes(&self) -> Arc<AtomicU64> {
882        Arc::clone(&self.peak_ram_bytes)
883    }
884
885    fn finish(&mut self) -> u64 {
886        self.stop_requested.store(true, Ordering::Relaxed);
887        if let Some(handle) = self.handle.take() {
888            handle.thread().unpark();
889            let _ = handle.join();
890        }
891        self.peak_ram_bytes.load(Ordering::Relaxed)
892    }
893}
894
895impl Drop for GenerationMonitor {
896    fn drop(&mut self) {
897        let _ = self.finish();
898    }
899}
900
901#[derive(Debug, Clone, PartialEq, Eq, JsonSchema)]
902pub enum ProcessRef {
903    Id(usize),
904    Name(String),
905    Unqualified(String),
906}
907
908#[derive(Debug, Clone, Default)]
909pub struct GraphImportOptions {
910    pub process_name: Option<String>,
911    pub process_id: Option<usize>,
912    pub process_definition: Option<ProcessDefinition>,
913    pub integrand_name: Option<String>,
914    pub overwrite: bool,
915    pub append: bool,
916}
917
918impl Serialize for ProcessRef {
919    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
920    where
921        S: serde::Serializer,
922    {
923        match self {
924            ProcessRef::Id(id) => serializer.serialize_u64(*id as u64),
925            ProcessRef::Name(name) => serializer.serialize_str(&format!("name:{name}")),
926            ProcessRef::Unqualified(value) => serializer.serialize_str(value),
927        }
928    }
929}
930
931impl<'de> Deserialize<'de> for ProcessRef {
932    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
933    where
934        D: serde::Deserializer<'de>,
935    {
936        use serde::de::{self, Visitor};
937        use std::fmt;
938
939        struct ProcessRefVisitor;
940
941        impl<'de> Visitor<'de> for ProcessRefVisitor {
942            type Value = ProcessRef;
943
944            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
945                formatter.write_str("a process reference string or numeric id")
946            }
947
948            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
949            where
950                E: de::Error,
951            {
952                usize::try_from(value)
953                    .map(ProcessRef::Id)
954                    .map_err(E::custom)
955            }
956
957            fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
958            where
959                E: de::Error,
960            {
961                usize::try_from(value)
962                    .map(ProcessRef::Id)
963                    .map_err(E::custom)
964            }
965
966            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
967            where
968                E: de::Error,
969            {
970                ProcessRef::from_str(value).map_err(E::custom)
971            }
972
973            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
974            where
975                E: de::Error,
976            {
977                self.visit_str(&value)
978            }
979        }
980
981        deserializer.deserialize_any(ProcessRefVisitor)
982    }
983}
984
985#[cfg(feature = "python")]
986impl<'a, 'py> pyo3::FromPyObject<'a, 'py> for ProcessRef {
987    type Error = pyo3::PyErr;
988
989    fn extract(obj: pyo3::Borrowed<'a, 'py, pyo3::types::PyAny>) -> pyo3::PyResult<Self> {
990        if let Ok(process_id) = <usize as pyo3::FromPyObject<'a, 'py>>::extract(obj) {
991            return Ok(ProcessRef::Id(process_id));
992        }
993
994        let selector = <String as pyo3::FromPyObject<'a, 'py>>::extract(obj).map_err(|_| {
995            pyo3::exceptions::PyTypeError::new_err(
996                "process selectors must be either an integer process id or a string selector",
997            )
998        })?;
999        ProcessRef::from_str(&selector).map_err(pyo3::exceptions::PyValueError::new_err)
1000    }
1001}
1002
1003impl FromStr for ProcessRef {
1004    type Err = String;
1005
1006    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
1007        if let Some(rest) = value.strip_prefix('#') {
1008            let id = rest
1009                .parse::<usize>()
1010                .map_err(|_| format!("Invalid process id in '{value}'"))?;
1011            return Ok(ProcessRef::Id(id));
1012        }
1013        if let Some(rest) = value.strip_prefix("name:") {
1014            if rest.is_empty() {
1015                return Err("Process name cannot be empty".to_string());
1016            }
1017            return Ok(ProcessRef::Name(rest.to_string()));
1018        }
1019        if value.is_empty() {
1020            return Err("Process reference cannot be empty".to_string());
1021        }
1022        Ok(ProcessRef::Unqualified(value.to_string()))
1023    }
1024}
1025
1026#[test]
1027fn try_complicated() {
1028    "GGHHH3loop_no_iterative_optimization_3L"
1029        .parse::<ProcessRef>()
1030        .unwrap();
1031    // ProcessRef::
1032}
1033
1034impl ProcessRef {
1035    pub fn resolve(&self, process_list: &ProcessList) -> Result<usize> {
1036        let process_count = process_list.processes.len();
1037        match self {
1038            ProcessRef::Id(id) => {
1039                if *id >= process_count {
1040                    return Err(eyre!(
1041                        "Process ID {} invalid, only {} processes available",
1042                        id,
1043                        process_count
1044                    ));
1045                }
1046                Ok(*id)
1047            }
1048            ProcessRef::Name(name) => process_list
1049                .processes
1050                .iter()
1051                .position(|p| p.definition.folder_name == *name)
1052                .ok_or_else(|| {
1053                    eyre!(
1054                        "No process named '{}'. Use 'display processes' to list available processes.",
1055                        name
1056                    )
1057                }),
1058            ProcessRef::Unqualified(value) => {
1059                let name_match = process_list
1060                    .processes
1061                    .iter()
1062                    .position(|p| p.definition.folder_name == *value);
1063                if let Ok(id) = value.parse::<usize>() {
1064                    let id_valid = id < process_count;
1065                    match (id_valid, name_match) {
1066                        (true, Some(_)) => Err(eyre!(
1067                            "Ambiguous process reference '{}'. Use '#{}' or 'name:{}' to disambiguate.",
1068                            value,
1069                            id,
1070                            value
1071                        )),
1072                        (true, None) => Ok(id),
1073                        (false, Some(index)) => Ok(index),
1074                        (false, None) => Err(eyre!(
1075                            "No process named '{}'. Use 'display processes' to list available processes.",
1076                            value
1077                        )),
1078                    }
1079                } else if let Some(index) = name_match {
1080                    Ok(index)
1081                } else {
1082                    Err(eyre!(
1083                        "No process named '{}'. Use 'display processes' to list available processes.",
1084                        value
1085                    ))
1086                }
1087            }
1088        }
1089    }
1090}
1091
1092pub trait ProcessListExt {
1093    fn find_integrand_ref(
1094        &self,
1095        process: Option<&ProcessRef>,
1096        integrand_name: Option<&String>,
1097    ) -> Result<(usize, String)>;
1098    fn get_amplitude_mut_ref(
1099        &mut self,
1100        process: Option<&ProcessRef>,
1101        integrand_name: Option<&String>,
1102    ) -> Result<&mut Amplitude>;
1103    fn get_cross_section_mut_ref(
1104        &mut self,
1105        process: Option<&ProcessRef>,
1106        integrand_name: Option<&String>,
1107    ) -> Result<&mut CrossSection>;
1108}
1109
1110impl ProcessListExt for ProcessList {
1111    fn find_integrand_ref(
1112        &self,
1113        process: Option<&ProcessRef>,
1114        integrand_name: Option<&String>,
1115    ) -> Result<(usize, String)> {
1116        let process_id = match process {
1117            Some(process_ref) => process_ref.resolve(self)?,
1118            None => self.find_process(None)?,
1119        };
1120        let integrand_name = self.processes[process_id]
1121            .collection
1122            .find_integrand(integrand_name.cloned())
1123            .with_note(|| format!("in process id {process_id}"))?;
1124        Ok((process_id, integrand_name))
1125    }
1126
1127    fn get_amplitude_mut_ref(
1128        &mut self,
1129        process: Option<&ProcessRef>,
1130        integrand_name: Option<&String>,
1131    ) -> Result<&mut Amplitude> {
1132        let (process_id, integrand_name) = self.find_integrand_ref(process, integrand_name)?;
1133        let process = &mut self.processes[process_id];
1134        match &mut process.collection {
1135            ProcessCollection::Amplitudes(amplitudes) => {
1136                amplitudes.get_mut(&integrand_name).ok_or_else(|| {
1137                    eyre!(
1138                        "No amplitude named '{}' in process '{}'",
1139                        integrand_name,
1140                        process.definition.folder_name
1141                    )
1142                })
1143            }
1144            ProcessCollection::CrossSections(_) => Err(eyre!(
1145                "Process '{}' does not contain amplitudes",
1146                process.definition.folder_name
1147            )),
1148        }
1149    }
1150
1151    fn get_cross_section_mut_ref(
1152        &mut self,
1153        process: Option<&ProcessRef>,
1154        integrand_name: Option<&String>,
1155    ) -> Result<&mut CrossSection> {
1156        let (process_id, integrand_name) = self.find_integrand_ref(process, integrand_name)?;
1157        let process = &mut self.processes[process_id];
1158        match &mut process.collection {
1159            ProcessCollection::CrossSections(crosssections) => {
1160                crosssections.get_mut(&integrand_name).ok_or_else(|| {
1161                    eyre!(
1162                        "No cross section named '{}' in process '{}'",
1163                        integrand_name,
1164                        process.definition.folder_name
1165                    )
1166                })
1167            }
1168            ProcessCollection::Amplitudes(_) => Err(eyre!(
1169                "Process '{}' does not contain crosssections",
1170                process.definition.folder_name
1171            )),
1172        }
1173    }
1174}
1175
1176pub trait SyncSettings {
1177    fn sync_settings(&self) -> Result<()>;
1178}
1179
1180impl SyncSettings for CLISettings {
1181    fn sync_settings(&self) -> Result<()> {
1182        // println!("Syncing settings {}", self.global.logfile_directive);
1183        set_file_log_filter(&self.global.logfile_directive)?;
1184        set_stderr_log_filter(&self.global.display_directive)?;
1185        set_log_style(self.global.log_style.to_runtime());
1186        Ok(())
1187    }
1188}
1189
1190// Static flag to control serialization behavior
1191static SERIALIZE_COMMANDS_AS_STRINGS: AtomicBool = AtomicBool::new(false);
1192
1193fn is_command_blocks_empty(command_blocks: &[CommandsBlock]) -> bool {
1194    command_blocks.is_empty()
1195}
1196
1197fn should_persist_command(command: &Commands) -> bool {
1198    !matches!(
1199        command,
1200        Commands::Quit(_) | Commands::StartCommandsBlock(_) | Commands::FinishCommandsBlock
1201    )
1202}
1203
1204/// Set whether CommandHistory should serialize as strings when the raw_string is available
1205pub fn set_serialize_commands_as_strings(value: bool) {
1206    SERIALIZE_COMMANDS_AS_STRINGS.store(value, std::sync::atomic::Ordering::Relaxed);
1207}
1208
1209/// Get the current setting for CommandHistory serialization behavior
1210pub fn get_serialize_commands_as_strings() -> bool {
1211    SERIALIZE_COMMANDS_AS_STRINGS.load(std::sync::atomic::Ordering::Relaxed)
1212}
1213
1214pub struct SerializeCommandsAsStringsGuard {
1215    previous: bool,
1216}
1217
1218impl SerializeCommandsAsStringsGuard {
1219    pub fn new(value: bool) -> Self {
1220        let previous = get_serialize_commands_as_strings();
1221        set_serialize_commands_as_strings(value);
1222        Self { previous }
1223    }
1224}
1225
1226impl Drop for SerializeCommandsAsStringsGuard {
1227    fn drop(&mut self) {
1228        set_serialize_commands_as_strings(self.previous);
1229    }
1230}
1231
1232/// Represents a command with optional raw string representation
1233///
1234/// This struct stores a parsed command or a template awaiting scoped variables,
1235/// plus the original string when available. This preserves the exact user input
1236/// while keeping structured command data accessible. Templates carry their own
1237/// required text in the command variant.
1238#[derive(Debug, Clone, PartialEq)]
1239pub struct CommandHistory {
1240    /// The parsed command or a template awaiting scoped variables
1241    pub command: Commands,
1242    /// The original string representation of the command, if available
1243    pub raw_string: Option<String>,
1244}
1245
1246impl JsonSchema for CommandHistory {
1247    fn schema_name() -> std::borrow::Cow<'static, str> {
1248        "CommandHistory".into()
1249    }
1250
1251    fn json_schema(generator: &mut schemars::SchemaGenerator) -> Schema {
1252        // Serialization exposes the command directly, including deferred template strings.
1253        schemars::json_schema!({
1254            "description": "A raw command string (including scoped templates) or a structured command.",
1255            "anyOf": [
1256                { "type": "string" },
1257                generator.subschema_for::<Commands>()
1258            ]
1259        })
1260    }
1261}
1262
1263impl Serialize for CommandHistory {
1264    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1265    where
1266        S: serde::Serializer,
1267    {
1268        if let Commands::CommandTemplate(raw) = &self.command {
1269            return raw.serialize(serializer);
1270        }
1271
1272        if get_serialize_commands_as_strings() {
1273            if let Some(ref raw_string) = self.raw_string {
1274                raw_string.serialize(serializer)
1275            } else {
1276                self.command.serialize(serializer)
1277            }
1278        } else {
1279            self.command.serialize(serializer)
1280        }
1281    }
1282}
1283
1284impl<'de> Deserialize<'de> for CommandHistory {
1285    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1286    where
1287        D: serde::Deserializer<'de>,
1288    {
1289        use serde::de::{self, Visitor};
1290        use std::fmt;
1291
1292        struct CommandHistoryVisitor;
1293
1294        impl<'de> Visitor<'de> for CommandHistoryVisitor {
1295            type Value = CommandHistory;
1296
1297            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1298                formatter.write_str("a string or a Commands structure")
1299            }
1300
1301            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1302            where
1303                E: de::Error,
1304            {
1305                CommandHistory::from_raw_string(value).map_err(|err| {
1306                    E::custom(format!(
1307                        "Failed to parse command string '{}': {}",
1308                        value, err
1309                    ))
1310                })
1311            }
1312
1313            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1314            where
1315                E: de::Error,
1316            {
1317                self.visit_str(&value)
1318            }
1319
1320            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1321            where
1322                A: de::SeqAccess<'de>,
1323            {
1324                // Handle TOML array format for enums like [Quit]
1325                let command =
1326                    Commands::deserialize(de::value::SeqAccessDeserializer::new(&mut seq))?;
1327                Ok(CommandHistory {
1328                    command,
1329                    raw_string: None,
1330                })
1331            }
1332
1333            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
1334            where
1335                A: de::MapAccess<'de>,
1336            {
1337                // Handle map format for enums
1338                let command = Commands::deserialize(de::value::MapAccessDeserializer::new(map))?;
1339                Ok(CommandHistory {
1340                    command,
1341                    raw_string: None,
1342                })
1343            }
1344        }
1345
1346        deserializer.deserialize_any(CommandHistoryVisitor)
1347    }
1348}
1349
1350impl CommandHistory {
1351    /// Create a new CommandHistory with just a command (no raw string)
1352    pub fn new(command: Commands) -> Self {
1353        Self {
1354            command,
1355            raw_string: None,
1356        }
1357    }
1358
1359    /// Create a new CommandHistory with both command and raw string
1360    pub fn new_with_raw(command: Commands, raw_string: String) -> Self {
1361        Self {
1362            command,
1363            raw_string: Some(raw_string),
1364        }
1365    }
1366
1367    pub fn new_template(raw_string: String) -> Self {
1368        Self::new(Commands::CommandTemplate(raw_string))
1369    }
1370
1371    pub fn is_template(&self) -> bool {
1372        matches!(self.command, Commands::CommandTemplate(_))
1373    }
1374
1375    pub fn raw_string(&self) -> Option<&str> {
1376        match &self.command {
1377            Commands::CommandTemplate(raw) => Some(raw),
1378            _ => self.raw_string.as_deref(),
1379        }
1380    }
1381
1382    pub fn semantically_eq(&self, other: &Self) -> bool {
1383        self.command == other.command
1384    }
1385
1386    /// Create a CommandHistory from a command (alias for new)
1387    pub fn from_command(command: Commands) -> Self {
1388        Self::new(command)
1389    }
1390
1391    /// Parse a raw string into a CommandHistory
1392    ///
1393    /// This function attempts to parse the raw string using clap, and if successful,
1394    /// creates a CommandHistory with both the parsed command and the original string.
1395    pub fn from_raw_string(raw_string: &str) -> Result<Self, clap::Error> {
1396        use clap::error::ErrorKind;
1397
1398        let args = split_command_line(raw_string)
1399            .map(normalize_clap_args)
1400            .map_err(|_| {
1401                clap::Error::raw(
1402                    ErrorKind::InvalidValue,
1403                    "Could not parse command: unmatched quotes or trailing escape",
1404                )
1405            })?;
1406
1407        match Self::from_args_and_raw(args, raw_string.to_string()) {
1408            Ok(command) => Ok(command),
1409            Err(_) if contains_placeholder(raw_string) => Ok(Self::new_template(raw_string.into())),
1410            Err(err) => Err(err),
1411        }
1412    }
1413
1414    pub fn from_args_and_raw(args: Vec<String>, raw_string: String) -> Result<Self, clap::Error> {
1415        use crate::Repl;
1416        use clap::Parser;
1417
1418        let cli = Repl::try_parse_from(
1419            std::iter::once("gammaloop").chain(args.iter().map(String::as_str)),
1420        )?;
1421
1422        Ok(Self::new_with_raw(cli.command, raw_string))
1423    }
1424}
1425
1426#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema, PartialEq)]
1427#[serde(default, deny_unknown_fields)]
1428pub struct RunHistory {
1429    /// Default runtime settings restored before replaying the recorded commands.
1430    #[serde(skip_serializing_if = "IsDefault::is_default")]
1431    pub default_runtime_settings: RuntimeSettings,
1432
1433    /// State and global CLI settings captured with this run history.
1434    #[serde(skip_serializing_if = "IsDefault::is_default")]
1435    pub cli_settings: CLISettings,
1436
1437    /// Named reusable command sequences declared by run cards.
1438    #[serde(skip_serializing_if = "is_command_blocks_empty")]
1439    pub command_blocks: Vec<CommandsBlock>,
1440    // #[serde(with = "serde_yaml::with::singleton_map_recursive")]
1441    // #[schemars(with = "Vec<CommandHistory>")]
1442    /// Ordered top-level commands persisted for replay.
1443    pub commands: Vec<CommandHistory>,
1444}
1445
1446#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema, PartialEq)]
1447#[serde(default, deny_unknown_fields)]
1448pub struct CommandsBlock {
1449    pub name: String,
1450    pub commands: Vec<CommandHistory>,
1451}
1452
1453#[derive(Debug, Deserialize, Default)]
1454#[serde(default, deny_unknown_fields)]
1455struct RawRunHistoryToml {
1456    default_runtime_settings: RuntimeSettings,
1457    cli_settings: CLISettings,
1458    command_blocks: Vec<RawCommandsBlockToml>,
1459    commands: Vec<TomlValue>,
1460}
1461
1462#[derive(Debug, Deserialize, Default)]
1463#[serde(default, deny_unknown_fields)]
1464struct RawCommandsBlockToml {
1465    name: String,
1466    commands: Vec<TomlValue>,
1467}
1468
1469impl CommandsBlock {
1470    pub fn semantically_eq(&self, other: &Self) -> bool {
1471        self.name == other.name
1472            && self.commands.len() == other.commands.len()
1473            && self
1474                .commands
1475                .iter()
1476                .zip(other.commands.iter())
1477                .all(|(left, right)| left.semantically_eq(right))
1478    }
1479}
1480
1481impl SmartSerde for RunHistory {
1482    fn has_schema_path(&self, online: bool) -> Option<Result<PathBuf>> {
1483        Some(get_schema_folder(online).map(|f| f.join("runhistory.json")))
1484    }
1485}
1486
1487impl RunHistory {
1488    pub fn freeze_boot_settings_from(&mut self, boot_run_history: &RunHistory) {
1489        self.cli_settings.global = boot_run_history.cli_settings.global.clone();
1490        self.default_runtime_settings = boot_run_history.default_runtime_settings.clone();
1491    }
1492
1493    pub fn frozen_boot_settings_match(&self, boot_run_history: &RunHistory) -> bool {
1494        self.cli_settings.global == boot_run_history.cli_settings.global
1495            && self.default_runtime_settings == boot_run_history.default_runtime_settings
1496    }
1497
1498    /// Add a command to the run history
1499    pub fn push(&mut self, command: Commands) {
1500        self.push_with_raw(command, None);
1501    }
1502
1503    /// Add a command with optional raw string to the run history
1504    ///
1505    /// If raw_string is provided, it will be stored alongside the command
1506    /// for potential later serialization as a string.
1507    pub fn push_with_raw(&mut self, command: Commands, raw_string: Option<String>) {
1508        if should_persist_command(&command) {
1509            self.commands.push(CommandHistory {
1510                command,
1511                raw_string,
1512            });
1513        }
1514    }
1515
1516    pub fn schema() -> Schema {
1517        schema_for!(RunHistory)
1518    }
1519
1520    pub fn validate(&self) -> Result<()> {
1521        let mut seen_names = HashSet::with_capacity(self.command_blocks.len());
1522        for block in &self.command_blocks {
1523            if block.name.trim().is_empty() {
1524                return Err(eyre!(
1525                    "Run card `command_blocks` contains a block with an empty name"
1526                ));
1527            }
1528            if !seen_names.insert(block.name.clone()) {
1529                return Err(eyre!(
1530                    "Run card `command_blocks` contains duplicate block name '{}'",
1531                    block.name
1532                ));
1533            }
1534        }
1535        Ok(())
1536    }
1537
1538    pub fn command_block(&self, name: &str) -> Option<&CommandsBlock> {
1539        self.command_blocks.iter().find(|block| block.name == name)
1540    }
1541
1542    pub fn command_block_placeholder_names(&self, name: &str) -> BTreeSet<String> {
1543        self.command_block_placeholder_specs(name)
1544            .into_iter()
1545            .map(|spec| spec.name)
1546            .collect()
1547    }
1548
1549    pub fn command_block_placeholder_specs(&self, name: &str) -> BTreeSet<PlaceholderSpec> {
1550        let mut placeholders = BTreeSet::new();
1551        let mut visited = HashSet::new();
1552        self.collect_command_block_placeholder_specs(name, &mut visited, &mut placeholders);
1553        placeholders
1554    }
1555
1556    fn collect_command_block_placeholder_specs(
1557        &self,
1558        name: &str,
1559        visited: &mut HashSet<String>,
1560        placeholders: &mut BTreeSet<PlaceholderSpec>,
1561    ) {
1562        if !visited.insert(name.to_string()) {
1563            return;
1564        }
1565
1566        let Some(block) = self.command_block(name) else {
1567            return;
1568        };
1569
1570        for command in &block.commands {
1571            if let Some(raw) = command.raw_string() {
1572                placeholders.extend(placeholder_specs(raw));
1573            }
1574            let Commands::Run(run) = &command.command else {
1575                continue;
1576            };
1577            for nested_name in run.selected_block_names() {
1578                let mut nested_placeholders = BTreeSet::new();
1579                self.collect_command_block_placeholder_specs(
1580                    nested_name,
1581                    visited,
1582                    &mut nested_placeholders,
1583                );
1584                for defined in &run.defines {
1585                    nested_placeholders.retain(|spec| spec.name.as_str() != defined.key.as_str());
1586                }
1587                placeholders.extend(nested_placeholders);
1588            }
1589        }
1590        visited.remove(name);
1591    }
1592
1593    pub fn select_command_blocks(
1594        &self,
1595        selected_block_names: &[String],
1596    ) -> Result<Vec<CommandsBlock>> {
1597        let mut selected = Vec::with_capacity(selected_block_names.len());
1598        for name in selected_block_names {
1599            let block = self.command_block(name).ok_or_else(|| {
1600                eyre!(
1601                    "Unknown command block '{}'. Available command blocks: {}",
1602                    name,
1603                    self.command_blocks
1604                        .iter()
1605                        .map(|block| block.name.as_str())
1606                        .collect::<Vec<_>>()
1607                        .join(", ")
1608                )
1609            })?;
1610            selected.push(block.clone());
1611        }
1612        Ok(selected)
1613    }
1614
1615    pub fn conflicting_command_block_names(&self, command_blocks: &[CommandsBlock]) -> Vec<String> {
1616        command_blocks
1617            .iter()
1618            .filter_map(|new_block| match self.command_block(&new_block.name) {
1619                Some(existing_block) if !existing_block.semantically_eq(new_block) => {
1620                    Some(new_block.name.clone())
1621                }
1622                _ => None,
1623            })
1624            .collect()
1625    }
1626
1627    pub fn merge_command_blocks_with_overwrite(
1628        &mut self,
1629        command_blocks: &[CommandsBlock],
1630        overwrite_conflicts: bool,
1631    ) -> Result<()> {
1632        for new_block in command_blocks {
1633            match self
1634                .command_blocks
1635                .iter()
1636                .position(|existing| existing.name == new_block.name)
1637            {
1638                Some(index) if self.command_blocks[index].semantically_eq(new_block) => {}
1639                Some(index) if overwrite_conflicts => {
1640                    self.command_blocks[index] = new_block.clone();
1641                }
1642                Some(_) => {
1643                    return Err(eyre!(
1644                        "Run card command block '{}' redefines an existing block with different commands",
1645                        new_block.name
1646                    ));
1647                }
1648                None => self.command_blocks.push(new_block.clone()),
1649            }
1650        }
1651        self.validate()
1652    }
1653
1654    pub fn merge_command_blocks(&mut self, command_blocks: &[CommandsBlock]) -> Result<()> {
1655        self.merge_command_blocks_with_overwrite(command_blocks, false)
1656    }
1657
1658    pub fn apply_session_settings(
1659        &self,
1660        global_settings: &mut CLISettings,
1661        default_runtime_settings: &mut RuntimeSettings,
1662    ) -> Result<()> {
1663        if self.cli_settings.global != GlobalSettings::default() {
1664            global_settings.global = self.cli_settings.global.clone();
1665            global_settings.sync_settings()?;
1666        }
1667        if self.default_runtime_settings != RuntimeSettings::default() {
1668            *default_runtime_settings = self.default_runtime_settings.clone();
1669        }
1670        Ok(())
1671    }
1672
1673    pub fn run(
1674        &mut self,
1675        state: &mut State,
1676        global_settings: &mut CLISettings,
1677        default_runtime_settings: &mut RuntimeSettings,
1678    ) -> Result<ControlFlow<SaveState>> {
1679        let mut session_state = crate::session::CliSessionState::default();
1680        let mut session = crate::session::CliSession::new(
1681            state,
1682            self,
1683            global_settings,
1684            default_runtime_settings,
1685            &mut session_state,
1686        );
1687        session.replay_run_history()
1688    }
1689
1690    pub(crate) fn filtered_for_save(&self) -> Self {
1691        let mut filtered = self.clone();
1692        filtered.commands.retain(|command_history| {
1693            command_history.is_template() || should_persist_command(&command_history.command)
1694        });
1695        filtered
1696    }
1697
1698    pub(crate) fn to_toml_string(&self, serialize_commands_as_strings: bool) -> Result<String> {
1699        let _serialize_commands_guard =
1700            SerializeCommandsAsStringsGuard::new(serialize_commands_as_strings);
1701        render_smart_toml(&self.filtered_for_save())
1702    }
1703
1704    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
1705        let path = path.as_ref();
1706        debug!("Loaded run history from file {}", path.display());
1707
1708        let runhistory = match path.extension().and_then(|ext| ext.to_str()) {
1709            Some("toml") => Self::load_toml(path)?,
1710            _ => Self::from_file(path, "run history")?,
1711        };
1712        runhistory.validate()?;
1713        Ok(runhistory)
1714    }
1715
1716    pub fn save_toml(
1717        &self,
1718        root_folder: &Path,
1719        override_state_file: bool,
1720        _strict: bool,
1721    ) -> Result<()> {
1722        self.filtered_for_save()
1723            .to_file(root_folder.join("run.toml"), override_state_file)?;
1724
1725        //Self::schema().to_file(root_folder.join("run_schema.json"))?;
1726        Ok(())
1727    }
1728
1729    pub fn save_yaml(
1730        &self,
1731        root_folder: &Path,
1732        override_state_file: bool,
1733        _strict: bool,
1734    ) -> Result<()> {
1735        self.filtered_for_save()
1736            .to_file(root_folder.join("run.yaml"), override_state_file)?;
1737        //Self::schema().to_file(root_folder.join("run_schema.json"))?;
1738        Ok(())
1739    }
1740
1741    fn load_toml(path: &Path) -> Result<Self> {
1742        let raw = fs::read_to_string(path)
1743            .with_context(|| format!("Could not open run history file {}", path.display()))?;
1744        let raw_run_history: RawRunHistoryToml =
1745            toml::from_str(&raw).wrap_err("Error parsing run history toml")?;
1746
1747        let commands = raw_run_history
1748            .commands
1749            .into_iter()
1750            .enumerate()
1751            .map(|(index, value)| {
1752                parse_toml_command_history(value, &format!("top-level command #{}", index + 1))
1753            })
1754            .collect::<Result<Vec<_>>>()?;
1755
1756        let command_blocks = raw_run_history
1757            .command_blocks
1758            .into_iter()
1759            .map(|block| {
1760                let RawCommandsBlockToml { name, commands } = block;
1761                let commands = commands
1762                    .into_iter()
1763                    .enumerate()
1764                    .map(|(index, value)| {
1765                        parse_toml_command_history(
1766                            value,
1767                            &format!("command block '{}' command #{}", name, index + 1),
1768                        )
1769                    })
1770                    .collect::<Result<Vec<_>>>()?;
1771                Ok(CommandsBlock { name, commands })
1772            })
1773            .collect::<Result<Vec<_>>>()?;
1774
1775        Ok(Self {
1776            default_runtime_settings: raw_run_history.default_runtime_settings,
1777            cli_settings: raw_run_history.cli_settings,
1778            command_blocks,
1779            commands,
1780        })
1781    }
1782}
1783
1784fn parse_toml_command_history(value: TomlValue, context: &str) -> Result<CommandHistory> {
1785    match value {
1786        TomlValue::String(raw) => CommandHistory::from_raw_string(&raw)
1787            .map_err(|err| eyre!("Failed to parse {} '{}': {}", context, raw, err)),
1788        other => other
1789            .try_into::<CommandHistory>()
1790            .map_err(|err| eyre!("Failed to parse {}: {}", context, err)),
1791    }
1792}
1793
1794#[cfg_attr(
1795    feature = "python",
1796    pyo3::pyclass(from_py_object, unsendable, name = "GammaLoopState")
1797)]
1798#[derive(Clone)]
1799pub struct State {
1800    /// Active physics model used to interpret processes and integrands.
1801    pub model: Model,
1802    /// Numerical input-parameter values currently applied to the model.
1803    pub model_parameters: InputParamCard<F<f64>>,
1804    /// Imported processes together with their generated integrands.
1805    pub process_list: ProcessList,
1806    /// Generation provenance indexed by process and integrand.
1807    pub generation_summaries: BTreeMap<IntegrandGenerationSummaryKey, IntegrandGenerationSummary>,
1808}
1809
1810const STATE_MANIFEST_FILE: &str = "state_manifest.toml";
1811const INTEGRAND_GENERATION_SUMMARY_FILE: &str = "generation_summary.json";
1812// Version 20 removes the physical-cut reversal mask from threshold runtime data.
1813// Projected E-surfaces now certify their own oriented momentum boundary.
1814// Version 19 stores ordered generated representations and their separate expression,
1815// evaluator and denominator payloads using main's evaluator format. Reject older
1816// main and combined-factorization states before importing symbolic data.
1817// Version 15 gives each orientation-specific Fermi sector a one-entry evaluator
1818// catalogue indexed locally from zero. Older full-catalogue sectors must be regenerated.
1819// Version 14 stores one source-frame sign per generated CFF and rational component,
1820// replacing the duplicate core/denominator signs in the positional bincode layout.
1821// Version 13 persists the selected medium in graph parameter builders. Amplitude graph
1822// terms store denominator H-surfaces and zero-temperature Fermi-surface evaluators.
1823// Frozen SymJIT, C++, and assembly modes for amplitudes and cross sections store
1824// CompilationOptionsSnapshot, including jit_direct_translation:
1825// SymJIT replaces its bare optimization level, while C++/assembly snapshots gain the field.
1826// Older positional bincode layouts must be regenerated.
1827// Version 12 names square roots OnShellEnergy and energy sums Esurface. Reject older
1828// states before Symbolica import can assign the new meaning to an old Esurface atom.
1829// Version 11 persists function inlining policies and caller-scope alias metadata.
1830// Version 10 records UFO and subgraph printer registrations, including symbols removed
1831// from a restricted model. Older archives cannot restore those callbacks and must be regenerated.
1832// Version 9 combines the Symbolica 3 evaluator/CFF payloads with advanced sampling
1833// and multiplier layouts. Earlier states must be regenerated.
1834// Version 8 adds multiplier function-map metadata and on-shell energy inputs to
1835// the positional bincode layouts. Older generated states must be regenerated.
1836// Version 7 stores CFF coefficients using native Rational encoding.
1837// Version 7 stores master-topology amplitude metadata and removes the coerced
1838// common-parent LU subspaces. Older generated states must be regenerated.
1839// Version 6 removes obsolete deferred-integrand fields from the positional
1840// amplitude and cut-integrand layouts.
1841// Version 5 persists component-local generated-CFF ownership and prefactor
1842// metadata. Older states use a previous positional bincode layout and must be
1843// regenerated rather than decoded as the new expression type.
1844// Local UV forest contributions remain compatible with this layout because
1845// they are combined into one persisted integrand before evaluator construction.
1846// Version 18 combines the canonical FeynKit model and current compact runtime layout.
1847// Older states from either development branch must be regenerated.
1848// Version 19 retains tensor interfaces in runtime graph fragments and numerator
1849// definitions. Older positional archives must be regenerated.
1850// Version 20 also retains the graph's global numerator and projector interfaces.
1851// Version 21 stores fully indexed tensor interfaces without PartialIndex wire tags.
1852// Older positional archives must be regenerated; unresolved ports are not assigned indices.
1853// Version 22 combines indexed FeynKit tensors with ordered CFF/LTD runtime payloads.
1854// Main version20 and published FeynKit version21 have incompatible layouts and
1855// must be rejected before model parsing, symbolic import or process decoding.
1856// Version 23 persists each graph's model as a structural fingerprint and rebinds
1857// graphs to the state's model.json instead of embedding a model copy per graph.
1858// It also keeps full finalized cuts beside selected cuts and maps compact integrand
1859// terms to their stored source graphs. Older positional archives must be regenerated.
1860// Version 24 adds the fixed on-shell spatial references, exact subtraction
1861// velocities and axis-angle rotations to the shared-model graph layout.
1862// States from both version-23 branches require regeneration.
1863// Version 25 stores regional tensor interfaces and raw leaf ports in tensor archive v2.
1864const CURRENT_STATE_MANIFEST_VERSION: u32 = 25;
1865const GENERATION_THREAD_STACK_SIZE_BYTES: usize = 32 * 1024 * 1024;
1866
1867#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1868#[serde(deny_unknown_fields)]
1869struct StateManifest {
1870    version: u32,
1871    #[serde(default)]
1872    ufo_print_symbols: Vec<String>,
1873    #[serde(default)]
1874    linnet_subgraph_print_labels: Vec<String>,
1875}
1876
1877impl Default for StateManifest {
1878    fn default() -> Self {
1879        Self {
1880            version: CURRENT_STATE_MANIFEST_VERSION,
1881            ufo_print_symbols: Vec::new(),
1882            linnet_subgraph_print_labels: Vec::new(),
1883        }
1884    }
1885}
1886
1887fn ensure_supported_state_manifest_version(manifest: &StateManifest) -> Result<()> {
1888    if manifest.version < CURRENT_STATE_MANIFEST_VERSION {
1889        return Err(eyre!(
1890            "State version {} predates the supported version {} and cannot be migrated. Please regenerate the saved state with this gammaloop binary.",
1891            manifest.version,
1892            CURRENT_STATE_MANIFEST_VERSION
1893        ));
1894    }
1895    if manifest.version > CURRENT_STATE_MANIFEST_VERSION {
1896        return Err(eyre!(
1897            "State version {} is newer than this binary supports (max {}). Please upgrade gammaloop.",
1898            manifest.version,
1899            CURRENT_STATE_MANIFEST_VERSION
1900        ));
1901    }
1902
1903    Ok(())
1904}
1905
1906fn validate_state_layout(manifest: &StateManifest, save_path: &Path) -> Result<()> {
1907    ensure_supported_state_manifest_version(manifest)?;
1908
1909    match manifest.version {
1910        CURRENT_STATE_MANIFEST_VERSION => {
1911            if !save_path.join("symbolica_state.bin").exists() {
1912                return Err(eyre!(
1913                    "Saved state at '{}' is missing required file symbolica_state.bin",
1914                    save_path.display()
1915                ));
1916            }
1917            if !save_path.join("processes").exists() {
1918                return Err(eyre!(
1919                    "Saved state at '{}' is missing required folder processes/",
1920                    save_path.display()
1921                ));
1922            }
1923            if !save_path.join("model.json").exists() {
1924                return Err(eyre!(
1925                    "Saved state at '{}' is missing required file model.json",
1926                    save_path.display()
1927                ));
1928            }
1929            Ok(())
1930        }
1931        _ => Err(eyre!(
1932            "State version {} is not supported by this binary.",
1933            manifest.version
1934        )),
1935    }
1936}
1937
1938#[derive(Debug, Clone, PartialEq, Eq)]
1939pub enum StateFolderKind {
1940    /// The configured state path does not exist.
1941    Missing,
1942    /// The state directory is empty apart from its optional `logs` directory.
1943    Scratch,
1944    /// The directory contains data but no state manifest.
1945    Unmanifested,
1946    /// The directory contains a supported manifest and all required state files.
1947    Saved,
1948    /// The path cannot be used as a saved state; the payload explains why.
1949    Invalid(String),
1950}
1951
1952fn is_scratch_state_entry(entry: &fs::DirEntry) -> bool {
1953    entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false)
1954        && entry.file_name().to_string_lossy() == "logs"
1955}
1956
1957pub fn classify_state_folder(save_path: &Path) -> Result<StateFolderKind> {
1958    if !save_path.exists() {
1959        return Ok(StateFolderKind::Missing);
1960    }
1961    if !save_path.is_dir() {
1962        return Ok(StateFolderKind::Invalid(format!(
1963            "'{}' exists but is not a directory",
1964            save_path.display()
1965        )));
1966    }
1967
1968    let manifest_path = save_path.join(STATE_MANIFEST_FILE);
1969    if manifest_path.exists() {
1970        let manifest = load_state_manifest(save_path)?;
1971        return Ok(match validate_state_layout(&manifest, save_path) {
1972            Ok(()) => StateFolderKind::Saved,
1973            Err(err) => StateFolderKind::Invalid(err.to_string()),
1974        });
1975    }
1976
1977    let mut entries = fs::read_dir(save_path)
1978        .with_context(|| format!("Trying to read state folder '{}'", save_path.display()))?;
1979    if entries.by_ref().all(|entry| {
1980        entry
1981            .map(|entry| is_scratch_state_entry(&entry))
1982            .unwrap_or(false)
1983    }) {
1984        return Ok(StateFolderKind::Scratch);
1985    }
1986
1987    Ok(StateFolderKind::Unmanifested)
1988}
1989
1990fn load_state_manifest(save_path: &Path) -> Result<StateManifest> {
1991    let manifest_path = save_path.join(STATE_MANIFEST_FILE);
1992    let raw_manifest = fs::read_to_string(&manifest_path).with_context(|| {
1993        format!(
1994            "Trying to read state manifest file {}",
1995            manifest_path.display()
1996        )
1997    })?;
1998    let manifest = toml::from_str::<StateManifest>(&raw_manifest).map_err(|error| {
1999        eyre!(
2000            "Trying to parse state manifest file {}: {error}",
2001            manifest_path.display()
2002        )
2003    })?;
2004    ensure_supported_state_manifest_version(&manifest)?;
2005    Ok(manifest)
2006}
2007
2008fn save_state_manifest(save_path: &Path) -> Result<()> {
2009    // Symbolica exports the entire symbol registry, including couplings removed from the
2010    // active model by restrictions. Its archive cannot serialize their print callbacks.
2011    let mut ufo_print_symbols: Vec<_> = symbolica::state::State::symbol_iter()
2012        .filter(|(symbol, _)| {
2013            symbol.get_namespace() == "UFO" && symbol.get_print_function().is_some()
2014        })
2015        .map(|(symbol, _)| symbol.get_stripped_name().to_owned())
2016        .collect();
2017    ufo_print_symbols.sort_unstable();
2018    let mut linnet_subgraph_print_labels: Vec<_> = symbolica::state::State::symbol_iter()
2019        .filter(|(symbol, _)| {
2020            symbol.get_namespace() == "linnet" && symbol.get_print_function().is_some()
2021        })
2022        .filter_map(|(symbol, _)| {
2023            symbol
2024                .get_stripped_name()
2025                .strip_prefix("S_")
2026                .map(str::to_owned)
2027        })
2028        .collect();
2029    linnet_subgraph_print_labels.sort_unstable();
2030    let manifest = StateManifest {
2031        ufo_print_symbols,
2032        linnet_subgraph_print_labels,
2033        ..StateManifest::default()
2034    };
2035    let raw_manifest =
2036        toml::to_string_pretty(&manifest).context("Trying to serialize state manifest to TOML")?;
2037    fs::write(save_path.join(STATE_MANIFEST_FILE), raw_manifest).with_context(|| {
2038        format!(
2039            "Trying to write state manifest file {}",
2040            save_path.join(STATE_MANIFEST_FILE).display()
2041        )
2042    })?;
2043    Ok(())
2044}
2045
2046fn integrand_generation_summary_path(
2047    root_folder: &Path,
2048    process: &Process,
2049    integrand_name: &str,
2050) -> PathBuf {
2051    let process_kind_folder = match &process.collection {
2052        ProcessCollection::Amplitudes(_) => "amplitudes",
2053        ProcessCollection::CrossSections(_) => "cross_sections",
2054    };
2055
2056    root_folder
2057        .join("processes")
2058        .join(process_kind_folder)
2059        .join(&process.definition.folder_name)
2060        .join(integrand_name)
2061        .join(INTEGRAND_GENERATION_SUMMARY_FILE)
2062}
2063
2064fn process_kind_folder(root_folder: &Path, process: &Process) -> PathBuf {
2065    let process_kind_folder = match &process.collection {
2066        ProcessCollection::Amplitudes(_) => "amplitudes",
2067        ProcessCollection::CrossSections(_) => "cross_sections",
2068    };
2069
2070    root_folder.join("processes").join(process_kind_folder)
2071}
2072
2073fn process_artifact_folder(root_folder: &Path, process: &Process) -> PathBuf {
2074    process_kind_folder(root_folder, process).join(&process.definition.folder_name)
2075}
2076
2077fn integrand_artifact_folder(
2078    root_folder: &Path,
2079    process: &Process,
2080    integrand_name: &str,
2081) -> PathBuf {
2082    process_artifact_folder(root_folder, process).join(integrand_name)
2083}
2084
2085fn generated_integrand_artifact_path(
2086    root_folder: &Path,
2087    process: &Process,
2088    integrand_name: &str,
2089) -> PathBuf {
2090    integrand_artifact_folder(root_folder, process, integrand_name).join("integrand")
2091}
2092
2093fn ensure_existing_path_under_root(path: &Path, root: &Path, description: &str) -> Result<PathBuf> {
2094    let canonical_root = root
2095        .canonicalize()
2096        .with_context(|| format!("Trying to resolve artifact cleanup root {}", root.display()))?;
2097    let canonical_path = path.canonicalize().with_context(|| {
2098        format!(
2099            "Trying to resolve {} path {} before removal",
2100            description,
2101            path.display()
2102        )
2103    })?;
2104    if !canonical_path.starts_with(&canonical_root) {
2105        return Err(eyre!(
2106            "Refusing to remove {} path {} because it resolves outside {}",
2107            description,
2108            canonical_path.display(),
2109            canonical_root.display()
2110        ));
2111    }
2112    Ok(canonical_path)
2113}
2114
2115fn remove_file_if_exists_under_root(path: &Path, root: &Path, description: &str) -> Result<bool> {
2116    if !path.try_exists().with_context(|| {
2117        format!(
2118            "Trying to check whether {} path {} exists",
2119            description,
2120            path.display()
2121        )
2122    })? {
2123        return Ok(false);
2124    }
2125    let canonical_path = ensure_existing_path_under_root(path, root, description)?;
2126    fs::remove_file(path).with_context(|| {
2127        format!(
2128            "Trying to remove {} path {}",
2129            description,
2130            canonical_path.display()
2131        )
2132    })?;
2133    Ok(true)
2134}
2135
2136fn remove_dir_if_exists_under_root(path: &Path, root: &Path, description: &str) -> Result<bool> {
2137    if !path.try_exists().with_context(|| {
2138        format!(
2139            "Trying to check whether {} path {} exists",
2140            description,
2141            path.display()
2142        )
2143    })? {
2144        return Ok(false);
2145    }
2146    let canonical_path = ensure_existing_path_under_root(path, root, description)?;
2147    fs::remove_dir_all(path).with_context(|| {
2148        format!(
2149            "Trying to remove {} path {}",
2150            description,
2151            canonical_path.display()
2152        )
2153    })?;
2154    Ok(true)
2155}
2156
2157fn remove_saved_process_artifacts(root_folder: &Path, process: &Process) -> Result<bool> {
2158    let root = process_kind_folder(root_folder, process);
2159    let path = process_artifact_folder(root_folder, process);
2160    remove_dir_if_exists_under_root(&path, &root, "saved process artifacts")
2161}
2162
2163fn remove_saved_integrand_artifacts(
2164    root_folder: &Path,
2165    process: &Process,
2166    integrand_name: &str,
2167) -> Result<bool> {
2168    let root = process_artifact_folder(root_folder, process);
2169    let path = integrand_artifact_folder(root_folder, process, integrand_name);
2170    remove_dir_if_exists_under_root(&path, &root, "saved integrand artifacts")
2171}
2172
2173fn validate_output_name(value: &str, flag_name: &str) -> Result<()> {
2174    if value.trim().is_empty() {
2175        return Err(eyre!("{flag_name} must not be empty"));
2176    }
2177    Ok(())
2178}
2179
2180fn rename_process_integrand(integrand: Option<&mut ProcessIntegrand>, new_name: &str) {
2181    let Some(integrand) = integrand else {
2182        return;
2183    };
2184    let _ = integrand.get_mut_settings();
2185    match integrand {
2186        ProcessIntegrand::Amplitude(amplitude) => {
2187            amplitude.data.name = new_name.to_string();
2188        }
2189        ProcessIntegrand::CrossSection(cross_section) => {
2190            cross_section.data.name = new_name.to_string();
2191        }
2192    }
2193}
2194
2195fn load_integrand_generation_summaries(
2196    root_folder: &Path,
2197    process_list: &ProcessList,
2198) -> Result<BTreeMap<IntegrandGenerationSummaryKey, IntegrandGenerationSummary>> {
2199    let mut summaries = BTreeMap::new();
2200
2201    for (process_id, process) in process_list.processes.iter().enumerate() {
2202        for integrand_name in process.collection.get_integrand_names() {
2203            let summary_path =
2204                integrand_generation_summary_path(root_folder, process, integrand_name);
2205            if !summary_path.exists() {
2206                continue;
2207            }
2208
2209            let raw_summary = fs::read_to_string(&summary_path).with_context(|| {
2210                format!(
2211                    "Trying to read integrand generation summary {}",
2212                    summary_path.display()
2213                )
2214            })?;
2215            let mut summary: IntegrandGenerationSummary = serde_json::from_str(&raw_summary)
2216                .with_context(|| {
2217                    format!(
2218                        "Trying to parse integrand generation summary {}",
2219                        summary_path.display()
2220                    )
2221                })?;
2222            // Reports persist the process id from the state that generated them. A
2223            // selective load renumbers the in-memory process list densely, so the
2224            // summary must follow its owning process rather than retain a stale id.
2225            for report in &mut summary.reports {
2226                report.process_id = process_id;
2227            }
2228            summaries.insert(
2229                IntegrandGenerationSummaryKey {
2230                    process_id,
2231                    integrand_name: integrand_name.to_string(),
2232                },
2233                summary,
2234            );
2235        }
2236    }
2237
2238    Ok(summaries)
2239}
2240
2241impl State {
2242    fn overridable_model_parameter_names(card: &InputParamCard<F<f64>>) -> Vec<String> {
2243        let mut names = card
2244            .keys()
2245            .map(|symbol| symbol.to_string())
2246            .collect::<Vec<_>>();
2247        names.sort();
2248        names
2249    }
2250
2251    fn resolve_overridable_model_parameter_type(
2252        model: &Model,
2253        card: &InputParamCard<F<f64>>,
2254        parameter_name: &str,
2255    ) -> Result<gammalooprs::model::ParameterType> {
2256        let possibilities = Self::overridable_model_parameter_names(card);
2257        let parameter_type = external_model_parameter_type(model, parameter_name)
2258            .ok_or_else(|| eyre!("No model parameter named '{parameter_name}'"))
2259            .with_note(|| {
2260                format!(
2261                    "Possible model parameters are: {}",
2262                    possibilities.join(", ")
2263                )
2264            })?;
2265
2266        let symbol = UFOSymbol::from(parameter_name);
2267        if !card.contains_key(&symbol) {
2268            return Err(eyre!(
2269                "Model parameter '{parameter_name}' cannot be overridden because it is not present in the shared top-level model_parameters.json"
2270            ))
2271            .with_note(|| format!("Possible model parameters are: {}", possibilities.join(", ")));
2272        }
2273
2274        Ok(parameter_type)
2275    }
2276
2277    pub fn find_generated_integrand_ref_by_name(
2278        &self,
2279        integrand_name: &str,
2280    ) -> Result<(usize, String)> {
2281        let matches = self
2282            .process_list
2283            .processes
2284            .iter()
2285            .enumerate()
2286            .filter_map(|(process_id, process)| {
2287                let found = match &process.collection {
2288                    ProcessCollection::Amplitudes(amplitudes) => amplitudes
2289                        .get(integrand_name)
2290                        .filter(|amplitude| amplitude.integrand.is_some())
2291                        .map(|_| (process_id, process.definition.folder_name.clone())),
2292                    ProcessCollection::CrossSections(cross_sections) => cross_sections
2293                        .get(integrand_name)
2294                        .filter(|cross_section| cross_section.integrand.is_some())
2295                        .map(|_| (process_id, process.definition.folder_name.clone())),
2296                };
2297                found.map(|(process_id, process_name)| {
2298                    (process_id, process_name, integrand_name.to_string())
2299                })
2300            })
2301            .collect::<Vec<_>>();
2302
2303        match matches.as_slice() {
2304            [(process_id, _, canonical_name)] => Ok((*process_id, canonical_name.clone())),
2305            [] => Err(eyre!(
2306                "No generated integrand named '{integrand_name}' was found. Per-integrand model parameters are only supported for generated integrands."
2307            )),
2308            _ => {
2309                let names = matches
2310                    .iter()
2311                    .map(|(process_id, process_name, _)| format!("#{process_id} ({process_name})"))
2312                    .collect::<Vec<_>>();
2313                Err(eyre!(
2314                    "Integrand name '{integrand_name}' is ambiguous across generated integrands"
2315                ))
2316                .with_note(|| format!("Matching processes: {}", names.join(", ")))
2317            }
2318        }
2319    }
2320
2321    /// Replace the session model by the one at `path`, with its own values as
2322    /// the parameter card.
2323    pub fn import_model(&mut self, path: impl AsRef<Path>) -> Result<()> {
2324        Model::with_parameter_display_transaction(|| {
2325            let model = Model::from_path(path)?;
2326            let card = model.default_param_card();
2327            self.replace_model(model, card)
2328        })
2329    }
2330
2331    /// Replace the session model and its parameter card, and rebind every held
2332    /// graph to the new model so that graphs and session read the same values.
2333    ///
2334    /// The card is authoritative: `card` is applied to `model` before anything
2335    /// else, so the stored model, the card and every graph agree, also after
2336    /// saving and loading. All checks run on that candidate before the state
2337    /// changes, so on error the state is unchanged:
2338    /// - held graphs index the model's records, so a model with different
2339    ///   records is refused while any process holds graphs;
2340    /// - for a generated integrand whose generation decided on model values
2341    ///   (see [`GenerationPoint::depends_on_model_values`]), the point it
2342    ///   resolves to must stay at its generation point (see [`Self::ensure_generation_point_kept`]);
2343    /// - every generated integrand must resolve its settings overlay against
2344    ///   the new card, and the resulting model must supply every model value
2345    ///   its parameter builders read.
2346    ///
2347    /// The integrands' runtime caches are invalidated, so their next warm-up
2348    /// uses the new values.
2349    /// Model construction also registers standalone display labels. When an
2350    /// application constructs a candidate that this method can reject, enclose
2351    /// both operations in [Model::with_parameter_display_transaction].
2352    /// File imports and CLI model imports already provide this scope.
2353    ///
2354    pub fn replace_model(&mut self, model: Model, card: InputParamCard<F<f64>>) -> Result<()> {
2355        Model::with_parameter_display_transaction(|| {
2356            let mut candidate = model;
2357            let checked = self
2358                .process_list
2359                .ensure_graphs_bound_to(&candidate)
2360                .and_then(|()| {
2361                    candidate.apply_param_card(&card)?;
2362                    self.ensure_model_replaceable(&candidate, &card)
2363                });
2364            if let Err(error) = checked {
2365                return Err(error.wrap_err(format!(
2366                    "Model '{}' was not applied; the state is unchanged",
2367                    candidate.name()
2368                )));
2369            }
2370            self.model = candidate;
2371            self.model_parameters = card;
2372            self.process_list
2373                .rebind_graph_models(&Arc::new(self.model.clone()));
2374            Ok(())
2375        })
2376    }
2377
2378    /// The value checks of [`Self::replace_model`] for a candidate model and
2379    /// card with the records of the held graphs.
2380    fn ensure_model_replaceable(&self, model: &Model, card: &InputParamCard<F<f64>>) -> Result<()> {
2381        for (process_id, process) in self.process_list.processes.iter().enumerate() {
2382            let folder = &process.definition.folder_name;
2383            let integrands: Vec<(&String, &ProcessIntegrand)> = match &process.collection {
2384                ProcessCollection::Amplitudes(amplitudes) => amplitudes
2385                    .iter()
2386                    .filter_map(|(name, amplitude)| Some((name, amplitude.integrand.as_ref()?)))
2387                    .collect(),
2388                ProcessCollection::CrossSections(cross_sections) => cross_sections
2389                    .iter()
2390                    .filter_map(|(name, cross_section)| {
2391                        Some((name, cross_section.integrand.as_ref()?))
2392                    })
2393                    .collect(),
2394            };
2395            for (name, integrand) in integrands {
2396                // The model every evaluation of this integrand warms up with.
2397                let effective = Self::effective_model(model, card, integrand.get_settings())
2398                    .wrap_err_with(|| {
2399                        format!(
2400                            "integrand '{name}' of process '{folder}' has model settings that the \
2401                             new parameter card cannot resolve; reset them with `set model -p \
2402                             name:{folder} -i {name} defaults` first"
2403                        )
2404                    })?;
2405                self.ensure_effective_point_kept(
2406                    process_id,
2407                    name,
2408                    &effective,
2409                    integrand.get_settings(),
2410                )?;
2411                integrand
2412                    .graphs()
2413                    .into_iter()
2414                    .try_for_each(|graph| {
2415                        graph
2416                            .param_builder
2417                            .ensure_model_values(&effective)
2418                            .wrap_err_with(|| format!("graph '{}'", graph.name))
2419                    })
2420                    .wrap_err_with(|| {
2421                        format!("integrand '{name}' of process '{folder}' cannot use the new model")
2422                    })?;
2423            }
2424        }
2425        Ok(())
2426    }
2427
2428    /// Check, before anything is written, that a save can be loaded back:
2429    /// saved graphs persist only their model's identity and rebind to the saved
2430    /// model.json. This is an identity check only, so a state of ungenerated
2431    /// graphs needs no numerical model values.
2432    pub fn ensure_graphs_match_model(&self) -> Result<()> {
2433        self.process_list
2434            .ensure_graphs_bound_to(&self.model)
2435            .wrap_err("State was not saved: its graphs do not match its model")
2436    }
2437
2438    /// The model handle that graphs imported now share with the held graphs.
2439    pub fn shared_graph_model(&self) -> Arc<Model> {
2440        self.process_list
2441            .shared_graph_model()
2442            .filter(|model| model.fingerprint() == self.model.fingerprint())
2443            .cloned()
2444            .unwrap_or_else(|| Arc::new(self.model.clone()))
2445    }
2446
2447    fn matching_process_ids(&self, process: Option<&ProcessRef>) -> Result<Vec<usize>> {
2448        let Some(process) = process else {
2449            return Ok((0..self.process_list.processes.len()).collect());
2450        };
2451
2452        match process {
2453            ProcessRef::Id(id) => Ok((*id < self.process_list.processes.len())
2454                .then_some(*id)
2455                .into_iter()
2456                .collect()),
2457            ProcessRef::Name(name) => Ok(self
2458                .process_list
2459                .processes
2460                .iter()
2461                .position(|p| p.definition.folder_name == *name)
2462                .into_iter()
2463                .collect()),
2464            ProcessRef::Unqualified(value) => {
2465                let name_match = self
2466                    .process_list
2467                    .processes
2468                    .iter()
2469                    .position(|p| p.definition.folder_name == *value);
2470                if let Ok(id) = value.parse::<usize>() {
2471                    let id_valid = id < self.process_list.processes.len();
2472                    match (id_valid, name_match) {
2473                        (true, Some(_)) => Err(eyre!(
2474                            "Ambiguous process reference '{}'. Use '#{}' or 'name:{}' to disambiguate.",
2475                            value,
2476                            id,
2477                            value
2478                        )),
2479                        (true, None) => Ok(vec![id]),
2480                        (false, Some(index)) => Ok(vec![index]),
2481                        (false, None) => Ok(vec![]),
2482                    }
2483                } else {
2484                    Ok(name_match.into_iter().collect())
2485                }
2486            }
2487        }
2488    }
2489
2490    pub fn remove_selected_integrands(
2491        &mut self,
2492        process: Option<&ProcessRef>,
2493        integrand_name: Option<&str>,
2494    ) -> Result<Vec<RemovedIntegrand>> {
2495        let process_ids = self.matching_process_ids(process)?;
2496        let mut removed = Vec::new();
2497
2498        for process_id in process_ids.into_iter().rev() {
2499            let process_name = self.process_list.processes[process_id]
2500                .definition
2501                .folder_name
2502                .clone();
2503            let integrand_names = {
2504                let collection = &self.process_list.processes[process_id].collection;
2505                match integrand_name {
2506                    Some(name) => collection
2507                        .get_integrand_names()
2508                        .into_iter()
2509                        .find(|candidate| *candidate == name)
2510                        .map(|name| vec![name.to_string()])
2511                        .unwrap_or_default(),
2512                    None => collection
2513                        .get_integrand_names()
2514                        .into_iter()
2515                        .map(str::to_string)
2516                        .collect(),
2517                }
2518            };
2519
2520            if integrand_names.is_empty() {
2521                continue;
2522            }
2523
2524            {
2525                let process_entry = &mut self.process_list.processes[process_id];
2526                for integrand_name in &integrand_names {
2527                    process_entry.collection.remove_integrand(integrand_name)?;
2528                }
2529            }
2530            for integrand_name in &integrand_names {
2531                self.generation_summaries
2532                    .remove(&IntegrandGenerationSummaryKey {
2533                        process_id,
2534                        integrand_name: integrand_name.clone(),
2535                    });
2536            }
2537
2538            let removed_empty_process = self.process_list.processes[process_id]
2539                .collection
2540                .get_integrand_names()
2541                .is_empty();
2542            if removed_empty_process {
2543                self.process_list.processes.remove(process_id);
2544                self.remove_generation_summaries_for_process(process_id);
2545            }
2546
2547            for integrand_name in integrand_names {
2548                removed.push(RemovedIntegrand {
2549                    process_id,
2550                    process_name: process_name.clone(),
2551                    integrand_name,
2552                    removed_empty_process,
2553                });
2554            }
2555        }
2556
2557        removed.reverse();
2558        Ok(removed)
2559    }
2560
2561    pub fn remove_process(&mut self, process: Option<&ProcessRef>) -> Result<RemovedProcess> {
2562        let process_id = self.resolve_process_ref(process)?;
2563        let removed = self.process_list.processes.remove(process_id);
2564        self.remove_generation_summaries_for_process(process_id);
2565        Ok(RemovedProcess {
2566            process_id,
2567            process_name: removed.definition.folder_name,
2568        })
2569    }
2570
2571    pub fn remove_integrand(
2572        &mut self,
2573        process: &ProcessRef,
2574        integrand_name: &str,
2575    ) -> Result<RemovedIntegrand> {
2576        let process_id = process.resolve(&self.process_list)?;
2577        let (process_name, canonical_integrand_name, removed_empty_process) = {
2578            let process_entry = &mut self.process_list.processes[process_id];
2579            let process_name = process_entry.definition.folder_name.clone();
2580            let canonical_integrand_name = process_entry
2581                .collection
2582                .find_integrand(Some(integrand_name.to_string()))?;
2583            process_entry
2584                .collection
2585                .remove_integrand(&canonical_integrand_name)?;
2586            let removed_empty_process = process_entry.collection.get_integrand_names().is_empty();
2587            (
2588                process_name,
2589                canonical_integrand_name,
2590                removed_empty_process,
2591            )
2592        };
2593        self.generation_summaries
2594            .remove(&IntegrandGenerationSummaryKey {
2595                process_id,
2596                integrand_name: canonical_integrand_name.clone(),
2597            });
2598
2599        if removed_empty_process {
2600            self.process_list.processes.remove(process_id);
2601            self.remove_generation_summaries_for_process(process_id);
2602        }
2603
2604        Ok(RemovedIntegrand {
2605            process_id,
2606            process_name,
2607            integrand_name: canonical_integrand_name,
2608            removed_empty_process,
2609        })
2610    }
2611
2612    pub fn resolve_process_ref(&self, process: Option<&ProcessRef>) -> Result<usize> {
2613        match process {
2614            Some(process_ref) => process_ref.resolve(&self.process_list),
2615            None => self.process_list.find_process(None),
2616        }
2617    }
2618
2619    pub fn find_integrand_ref(
2620        &self,
2621        process: Option<&ProcessRef>,
2622        integrand_name: Option<&String>,
2623    ) -> Result<(usize, String)> {
2624        let process_id = self.resolve_process_ref(process)?;
2625        let integrand_name = self.process_list.processes[process_id]
2626            .collection
2627            .find_integrand(integrand_name.cloned())
2628            .with_note(|| format!("in process id {process_id}"))?;
2629        Ok((process_id, integrand_name))
2630    }
2631
2632    pub fn get_integrand_info(
2633        &self,
2634        process: Option<&ProcessRef>,
2635        integrand_name: Option<&String>,
2636    ) -> Result<IntegrandInfo> {
2637        let (process_id, integrand_name) = self.find_integrand_ref(process, integrand_name)?;
2638        collect_integrand_info(self, process_id, &integrand_name)
2639    }
2640
2641    pub fn duplicate_integrand(
2642        &mut self,
2643        process: Option<&ProcessRef>,
2644        integrand_name: Option<&String>,
2645        output_process_name: &str,
2646        output_integrand_name: &str,
2647    ) -> Result<()> {
2648        validate_output_name(output_process_name, "--output_process_name")?;
2649        validate_output_name(output_integrand_name, "--output_integrand_name")?;
2650
2651        let (source_process_id, source_integrand_name) =
2652            self.find_integrand_ref(process, integrand_name)?;
2653        let mut payload =
2654            self.cloned_integrand_payload(source_process_id, &source_integrand_name)?;
2655        payload.rename(output_integrand_name);
2656        let insertion = self.insert_integrand_copy(
2657            source_process_id,
2658            &source_integrand_name,
2659            output_process_name,
2660            output_integrand_name,
2661            payload,
2662            false,
2663            false,
2664            None,
2665            false,
2666        )?;
2667        self.copy_generation_summary(
2668            source_process_id,
2669            &source_integrand_name,
2670            insertion.process_id,
2671            &insertion.integrand_name,
2672        );
2673        Ok(())
2674    }
2675
2676    /// Give a copied integrand the generation summary of its source, with the
2677    /// source's exact generation point: the copy was generated there too.
2678    /// Reports of graphs the copy no longer holds are dropped.
2679    fn copy_generation_summary(
2680        &mut self,
2681        source_process_id: usize,
2682        source_integrand_name: &str,
2683        process_id: usize,
2684        integrand_name: &str,
2685    ) {
2686        let key = IntegrandGenerationSummaryKey {
2687            process_id,
2688            integrand_name: integrand_name.to_string(),
2689        };
2690        let generated = self
2691            .process_list
2692            .get_integrand(process_id, integrand_name)
2693            .is_ok_and(|resolved| resolved.integrand.is_some());
2694        let source = self
2695            .generation_summary(source_process_id, source_integrand_name)
2696            .cloned();
2697        let Some(mut summary) = source.filter(|_| generated) else {
2698            self.generation_summaries.remove(&key);
2699            return;
2700        };
2701        let graph_names: BTreeSet<String> =
2702            match &self.process_list.processes[process_id].collection {
2703                ProcessCollection::Amplitudes(amplitudes) => amplitudes
2704                    .get(integrand_name)
2705                    .map(|amplitude| {
2706                        amplitude
2707                            .graphs
2708                            .iter()
2709                            .map(|graph| graph.graph.name.clone())
2710                            .collect()
2711                    })
2712                    .unwrap_or_default(),
2713                ProcessCollection::CrossSections(cross_sections) => cross_sections
2714                    .get(integrand_name)
2715                    .map(|cross_section| {
2716                        cross_section
2717                            .supergraphs
2718                            .iter()
2719                            .map(|graph| graph.graph.name.clone())
2720                            .collect()
2721                    })
2722                    .unwrap_or_default(),
2723            };
2724        summary
2725            .reports
2726            .retain(|report| graph_names.contains(&report.graph_name));
2727        for report in &mut summary.reports {
2728            report.process_id = process_id;
2729            report.integrand_name = integrand_name.to_string();
2730        }
2731        self.generation_summaries.insert(key, summary);
2732    }
2733
2734    pub fn select_integrand_graph_groups(
2735        &mut self,
2736        process: Option<&ProcessRef>,
2737        integrand_name: Option<&String>,
2738        selection: &GraphGroupSelectionSpec,
2739        target: &GraphGroupSelectionTarget,
2740        context: GraphGroupSelectionContext<'_>,
2741    ) -> Result<SelectedGraphGroups> {
2742        if target.clear_existing_processes && !target.is_copy_mode() {
2743            return Err(eyre!(
2744                "--clear-existing-processes requires --output_process or --output_integrand for `select`"
2745            ));
2746        }
2747
2748        let (source_process_id, source_integrand_name) =
2749            self.find_integrand_ref(process, integrand_name)?;
2750        let (source_process_name, plan, discarded_generated_integrand) = {
2751            let process_entry = &self.process_list.processes[source_process_id];
2752            let process_name = process_entry.definition.folder_name.clone();
2753            match &process_entry.collection {
2754                ProcessCollection::Amplitudes(amplitudes) => {
2755                    if selection.has_raised_cut_rules() {
2756                        return Err(eyre!(
2757                            "Raised-cut signature selection can only be used with cross-section integrands."
2758                        ));
2759                    }
2760                    if selection.mode() == GraphGroupSelectionMode::CrossSectionAmplitudeGraphs {
2761                        return Err(eyre!(
2762                            "`select --amplitude-graphs` can only be used with cross-section integrands."
2763                        ));
2764                    }
2765                    let amplitude = amplitudes.get(&source_integrand_name).ok_or_else(|| {
2766                        eyre!(
2767                            "No amplitude named '{}' in process '{}'",
2768                            source_integrand_name,
2769                            process_name
2770                        )
2771                    })?;
2772                    let plan = amplitude.plan_graph_group_selection(selection, &self.model)?;
2773                    amplitude.validate_graph_group_selection_plan(&plan)?;
2774                    (process_name, plan, amplitude.integrand.is_some())
2775                }
2776                ProcessCollection::CrossSections(cross_sections) => {
2777                    let cross_section =
2778                        cross_sections.get(&source_integrand_name).ok_or_else(|| {
2779                            eyre!(
2780                                "No cross section named '{}' in process '{}'",
2781                                source_integrand_name,
2782                                process_name
2783                            )
2784                        })?;
2785                    let plan = cross_section.plan_graph_group_selection_with_context(
2786                        selection,
2787                        &self.model,
2788                        &process_entry.definition,
2789                        context.generation_settings,
2790                    )?;
2791                    cross_section.validate_graph_group_selection_plan(&plan)?;
2792                    (process_name, plan, cross_section.integrand.is_some())
2793                }
2794            }
2795        };
2796        let report = plan.report().clone();
2797        let source = SelectionSource {
2798            process_id: source_process_id,
2799            process_name: source_process_name,
2800            integrand_name: source_integrand_name,
2801        };
2802
2803        if target.is_copy_mode() {
2804            return self.select_integrand_graph_groups_to_output(
2805                &source,
2806                &plan,
2807                report,
2808                target,
2809                context.state_folder,
2810                context.read_only_state,
2811            );
2812        }
2813
2814        let mut removed_generated_artifacts = false;
2815        let mut removed_generation_summary = false;
2816        if discarded_generated_integrand {
2817            if context.read_only_state {
2818                return Err(eyre!(
2819                    "Cannot select graph groups for generated integrand '{}' in process '{}' because this session was started with --read-only-state. Restart without --read-only-state or select before generation.",
2820                    source.integrand_name,
2821                    source.process_name
2822                ));
2823            }
2824
2825            let process_entry = &self.process_list.processes[source.process_id];
2826            let integrand_artifact_root = integrand_artifact_folder(
2827                context.state_folder,
2828                process_entry,
2829                &source.integrand_name,
2830            );
2831            let generated_artifact_path = generated_integrand_artifact_path(
2832                context.state_folder,
2833                process_entry,
2834                &source.integrand_name,
2835            );
2836            removed_generated_artifacts = remove_dir_if_exists_under_root(
2837                &generated_artifact_path,
2838                &integrand_artifact_root,
2839                "generated integrand artifact",
2840            )?;
2841            let generation_summary_path = integrand_generation_summary_path(
2842                context.state_folder,
2843                process_entry,
2844                &source.integrand_name,
2845            );
2846            removed_generation_summary = remove_file_if_exists_under_root(
2847                &generation_summary_path,
2848                &integrand_artifact_root,
2849                "integrand generation summary",
2850            )?;
2851        }
2852
2853        {
2854            let process_entry = &mut self.process_list.processes[source.process_id];
2855            match &mut process_entry.collection {
2856                ProcessCollection::Amplitudes(amplitudes) => {
2857                    let amplitude =
2858                        amplitudes.get_mut(&source.integrand_name).ok_or_else(|| {
2859                            eyre!(
2860                                "No amplitude named '{}' in process '{}'",
2861                                source.integrand_name,
2862                                source.process_name
2863                            )
2864                        })?;
2865                    amplitude.apply_graph_group_selection(&plan)?;
2866                }
2867                ProcessCollection::CrossSections(cross_sections) => {
2868                    let cross_section =
2869                        cross_sections
2870                            .get_mut(&source.integrand_name)
2871                            .ok_or_else(|| {
2872                                eyre!(
2873                                    "No cross section named '{}' in process '{}'",
2874                                    source.integrand_name,
2875                                    source.process_name
2876                                )
2877                            })?;
2878                    cross_section.apply_graph_group_selection(&plan)?;
2879                }
2880            }
2881        }
2882
2883        if discarded_generated_integrand {
2884            self.generation_summaries
2885                .remove(&IntegrandGenerationSummaryKey {
2886                    process_id: source.process_id,
2887                    integrand_name: source.integrand_name.clone(),
2888                });
2889        }
2890
2891        Ok(SelectedGraphGroups {
2892            source_process_id: source.process_id,
2893            source_process_name: source.process_name.clone(),
2894            source_integrand_name: source.integrand_name.clone(),
2895            process_id: source.process_id,
2896            process_name: source.process_name,
2897            integrand_name: source.integrand_name,
2898            report,
2899            copied_to_output: false,
2900            replaced_existing_target: false,
2901            removed_target_artifacts: false,
2902            discarded_generated_integrand,
2903            removed_generated_artifacts,
2904            removed_generation_summary,
2905        })
2906    }
2907
2908    fn select_integrand_graph_groups_to_output(
2909        &mut self,
2910        source: &SelectionSource,
2911        plan: &GraphGroupSelectionPlan,
2912        report: GraphGroupSelectionReport,
2913        target: &GraphGroupSelectionTarget,
2914        state_folder: &Path,
2915        read_only_state: bool,
2916    ) -> Result<SelectedGraphGroups> {
2917        let output_process_name = target
2918            .output_process_name
2919            .as_deref()
2920            .unwrap_or(&source.process_name);
2921        let output_integrand_name = target
2922            .output_integrand_name
2923            .as_deref()
2924            .unwrap_or(&source.integrand_name);
2925
2926        validate_output_name(output_process_name, "--output_process")?;
2927        validate_output_name(output_integrand_name, "--output_integrand")?;
2928
2929        if output_process_name == source.process_name
2930            && output_integrand_name == source.integrand_name
2931        {
2932            return Err(eyre!(
2933                "Copy-mode select target '{} / {}' is the selected source integrand. Omit --output_process/--output_integrand for in-place selection or choose a different output target.",
2934                output_process_name,
2935                output_integrand_name
2936            ));
2937        }
2938
2939        let target_process_id = self
2940            .process_list
2941            .processes
2942            .iter()
2943            .position(|process| process.definition.folder_name == output_process_name);
2944        let replace_existing_process = target.output_process_name.is_some()
2945            && target.clear_existing_processes
2946            && target_process_id.is_some_and(|process_id| process_id != source.process_id);
2947
2948        let mut payload =
2949            self.cloned_integrand_payload(source.process_id, &source.integrand_name)?;
2950        payload.rename(output_integrand_name);
2951        payload.apply_graph_group_selection(plan)?;
2952
2953        let insertion = self.insert_integrand_copy(
2954            source.process_id,
2955            &source.integrand_name,
2956            output_process_name,
2957            output_integrand_name,
2958            payload,
2959            target.clear_existing_processes,
2960            replace_existing_process,
2961            Some(state_folder),
2962            read_only_state,
2963        )?;
2964        self.copy_generation_summary(
2965            source.process_id,
2966            &source.integrand_name,
2967            insertion.process_id,
2968            &insertion.integrand_name,
2969        );
2970
2971        Ok(SelectedGraphGroups {
2972            source_process_id: source.process_id,
2973            source_process_name: source.process_name.clone(),
2974            source_integrand_name: source.integrand_name.clone(),
2975            process_id: insertion.process_id,
2976            process_name: insertion.process_name,
2977            integrand_name: insertion.integrand_name,
2978            report,
2979            copied_to_output: true,
2980            replaced_existing_target: insertion.replaced_existing_target,
2981            removed_target_artifacts: insertion.removed_target_artifacts,
2982            discarded_generated_integrand: false,
2983            removed_generated_artifacts: false,
2984            removed_generation_summary: false,
2985        })
2986    }
2987
2988    fn cloned_integrand_payload(
2989        &self,
2990        source_process_id: usize,
2991        source_integrand_name: &str,
2992    ) -> Result<IntegrandCopyPayload> {
2993        let source_process = &self.process_list.processes[source_process_id];
2994        match &source_process.collection {
2995            ProcessCollection::Amplitudes(amplitudes) => amplitudes
2996                .get(source_integrand_name)
2997                .cloned()
2998                .map(IntegrandCopyPayload::Amplitude)
2999                .ok_or_else(|| eyre!("Missing source amplitude '{}'", source_integrand_name)),
3000            ProcessCollection::CrossSections(cross_sections) => cross_sections
3001                .get(source_integrand_name)
3002                .cloned()
3003                .map(IntegrandCopyPayload::CrossSection)
3004                .ok_or_else(|| eyre!("Missing source cross section '{}'", source_integrand_name)),
3005        }
3006    }
3007
3008    #[allow(clippy::too_many_arguments)]
3009    fn insert_integrand_copy(
3010        &mut self,
3011        source_process_id: usize,
3012        source_integrand_name: &str,
3013        output_process_name: &str,
3014        output_integrand_name: &str,
3015        payload: IntegrandCopyPayload,
3016        clear_existing_processes: bool,
3017        replace_existing_process: bool,
3018        state_folder: Option<&Path>,
3019        read_only_state: bool,
3020    ) -> Result<IntegrandCopyInsertion> {
3021        if let Some(destination_process_id) = self
3022            .process_list
3023            .processes
3024            .iter()
3025            .position(|process| process.definition.folder_name == output_process_name)
3026        {
3027            if replace_existing_process {
3028                if read_only_state {
3029                    return Err(eyre!(
3030                        "Cannot overwrite output process '{}' because this session was started with --read-only-state.",
3031                        output_process_name
3032                    ));
3033                }
3034                let removed_target_artifacts = if let Some(state_folder) = state_folder {
3035                    remove_saved_process_artifacts(
3036                        state_folder,
3037                        &self.process_list.processes[destination_process_id],
3038                    )?
3039                } else {
3040                    false
3041                };
3042                self.remove_generation_summaries_for_process_without_shifting(
3043                    destination_process_id,
3044                );
3045                let process = self.single_integrand_process(
3046                    source_process_id,
3047                    destination_process_id,
3048                    output_process_name,
3049                    payload,
3050                );
3051                self.process_list.processes[destination_process_id] = process;
3052                return Ok(IntegrandCopyInsertion {
3053                    process_id: destination_process_id,
3054                    process_name: output_process_name.to_string(),
3055                    integrand_name: output_integrand_name.to_string(),
3056                    replaced_existing_target: true,
3057                    removed_target_artifacts,
3058                });
3059            }
3060
3061            // A process decides from its own generation history whether its
3062            // generated integrands depend on model values when their summary
3063            // is missing, so a value-dependent integrand may not join a
3064            // process whose history records value-independent generation.
3065            let destination = &self.process_list.processes[destination_process_id];
3066            if payload.is_generated()
3067                && self.integrand_depends_on_model_values(source_process_id, source_integrand_name)
3068                && destination
3069                    .settings_history
3070                    .as_ref()
3071                    .is_some_and(|history| {
3072                        !history
3073                            .generation
3074                            .threshold_subtraction
3075                            .check_esurface_at_generation
3076                    })
3077            {
3078                return Err(eyre!(
3079                    "Cannot copy integrand '{source_integrand_name}' into process \
3080                     '{output_process_name}': its generation decided on the generation-time model \
3081                     values (generation.threshold_subtraction.check_esurface_at_generation, or no \
3082                     recorded generation settings), but process '{output_process_name}' was \
3083                     generated without that setting, so the dependence would rest on the copy's \
3084                     optional generation summary alone; copy it into a new process or into a \
3085                     process generated with the same setting"
3086                ));
3087            }
3088
3089            let target_exists = self.process_list.processes[destination_process_id]
3090                .collection
3091                .get_integrand_names()
3092                .contains(&output_integrand_name);
3093            if target_exists {
3094                if !clear_existing_processes {
3095                    return Err(eyre!(
3096                        "An integrand '{}' already exists in process '{}'",
3097                        output_integrand_name,
3098                        output_process_name
3099                    ));
3100                }
3101                if read_only_state {
3102                    return Err(eyre!(
3103                        "Cannot overwrite output integrand '{}' in process '{}' because this session was started with --read-only-state.",
3104                        output_integrand_name,
3105                        output_process_name
3106                    ));
3107                }
3108            }
3109
3110            if !payload
3111                .is_compatible_with(&self.process_list.processes[destination_process_id].collection)
3112            {
3113                return Err(eyre!(
3114                    "Destination process '{}' exists but does not contain {}",
3115                    output_process_name,
3116                    payload.kind_name()
3117                ));
3118            }
3119
3120            let removed_target_artifacts = if target_exists {
3121                if let Some(state_folder) = state_folder {
3122                    remove_saved_integrand_artifacts(
3123                        state_folder,
3124                        &self.process_list.processes[destination_process_id],
3125                        output_integrand_name,
3126                    )?
3127                } else {
3128                    false
3129                }
3130            } else {
3131                false
3132            };
3133
3134            if target_exists {
3135                self.generation_summaries
3136                    .remove(&IntegrandGenerationSummaryKey {
3137                        process_id: destination_process_id,
3138                        integrand_name: output_integrand_name.to_string(),
3139                    });
3140            }
3141
3142            payload.insert_into_process(
3143                &mut self.process_list.processes[destination_process_id],
3144                output_process_name,
3145            )?;
3146            Ok(IntegrandCopyInsertion {
3147                process_id: destination_process_id,
3148                process_name: output_process_name.to_string(),
3149                integrand_name: output_integrand_name.to_string(),
3150                replaced_existing_target: target_exists,
3151                removed_target_artifacts,
3152            })
3153        } else {
3154            let process_id = self.process_list.processes.len();
3155            let process = self.single_integrand_process(
3156                source_process_id,
3157                process_id,
3158                output_process_name,
3159                payload,
3160            );
3161            self.process_list.add_process(process);
3162            Ok(IntegrandCopyInsertion {
3163                process_id,
3164                process_name: output_process_name.to_string(),
3165                integrand_name: output_integrand_name.to_string(),
3166                replaced_existing_target: false,
3167                removed_target_artifacts: false,
3168            })
3169        }
3170    }
3171
3172    fn single_integrand_process(
3173        &self,
3174        source_process_id: usize,
3175        process_id: usize,
3176        process_name: &str,
3177        payload: IntegrandCopyPayload,
3178    ) -> Process {
3179        let source_process = &self.process_list.processes[source_process_id];
3180        let mut definition = source_process.definition.clone();
3181        definition.folder_name = process_name.to_string();
3182        definition.process_id = process_id;
3183        Process {
3184            definition,
3185            settings_history: source_process.settings_history.clone(),
3186            collection: payload.into_collection(),
3187        }
3188    }
3189
3190    pub fn resolve_effective_model_parameter_card_for_settings(
3191        &self,
3192        settings: &RuntimeSettings,
3193    ) -> Result<InputParamCard<F<f64>>> {
3194        Self::effective_model_parameter_card(&self.model, &self.model_parameters, settings)
3195    }
3196
3197    /// The card that `settings` resolve to: `card` with the settings' model
3198    /// overlay applied, validated against `model`.
3199    fn effective_model_parameter_card(
3200        model: &Model,
3201        card: &InputParamCard<F<f64>>,
3202        settings: &RuntimeSettings,
3203    ) -> Result<InputParamCard<F<f64>>> {
3204        let shared_card = card;
3205        let mut card = shared_card.clone();
3206
3207        for (parameter_name, value) in &settings.model.external_parameters {
3208            let parameter_type =
3209                Self::resolve_overridable_model_parameter_type(model, shared_card, parameter_name)?;
3210            let value = Complex::new(value.0, value.1);
3211            validate_model_parameter_type(parameter_name, parameter_type, &value)?;
3212
3213            let parameter = card
3214                .get_mut(&UFOSymbol::from(parameter_name.as_str()))
3215                .ok_or_else(|| {
3216                    eyre!(
3217                        "Model parameter '{parameter_name}' is missing from the shared top-level model_parameters.json"
3218                    )
3219                })?;
3220            *parameter = value;
3221        }
3222
3223        Ok(card)
3224    }
3225
3226    pub fn resolve_serializable_model_parameter_card_for_settings(
3227        &self,
3228        settings: &RuntimeSettings,
3229    ) -> Result<SerializableInputParamCard<F<f64>>> {
3230        Ok(self
3231            .resolve_effective_model_parameter_card_for_settings(settings)?
3232            .to_serializable())
3233    }
3234
3235    pub fn resolve_effective_model_parameter_card_for_integrand(
3236        &self,
3237        process_id: usize,
3238        integrand_name: &str,
3239    ) -> Result<SerializableInputParamCard<F<f64>>> {
3240        let resolved = self
3241            .process_list
3242            .get_integrand(process_id, integrand_name)?;
3243        match resolved.get_settings() {
3244            Some(settings) => self.resolve_serializable_model_parameter_card_for_settings(settings),
3245            None => Ok(self.model_parameters.to_serializable()),
3246        }
3247    }
3248
3249    pub fn resolve_model_for_settings(&self, settings: &RuntimeSettings) -> Result<Model> {
3250        Self::effective_model(&self.model, &self.model_parameters, settings)
3251    }
3252
3253    /// The model an integrand with `settings` evaluates with: `model` with
3254    /// `card` and the settings' model overlay applied.
3255    fn effective_model(
3256        model: &Model,
3257        card: &InputParamCard<F<f64>>,
3258        settings: &RuntimeSettings,
3259    ) -> Result<Model> {
3260        let card = Self::effective_model_parameter_card(model, card, settings)?;
3261        let mut model = model.clone();
3262        model.apply_param_card(&card)?;
3263        Ok(model)
3264    }
3265
3266    pub fn resolve_model_for_integrand(
3267        &self,
3268        process_id: usize,
3269        integrand_name: &str,
3270    ) -> Result<Model> {
3271        let resolved = self
3272            .process_list
3273            .get_integrand(process_id, integrand_name)?;
3274        match resolved.get_settings() {
3275            Some(settings) => self.resolve_model_for_settings(settings),
3276            None => Ok(self.model.clone()),
3277        }
3278    }
3279
3280    pub fn generate_integrands(
3281        &mut self,
3282        global_settings: &GlobalSettings,
3283        runtime_default: LockedRuntimeSettings,
3284    ) -> Result<GenerationReports> {
3285        self.ensure_generation_consumes_the_effective_model(global_settings, runtime_default)?;
3286        self.run_generation_with_monitor(global_settings, move |state, generation_pool| {
3287            let mut reports = state.process_list.preprocess(
3288                &state.model,
3289                global_settings,
3290                &runtime_default,
3291                generation_pool,
3292            )?;
3293            merge_generated_graph_reports(
3294                &mut reports,
3295                state.process_list.generate_integrands(
3296                    &state.model,
3297                    global_settings,
3298                    runtime_default,
3299                    generation_pool,
3300                )?,
3301            );
3302            Ok(reports)
3303        })
3304    }
3305
3306    fn attach_process_id_to_named_reports(
3307        process_id: usize,
3308        reports: Vec<NamedGraphGenerationReport>,
3309    ) -> Vec<GeneratedGraphReport> {
3310        reports
3311            .into_iter()
3312            .map(|report| GeneratedGraphReport {
3313                process_id,
3314                integrand_name: report.integrand_name,
3315                graph_name: report.graph_name,
3316                stats: report.stats,
3317            })
3318            .collect()
3319    }
3320
3321    pub fn generate_integrand(
3322        &mut self,
3323        global_settings: &GlobalSettings,
3324        runtime_default: LockedRuntimeSettings,
3325        process_id: usize,
3326        integrand_name: Option<String>,
3327    ) -> Result<GenerationReports> {
3328        self.ensure_generation_consumes_the_effective_model(global_settings, runtime_default)?;
3329        self.run_generation_with_monitor(global_settings, move |state, generation_pool| {
3330            let p = &mut state.process_list.processes[process_id];
3331            let process_name = p.definition.folder_name.clone();
3332            if let Some(name) = &integrand_name {
3333                let _ = p.get_integrand(name)?;
3334                // A process has one shared generation history. Do not relabel
3335                // a generated sibling with settings which only this target uses.
3336                for other in p.get_integrand_names() {
3337                    if other != name.as_str()
3338                        && p.get_integrand(other)?.integrand.is_some()
3339                        && p.settings_history.as_ref().is_none_or(|history| {
3340                            history.generation != global_settings.generation
3341                        })
3342                    {
3343                        return Err(eyre!(
3344                            "Cannot generate only integrand '{}' in process '{}' with absent or different shared generation settings while sibling '{}' is already generated; regenerate the whole process without --integrand-name",
3345                            name, process_name, other
3346                        ));
3347                    }
3348                }
3349                let mut reports = Vec::new();
3350                match &mut p.collection {
3351                    ProcessCollection::Amplitudes(a) => {
3352                        if let Some(a) = a.get_mut(name) {
3353                            begin_phase(
3354                                GenerationProgressPhase::GraphPreprocessing,
3355                                GenerationProcessKind::Amplitude,
3356                                &process_name,
3357                                &a.name,
3358                                a.graphs.len(),
3359                                None,
3360                            );
3361                            merge_generated_graph_reports(
3362                                &mut reports,
3363                                Self::attach_process_id_to_named_reports(
3364                                    process_id,
3365                                    a.preprocess(
3366                                        &state.model,
3367                                        &global_settings.generation,
3368                                        &runtime_default,
3369                                        generation_pool,
3370                                    )?,
3371                                ),
3372                            );
3373                            merge_generated_graph_reports(
3374                                &mut reports,
3375                                Self::attach_process_id_to_named_reports(
3376                                    process_id,
3377                                    a.build_integrand(
3378                                        &state.model,
3379                                        &process_name,
3380                                        global_settings,
3381                                        runtime_default,
3382                                        generation_pool,
3383                                    )?,
3384                                ),
3385                            );
3386                        } else {
3387                            return Err(eyre!(
3388                                "No amplitude named '{}' in process id {}",
3389                                name,
3390                                process_id
3391                            ));
3392                        }
3393                    }
3394                    ProcessCollection::CrossSections(cs) => {
3395                        if let Some(cs) = cs.get_mut(name) {
3396                            merge_generated_graph_reports(
3397                                &mut reports,
3398                                Self::attach_process_id_to_named_reports(
3399                                    process_id,
3400                                    cs.preprocess(
3401                                        &state.model,
3402                                        &p.definition,
3403                                        &global_settings.generation,
3404                                        runtime_default,
3405                                        generation_pool,
3406                                    )?,
3407                                ),
3408                            );
3409                            merge_generated_graph_reports(
3410                                &mut reports,
3411                                Self::attach_process_id_to_named_reports(
3412                                    process_id,
3413                                    cs.build_integrand(
3414                                        &state.model,
3415                                        &p.definition,
3416                                        global_settings,
3417                                        runtime_default,
3418                                        generation_pool,
3419                                    )?,
3420                                ),
3421                            );
3422                        } else {
3423                            return Err(eyre!(
3424                                "No cross section named '{}' in process id {}",
3425                                name,
3426                                process_id
3427                            ));
3428                        }
3429                    }
3430                }
3431                // Named generation bypasses Process::preprocess, which normally
3432                // records the settings required by persistent source exports.
3433                p.settings_history = Some(global_settings.clone());
3434                Ok(reports)
3435            } else {
3436                let mut reports = p.preprocess(
3437                    &state.model,
3438                    global_settings,
3439                    &runtime_default,
3440                    generation_pool,
3441                )?;
3442                merge_generated_graph_reports(
3443                    &mut reports,
3444                    p.generate_integrands(
3445                        &state.model,
3446                        global_settings,
3447                        runtime_default,
3448                        generation_pool,
3449                    )?,
3450                );
3451                Ok(reports)
3452            }
3453        })
3454    }
3455
3456    fn run_generation_with_monitor<F>(
3457        &mut self,
3458        global_settings: &GlobalSettings,
3459        generation: F,
3460    ) -> Result<GenerationReports>
3461    where
3462        F: FnOnce(&mut Self, &rayon::ThreadPool) -> Result<Vec<GeneratedGraphReport>>,
3463    {
3464        let generation_pool = rayon::ThreadPoolBuilder::new()
3465            .num_threads(global_settings.n_cores.generate)
3466            .stack_size(GENERATION_THREAD_STACK_SIZE_BYTES)
3467            .build()?;
3468        let generation_cores = generation_pool.current_num_threads();
3469        clear_interrupt_request();
3470        let mut monitor = GenerationMonitor::start()?;
3471        let stderr_is_terminal = io::stderr().is_terminal();
3472        let progress_mode = if generation_cores == 1 && stderr_is_terminal {
3473            GenerationProgressMode::Detailed
3474        } else {
3475            GenerationProgressMode::Aggregate
3476        };
3477        let _progress_mode_guard = GenerationProgressModeGuard::set(progress_mode);
3478        let _progress_observer_guard = if generation_cores > 1 && stderr_is_terminal {
3479            let reporter = AggregateGenerationProgressReporter::new(
3480                monitor.current_ram_bytes(),
3481                monitor.peak_ram_bytes(),
3482                generation_cores as u64,
3483            );
3484            Some(GenerationProgressObserverGuard::set(reporter))
3485        } else {
3486            None
3487        };
3488        let generation_result = generation(self, &generation_pool);
3489        let peak_ram_bytes = monitor.finish();
3490        clear_interrupt_request();
3491
3492        let reports = GenerationReports {
3493            reports: generation_result
3494                .inspect_err(|_| self.refresh_dependent_generation_points())?,
3495            resources: GenerationResourceSummary {
3496                peak_ram_bytes,
3497                generation_cores,
3498            },
3499        };
3500        // Every generation records its integrands' summaries with their
3501        // generation points, whichever entry point requested it.
3502        self.record_generation_summary(&reports.reports, reports.resources);
3503        Ok(reports)
3504    }
3505
3506    pub fn compile_integrands(
3507        &mut self,
3508        folder: impl AsRef<Path>,
3509        override_existing: bool,
3510        global_settings: &GlobalSettings,
3511        process_id: Option<usize>,
3512        integrand_name: Option<String>,
3513    ) -> Result<Vec<GeneratedGraphReport>> {
3514        let compile_pool = rayon::ThreadPoolBuilder::new()
3515            .num_threads(global_settings.n_cores.compile)
3516            .build()?;
3517        self.process_list.compile(
3518            folder,
3519            override_existing,
3520            process_id,
3521            integrand_name,
3522            &compile_pool,
3523        )
3524    }
3525
3526    pub fn generation_summary(
3527        &self,
3528        process_id: usize,
3529        integrand_name: &str,
3530    ) -> Option<&IntegrandGenerationSummary> {
3531        self.generation_summaries
3532            .get(&IntegrandGenerationSummaryKey {
3533                process_id,
3534                integrand_name: integrand_name.to_string(),
3535            })
3536    }
3537
3538    pub fn record_generation_summary(
3539        &mut self,
3540        reports: &[GeneratedGraphReport],
3541        resources: GenerationResourceSummary,
3542    ) {
3543        let mut reports_by_integrand: BTreeMap<
3544            IntegrandGenerationSummaryKey,
3545            Vec<GeneratedGraphReport>,
3546        > = BTreeMap::new();
3547
3548        for report in reports {
3549            let Some(process) = self.process_list.processes.get(report.process_id) else {
3550                continue;
3551            };
3552            if !process
3553                .collection
3554                .get_integrand_names()
3555                .contains(&report.integrand_name.as_str())
3556            {
3557                continue;
3558            }
3559
3560            reports_by_integrand
3561                .entry(IntegrandGenerationSummaryKey {
3562                    process_id: report.process_id,
3563                    integrand_name: report.integrand_name.clone(),
3564                })
3565                .or_default()
3566                .push(report.clone());
3567        }
3568
3569        for (key, reports) in reports_by_integrand {
3570            let generation_point = self.current_generation_point(&key);
3571            self.generation_summaries.insert(
3572                key,
3573                IntegrandGenerationSummary {
3574                    peak_ram_bytes: resources.peak_ram_bytes,
3575                    reports,
3576                    generation_point,
3577                },
3578            );
3579        }
3580    }
3581
3582    /// Keep generation points sound after a generation that returned an error.
3583    ///
3584    /// A generation that fails part-way may already have installed some
3585    /// integrands and updated their process' generation settings, while their
3586    /// summaries still describe the previous build, or no build. Every
3587    /// generated integrand of a process that is now value-dependent is
3588    /// recorded at its current point, also when it has no summary yet. Without
3589    /// that record, a later failed preprocessing could overwrite the process'
3590    /// settings and drop the fallback guard while the payload stays installed.
3591    /// An integrand installed by this generation gets the point it was built
3592    /// at; an earlier payload is held at its own values, which can only refuse
3593    /// more. Integrands of processes that are not value-dependent keep their
3594    /// records; a dependent one among them can only refuse more. The previous
3595    /// statistics of a summary are kept; a new summary has none.
3596    fn refresh_dependent_generation_points(&mut self) {
3597        for (process_id, process) in self.process_list.processes.iter().enumerate() {
3598            if !process.generation_depends_on_model_values() {
3599                continue;
3600            }
3601            for integrand_name in process.get_integrand_names() {
3602                let key = IntegrandGenerationSummaryKey {
3603                    process_id,
3604                    integrand_name: integrand_name.to_owned(),
3605                };
3606                if let Some(point) = self.current_generation_point(&key) {
3607                    self.generation_summaries
3608                        .entry(key)
3609                        .or_insert_with(|| IntegrandGenerationSummary {
3610                            peak_ram_bytes: 0,
3611                            reports: Vec::new(),
3612                            generation_point: None,
3613                        })
3614                        .generation_point = Some(point);
3615                }
3616            }
3617        }
3618    }
3619
3620    /// The point a just-generated integrand was generated at: its effective
3621    /// input parameters and stored kinematics, and whether its process'
3622    /// generation decided on them. Value-dependent generation is refused
3623    /// unless the effective model equals the model it consumes (see
3624    /// [`Self::ensure_generation_consumes_the_effective_model`]), so these are
3625    /// exactly the values its decisions used.
3626    fn current_generation_point(
3627        &self,
3628        key: &IntegrandGenerationSummaryKey,
3629    ) -> Option<GenerationPoint> {
3630        let integrand = self
3631            .process_list
3632            .get_integrand(key.process_id, &key.integrand_name)
3633            .ok()?
3634            .require_generated()
3635            .ok()?;
3636        let settings = integrand.get_settings();
3637        let effective =
3638            Self::effective_model(&self.model, &self.model_parameters, settings).ok()?;
3639        let depends =
3640            self.process_list.processes[key.process_id].generation_depends_on_model_values();
3641        GenerationPoint::new(&effective, settings, depends).ok()
3642    }
3643
3644    /// Refuse value-dependent generation whose integrands would evaluate with
3645    /// other model values than the ones generation consumes. Generation
3646    /// consumes the session model itself, while the generated integrands
3647    /// evaluate with the session card and the runtime defaults' model overlay
3648    /// applied; with `check_esurface_at_generation` threshold decisions would
3649    /// then be made at values the integrand never uses. Without the check,
3650    /// generation is unchanged.
3651    fn ensure_generation_consumes_the_effective_model(
3652        &self,
3653        global_settings: &GlobalSettings,
3654        runtime_default: LockedRuntimeSettings,
3655    ) -> Result<()> {
3656        if !global_settings
3657            .generation
3658            .threshold_subtraction
3659            .check_esurface_at_generation
3660        {
3661            return Ok(());
3662        }
3663        let settings = RuntimeSettings::from(runtime_default);
3664        let effective = Self::effective_model(&self.model, &self.model_parameters, &settings)?;
3665        let consumed = GenerationPoint::new(&self.model, &settings, true)?;
3666        let evaluated = GenerationPoint::new(&effective, &settings, true)?;
3667        match consumed.difference(&evaluated) {
3668            None => Ok(()),
3669            Some(difference) => Err(eyre!(
3670                "generation.threshold_subtraction.check_esurface_at_generation decides which \
3671                 threshold counterterms exist with the session model, but {difference} differs \
3672                 in the model the generated integrands would evaluate with (the session card \
3673                 with the runtime model overlay applied); clear the runtime model overlay or \
3674                 apply the card with `set model`, then generate"
3675            )),
3676        }
3677    }
3678
3679    /// The recorded generation point of a generated integrand, if any.
3680    fn recorded_generation_point(
3681        &self,
3682        process_id: usize,
3683        integrand_name: &str,
3684    ) -> Option<&GenerationPoint> {
3685        self.generation_summary(process_id, integrand_name)
3686            .and_then(|summary| summary.generation_point.as_ref())
3687    }
3688
3689    /// Whether a generated integrand must stay at its generation point: as
3690    /// recorded with its point, or, without a record, conservatively from
3691    /// its process (see [`Process::generation_depends_on_model_values`]).
3692    fn integrand_depends_on_model_values(&self, process_id: usize, integrand_name: &str) -> bool {
3693        self.recorded_generation_point(process_id, integrand_name)
3694            .map_or_else(
3695                || self.process_list.processes[process_id].generation_depends_on_model_values(),
3696                |point| point.depends_on_model_values,
3697            )
3698    }
3699
3700    /// Refuse a model, card or settings change that moves a value-dependent
3701    /// generated integrand (see [`GenerationPoint::depends_on_model_values`])
3702    /// away from the point it was generated at. `model`, `card` and `settings`
3703    /// are the candidate session model, session card and integrand settings;
3704    /// the integrand resolves its overlay against them as every evaluation
3705    /// does, and its complete effective input parameters and kinematics
3706    /// must equal the recorded ones exactly.
3707    ///
3708    /// Without a record (an integrand copied without its summary), the
3709    /// reference is the current point, so any change is refused. Loading a
3710    /// state refuses such integrands outright, since the loaded values cannot
3711    /// be verified.
3712    pub fn ensure_generation_point_kept(
3713        &self,
3714        process_id: usize,
3715        integrand_name: &str,
3716        model: &Model,
3717        card: &InputParamCard<F<f64>>,
3718        settings: &RuntimeSettings,
3719    ) -> Result<()> {
3720        if !self.integrand_depends_on_model_values(process_id, integrand_name) {
3721            return Ok(());
3722        }
3723        self.ensure_effective_point_kept(
3724            process_id,
3725            integrand_name,
3726            &Self::effective_model(model, card, settings)?,
3727            settings,
3728        )
3729    }
3730
3731    /// [`Self::ensure_generation_point_kept`] for an already resolved
3732    /// effective model of the integrand.
3733    fn ensure_effective_point_kept(
3734        &self,
3735        process_id: usize,
3736        integrand_name: &str,
3737        effective_model: &Model,
3738        settings: &RuntimeSettings,
3739    ) -> Result<()> {
3740        if !self.integrand_depends_on_model_values(process_id, integrand_name) {
3741            return Ok(());
3742        }
3743        let candidate = GenerationPoint::new(effective_model, settings, true)?;
3744        let reference = match self.recorded_generation_point(process_id, integrand_name) {
3745            Some(point) => point.clone(),
3746            None => {
3747                let current = self
3748                    .process_list
3749                    .get_integrand(process_id, integrand_name)?
3750                    .require_generated()?
3751                    .get_settings();
3752                GenerationPoint::new(&self.resolve_model_for_settings(current)?, current, true)?
3753            }
3754        };
3755        let Some(difference) = reference.difference(&candidate) else {
3756            return Ok(());
3757        };
3758        let folder = &self.process_list.processes[process_id]
3759            .definition
3760            .folder_name;
3761        Err(eyre!(
3762            "integrand '{integrand_name}' of process '{folder}' was generated with the model values \
3763             and kinematics deciding which threshold counterterms exist \
3764             (generation.threshold_subtraction.check_esurface_at_generation, or no recorded \
3765             generation settings), and {difference} would differ from that generation point; \
3766             remove it with `remove processes -p name:{folder}` and regenerate it at the new point"
3767        ))
3768    }
3769
3770    /// Check a loaded state: every value-dependent generated integrand must
3771    /// have a recorded generation point, and its current settings with the
3772    /// session model and card must be exactly at that point. Without a record
3773    /// the state cannot be verified as unchanged, so it is refused.
3774    fn ensure_generation_points_kept(&self) -> Result<()> {
3775        for (process_id, process) in self.process_list.processes.iter().enumerate() {
3776            let folder = &process.definition.folder_name;
3777            for name in process.collection.get_integrand_names() {
3778                let resolved = self.process_list.get_integrand(process_id, name)?;
3779                if let Some(settings) = resolved.get_settings() {
3780                    if self.recorded_generation_point(process_id, name).is_none()
3781                        && process.generation_depends_on_model_values()
3782                    {
3783                        return Err(eyre!(
3784                            "integrand '{name}' of process '{folder}' was generated with model \
3785                             values and kinematics deciding which threshold counterterms exist, \
3786                             but its generation point was not recorded, so the loaded model \
3787                             values and kinematics cannot be verified as unchanged; regenerate \
3788                             it, loading the other processes with `--processes` if needed"
3789                        ));
3790                    }
3791                    self.ensure_generation_point_kept(
3792                        process_id,
3793                        name,
3794                        &self.model,
3795                        &self.model_parameters,
3796                        settings,
3797                    )?;
3798                }
3799            }
3800        }
3801        Ok(())
3802    }
3803
3804    fn remove_generation_summaries_for_process(&mut self, process_id: usize) {
3805        let mut updated = BTreeMap::new();
3806        for (mut key, mut summary) in std::mem::take(&mut self.generation_summaries) {
3807            if key.process_id == process_id {
3808                continue;
3809            }
3810            if key.process_id > process_id {
3811                key.process_id -= 1;
3812                for report in &mut summary.reports {
3813                    if report.process_id > process_id {
3814                        report.process_id -= 1;
3815                    }
3816                }
3817            }
3818            updated.insert(key, summary);
3819        }
3820        self.generation_summaries = updated;
3821    }
3822
3823    fn remove_generation_summaries_for_process_without_shifting(&mut self, process_id: usize) {
3824        self.generation_summaries
3825            .retain(|key, _| key.process_id != process_id);
3826    }
3827
3828    pub fn export_dots(
3829        &mut self,
3830        path: impl AsRef<Path>,
3831        settings: &DotExportSettings,
3832    ) -> Result<()> {
3833        self.process_list.export_dot(path, settings)?;
3834        Ok(())
3835    }
3836
3837    pub fn import_graphs(
3838        &mut self,
3839        mut graphs: Vec<Graph>,
3840        options: GraphImportOptions,
3841    ) -> Result<()> {
3842        // Everything below indexes the graphs' typed identifiers against
3843        // `self.model`; bind them to the shared session model first.
3844        let model = self.shared_graph_model();
3845        for graph in &graphs {
3846            graph.ensure_bound_to(&model).wrap_err_with(|| {
3847                format!(
3848                    "Cannot import graph '{}' into a state using model '{}'; import the model \
3849                     the graph was built with first",
3850                    graph.name,
3851                    model.name()
3852                )
3853            })?;
3854        }
3855        for graph in &mut graphs {
3856            graph.rebind_model(&model);
3857        }
3858        let GraphImportOptions {
3859            process_name,
3860            process_id,
3861            process_definition,
3862            integrand_name,
3863            overwrite,
3864            append,
3865        } = options;
3866        let generation_type = Self::infer_graph_list_generation_type(&graphs)?;
3867        if let Some(definition) = &process_definition {
3868            if definition.generation_type != generation_type {
3869                return Err(eyre!(
3870                    "--process-spec describes a {} process, but the imported graph list is {}",
3871                    definition.generation_type,
3872                    generation_type
3873                ));
3874            }
3875        }
3876
3877        let integrand_base_name = integrand_name.clone().unwrap_or("default".to_string());
3878        let process = if let Some(proc_id) = process_id {
3879            if proc_id >= self.process_list.processes.len() {
3880                return Err(eyre!(
3881                    "Process ID {} invalid, only {} processes available",
3882                    proc_id,
3883                    self.process_list.processes.len()
3884                ));
3885            }
3886            Some(&mut self.process_list.processes[proc_id])
3887        } else {
3888            let p_name = match process_name {
3889                Some(n) => n,
3890                None => {
3891                    return Err(eyre!(
3892                        "Either process ID or process name must be provided when importing graphs"
3893                    ));
3894                }
3895            };
3896            if let Some(existing_proc) = self
3897                .process_list
3898                .processes
3899                .iter_mut()
3900                .find(|p| p.definition.folder_name == p_name)
3901            {
3902                Some(existing_proc)
3903            } else {
3904                let mut process_definition = match process_definition.clone() {
3905                    Some(definition) => definition,
3906                    None => {
3907                        // Final states are inferred from physical cuts only, so
3908                        // they are undetermined when every graph is selection-only.
3909                        let all_selection_only = graphs
3910                            .iter()
3911                            .all(|graph| !graph.finalized_spectator_cuts.is_empty());
3912                        if let Some(graph) = graphs.first().filter(|_| all_selection_only) {
3913                            return Err(eyre!(
3914                                "An explicit --process-spec is required to import graphs that are all selection-only, such as '{}': no physical cut determines the final state. Integrand construction is unsupported for these graphs",
3915                                graph.name
3916                            ));
3917                        }
3918                        ProcessDefinition::from_graph_list(&graphs, generation_type, &self.model)?
3919                    }
3920                };
3921                process_definition.process_id = self.process_list.processes.len();
3922                let process = Process::from_graph_list(
3923                    p_name,
3924                    integrand_base_name.clone(),
3925                    // TODO: avoid clone here
3926                    graphs.clone(),
3927                    generation_type,
3928                    Some(process_definition),
3929                    None,
3930                    &self.model,
3931                )?;
3932
3933                self.process_list.add_process(process);
3934                None
3935            }
3936        };
3937        if let Some(p) = process {
3938            if let Some(mut imported_definition) = process_definition {
3939                imported_definition.folder_name = p.definition.folder_name.clone();
3940                imported_definition.process_id = p.definition.process_id;
3941                if imported_definition != p.definition {
3942                    return Err(eyre!(
3943                        "--process-spec does not match existing process '{}'. Import the graphs into a new process or use the same process specification that created this process.",
3944                        p.definition.folder_name
3945                    ));
3946                }
3947            }
3948
3949            let existing_names = p.get_integrand_names();
3950            let integrand_name = if existing_names.contains(&integrand_base_name.as_str()) {
3951                if append {
3952                    let mut integrand_i = 0;
3953                    while existing_names
3954                        .iter()
3955                        .any(|ce| *ce == format!("{}_{}", integrand_base_name, integrand_i))
3956                    {
3957                        integrand_i += 1;
3958                    }
3959                    format!("{}_{}", integrand_base_name, integrand_i)
3960                } else if overwrite {
3961                    p.collection.remove_integrand(&integrand_base_name)?;
3962                    integrand_base_name.clone()
3963                } else {
3964                    return Err(eyre!(
3965                        "Integrand name '{}' already exists in process '{}', use either --overwrite or --append flag when loading graphs",
3966                        integrand_base_name,
3967                        p.definition.folder_name
3968                    ));
3969                }
3970            } else {
3971                integrand_base_name.clone()
3972            };
3973
3974            match generation_type {
3975                GenerationType::Amplitude => p
3976                    .collection
3977                    .add_amplitude(Amplitude::from_graph_list(integrand_name.clone(), graphs)?),
3978                GenerationType::CrossSection => {
3979                    p.collection
3980                        .add_cross_section(CrossSection::from_graph_list(
3981                            integrand_name.clone(),
3982                            graphs,
3983                        )?)
3984                }
3985            }
3986        }
3987
3988        Ok(())
3989    }
3990
3991    pub(crate) fn infer_graph_list_generation_type(graphs: &[Graph]) -> Result<GenerationType> {
3992        if graphs.iter().all(|g| g.initial_state_cut.nedges(g) == 0) {
3993            Ok(GenerationType::Amplitude)
3994        } else if graphs.iter().all(|g| g.initial_state_cut.nedges(g) > 0) {
3995            Ok(GenerationType::CrossSection)
3996        } else {
3997            Err(eyre!(
3998                "Mix of amplitude and cross section graphs in the same file is not supported"
3999            ))
4000        }
4001    }
4002
4003    pub fn new(log_dir: impl AsRef<Path>, log_file_name: Option<String>) -> Self {
4004        super::tracing::init_tracing(log_dir.as_ref().join("logs"), log_file_name);
4005        let _ = initialise();
4006
4007        Self {
4008            model: Model::empty("ModelNotLoaded"),
4009            process_list: ProcessList::default(),
4010            model_parameters: InputParamCard::default(),
4011            generation_summaries: BTreeMap::new(),
4012        }
4013    }
4014
4015    pub fn new_test() -> Self {
4016        init_test_tracing();
4017
4018        Self {
4019            model: Model::empty("ModelNotLoaded"),
4020            process_list: ProcessList::default(),
4021            model_parameters: InputParamCard::default(),
4022            generation_summaries: BTreeMap::new(),
4023        }
4024    }
4025
4026    pub fn new_bench() -> Self {
4027        init_bench_tracing();
4028
4029        Self {
4030            model: Model::empty("ModelNotLoaded"),
4031            process_list: ProcessList::default(),
4032            model_parameters: InputParamCard::default(),
4033            generation_summaries: BTreeMap::new(),
4034        }
4035    }
4036}
4037
4038#[derive(Debug, Clone, PartialEq, Eq)]
4039pub struct RemovedProcess {
4040    pub process_id: usize,
4041    pub process_name: String,
4042}
4043
4044#[derive(Debug, Clone, PartialEq, Eq)]
4045pub struct RemovedIntegrand {
4046    pub process_id: usize,
4047    pub process_name: String,
4048    pub integrand_name: String,
4049    pub removed_empty_process: bool,
4050}
4051
4052impl State {
4053    pub fn load(
4054        save_path: PathBuf,
4055        model_path: Option<PathBuf>,
4056        trace_logs_filename: Option<String>,
4057    ) -> Result<Self> {
4058        Self::load_with_selection(save_path, model_path, trace_logs_filename, None)
4059    }
4060
4061    pub fn load_with_selection(
4062        save_path: PathBuf,
4063        model_path: Option<PathBuf>,
4064        trace_logs_filename: Option<String>,
4065        selection: Option<&ProcessLoadSelection>,
4066    ) -> Result<Self> {
4067        Model::with_parameter_display_transaction(|| {
4068            // let root_folder = root_folder.join("gammaloop_state");
4069            let manifest = load_state_manifest(&save_path)?;
4070            validate_state_layout(&manifest, &save_path)?;
4071            // Install GammaLoop's subscriber before importing Symbolica state. Symbolica warnings
4072            // initialize its fallback subscriber on first use, which would otherwise claim the global
4073            // tracing dispatch and escape ANSI styling in all subsequent GammaLoop output.
4074            let mut loaded_state = State::new(&save_path, trace_logs_filename);
4075            debug!("Loading state manifest version {}", manifest.version);
4076
4077            // Restore even symbols absent from the restricted model before parsing expressions
4078            // or importing the archive: Symbolica cannot attach callbacks to a plain symbol later.
4079            for name in &manifest.ufo_print_symbols {
4080                let _ = UFOSymbol::from(name);
4081            }
4082            for label in &manifest.linnet_subgraph_print_labels {
4083                let _ = SuBitGraph::symbol_from_label(label.clone());
4084            }
4085
4086            // Load the model before importing Symbolica state so UFO symbols retain their custom print
4087            // callbacks; the import then remaps serialized symbol ids onto those definitions.
4088            let mut model = if let Some(model_path) = &model_path {
4089                info!("Loading model from {}", model_path.display());
4090                Model::from_path(model_path)?
4091            } else {
4092                let model_dir = save_path.join("model.json");
4093                info!(
4094                    "Loading model from default location: {}",
4095                    model_dir.display()
4096                );
4097                Model::from_path(model_dir)?
4098            };
4099
4100            debug!("Loaded model: {}", model.name());
4101
4102            let input_param_card = if save_path.join("model_parameters.json").exists() {
4103                let a = InputParamCard::from_file(save_path.join("model_parameters.json"))?;
4104
4105                model.apply_param_card(&a).wrap_err_with(|| {
4106                    format!(
4107                        "Saved parameter card {} cannot be applied to the saved model",
4108                        save_path.join("model_parameters.json").display()
4109                    )
4110                })?;
4111                a
4112            } else {
4113                model.default_param_card()
4114            };
4115
4116            let symbolica_state = symbolica::state::State::import(
4117                &mut fs::File::open(save_path.join("symbolica_state.bin"))
4118                    .context("Trying to open symbolica state binary")?,
4119                None,
4120            )?;
4121
4122            // Every decoded graph binds to this one shared model.
4123            let model = Arc::new(model);
4124            let context: GammaLoopContextContainer<'_> = GammaLoopContextContainer {
4125                state_map: &symbolica_state,
4126                model: &model,
4127            };
4128
4129            let process_list = ProcessList::load_with_selection(&save_path, context, selection)
4130                .context("Trying to load processList")?;
4131
4132            loaded_state.process_list = process_list;
4133            loaded_state.model = Arc::unwrap_or_clone(model);
4134            loaded_state.model_parameters = input_param_card;
4135            loaded_state.generation_summaries =
4136                load_integrand_generation_summaries(&save_path, &loaded_state.process_list)?;
4137            // A card edited on disk must not silently move value-dependent integrands.
4138            loaded_state
4139                .ensure_generation_points_kept()
4140                .wrap_err("State was not loaded: it no longer matches its generation point")?;
4141            Ok(loaded_state)
4142        })
4143    }
4144
4145    pub fn activate_loaded_integrand_backends(
4146        &mut self,
4147        allow_symjit_fallback: bool,
4148    ) -> Result<()> {
4149        self.process_list
4150            .activate_loaded_integrand_backends(allow_symjit_fallback)
4151    }
4152
4153    pub fn compile(
4154        &mut self,
4155        root_folder: &Path,
4156        override_compiled: bool,
4157        settings: &GlobalSettings,
4158    ) -> Result<()> {
4159        fs::create_dir_all(root_folder)?;
4160
4161        let compile_pool = rayon::ThreadPoolBuilder::new()
4162            .num_threads(settings.n_cores.compile)
4163            .build()?;
4164        self.process_list
4165            .compile(root_folder, override_compiled, None, None, &compile_pool)?;
4166        Ok(())
4167    }
4168
4169    fn save_generation_summaries(&self, root_folder: &Path) -> Result<()> {
4170        for (process_id, process) in self.process_list.processes.iter().enumerate() {
4171            for integrand_name in process.collection.get_integrand_names() {
4172                let summary_path =
4173                    integrand_generation_summary_path(root_folder, process, integrand_name);
4174                let key = IntegrandGenerationSummaryKey {
4175                    process_id,
4176                    integrand_name: integrand_name.to_string(),
4177                };
4178                if let Some(summary) = self.generation_summaries.get(&key) {
4179                    if let Some(parent) = summary_path.parent() {
4180                        fs::create_dir_all(parent)?;
4181                    }
4182                    let raw_summary = serde_json::to_string_pretty(summary).with_context(|| {
4183                        format!(
4184                            "Trying to serialize integrand generation summary {}",
4185                            summary_path.display()
4186                        )
4187                    })?;
4188                    fs::write(&summary_path, raw_summary).with_context(|| {
4189                        format!(
4190                            "Trying to write integrand generation summary {}",
4191                            summary_path.display()
4192                        )
4193                    })?;
4194                } else if summary_path.exists() {
4195                    fs::remove_file(&summary_path).with_context(|| {
4196                        format!(
4197                            "Trying to remove stale integrand generation summary {}",
4198                            summary_path.display()
4199                        )
4200                    })?;
4201                }
4202            }
4203        }
4204
4205        Ok(())
4206    }
4207
4208    pub fn save(
4209        &mut self,
4210        root_folder: &Path,
4211        override_state_file: bool,
4212        strict: bool,
4213    ) -> Result<()> {
4214        self.ensure_graphs_match_model()?;
4215
4216        // let root_folder = root_folder.join("gammaloop_state");
4217
4218        // check if the export root exists, if not create it, if it does return error
4219        let mut selected_root_folder = PathBuf::from(root_folder);
4220        let mut user_input = String::new();
4221        if !root_folder.exists() {
4222            fs::create_dir_all(root_folder)?;
4223        } else {
4224            if strict {
4225                return Err(eyre!(
4226                    "Export root already exists, please choose a different path or remove the existing directory",
4227                ));
4228            }
4229
4230            if !override_state_file {
4231                while selected_root_folder.exists() {
4232                    println!(
4233                        "Gammaloop export root {} already exists. Specify 'o' for overwriting, 'n' for not saving, or '<NEW_PATH>' to specify where to save current state to:",
4234                        selected_root_folder.display()
4235                    );
4236                    user_input.clear();
4237                    io::stdin()
4238                        .read_line(&mut user_input)
4239                        .expect("Could not read user-specified gammaloop state export destination");
4240                    //user_input = user_input.trim().into();
4241                    match user_input.trim() {
4242                        "o" => break,
4243                        "n" => {
4244                            return Ok(());
4245                        }
4246                        new_path => {
4247                            selected_root_folder = PathBuf::from(new_path);
4248                            continue;
4249                        }
4250                    }
4251                }
4252            }
4253        }
4254
4255        if selected_root_folder.join(STATE_MANIFEST_FILE).exists() {
4256            load_state_manifest(&selected_root_folder)?;
4257        }
4258        fs::create_dir_all(&selected_root_folder)?;
4259
4260        let mut state_file =
4261        // info!("Hi");
4262            fs::File::create(selected_root_folder.join("symbolica_state.bin"))?;
4263
4264        symbolica::state::State::export(&mut state_file)?;
4265        self.process_list
4266            .save(&selected_root_folder, override_state_file)?;
4267        self.save_generation_summaries(&selected_root_folder)?;
4268
4269        // let binary = bincode::encode_to_vec(&self.integrands, bincode::config::standard())?;
4270        // fs::write(root_folder.join("process_list.bin"), binary)?;?
4271        self.model
4272            .write_json(selected_root_folder.join("model.json"))?;
4273        self.model_parameters.to_file(
4274            selected_root_folder.join("model_parameters.json"),
4275            override_state_file,
4276        )?;
4277        save_state_manifest(&selected_root_folder)?;
4278        Ok(())
4279    }
4280}
4281
4282#[cfg(test)]
4283mod tests {
4284    use std::{fs, process::Command};
4285
4286    use crate::{OneShot, StateLoadOption, DEFAULT_RUNTIME_SETTINGS_FILENAME, LOG_TEST_MUTEX};
4287    use gammalooprs::{
4288        graph::Graph,
4289        initialisation::test_initialise,
4290        integrands::process::{ActiveF64Backend, GaussianReferenceFunction},
4291        model::ModelGammaLoopExt,
4292        momentum::{Dep, ExternalMomenta, Helicity},
4293        processes::{
4294            process::ProcessCollection, GenerationProcessKind, GenerationProgressObserver,
4295            GenerationProgressObserverGuard, GenerationProgressPhase, RaisedPropagatorScope,
4296            RaisedPropagatorSignature, SelectionPolarity,
4297        },
4298        request_interrupt,
4299        settings::global::{CompilationMode, FrozenCompilationMode},
4300        settings::{
4301            runtime::kinematic::{improvement::PhaseSpaceImprovementSettings, Externals},
4302            KinematicsSettings, RuntimeSettings,
4303        },
4304        utils::{
4305            load_generic_model,
4306            serde_utils::{ShowDefaultsGuard, SHOWDEFAULTS},
4307        },
4308    };
4309    use serde_json::Value as JsonValue;
4310    use spenso::shadowing::symbolica_utils::SpensoPrintSettings;
4311    use symbolica::atom::{Atom, AtomCore, NamespacedSymbol, Symbol};
4312    use symbolica::numerical_integration::Sample;
4313    use symbolica::printer::PrintOptions;
4314    use tempfile::tempdir;
4315
4316    use crate::commands::{
4317        display::Display,
4318        generate::ProcessArgs,
4319        save::SaveState,
4320        set::{KvPair, ModelSetValue, ProcessSetArgs, Set, SetArgs},
4321    };
4322
4323    use super::*;
4324
4325    const STATE_LOAD_ORDER_CHILD: &str = "GAMMALOOP_STATE_LOAD_ORDER_CHILD";
4326    const STATE_LOAD_ORDER_TEST: &str =
4327        "state::tests::state_load_preserves_ufo_symbols_and_model_values";
4328
4329    #[cfg(target_os = "linux")]
4330    #[test]
4331    fn generation_ram_monitor_parses_resident_bytes() {
4332        assert_eq!(
4333            GenerationMonitor::parse_resident_memory_bytes(
4334                "Name:\tgammaloop\nVmSize:\t9999 kB\nVmRSS:\t 123 kB\nRssAnon:\t100 kB\n"
4335            ),
4336            Some(123 * 1024)
4337        );
4338        assert_eq!(
4339            GenerationMonitor::parse_resident_memory_bytes("VmRSS: 0 kB\n"),
4340            Some(0)
4341        );
4342        for status in [
4343            "VmSize: 123 kB\n",
4344            "VmRSS: invalid kB\n",
4345            "VmRSS: 123\n",
4346            "VmRSS: 123 MB\n",
4347            "VmRSS: 123 kB extra\n",
4348            "VmRSS: 18446744073709551615 kB\n",
4349        ] {
4350            assert_eq!(GenerationMonitor::parse_resident_memory_bytes(status), None);
4351        }
4352    }
4353
4354    #[cfg(target_os = "linux")]
4355    #[test]
4356    fn generation_ram_monitor_records_short_generation() {
4357        let mut monitor = GenerationMonitor::start().unwrap();
4358        let initial_memory = monitor.current_ram_bytes().load(Ordering::Relaxed);
4359        assert!(initial_memory > 0);
4360        let peak_memory = monitor.finish();
4361        assert!(peak_memory >= initial_memory);
4362        assert!(peak_memory >= monitor.current_ram_bytes().load(Ordering::Relaxed));
4363        assert!(monitor.stop_requested.load(Ordering::Relaxed));
4364        assert!(monitor.handle.is_none());
4365        assert_eq!(monitor.finish(), peak_memory);
4366    }
4367
4368    #[test]
4369    fn generation_ram_monitor_wakes_on_finish() {
4370        let stop_requested = Arc::new(AtomicBool::new(false));
4371        let stop_for_thread = Arc::clone(&stop_requested);
4372        let (ready, ready_receiver) = std::sync::mpsc::channel();
4373        let handle = thread::spawn(move || {
4374            ready.send(()).unwrap();
4375            loop {
4376                thread::park();
4377                if stop_for_thread.load(Ordering::Relaxed) {
4378                    break;
4379                }
4380            }
4381        });
4382        let mut monitor = GenerationMonitor {
4383            peak_ram_bytes: Arc::new(AtomicU64::new(123)),
4384            current_ram_bytes: Arc::new(AtomicU64::new(123)),
4385            stop_requested,
4386            handle: Some(handle),
4387        };
4388        ready_receiver.recv().unwrap();
4389        assert_eq!(monitor.finish(), 123);
4390    }
4391
4392    #[test]
4393    fn state_load_preserves_ufo_symbols_and_model_values() {
4394        if let Some(state_path) = std::env::var_os(STATE_LOAD_ORDER_CHILD) {
4395            for _ in 0..2 {
4396                let state = State::load(PathBuf::from(&state_path), None, None).unwrap();
4397                let ProcessCollection::Amplitudes(amplitudes) =
4398                    &state.process_list.processes[0].collection
4399                else {
4400                    panic!("expected an amplitude");
4401                };
4402                let mut params = amplitudes["default"].graphs[0].graph.param_builder.clone();
4403                let saved_values = params.values.clone();
4404                assert_eq!(saved_values.len(), 3);
4405                assert!(!params.pairs.model_parameters.params.is_empty());
4406                params.update_model_values(&state.model).unwrap();
4407                for (actual, expected) in params.values.iter().zip(&saved_values) {
4408                    for (actual, expected) in actual.iter().zip(expected) {
4409                        for (actual, expected) in
4410                            [(actual.re.0, expected.re.0), (actual.im.0, expected.im.0)]
4411                        {
4412                            assert!(
4413                                (actual - expected).abs() <= 1e-13 * expected.abs().max(1.0),
4414                                "model value changed after reload: {actual} != {expected}"
4415                            );
4416                        }
4417                    }
4418                }
4419                let mut model = state.model.clone();
4420                let mut card = model.default_param_card();
4421                card.insert("aS".into(), Complex::new_re(F(1.0)));
4422                model.apply_param_card(&card).unwrap();
4423                params.update_model_values(&model).unwrap();
4424                let coupling = model.get_coupling("GC_12");
4425                let position = params.pairs.model_parameters.value_range.start
4426                    + params
4427                        .pairs
4428                        .model_parameters
4429                        .params
4430                        .iter()
4431                        .position(|param| {
4432                            *param == Atom::from(UFOSymbol::from(coupling.name.as_str()))
4433                        })
4434                        .unwrap();
4435                for (value_index, values) in params.values.iter().enumerate() {
4436                    assert_eq!(
4437                        values[position * (value_index + 1)],
4438                        Complex::new(F(coupling.value.unwrap().re), F(coupling.value.unwrap().im))
4439                    );
4440                }
4441                for name in ["G", "orphan_ufo_printer"] {
4442                    let symbol = UFOSymbol::from(name);
4443                    assert!(symbol.0.get_print_function().is_some(), "{name}");
4444                    let rendered = Atom::from(symbol)
4445                        .printer(SpensoPrintSettings::typst_options())
4446                        .to_string();
4447                    assert_eq!(rendered, format!("\"{name}\""));
4448                }
4449                for label in ["Dd0E4", "1⦻2"] {
4450                    let symbol = symbolica::get_symbol!(&format!("linnet::S_{label}")).unwrap();
4451                    assert!(symbol.get_print_function().is_some(), "{label}");
4452                    assert_eq!(
4453                        Atom::var(symbol)
4454                            .printer(SpensoPrintSettings::typst_options())
4455                            .to_string(),
4456                        format!("#S(g,\"{label}\")")
4457                    );
4458                }
4459            }
4460            return;
4461        }
4462
4463        let temp = tempdir().unwrap();
4464        let mut state = State::new(temp.path(), None);
4465        // Force a different registration order from the alphabetical manifest replay.
4466        let _ = UFOSymbol::from("GC_12");
4467        state.model = load_generic_model("sm");
4468        state.model_parameters = state.model.default_param_card();
4469        let mut graphs = Graph::from_finalized_runtime_string(
4470            r#"digraph model_values {
4471                num=1; overall_factor=1; overall_factor_evaluated=1; projector=1;
4472                A [num=1];
4473                A:0 -> A:1 [particle="a", num=1, mass=0, id=0, lmb_id=0,
4474                    lmb_rep="K(0,a___)", source="{ufo_order:0}", sink="{ufo_order:1}"];
4475            }"#,
4476            &state.model,
4477        )
4478        .unwrap();
4479        graphs[0].param_builder.initialize_duals(3);
4480        state
4481            .import_graphs(
4482                graphs,
4483                GraphImportOptions {
4484                    process_name: Some("model_values".into()),
4485                    process_id: None,
4486                    process_definition: None,
4487                    integrand_name: Some("default".into()),
4488                    overwrite: false,
4489                    append: false,
4490                },
4491            )
4492            .unwrap();
4493        // Reproduce a coupling removed by a restriction: it survives in Symbolica's
4494        // global registry but has no declaration in the saved model.
4495        let _ = UFOSymbol::from("orphan_ufo_printer");
4496        for label in ["Dd0E4", "1⦻2"] {
4497            let _ = SuBitGraph::symbol_from_label(label.to_owned());
4498        }
4499        state.save(temp.path(), true, false).unwrap();
4500        let manifest = load_state_manifest(temp.path()).unwrap();
4501        assert_eq!(manifest.version, CURRENT_STATE_MANIFEST_VERSION);
4502        assert!(manifest
4503            .ufo_print_symbols
4504            .contains(&"orphan_ufo_printer".to_owned()));
4505        assert!(!fs::read_to_string(temp.path().join("model.json"))
4506            .unwrap()
4507            .contains("orphan_ufo_printer"));
4508
4509        let output = Command::new(std::env::current_exe().unwrap())
4510            .arg(STATE_LOAD_ORDER_TEST)
4511            .arg("--exact")
4512            .arg("--nocapture")
4513            .env(STATE_LOAD_ORDER_CHILD, temp.path())
4514            .env_remove("GL_ALL_LOG_FILTER")
4515            .env("GL_DISPLAY_FILTER", "warn")
4516            .output()
4517            .unwrap();
4518        let transcript = format!(
4519            "stdout:\n{}\nstderr:\n{}",
4520            String::from_utf8_lossy(&output.stdout),
4521            String::from_utf8_lossy(&output.stderr),
4522        );
4523        assert!(
4524            output.status.success(),
4525            "child failed: {}\n{transcript}",
4526            output.status
4527        );
4528        assert!(
4529            !transcript.contains("Imported symbol UFO::")
4530                && !transcript.contains("Imported symbol linnet::S_"),
4531            "{transcript}"
4532        );
4533    }
4534
4535    fn build_generated_scalar_bubble_state_with_external_backend() -> State {
4536        test_initialise().expect("test initialisation should succeed");
4537        let mut state = State::new_test();
4538        state.model = load_generic_model("scalars");
4539        state.model_parameters = state.model.default_param_card();
4540
4541        let graph_path =
4542            crate::test_workspace_root().join("tests/resources/graphs/scalar_bubble.dot");
4543        let graphs = Graph::from_finalized_runtime_path(&graph_path, &state.model)
4544            .expect("scalar bubble graph fixture should load");
4545
4546        state
4547            .import_graphs(
4548                graphs,
4549                GraphImportOptions {
4550                    process_name: Some("scalar_bubble".to_string()),
4551                    process_id: None,
4552                    process_definition: None,
4553                    integrand_name: Some("default".to_string()),
4554                    overwrite: false,
4555                    append: false,
4556                },
4557            )
4558            .expect("graph import should succeed");
4559
4560        let mut cli_settings = CLISettings::default();
4561        cli_settings.global.generation.evaluator.compile = true;
4562        cli_settings.global.generation.compile.compilation_mode = CompilationMode::Assembly;
4563
4564        let runtime_defaults = RuntimeSettings::default();
4565        state
4566            .generate_integrands(&cli_settings.global, (&runtime_defaults).into())
4567            .expect("integrand generation should succeed");
4568
4569        state
4570    }
4571
4572    #[test]
4573    fn named_generation_records_common_settings_for_persistent_uv_exports() -> Result<()> {
4574        use gammalooprs::{
4575            cff::{expression::AllOrientations, surface::GammaLoopSurfaceCache},
4576            uv::{export::UVForestExportSettings, UVOrchestrator},
4577        };
4578
4579        test_initialise()?;
4580        for (folder, source, model) in [
4581            (
4582                "amplitudes",
4583                include_str!("../../../tests/resources/graphs/scalar_bubble.dot"),
4584                load_generic_model("scalars"),
4585            ),
4586            (
4587                "cross_sections",
4588                include_str!(
4589                    "../../../tests/resources/graphs/mass_approach_scalar_self_energy.dot"
4590                ),
4591                Model::from_json(include_str!(
4592                    "../../../assets/models/json/scalars/scalars_2p_3p.json"
4593                ))?,
4594            ),
4595        ] {
4596            let temp = tempdir()?;
4597            let mut state = State::new_test();
4598            state.model = model;
4599            state.model_parameters = state.model.default_param_card();
4600            let mut graphs = Graph::import_dot(source, &state.model)?;
4601            graphs.truncate(1);
4602            let graph_name = graphs[0].name.clone();
4603            for name in ["first", "second"] {
4604                state.import_graphs(
4605                    graphs.clone(),
4606                    GraphImportOptions {
4607                        process_name: Some("named_export".into()),
4608                        process_id: None,
4609                        process_definition: None,
4610                        integrand_name: Some(name.into()),
4611                        overwrite: false,
4612                        append: false,
4613                    },
4614                )?;
4615            }
4616            let mut settings = GlobalSettings::default();
4617            settings.n_cores.generate = 1;
4618            settings.generation.uv.orchestrator = UVOrchestrator::HedgePoset;
4619            assert!(!settings.generation.evaluator.compile);
4620            assert!(!settings.generation.evaluator.store_atom);
4621            assert!(settings.generation.uv.subtract_uv);
4622            assert!(settings.generation.uv.generate_integrated);
4623            assert!(settings.generation.uv.softct);
4624            assert!(settings.generation.threshold_subtraction.enable_thresholds);
4625            let runtime = RuntimeSettings::default();
4626            assert!(state.process_list.processes[0].settings_history.is_none());
4627            for name in ["first", "second"] {
4628                // The second named build must keep the already-generated sibling's
4629                // identical source settings, without regenerating the whole process.
4630                state.generate_integrand(&settings, (&runtime).into(), 0, Some(name.into()))?;
4631                assert_eq!(
4632                    state.process_list.processes[0].settings_history.as_ref(),
4633                    Some(&settings)
4634                );
4635                state.process_list.processes[0]
4636                    .get_integrand(name)?
4637                    .require_generated()?;
4638            }
4639
4640            let source_expressions = |state: &State| {
4641                ["first", "second"].map(|name| {
4642                    let source = match &state.process_list.processes[0].collection {
4643                        ProcessCollection::Amplitudes(amplitudes) => {
4644                            &amplitudes[name].graphs[0].derived_data.representations
4645                                [&three_dimensional_reps::RepresentationMode::Cff]
4646                                .expression
4647                        }
4648                        ProcessCollection::CrossSections(cross_sections) => {
4649                            &cross_sections[name].supergraphs[0].derived_data.expressions
4650                                [&three_dimensional_reps::RepresentationMode::Cff]
4651                        }
4652                    };
4653                    source
4654                        .expression
4655                        .to_atom(AllOrientations)
4656                        .replace_multiple(source.expression.surfaces.get_all_replacements_gs(&[]))
4657                })
4658            };
4659
4660            // This State boundary cannot safely overwrite a generated sibling's
4661            // provenance. Check both missing and conflicting process history.
4662            let mut changed = settings.clone();
4663            changed.generation.explicit_orientation_sum_only = true;
4664            for missing_history in [false, true] {
4665                if missing_history {
4666                    state.process_list.processes[0].settings_history = None;
4667                }
4668                let before = source_expressions(&state);
4669                let history_before = state.process_list.processes[0].settings_history.clone();
4670                let error = state
4671                    .generate_integrand(
4672                        if missing_history { &settings } else { &changed },
4673                        (&runtime).into(),
4674                        0,
4675                        Some("first".into()),
4676                    )
4677                    .unwrap_err();
4678                assert!(
4679                    error.to_string().contains("regenerate the whole process"),
4680                    "{error:?}"
4681                );
4682                assert!(
4683                    source_expressions(&state)
4684                        .into_iter()
4685                        .zip(before)
4686                        .all(|(actual, expected)| (actual - expected).expand().is_zero()),
4687                    "named-generation source expressions changed after rejected generation"
4688                );
4689                assert_eq!(
4690                    state.process_list.processes[0].settings_history,
4691                    history_before
4692                );
4693                for name in ["first", "second"] {
4694                    state.process_list.processes[0]
4695                        .get_integrand(name)?
4696                        .require_generated()?;
4697                }
4698                state.process_list.processes[0].settings_history = Some(settings.clone());
4699            }
4700
4701            let source_before = source_expressions(&state);
4702            let mut exported_expression: Option<Atom> = None;
4703            for loaded in [false, true] {
4704                let process = &state.process_list.processes[0];
4705                assert_eq!(process.settings_history.as_ref(), Some(&settings));
4706                assert!(
4707                    source_expressions(&state)
4708                        .into_iter()
4709                        .zip(&source_before)
4710                        .all(|(actual, expected)| (actual - expected).expand().is_zero()),
4711                    "named-generation source expressions changed after persistence"
4712                );
4713                for computed in [false, true] {
4714                    let output = temp.path().join(format!("export-{loaded}-{computed}"));
4715                    state.process_list.export_uv_forests(
4716                        &state.model,
4717                        &output,
4718                        0,
4719                        "first",
4720                        &[0],
4721                        &UVForestExportSettings { computed },
4722                    )?;
4723                    let graph_dir = output
4724                        .join("processes")
4725                        .join(folder)
4726                        .join("named_export/first");
4727                    assert!(graph_dir.join(format!("{graph_name}.forest.dot")).is_file());
4728                    let nodes = graph_dir.join(format!("{graph_name}_nodes"));
4729                    if computed {
4730                        let mut exported_graph = false;
4731                        let mut expression = Atom::Zero;
4732                        for forest in fs::read_dir(&nodes)? {
4733                            for node in fs::read_dir(forest?.path())? {
4734                                let node = node?;
4735                                let dot = fs::read_to_string(node.path())?;
4736                                assert!(dot.contains("forest_residue_index"));
4737                                for graph in
4738                                    Graph::from_finalized_runtime_string(&dot, &state.model)?
4739                                {
4740                                    exported_graph = true;
4741                                    expression += graph.full_numerator_atom();
4742                                }
4743                            }
4744                        }
4745                        assert!(exported_graph, "computed export must contain a graph");
4746                        // Re-import the public export to compare its consumed function,
4747                        // including persisted source conventions, independently of node layout.
4748                        if let Some(expected) = &exported_expression {
4749                            assert!(
4750                                (&expression - expected).expand().is_zero(),
4751                                "computed UV export changed after persistence"
4752                            );
4753                        } else {
4754                            exported_expression = Some(expression);
4755                        }
4756                    } else {
4757                        assert!(!nodes.exists());
4758                    }
4759                }
4760                if !loaded {
4761                    let saved = temp.path().join("saved");
4762                    state.save(&saved, true, false)?;
4763                    let history_path = saved
4764                        .join("processes")
4765                        .join(folder)
4766                        .join("named_export/settings_history.toml");
4767                    let history: GlobalSettings =
4768                        toml::from_str(&fs::read_to_string(history_path)?)?;
4769                    assert_eq!(history, settings);
4770                    state = State::load(saved, None, None)?;
4771                }
4772            }
4773        }
4774        Ok(())
4775    }
4776
4777    #[test]
4778    fn aggregate_generation_progress_tracks_counts_and_timings() {
4779        let current_ram_bytes = Arc::new(AtomicU64::new(256 * 1024 * 1024));
4780        let peak_ram_bytes = Arc::new(AtomicU64::new(512 * 1024 * 1024));
4781        let reporter =
4782            AggregateGenerationProgressReporter::new_hidden(current_ram_bytes, peak_ram_bytes);
4783
4784        reporter.begin_phase(
4785            GenerationProgressPhase::GraphPreprocessing,
4786            GenerationProcessKind::CrossSection,
4787            "proc",
4788            "itg",
4789            2,
4790            None,
4791        );
4792        reporter.graph_started(GenerationProcessKind::CrossSection, "itg", "GL01", None);
4793        reporter.cuts_discovered("itg", "GL01", 4, 2);
4794        {
4795            let state = reporter
4796                .state
4797                .lock()
4798                .expect("aggregate generation progress state mutex is poisoned");
4799            assert_eq!(state.done_graphs, 0);
4800            assert_eq!(state.discovered_st_cuts, 4);
4801            assert_eq!(state.discovered_valid_cuts, 2);
4802            assert_eq!(
4803                AggregateGenerationProgressReporter::progress_units(&state),
4804                (0, 2)
4805            );
4806            assert_eq!(
4807                AggregateGenerationProgressReporter::graph_progress_counts(&state),
4808                (0, 1, 2)
4809            );
4810        }
4811        reporter.graph_finished(
4812            GenerationProcessKind::CrossSection,
4813            "itg",
4814            "GL01",
4815            &GraphGenerationStats {
4816                timings: gammalooprs::processes::GenerationTimings {
4817                    total_time: Duration::from_secs(3),
4818                    ..Default::default()
4819                },
4820                ..GraphGenerationStats::default()
4821            },
4822            None,
4823        );
4824        {
4825            let state = reporter
4826                .state
4827                .lock()
4828                .expect("aggregate generation progress state mutex is poisoned");
4829            assert_eq!(state.done_graphs, 1);
4830            assert_eq!(state.stats.timings.total_time, Duration::from_secs(3));
4831            assert_eq!(
4832                AggregateGenerationProgressReporter::graph_progress_counts(&state),
4833                (1, 0, 2)
4834            );
4835        }
4836
4837        reporter.begin_phase(
4838            GenerationProgressPhase::GraphGeneration,
4839            GenerationProcessKind::CrossSection,
4840            "proc",
4841            "itg",
4842            2,
4843            Some(3),
4844        );
4845        reporter.graph_started(GenerationProcessKind::CrossSection, "itg", "GL01", Some(1));
4846        reporter.graph_started(GenerationProcessKind::CrossSection, "itg", "GL02", Some(2));
4847        {
4848            let state = reporter
4849                .state
4850                .lock()
4851                .expect("aggregate generation progress state mutex is poisoned");
4852            assert_eq!(
4853                AggregateGenerationProgressReporter::graph_progress_counts(&state),
4854                (0, 2, 2)
4855            );
4856        }
4857        reporter.graph_finished(
4858            GenerationProcessKind::CrossSection,
4859            "itg",
4860            "GL01",
4861            &GraphGenerationStats {
4862                timings: gammalooprs::processes::GenerationTimings {
4863                    evaluator_count: 2,
4864                    total_time: Duration::from_secs(4),
4865                    evaluator_spenso_time: Duration::from_secs(1),
4866                    evaluator_symbolica_time: Duration::from_secs(1),
4867                    evaluator_compile_time: Duration::ZERO,
4868                },
4869                ..GraphGenerationStats::default()
4870            },
4871            None,
4872        );
4873        reporter.cut_finished("itg", "GL01", 1);
4874        reporter.graph_finished(
4875            GenerationProcessKind::CrossSection,
4876            "itg",
4877            "GL02",
4878            &GraphGenerationStats {
4879                timings: gammalooprs::processes::GenerationTimings {
4880                    evaluator_count: 3,
4881                    total_time: Duration::from_secs(6),
4882                    evaluator_spenso_time: Duration::from_secs(2),
4883                    evaluator_symbolica_time: Duration::ZERO,
4884                    evaluator_compile_time: Duration::ZERO,
4885                },
4886                ..GraphGenerationStats::default()
4887            },
4888            None,
4889        );
4890        reporter.cut_finished("itg", "GL02", 2);
4891
4892        {
4893            let state = reporter
4894                .state
4895                .lock()
4896                .expect("aggregate generation progress state mutex is poisoned");
4897            assert_eq!(state.done_graphs, 2);
4898            assert_eq!(state.done_cuts, 3);
4899            assert!(state.active_graphs.is_empty());
4900            assert_eq!(state.last_graph.as_deref(), Some("GL02"));
4901            assert_eq!(state.stats.timings.evaluator_count, 5);
4902            assert_eq!(state.stats.timings.total_time, Duration::from_secs(10));
4903            assert_eq!(state.stats.expression_build_time(), Duration::from_secs(6));
4904            assert_eq!(
4905                state.stats.timings.evaluator_spenso_time,
4906                Duration::from_secs(3)
4907            );
4908            assert_eq!(
4909                state.stats.timings.evaluator_symbolica_time,
4910                Duration::from_secs(1)
4911            );
4912            assert_eq!(
4913                AggregateGenerationProgressReporter::progress_units(&state),
4914                (5, 5)
4915            );
4916            assert_eq!(
4917                AggregateGenerationProgressReporter::graph_progress_counts(&state),
4918                (2, 0, 2)
4919            );
4920        }
4921
4922        reporter.backend_started(GenerationProcessKind::CrossSection, "itg", 2);
4923        reporter.backend_finished(
4924            GenerationProcessKind::CrossSection,
4925            "itg",
4926            Duration::from_secs(2),
4927        );
4928
4929        let state = reporter
4930            .state
4931            .lock()
4932            .expect("aggregate generation progress state mutex is poisoned");
4933        assert_eq!(state.phase, Some(GenerationProgressPhase::Backend));
4934        assert_eq!(state.done_graphs, 2);
4935        assert_eq!(state.stats.timings.total_time, Duration::from_secs(12));
4936        assert_eq!(
4937            state.stats.timings.evaluator_compile_time,
4938            Duration::from_secs(2)
4939        );
4940    }
4941
4942    #[test]
4943    fn aggregate_generation_progress_tracks_amplitude_preprocessing() {
4944        let reporter = AggregateGenerationProgressReporter::new_hidden(
4945            Arc::new(AtomicU64::new(0)),
4946            Arc::new(AtomicU64::new(0)),
4947        );
4948
4949        reporter.begin_phase(
4950            GenerationProgressPhase::GraphPreprocessing,
4951            GenerationProcessKind::Amplitude,
4952            "proc",
4953            "amp",
4954            3,
4955            None,
4956        );
4957        reporter.graph_started(GenerationProcessKind::Amplitude, "amp", "GL01", None);
4958        reporter.graph_started(GenerationProcessKind::Amplitude, "amp", "GL02", None);
4959
4960        {
4961            let state = reporter
4962                .state
4963                .lock()
4964                .expect("aggregate generation progress state mutex is poisoned");
4965            assert_eq!(state.kind, Some(GenerationProcessKind::Amplitude));
4966            assert_eq!(state.process, "proc");
4967            assert_eq!(state.integrand, "amp");
4968            assert_eq!(
4969                AggregateGenerationProgressReporter::progress_units(&state),
4970                (0, 3)
4971            );
4972            assert_eq!(
4973                AggregateGenerationProgressReporter::graph_progress_counts(&state),
4974                (0, 2, 3)
4975            );
4976        }
4977
4978        reporter.graph_finished(
4979            GenerationProcessKind::Amplitude,
4980            "amp",
4981            "GL01",
4982            &GraphGenerationStats::default(),
4983            None,
4984        );
4985
4986        let state = reporter
4987            .state
4988            .lock()
4989            .expect("aggregate generation progress state mutex is poisoned");
4990        assert_eq!(
4991            AggregateGenerationProgressReporter::progress_units(&state),
4992            (1, 3)
4993        );
4994        assert_eq!(
4995            AggregateGenerationProgressReporter::graph_progress_counts(&state),
4996            (1, 1, 3)
4997        );
4998        assert_eq!(state.last_graph.as_deref(), Some("GL01"));
4999    }
5000
5001    #[test]
5002    fn aggregate_generation_progress_formats_memory_and_time_shares() {
5003        assert_eq!(
5004            AggregateGenerationProgressReporter::progress_memory(512 * 1024 * 1024),
5005            "   512 MiB"
5006        );
5007        assert_eq!(
5008            AggregateGenerationProgressReporter::progress_memory(5 * 1024 * 1024 * 1024),
5009            "  5.00 GiB"
5010        );
5011
5012        assert_eq!(
5013            AggregateGenerationProgressReporter::progress_percent(0.0),
5014            "0%"
5015        );
5016        assert_eq!(
5017            AggregateGenerationProgressReporter::progress_percent(0.009),
5018            "0%"
5019        );
5020        assert_eq!(
5021            AggregateGenerationProgressReporter::progress_percent(0.024),
5022            "0.024%"
5023        );
5024        assert_eq!(
5025            AggregateGenerationProgressReporter::progress_percent(0.24),
5026            "0.24%"
5027        );
5028        assert_eq!(
5029            AggregateGenerationProgressReporter::progress_percent(2.4),
5030            "2.4%"
5031        );
5032        assert_eq!(
5033            AggregateGenerationProgressReporter::progress_percent(54.0),
5034            "54%"
5035        );
5036
5037        assert_eq!(
5038            AggregateGenerationProgressReporter::progress_time_share(
5039                Duration::ZERO,
5040                Duration::ZERO,
5041            ),
5042            "--"
5043        );
5044        assert_eq!(
5045            AggregateGenerationProgressReporter::progress_time_share(
5046                Duration::ZERO,
5047                Duration::from_secs(4),
5048            ),
5049            "0%"
5050        );
5051        assert_eq!(
5052            AggregateGenerationProgressReporter::progress_time_share(
5053                Duration::from_secs(1),
5054                Duration::from_secs(4),
5055            ),
5056            "25%"
5057        );
5058    }
5059
5060    fn build_scalar_bubble_diagram_state() -> State {
5061        test_initialise().expect("test initialisation should succeed");
5062        let mut state = State::new_test();
5063        state.model = load_generic_model("scalars");
5064        state.model_parameters = state.model.default_param_card();
5065
5066        let graph_path =
5067            crate::test_workspace_root().join("tests/resources/graphs/scalar_bubble.dot");
5068        let graphs = Graph::from_finalized_runtime_path(&graph_path, &state.model)
5069            .expect("scalar bubble graph fixture should load");
5070        state
5071            .import_graphs(
5072                graphs,
5073                GraphImportOptions {
5074                    process_name: Some("scalar_bubble".to_string()),
5075                    process_id: None,
5076                    process_definition: None,
5077                    integrand_name: Some("default".to_string()),
5078                    overwrite: false,
5079                    append: false,
5080                },
5081            )
5082            .expect("graph import should succeed");
5083        state
5084    }
5085
5086    fn scalar_bubble_master_graph_name(state: &State, integrand_name: &str) -> String {
5087        let process = &state.process_list.processes[0];
5088        match &process.collection {
5089            ProcessCollection::Amplitudes(amplitudes) => amplitudes
5090                .get(integrand_name)
5091                .expect("amplitude should exist")
5092                .graphs[0]
5093                .graph
5094                .name
5095                .clone(),
5096            ProcessCollection::CrossSections(cross_sections) => cross_sections
5097                .get(integrand_name)
5098                .expect("cross section should exist")
5099                .supergraphs[0]
5100                .graph
5101                .name
5102                .clone(),
5103        }
5104    }
5105
5106    #[test]
5107    fn select_copy_mode_creates_pregenerated_target_without_mutating_source() {
5108        let _guard = crate::LOG_TEST_MUTEX
5109            .lock()
5110            .unwrap_or_else(|err| err.into_inner());
5111        let mut state = build_scalar_bubble_diagram_state();
5112        let temp = tempdir().unwrap();
5113        let graph_name = scalar_bubble_master_graph_name(&state, "default");
5114        let selection = GraphGroupSelectionSpec::new().with_master_graph_names(vec![graph_name]);
5115        let target = GraphGroupSelectionTarget::copy(None, Some("selected".to_string()), false);
5116
5117        let selected = state
5118            .select_integrand_graph_groups(
5119                Some(&ProcessRef::Name("scalar_bubble".to_string())),
5120                Some(&"default".to_string()),
5121                &selection,
5122                &target,
5123                GraphGroupSelectionContext::new(&GenerationSettings::default(), temp.path(), false),
5124            )
5125            .unwrap();
5126
5127        assert!(selected.copied_to_output);
5128        assert_eq!(selected.process_id, 0);
5129        assert_eq!(selected.integrand_name, "selected");
5130        let process = &state.process_list.processes[0];
5131        assert!(process
5132            .collection
5133            .get_integrand_names()
5134            .contains(&"default"));
5135        assert!(process
5136            .collection
5137            .get_integrand_names()
5138            .contains(&"selected"));
5139        match &process.collection {
5140            ProcessCollection::Amplitudes(amplitudes) => {
5141                assert!(amplitudes["default"].integrand.is_none());
5142                assert!(amplitudes["selected"].integrand.is_none());
5143                assert_eq!(amplitudes["default"].graphs.len(), 1);
5144                assert_eq!(amplitudes["selected"].graphs.len(), 1);
5145            }
5146            ProcessCollection::CrossSections(cross_sections) => {
5147                assert!(cross_sections["default"].integrand.is_none());
5148                assert!(cross_sections["selected"].integrand.is_none());
5149                assert_eq!(cross_sections["default"].supergraphs.len(), 1);
5150                assert_eq!(cross_sections["selected"].supergraphs.len(), 1);
5151            }
5152        }
5153    }
5154
5155    #[test]
5156    fn select_copy_mode_rejects_and_clears_existing_target_integrand() {
5157        let _guard = crate::LOG_TEST_MUTEX
5158            .lock()
5159            .unwrap_or_else(|err| err.into_inner());
5160        let mut state = build_scalar_bubble_diagram_state();
5161        let temp = tempdir().unwrap();
5162        let graph_name = scalar_bubble_master_graph_name(&state, "default");
5163        let selection = GraphGroupSelectionSpec::new().with_master_graph_names(vec![graph_name]);
5164        let target = GraphGroupSelectionTarget::copy(None, Some("selected".to_string()), false);
5165
5166        state
5167            .select_integrand_graph_groups(
5168                Some(&ProcessRef::Name("scalar_bubble".to_string())),
5169                Some(&"default".to_string()),
5170                &selection,
5171                &target,
5172                GraphGroupSelectionContext::new(&GenerationSettings::default(), temp.path(), false),
5173            )
5174            .unwrap();
5175        let err = state
5176            .select_integrand_graph_groups(
5177                Some(&ProcessRef::Name("scalar_bubble".to_string())),
5178                Some(&"default".to_string()),
5179                &selection,
5180                &target,
5181                GraphGroupSelectionContext::new(&GenerationSettings::default(), temp.path(), false),
5182            )
5183            .unwrap_err();
5184        assert!(format!("{err}").contains("already exists"));
5185
5186        let process = &state.process_list.processes[0];
5187        let kind_folder = match &process.collection {
5188            ProcessCollection::Amplitudes(_) => "amplitudes",
5189            ProcessCollection::CrossSections(_) => "cross_sections",
5190        };
5191        let stale_integrand_folder = temp
5192            .path()
5193            .join("processes")
5194            .join(kind_folder)
5195            .join("scalar_bubble")
5196            .join("selected");
5197        fs::create_dir_all(stale_integrand_folder.join("integrand")).unwrap();
5198        state.generation_summaries.insert(
5199            IntegrandGenerationSummaryKey {
5200                process_id: 0,
5201                integrand_name: "selected".to_string(),
5202            },
5203            IntegrandGenerationSummary {
5204                peak_ram_bytes: 1,
5205                reports: Vec::new(),
5206                generation_point: None,
5207            },
5208        );
5209
5210        let clear_target =
5211            GraphGroupSelectionTarget::copy(None, Some("selected".to_string()), true);
5212        let selected = state
5213            .select_integrand_graph_groups(
5214                Some(&ProcessRef::Name("scalar_bubble".to_string())),
5215                Some(&"default".to_string()),
5216                &selection,
5217                &clear_target,
5218                GraphGroupSelectionContext::new(&GenerationSettings::default(), temp.path(), false),
5219            )
5220            .unwrap();
5221        assert!(selected.replaced_existing_target);
5222        assert!(selected.removed_target_artifacts);
5223        assert!(!stale_integrand_folder.exists());
5224        assert!(!state
5225            .generation_summaries
5226            .contains_key(&IntegrandGenerationSummaryKey {
5227                process_id: 0,
5228                integrand_name: "selected".to_string(),
5229            }));
5230
5231        let err = state
5232            .select_integrand_graph_groups(
5233                Some(&ProcessRef::Name("scalar_bubble".to_string())),
5234                Some(&"default".to_string()),
5235                &selection,
5236                &clear_target,
5237                GraphGroupSelectionContext::new(&GenerationSettings::default(), temp.path(), true),
5238            )
5239            .unwrap_err();
5240        assert!(format!("{err}").contains("--read-only-state"));
5241    }
5242
5243    #[test]
5244    fn select_amplitude_graphs_mode_rejects_amplitude_integrands() {
5245        let _guard = crate::LOG_TEST_MUTEX
5246            .lock()
5247            .unwrap_or_else(|err| err.into_inner());
5248        let mut state = build_scalar_bubble_diagram_state();
5249        let temp = tempdir().unwrap();
5250        let graph_name = scalar_bubble_master_graph_name(&state, "default");
5251        let selection = GraphGroupSelectionSpec::new()
5252            .with_mode(GraphGroupSelectionMode::CrossSectionAmplitudeGraphs)
5253            .with_master_graph_names(vec![graph_name]);
5254        let target = GraphGroupSelectionTarget::in_place();
5255
5256        let err = state
5257            .select_integrand_graph_groups(
5258                Some(&ProcessRef::Name("scalar_bubble".to_string())),
5259                Some(&"default".to_string()),
5260                &selection,
5261                &target,
5262                GraphGroupSelectionContext::new(&GenerationSettings::default(), temp.path(), false),
5263            )
5264            .unwrap_err();
5265
5266        assert!(format!("{err}").contains("--amplitude-graphs"));
5267    }
5268
5269    #[test]
5270    fn select_raised_cut_filters_reject_amplitude_integrands() {
5271        let _guard = crate::LOG_TEST_MUTEX
5272            .lock()
5273            .unwrap_or_else(|err| err.into_inner());
5274        let mut state = build_scalar_bubble_diagram_state();
5275        let temp = tempdir().unwrap();
5276        let selection = GraphGroupSelectionSpec::new().with_raised_cut_signatures(
5277            SelectionPolarity::With,
5278            RaisedPropagatorScope::All,
5279            vec![RaisedPropagatorSignature::from_str("[]").unwrap()],
5280        );
5281        let target = GraphGroupSelectionTarget::in_place();
5282
5283        let err = state
5284            .select_integrand_graph_groups(
5285                Some(&ProcessRef::Name("scalar_bubble".to_string())),
5286                Some(&"default".to_string()),
5287                &selection,
5288                &target,
5289                GraphGroupSelectionContext::new(&GenerationSettings::default(), temp.path(), false),
5290            )
5291            .unwrap_err();
5292
5293        assert!(format!("{err}").contains("cross-section integrands"));
5294    }
5295
5296    #[test]
5297    fn test_run_history() {
5298        use crate::state::RunHistory;
5299        //SHOWDEFAULTS.store(true, std::sync::atomic::Ordering::Relaxed);
5300        let mut run_history: RunHistory = Default::default();
5301        let kinematics_settings = KinematicsSettings {
5302            e_cm: 100.0,
5303            externals: Externals::Constant {
5304                momenta: vec![
5305                    ExternalMomenta::Independent([F(1.), F(2.), F(3.), F(4.)]),
5306                    ExternalMomenta::Dependent(Dep::Dep),
5307                ],
5308                improvement_settings: PhaseSpaceImprovementSettings::default(),
5309                helicities: vec![Helicity::PLUS, Helicity::MINUS],
5310                f_64_cache: None,
5311                f_128_cache: None,
5312                arb_cache: Default::default(),
5313            },
5314        };
5315
5316        run_history.push(Commands::Set(Set::Global {
5317            input: SetArgs::Stored,
5318        }));
5319
5320        run_history.default_runtime_settings.kinematics = kinematics_settings;
5321        set_serialize_commands_as_strings(true);
5322        let toml = toml::to_string_pretty(&run_history).unwrap();
5323        println!("{}", toml);
5324        let deserialized: RunHistory = toml::from_str(&toml).unwrap();
5325        assert_eq!(run_history, deserialized);
5326        SHOWDEFAULTS.store(false, std::sync::atomic::Ordering::Relaxed);
5327
5328        run_history.to_file("test_path.toml", true).unwrap();
5329        let deserialized_from_file = RunHistory::from_file("test_path.toml", " ").unwrap();
5330        assert_eq!(run_history, deserialized_from_file);
5331    }
5332
5333    #[test]
5334    fn run_history_applies_default_runtime_before_commands() {
5335        let mut run_history = RunHistory {
5336            default_runtime_settings: toml::from_str(
5337                r#"
5338[sampling]
5339graphs = "monte_carlo"
5340orientations = "summed"
5341sampling_multichanneling = false
5342sampling_channels = "summed"
5343coordinate_system = "tropical"
5344mapping = "linear"
5345b = 1.0
5346"#,
5347            )
5348            .unwrap(),
5349            ..Default::default()
5350        };
5351
5352        let mut state = State::new_test();
5353        let mut cli_settings = CLISettings::default();
5354        let mut default_runtime_settings = RuntimeSettings::default();
5355
5356        let _ = run_history
5357            .run(&mut state, &mut cli_settings, &mut default_runtime_settings)
5358            .unwrap();
5359
5360        assert_eq!(
5361            default_runtime_settings.sampling,
5362            run_history.default_runtime_settings.sampling
5363        );
5364    }
5365
5366    #[test]
5367    fn test_command_history_serialization() {
5368        use super::{set_serialize_commands_as_strings, CommandHistory};
5369        use crate::commands::Commands;
5370
5371        // Test basic construction
5372        let cmd_history = CommandHistory::new(Commands::Quit(SaveState::default()));
5373        assert_eq!(cmd_history.raw_string, None);
5374
5375        // Test with raw string
5376        let cmd_history_with_raw =
5377            CommandHistory::new_with_raw(Commands::Quit(SaveState::default()), "quit".to_string());
5378        assert_eq!(cmd_history_with_raw.raw_string, Some("quit".to_string()));
5379
5380        // Test serialization as Commands (default behavior)
5381        set_serialize_commands_as_strings(false);
5382
5383        let json = serde_json::to_string(&cmd_history).unwrap();
5384        let deserialized_json: CommandHistory = serde_json::from_str(&json).unwrap();
5385        let toml = toml::to_string(&cmd_history).unwrap();
5386        let deserialized_toml: CommandHistory = toml::from_str(&toml).unwrap();
5387        assert_eq!(cmd_history, deserialized_json);
5388        assert_eq!(cmd_history, deserialized_toml);
5389
5390        // Test serialization as string
5391        set_serialize_commands_as_strings(true);
5392
5393        let json_string = serde_json::to_string_pretty(&cmd_history_with_raw).unwrap();
5394        assert!(json_string.contains("quit"));
5395
5396        // Reset flag
5397        set_serialize_commands_as_strings(false);
5398    }
5399
5400    #[test]
5401    fn test_command_history_toml_and_json_formats() {
5402        use super::{set_serialize_commands_as_strings, CommandHistory};
5403        use crate::commands::Commands;
5404
5405        // Test different command types
5406        let quit_cmd = CommandHistory::new(Commands::Quit(SaveState::default()));
5407        let quit_with_raw =
5408            CommandHistory::new_with_raw(Commands::Quit(SaveState::default()), "quit".to_string());
5409
5410        // Test JSON serialization/deserialization
5411        {
5412            // Test Commands format in JSON
5413            set_serialize_commands_as_strings(false);
5414            let json = serde_json::to_string_pretty(&quit_cmd).unwrap();
5415            let deserialized: CommandHistory = serde_json::from_str(&json).unwrap();
5416            assert_eq!(quit_cmd, deserialized);
5417
5418            // Test string format in JSON
5419            set_serialize_commands_as_strings(true);
5420            let json_string = serde_json::to_string_pretty(&quit_with_raw).unwrap();
5421            assert!(json_string.contains("quit"));
5422            let deserialized_string: CommandHistory = serde_json::from_str(&json_string).unwrap();
5423            assert_eq!(quit_with_raw, deserialized_string);
5424        }
5425
5426        // Test TOML serialization/deserialization with wrapper struct
5427        {
5428            #[derive(serde::Serialize, serde::Deserialize)]
5429            struct CommandWrapper {
5430                command: CommandHistory,
5431            }
5432
5433            // Test Commands format in TOML
5434            set_serialize_commands_as_strings(false);
5435            let wrapper = CommandWrapper {
5436                command: quit_cmd.clone(),
5437            };
5438            let toml = toml::to_string_pretty(&wrapper).unwrap();
5439            let deserialized_wrapper: CommandWrapper = toml::from_str(&toml).unwrap();
5440            assert_eq!(quit_cmd, deserialized_wrapper.command);
5441
5442            // Test string format in TOML
5443            set_serialize_commands_as_strings(true);
5444            let wrapper_string = CommandWrapper {
5445                command: quit_with_raw.clone(),
5446            };
5447            let toml_string = toml::to_string_pretty(&wrapper_string).unwrap();
5448            assert!(toml_string.contains("quit"));
5449            let deserialized_string_wrapper: CommandWrapper = toml::from_str(&toml_string).unwrap();
5450            assert_eq!(quit_with_raw, deserialized_string_wrapper.command);
5451        }
5452
5453        // Test cross-format compatibility: serialize in one format, deserialize in another
5454        {
5455            set_serialize_commands_as_strings(false);
5456
5457            // Serialize as JSON, deserialize the Commands directly from JSON Value
5458            let json = serde_json::to_string(&quit_cmd).unwrap();
5459            let json_value: serde_json::Value = serde_json::from_str(&json).unwrap();
5460            let from_json: CommandHistory = serde_json::from_value(json_value).unwrap();
5461            assert_eq!(quit_cmd, from_json);
5462        }
5463        // Reset flag
5464        set_serialize_commands_as_strings(false);
5465    }
5466
5467    #[test]
5468    fn run_history_push_with_raw_skips_quit_and_definition_commands() {
5469        use super::RunHistory;
5470        use crate::commands::{run::Run, StartCommandsBlock};
5471
5472        let mut run_history = RunHistory::default();
5473        run_history.push_with_raw(
5474            Commands::Run(Run {
5475                block_names: vec!["block_a".to_string()],
5476                defines: Vec::new(),
5477                commands: None,
5478            }),
5479            Some("run block_a".to_string()),
5480        );
5481        run_history.push_with_raw(
5482            Commands::Quit(SaveState::default()),
5483            Some("quit".to_string()),
5484        );
5485        run_history.push_with_raw(
5486            Commands::StartCommandsBlock(StartCommandsBlock {
5487                name: "block_a".to_string(),
5488            }),
5489            Some("start_commands_block block_a".to_string()),
5490        );
5491        run_history.push_with_raw(
5492            Commands::FinishCommandsBlock,
5493            Some("finish_commands_block".to_string()),
5494        );
5495
5496        assert_eq!(run_history.commands.len(), 1);
5497        assert_eq!(
5498            run_history.commands[0].raw_string.as_deref(),
5499            Some("run block_a")
5500        );
5501    }
5502
5503    #[test]
5504    fn run_history_filtered_for_save_preserves_command_blocks() {
5505        let mut run_history = RunHistory {
5506            command_blocks: vec![
5507                CommandsBlock {
5508                    name: "generate".to_string(),
5509                    commands: vec![CommandHistory::new_with_raw(
5510                        Commands::Display(Display::Processes),
5511                        "display processes".to_string(),
5512                    )],
5513                },
5514                CommandsBlock {
5515                    name: "integrate".to_string(),
5516                    commands: vec![CommandHistory::new_with_raw(
5517                        CommandHistory::from_raw_string("quit -o").unwrap().command,
5518                        "quit -o".to_string(),
5519                    )],
5520                },
5521            ],
5522            ..Default::default()
5523        };
5524        run_history.push_with_raw(
5525            CommandHistory::from_raw_string("display processes")
5526                .unwrap()
5527                .command,
5528            Some("display processes".to_string()),
5529        );
5530
5531        let filtered = run_history.filtered_for_save();
5532        set_serialize_commands_as_strings(true);
5533        let toml = toml::to_string_pretty(&filtered).unwrap();
5534        set_serialize_commands_as_strings(false);
5535
5536        assert_eq!(filtered.command_blocks.len(), 2);
5537        assert!(toml.contains("commands = ["));
5538        assert!(toml.contains("[[command_blocks]]"));
5539        assert!(toml.contains("quit -o"));
5540    }
5541
5542    #[test]
5543    fn command_history_parses_multiline_set_string() {
5544        let raw = "set process -p epem_a_tth -i LO string '[integrator]\nn_start = 1000\n'";
5545        let cmd = CommandHistory::from_raw_string(raw).unwrap();
5546        assert_eq!(cmd.raw_string.as_deref(), Some(raw));
5547
5548        match cmd.command {
5549            Commands::Set(Set::Process { input, .. }) => match input {
5550                ProcessSetArgs::String { string } => {
5551                    assert_eq!(string, "[integrator]\nn_start = 1000\n");
5552                }
5553                other => panic!("Expected string set input, got {other:?}"),
5554            },
5555            other => panic!("Expected set process command, got {other:?}"),
5556        }
5557    }
5558
5559    #[test]
5560    fn command_history_parses_hash_process_refs() {
5561        // TOML reports positive integer IDs through the signed visitor, while
5562        // JSON uses the unsigned visitor. Both must round-trip numeric IDs.
5563        for process in [
5564            ProcessRef::Id(0),
5565            ProcessRef::Id(12),
5566            ProcessRef::Name("12".into()),
5567            ProcessRef::Unqualified("scalar_bubble".into()),
5568        ] {
5569            let refs = BTreeMap::from([("process".to_string(), process)]);
5570            let toml = toml::to_string(&refs).unwrap();
5571            assert_eq!(
5572                toml::from_str::<BTreeMap<String, ProcessRef>>(&toml).unwrap(),
5573                refs
5574            );
5575            let json = serde_json::to_string(&refs).unwrap();
5576            assert_eq!(
5577                serde_json::from_str::<BTreeMap<String, ProcessRef>>(&json).unwrap(),
5578                refs
5579            );
5580        }
5581        for invalid in ["process = -1", "process = 1.5"] {
5582            assert!(toml::from_str::<BTreeMap<String, ProcessRef>>(invalid).is_err());
5583        }
5584        assert!(serde_json::from_str::<ProcessRef>("-1").is_err());
5585
5586        let cmd = CommandHistory::from_raw_string("display integrand -p #12").unwrap();
5587        match cmd.command {
5588            Commands::Display(Display::Integrands {
5589                process,
5590                integrand_name,
5591                graphs,
5592                categories,
5593                hide_non_existing_thresholds,
5594                show_threshold_functions,
5595                show_sampling,
5596                show_threshold_subtraction,
5597            }) => {
5598                assert_eq!(process, Some(ProcessRef::Id(12)));
5599                assert_eq!(integrand_name, None);
5600                assert!(graphs.is_empty());
5601                assert!(categories.is_empty());
5602                assert!(!hide_non_existing_thresholds);
5603                assert!(!show_threshold_functions);
5604                assert_eq!(show_sampling, None);
5605                assert_eq!(show_threshold_subtraction, None);
5606            }
5607            other => panic!("Expected display integrand command, got {other:?}"),
5608        }
5609    }
5610
5611    #[test]
5612    fn command_history_requires_explicit_generate_mode() {
5613        assert!(CommandHistory::from_raw_string("generate e+ e- > d d~").is_err());
5614    }
5615
5616    #[test]
5617    fn run_history_parses_triple_quoted_set_kv_command() {
5618        let toml = r#"
5619commands = [
5620    """set default-runtime kv kinematics.externals='{"type":"constant","data":{"momenta":[[1.0,2.0,3.0,4.0],[5.0,6.0,-7.0,-8.0]],"helicities":[1,1]}}'""",
5621]
5622
5623[default_runtime_settings.general]
5624integral_unit = "picobarn"
5625"#;
5626
5627        let run_history: RunHistory = toml::from_str(toml).unwrap();
5628        assert_eq!(run_history.commands.len(), 1);
5629
5630        let expected_cmd = r#"set default-runtime kv kinematics.externals='{"type":"constant","data":{"momenta":[[1.0,2.0,3.0,4.0],[5.0,6.0,-7.0,-8.0]],"helicities":[1,1]}}'"#;
5631        let command_history = &run_history.commands[0];
5632        assert_eq!(command_history.raw_string.as_deref(), Some(expected_cmd));
5633
5634        match &command_history.command {
5635            Commands::Set(Set::DefaultRuntime {
5636                input: SetArgs::Kv { pairs },
5637            }) => {
5638                assert_eq!(pairs.len(), 1);
5639                assert_eq!(pairs[0].key, "kinematics.externals");
5640                assert_eq!(
5641                    pairs[0].value,
5642                    r#"{"type":"constant","data":{"momenta":[[1.0,2.0,3.0,4.0],[5.0,6.0,-7.0,-8.0]],"helicities":[1,1]}}"#
5643                );
5644            }
5645            other => panic!("Expected set default-runtime kv command, got {other:?}"),
5646        }
5647
5648        assert_eq!(
5649            run_history.default_runtime_settings.general.integral_unit,
5650            gammalooprs::settings::runtime::IntegralUnit::Picobarn
5651        );
5652    }
5653
5654    #[test]
5655    fn run_history_load_preserves_command_blocks() {
5656        let temp = tempdir().unwrap();
5657        let run_path = temp.path().join("run.toml");
5658        fs::write(
5659            &run_path,
5660            r#"
5661[[command_blocks]]
5662name = "zeta"
5663commands = ["quit -n"]
5664
5665[[command_blocks]]
5666name = "alpha"
5667commands = ["quit -o"]
5668"#,
5669        )
5670        .unwrap();
5671
5672        let run_history = RunHistory::load(&run_path).unwrap();
5673        assert!(run_history.commands.is_empty());
5674        assert_eq!(run_history.command_blocks.len(), 2);
5675    }
5676
5677    #[test]
5678    fn run_history_selects_named_command_blocks_in_order() {
5679        let temp = tempdir().unwrap();
5680        let run_path = temp.path().join("run.toml");
5681        fs::write(
5682            &run_path,
5683            r#"
5684[[command_blocks]]
5685name = "first"
5686commands = ["quit -n"]
5687
5688[[command_blocks]]
5689name = "second"
5690commands = ["quit -o"]
5691"#,
5692        )
5693        .unwrap();
5694
5695        let requested = vec!["second".to_string(), "first".to_string()];
5696        let run_history = RunHistory::load(&run_path).unwrap();
5697        let selected = run_history
5698            .select_command_blocks(requested.as_slice())
5699            .unwrap();
5700        assert_eq!(selected.len(), 2);
5701        assert_eq!(
5702            selected[0].commands[0].raw_string.as_deref(),
5703            Some("quit -o")
5704        );
5705        assert_eq!(
5706            selected[1].commands[0].raw_string.as_deref(),
5707            Some("quit -n")
5708        );
5709    }
5710
5711    #[test]
5712    fn run_history_selection_rejects_unknown_command_block() {
5713        let temp = tempdir().unwrap();
5714        let run_path = temp.path().join("run.toml");
5715        fs::write(
5716            &run_path,
5717            r#"
5718[[command_blocks]]
5719name = "first"
5720commands = ["quit -n"]
5721"#,
5722        )
5723        .unwrap();
5724
5725        let requested = vec!["missing".to_string()];
5726        let run_history = RunHistory::load(&run_path).unwrap();
5727        let err = run_history
5728            .select_command_blocks(requested.as_slice())
5729            .unwrap_err();
5730        let message = format!("{err}");
5731        assert!(message.contains("Unknown command block 'missing'"));
5732        assert!(message.contains("first"));
5733    }
5734
5735    #[test]
5736    fn run_history_selection_rejects_missing_command_block_when_only_legacy_commands_exist() {
5737        let temp = tempdir().unwrap();
5738        let run_path = temp.path().join("run.toml");
5739        fs::write(
5740            &run_path,
5741            r#"
5742commands = ["quit -o"]
5743"#,
5744        )
5745        .unwrap();
5746
5747        let requested = vec!["first".to_string()];
5748        let run_history = RunHistory::load(&run_path).unwrap();
5749        let err = run_history
5750            .select_command_blocks(requested.as_slice())
5751            .unwrap_err();
5752        assert!(format!("{err}").contains("Unknown command block"));
5753    }
5754
5755    #[test]
5756    fn run_history_load_accepts_commands_and_command_blocks_together() {
5757        let temp = tempdir().unwrap();
5758        let run_path = temp.path().join("run.toml");
5759        fs::write(
5760            &run_path,
5761            r#"
5762commands = ["quit -o"]
5763
5764[[command_blocks]]
5765name = "first"
5766commands = ["quit -n"]
5767"#,
5768        )
5769        .unwrap();
5770
5771        let run_history = RunHistory::load(&run_path).unwrap();
5772        assert_eq!(run_history.commands.len(), 1);
5773        assert_eq!(run_history.command_blocks.len(), 1);
5774        assert_eq!(
5775            run_history.commands[0].raw_string.as_deref(),
5776            Some("quit -o")
5777        );
5778    }
5779
5780    #[test]
5781    fn run_history_load_rejects_duplicate_command_block_names() {
5782        let temp = tempdir().unwrap();
5783        let run_path = temp.path().join("run.toml");
5784        fs::write(
5785            &run_path,
5786            r#"
5787[[command_blocks]]
5788name = "first"
5789commands = ["quit -o"]
5790
5791[[command_blocks]]
5792name = "first"
5793commands = ["quit -n"]
5794"#,
5795        )
5796        .unwrap();
5797
5798        let err = RunHistory::load(&run_path).unwrap_err();
5799        assert!(format!("{err}").contains("duplicate block name"));
5800    }
5801
5802    #[test]
5803    fn state_manifest_roundtrip_current_version() {
5804        let temp = tempdir().unwrap();
5805        save_state_manifest(temp.path()).unwrap();
5806
5807        let manifest = load_state_manifest(temp.path()).unwrap();
5808        assert_eq!(manifest.version, CURRENT_STATE_MANIFEST_VERSION);
5809    }
5810
5811    #[test]
5812    fn state_manifest_rejects_legacy_versions() {
5813        for version in 0..CURRENT_STATE_MANIFEST_VERSION {
5814            let temp = tempdir().unwrap();
5815            fs::write(
5816                temp.path().join(STATE_MANIFEST_FILE),
5817                format!("version = {version}\n"),
5818            )
5819            .unwrap();
5820
5821            let err = load_state_manifest(temp.path()).unwrap_err();
5822            let message = err.to_string();
5823            assert!(message.contains("cannot be migrated"));
5824            assert!(message.contains("regenerate the saved state"));
5825        }
5826    }
5827
5828    #[test]
5829    fn state_load_rejects_previous_branch_layouts_before_deserialization() {
5830        for version in [20, 21, 22, 23, 24] {
5831            let temp = tempdir().unwrap();
5832            fs::write(
5833                temp.path().join(STATE_MANIFEST_FILE),
5834                format!("version = {version}\n"),
5835            )
5836            .unwrap();
5837            // Every payload is deliberately unreadable. The version guard must
5838            // win before model parsing, symbolic import or positional decoding.
5839            fs::write(temp.path().join("model.json"), b"invalid model").unwrap();
5840            fs::write(temp.path().join("symbolica_state.bin"), b"invalid archive").unwrap();
5841            fs::create_dir(temp.path().join("processes")).unwrap();
5842            fs::write(
5843                temp.path().join("processes/processes.bin"),
5844                b"invalid processes",
5845            )
5846            .unwrap();
5847
5848            let error = match State::load(temp.path().to_path_buf(), None, None) {
5849                Ok(_) => panic!("previous branch layout {version} must be rejected"),
5850                Err(error) => error,
5851            };
5852            let message = error.to_string();
5853            assert!(message.contains(&format!("State version {version}")));
5854            assert!(message.contains(&format!(
5855                "supported version {CURRENT_STATE_MANIFEST_VERSION}"
5856            )));
5857            assert!(message.contains("regenerate the saved state"));
5858        }
5859    }
5860
5861    #[test]
5862    fn state_manifest_requires_an_explicit_version() {
5863        let temp = tempdir().unwrap();
5864        fs::write(temp.path().join(STATE_MANIFEST_FILE), "").unwrap();
5865
5866        let err = load_state_manifest(temp.path()).unwrap_err();
5867        assert!(err.to_string().contains("missing field `version`"));
5868    }
5869
5870    #[test]
5871    fn state_save_rejects_legacy_target_before_writing() {
5872        for version in [1, 20, 21, 22, 23, 24] {
5873            let temp = tempdir().unwrap();
5874            let symbolica_state = temp.path().join("symbolica_state.bin");
5875            fs::write(
5876                temp.path().join(STATE_MANIFEST_FILE),
5877                format!("version = {version}\n"),
5878            )
5879            .unwrap();
5880            fs::write(&symbolica_state, b"legacy sentinel").unwrap();
5881            let mut state = State::new_test();
5882
5883            let err = state.save(temp.path(), true, false).unwrap_err();
5884            assert!(err.to_string().contains("cannot be migrated"));
5885            assert_eq!(fs::read(symbolica_state).unwrap(), b"legacy sentinel");
5886            assert!(!temp.path().join("model.json").exists());
5887        }
5888    }
5889
5890    #[test]
5891    fn state_manifest_rejects_future_versions() {
5892        let temp = tempdir().unwrap();
5893        let future_manifest = StateManifest {
5894            version: CURRENT_STATE_MANIFEST_VERSION + 1,
5895            ..StateManifest::default()
5896        };
5897        fs::write(
5898            temp.path().join(STATE_MANIFEST_FILE),
5899            toml::to_string_pretty(&future_manifest).unwrap(),
5900        )
5901        .unwrap();
5902
5903        let err = load_state_manifest(temp.path()).unwrap_err();
5904        assert!(format!("{err}").contains("newer than this binary supports"));
5905    }
5906
5907    #[test]
5908    fn state_manifest_rejects_pre_feynkit_unification_versions() {
5909        let temp = tempdir().unwrap();
5910        let legacy_manifest = StateManifest {
5911            version: 1,
5912            ufo_print_symbols: Vec::new(),
5913            linnet_subgraph_print_labels: Vec::new(),
5914        };
5915        fs::write(
5916            temp.path().join(STATE_MANIFEST_FILE),
5917            toml::to_string_pretty(&legacy_manifest).unwrap(),
5918        )
5919        .unwrap();
5920
5921        let err = load_state_manifest(temp.path()).unwrap_err();
5922        assert!(format!("{err}").contains("regenerate the saved state"));
5923    }
5924
5925    #[test]
5926    fn state_folder_classifies_saved_layout() {
5927        let temp = tempdir().unwrap();
5928        save_state_manifest(temp.path()).unwrap();
5929        fs::write(temp.path().join("model.json"), "{}").unwrap();
5930        fs::write(temp.path().join("symbolica_state.bin"), []).unwrap();
5931        fs::create_dir_all(temp.path().join("processes")).unwrap();
5932
5933        assert_eq!(
5934            classify_state_folder(temp.path()).unwrap(),
5935            StateFolderKind::Saved
5936        );
5937    }
5938
5939    #[test]
5940    fn state_folder_classifies_logs_only_folder_as_scratch() {
5941        let temp = tempdir().unwrap();
5942        fs::create_dir_all(temp.path().join("logs")).unwrap();
5943        fs::write(temp.path().join("logs").join("gammalog.jsonl"), "").unwrap();
5944
5945        assert_eq!(
5946            classify_state_folder(temp.path()).unwrap(),
5947            StateFolderKind::Scratch
5948        );
5949    }
5950
5951    #[test]
5952    fn state_folder_classifies_non_manifest_contents_as_unmanifested() {
5953        let temp = tempdir().unwrap();
5954        fs::create_dir_all(temp.path().join("processes").join("amplitudes")).unwrap();
5955
5956        assert_eq!(
5957            classify_state_folder(temp.path()).unwrap(),
5958            StateFolderKind::Unmanifested
5959        );
5960    }
5961
5962    #[test]
5963    fn activate_loaded_integrand_backends_falls_back_to_eager_when_external_artifacts_are_missing()
5964    {
5965        let mut state = build_generated_scalar_bubble_state_with_external_backend();
5966
5967        state.activate_loaded_integrand_backends(false).unwrap();
5968
5969        for process in &state.process_list.processes {
5970            match &process.collection {
5971                ProcessCollection::Amplitudes(amplitudes) => {
5972                    for amplitude in amplitudes.values() {
5973                        let integrand = amplitude.integrand.as_ref().unwrap();
5974                        if matches!(
5975                            integrand.frozen_compilation(),
5976                            FrozenCompilationMode::Cpp(_) | FrozenCompilationMode::Assembly(_)
5977                        ) {
5978                            assert_eq!(integrand.active_f64_backend(), ActiveF64Backend::Eager);
5979                        }
5980                    }
5981                }
5982                ProcessCollection::CrossSections(cross_sections) => {
5983                    for cross_section in cross_sections.values() {
5984                        let integrand = cross_section.integrand.as_ref().unwrap();
5985                        if matches!(
5986                            integrand.frozen_compilation(),
5987                            FrozenCompilationMode::Cpp(_) | FrozenCompilationMode::Assembly(_)
5988                        ) {
5989                            assert_eq!(integrand.active_f64_backend(), ActiveF64Backend::Eager);
5990                        }
5991                    }
5992                }
5993            }
5994        }
5995    }
5996
5997    #[test]
5998    fn saved_generated_process_runs_reference_acceptance_after_reload() -> Result<()> {
5999        use gammalooprs::{
6000            graph::GroupId,
6001            settings::runtime::{
6002                DiscreteGraphSamplingSettings, DiscreteGraphSamplingType, SamplingSettings,
6003                StabilityLevelSetting,
6004            },
6005        };
6006        use symbolica::numerical_integration::Sample;
6007
6008        let _guard = crate::LOG_TEST_MUTEX
6009            .lock()
6010            .unwrap_or_else(|err| err.into_inner());
6011        let bubble = build_generated_scalar_bubble_state_with_external_backend();
6012        let mut kite = State::new_test();
6013        kite.model = load_generic_model("scalars");
6014        kite.model_parameters = kite.model.default_param_card();
6015        kite.model_parameters
6016            .insert("mass_scalar_1".into(), Complex::new_re(F(1.0)));
6017        kite.model.apply_param_card(&kite.model_parameters)?;
6018        kite.import_graphs(
6019            Graph::import_dot(
6020                &std::fs::read_to_string(
6021                    crate::test_workspace_root().join("tests/resources/graphs/massive_kite.dot"),
6022                )?,
6023                &kite.model,
6024            )?,
6025            GraphImportOptions {
6026                process_name: Some("sampling_kite".into()),
6027                process_id: None,
6028                process_definition: None,
6029                integrand_name: Some("default".into()),
6030                overwrite: false,
6031                append: false,
6032            },
6033        )?;
6034        let global: GlobalSettings = toml::from_str(
6035            r#"
6036[n_cores]
6037generate = 1
6038[generation]
6039override_lmb_heuristics = true
6040[generation.uv]
6041subtract_uv = false
6042generate_integrated = false
6043[generation.evaluator]
6044compile = false
6045summed = false
6046summed_function_map = true
6047iterative_orientation_optimization = false
6048"#,
6049        )?;
6050        let mut runtime: RuntimeSettings = toml::from_str(
6051            r#"
6052[general]
6053evaluator_method = "SummedFunctionMap"
6054integral_unit = "none"
6055enable_cache = false
6056[kinematics]
6057e_cm = 5.0
6058[kinematics.externals]
6059type = "constant"
6060[kinematics.externals.data]
6061momenta = [[5.0, 0.0, 0.0, 0.0], "dependent"]
6062helicities = [0, 0]
6063[sampling]
6064graphs = "summed"
6065orientations = "summed"
6066sampling_multichanneling = true
6067sampling_channels = "summed"
6068power = 2.0
6069default_channel_selection = ["C", "D", "ordinary"]
6070[sampling.channel_definitions.massive_kite.C]
6071around = "surface(2,4,6)"
6072parent_lmb = [4,6]
6073subspace_lmb = [4,6]
6074[sampling.channel_definitions.massive_kite.D]
6075around = "surface(3,5,6)"
6076parent_lmb = [4,6]
6077subspace_lmb = [4,6]
6078[sampling.channel_definitions.massive_kite.ordinary]
6079around = "lmb(4,6)"
6080parent_lmb = [4,6]
6081[stability]
6082rotation_axis = [{type = "x"}, {type = "y"}]
6083"#,
6084        )?;
6085        runtime.stability.levels = vec![StabilityLevelSetting::default_double()];
6086        kite.generate_integrands(&global, (&runtime).into())?;
6087
6088        // Reuse the same saved-process acceptance path for a physical cut. Two
6089        // names deliberately share its geometry while retaining distinct radial
6090        // proposals; the broad components give the shifted Gaussian full support.
6091        let mut cut = State::new_test();
6092        cut.model = kite.model.clone();
6093        cut.model_parameters = cut.model.default_param_card();
6094        cut.import_graphs(
6095            Graph::import_dot(
6096                r#"digraph sampling_cut_bubble {
6097                    final_state="scalar_1,scalar_1";
6098                    num=1; edge [pdg=1001]; node [num=1];
6099                    ext [style=invis, is_cut=0];
6100                    ext -> a [id=0];
6101                    a -> b [id=1, lmb_id=0];
6102                    a -> b [id=2];
6103                    b -> ext [id=3];
6104                }"#,
6105                &cut.model,
6106            )?,
6107            GraphImportOptions {
6108                process_name: Some("sampling_cut".into()),
6109                process_id: None,
6110                process_definition: None,
6111                integrand_name: Some("default".into()),
6112                overwrite: false,
6113                append: false,
6114            },
6115        )?;
6116        let mut cut_runtime: RuntimeSettings = toml::from_str(
6117            r#"
6118[general]
6119evaluator_method = "SummedFunctionMap"
6120integral_unit = "none"
6121enable_cache = false
6122[kinematics]
6123e_cm = 5.0
6124[kinematics.externals]
6125type = "constant"
6126[kinematics.externals.data]
6127momenta = [[5.0, 0.0, 0.0, 0.0]]
6128helicities = ["summed_averaged"]
6129[sampling]
6130graphs = "summed"
6131orientations = "summed"
6132sampling_multichanneling = true
6133sampling_channels = "summed"
6134sampling_channel_weight = "map_density"
6135power = 2.0
6136default_channel_selection = ["matched", "wide"]
6137[sampling.channel_definitions.sampling_cut_bubble.matched]
6138around = "phase_space(cut(1,2))"
6139parent_lmb = [1]
6140subspace_lmb = [1]
6141radial_profile = "lu_h"
6142[sampling.channel_definitions.sampling_cut_bubble.wide]
6143around = "phase_space(cut(1,2))"
6144parent_lmb = [1]
6145subspace_lmb = [1]
6146radial_profile = { kind = "lu_h", approximation = "log_logistic", scale = 2.0, shape = 1.5, broad_fraction = 0.08 }
6147"#,
6148        )?;
6149        cut_runtime.stability.levels = vec![StabilityLevelSetting::default_double()];
6150        // Eager dual-program construction in an unoptimized test build needs
6151        // the same larger stack as the graph-generation fixtures.
6152        std::thread::scope(|scope| {
6153            std::thread::Builder::new()
6154                .stack_size(64 * 1024 * 1024)
6155                .spawn_scoped(scope, || {
6156                    cut.generate_integrands(&global, (&cut_runtime).into())
6157                })?
6158                .join()
6159                .unwrap()
6160        })?;
6161
6162        for (mut state, reference) in [
6163            (
6164                bubble,
6165                GaussianReferenceFunction::new(2.0, vec![0.7, -0.4, 0.2])?,
6166            ),
6167            (
6168                kite,
6169                GaussianReferenceFunction::new(1.2, vec![0.4, -0.3, 0.2, -0.2, 0.1, 0.35])?,
6170            ),
6171            (
6172                cut,
6173                GaussianReferenceFunction::new(1.5, vec![0.2, -0.3, 0.1])?,
6174            ),
6175        ] {
6176            let temp = tempdir()?;
6177            let saved = temp.path().join("saved");
6178            state.save(&saved, true, false)?;
6179            let mut loaded = State::load(saved, None, None)?;
6180            loaded.activate_loaded_integrand_backends(false)?;
6181            let integrand = loaded.process_list.get_integrand_mut(0, "default")?;
6182            std::thread::scope(|scope| {
6183                std::thread::Builder::new()
6184                    .stack_size(64 * 1024 * 1024)
6185                    .spawn_scoped(scope, || integrand.warm_up(&loaded.model))?
6186                    .join()
6187                    .unwrap()
6188            })?;
6189
6190            // Exercise the complete saved-process parameterization with genuine
6191            // multidimensional Halton points. Finiteness, normalization, moments
6192            // and Jacobian propagation are independent of a trained integration
6193            // grid. The deterministic dispersion is not a randomized-MC error.
6194            let coordinates = (1..=8192)
6195                .map(|index| {
6196                    [2, 3, 5, 7, 11, 13]
6197                        .iter()
6198                        .take(reference.center().len())
6199                        .map(|&base| {
6200                            let (mut index, mut fraction, mut value) = (index, 1.0, 0.0);
6201                            while index > 0 {
6202                                fraction /= base as f64;
6203                                value += (index % base) as f64 * fraction;
6204                                index /= base;
6205                            }
6206                            value
6207                        })
6208                        .collect::<Vec<_>>()
6209                })
6210                .collect::<Vec<_>>();
6211            let report = integrand.evaluate_reference_coordinates(&coordinates, &reference)?;
6212            assert_eq!(report.sample_count, coordinates.len());
6213            assert_eq!(report.finite_sample_count, coordinates.len());
6214            assert!((report.normalization - 1.0).abs() < 2.0e-2, "{report:?}");
6215            assert!(
6216                (report.second_moment - report.expected_second_moment).abs() < 2.0e-1,
6217                "{report:?}"
6218            );
6219
6220            if reference.center().len() == 6 {
6221                // The same saved three-channel catalogue must also reproduce
6222                // the full threshold-subtracted amplitude under explicit MC
6223                // selection; the reference overlay cannot stand in for this gate.
6224                let original_settings = integrand.get_settings().clone();
6225                let SamplingSettings::MultiChanneling(multichanneling) =
6226                    original_settings.sampling.clone()
6227                else {
6228                    panic!("expected summed kite channels")
6229                };
6230                let ids = integrand.group_sampling_channel_ids(
6231                    GroupId(0),
6232                    &multichanneling.parameterization_settings,
6233                )?;
6234                assert_eq!(ids.len(), 3);
6235                let xs = vec![F(0.19), F(0.27), F(0.61), F(0.39), F(0.72), F(0.58)];
6236                let summed_sample = Sample::Continuous(F(1.0), xs.clone());
6237                let summed = integrand
6238                    .evaluate_samples_raw(
6239                        EvaluationTarget::Physical(&loaded.model),
6240                        std::slice::from_ref(&summed_sample),
6241                        0,
6242                        false,
6243                        false,
6244                        Complex::new_zero(),
6245                    )?
6246                    .samples
6247                    .remove(0);
6248                let summed_reference =
6249                    integrand.evaluate_reference_sample_detailed(&summed_sample, &reference)?;
6250                let mut settings = original_settings.clone();
6251                settings.sampling =
6252                    SamplingSettings::DiscreteGraphs(DiscreteGraphSamplingSettings {
6253                        sample_orientations: false,
6254                        sampling_type: DiscreteGraphSamplingType::SamplingMultiChanneling(
6255                            multichanneling,
6256                        ),
6257                        ..Default::default()
6258                    });
6259                *integrand.get_mut_settings() = settings;
6260                integrand.warm_up(&loaded.model)?;
6261                let mut expected = Complex::<F<f64>>::new_zero();
6262                let mut expected_reference = (0.0, 0.0);
6263                for channel_id in ids {
6264                    let sample = Sample::Discrete(
6265                        F(1.0),
6266                        0,
6267                        Some(Box::new(Sample::Discrete(
6268                            F(1.0),
6269                            channel_id.0,
6270                            Some(Box::new(Sample::Continuous(F(1.0), xs.clone()))),
6271                        ))),
6272                    );
6273                    let result = integrand
6274                        .evaluate_samples_raw(
6275                            EvaluationTarget::Physical(&loaded.model),
6276                            std::slice::from_ref(&sample),
6277                            0,
6278                            false,
6279                            false,
6280                            Complex::new_zero(),
6281                        )?
6282                        .samples
6283                        .remove(0);
6284                    expected += result.integrand_result * result.parameterization_jacobian.unwrap();
6285                    let result =
6286                        integrand.evaluate_reference_sample_detailed(&sample, &reference)?;
6287                    let jacobian = result.evaluation.parameterization_jacobian.unwrap().0;
6288                    expected_reference.0 += result.evaluation.integrand_result.re.0 * jacobian;
6289                    expected_reference.1 += result.moments.second_moment.0 * jacobian;
6290                }
6291                let actual = summed.integrand_result * summed.parameterization_jacobian.unwrap();
6292                let scale = expected.re.0.abs() + expected.im.0.abs();
6293                assert!(scale > 1.0e-18 && scale.is_finite());
6294                assert!(
6295                    (actual.re.0 - expected.re.0).abs() + (actual.im.0 - expected.im.0).abs()
6296                        < 1.0e-9 * scale
6297                );
6298                let jacobian = summed_reference
6299                    .evaluation
6300                    .parameterization_jacobian
6301                    .unwrap()
6302                    .0;
6303                for (actual, expected) in [
6304                    (
6305                        summed_reference.evaluation.integrand_result.re.0 * jacobian,
6306                        expected_reference.0,
6307                    ),
6308                    (
6309                        summed_reference.moments.second_moment.0 * jacobian,
6310                        expected_reference.1,
6311                    ),
6312                ] {
6313                    assert!((actual - expected).abs() < 1.0e-10 * expected.abs().max(1.0));
6314                }
6315            }
6316
6317            // The loaded-state command uses the real sampling/training grids,
6318            // worker clones, native target and complex statistics. Re and Im
6319            // are normalization and normalized raw moment, not physical phases.
6320            std::thread::scope(|scope| {
6321                std::thread::Builder::new()
6322                    .stack_size(64 * 1024 * 1024)
6323                    .spawn_scoped(scope, || -> Result<()> {
6324                        use crate::commands::integrate::Integrate;
6325                        use gammalooprs::integrands::Integrand;
6326                        use gammalooprs::integrate::{
6327                            havana_integrate, slot_workspace_path, workspace_manifest_path,
6328                            workspace_state_path, HavanaIntegrateRequest, IntegrationSlot,
6329                            IntegrationState, IntegrationStatusKind, IntegrationWorkspaceManifest,
6330                            IterationBatchingSettings, SamplingCorrelationMode, SlotMeta,
6331                            WorkspaceSnapshotControl,
6332                        };
6333                        use gammalooprs::utils::serde_utils::SmartSerde;
6334                        use symbolica::numerical_integration::{Grid, MonteCarloRng};
6335
6336                        let process = loaded.process_list.get_integrand_mut(0, "default")?;
6337                        let settings = process.get_mut_settings();
6338                        settings.integrator.n_bins = 8;
6339                        settings.integrator.min_samples_for_update = 4;
6340                        settings.integrator.n_start = 256;
6341                        settings.integrator.n_increase = 0;
6342                        settings.integrator.n_max = 512;
6343                        settings.integrator.seed = 7331;
6344                        let mut command = Integrate::from_slots([(ProcessRef::Id(0), "default")]);
6345                        command.n_cores = Some(2);
6346                        command.workspace_path = Some(temp.path().join("reference_full"));
6347                        command.batch_size = Some(64);
6348                        command.batch_timing = 0.0;
6349                        // Exercise centered shorthand as well as shifted descriptors.
6350                        command.reference_gaussian = Some(
6351                            if process.kind_name() == "amplitude" && reference.center().len() == 3 {
6352                                GaussianReferenceFunction::new(reference.width(), vec![])?
6353                            } else {
6354                                reference.clone()
6355                            },
6356                        );
6357                        let resolved = command
6358                            .reference_gaussian
6359                            .as_ref()
6360                            .unwrap()
6361                            .for_integrand(process)?;
6362                        let mut cli = CLISettings::default();
6363                        cli.state.folder = temp.path().join("saved");
6364                        cli.session.set_user_requested_read_only_state(true);
6365                        let source_path = generated_integrand_artifact_path(
6366                            &cli.state.folder,
6367                            &loaded.process_list.processes[0],
6368                            "default",
6369                        )
6370                        .join("integrand.bin");
6371                        let before_source = fs::read(&source_path)?;
6372                        let full = command.run(&mut loaded, &cli)?;
6373                        let result = full.result.single_slot().unwrap();
6374                        assert_eq!(result.integral.neval, 512);
6375                        assert_eq!(result.target, Some(Complex::new(F(1.0), F(1.0))));
6376                        for (mean, error) in [
6377                            (result.integral.result.re.0, result.integral.error.re.0),
6378                            (result.integral.result.im.0, result.integral.error.im.0),
6379                        ] {
6380                            assert!(mean.is_finite() && error.is_finite() && error > 0.0);
6381                            assert!(
6382                                (mean - 1.0).abs() < 6.0 * error,
6383                                "reference mean={mean}, error={error}"
6384                            );
6385                        }
6386                        assert!(full.observables.is_empty());
6387                        let meta = SlotMeta {
6388                            process_name: result.process.clone(),
6389                            integrand_name: result.integrand.clone(),
6390                        };
6391                        let manifest = IntegrationWorkspaceManifest::from_file(
6392                            workspace_manifest_path(&full.workspace_path),
6393                            "reference manifest",
6394                        )?;
6395                        assert_eq!(manifest.reference_gaussians, vec![Some(resolved.clone())]);
6396                        assert_eq!(
6397                            manifest.reference_observable_convention.as_deref(),
6398                            Some(GaussianReferenceFunction::INTEGRATION_CONVENTION)
6399                        );
6400
6401                        // Produce a completed first-iteration checkpoint using the same
6402                        // engine and interrupt hook, then resume it through the CLI owner.
6403                        let partial = temp.path().join("reference_resume");
6404                        fs::create_dir_all(slot_workspace_path(&partial, &meta))?;
6405                        fs::copy(
6406                            workspace_manifest_path(&full.workspace_path),
6407                            workspace_manifest_path(&partial),
6408                        )?;
6409                        fs::copy(
6410                            slot_workspace_path(&full.workspace_path, &meta).join("settings.toml"),
6411                            slot_workspace_path(&partial, &meta).join("settings.toml"),
6412                        )?;
6413                        let process = loaded.process_list.get_integrand_mut(0, "default")?.clone();
6414                        let settings = process.get_settings().clone();
6415                        let mut slot = IntegrationSlot::new(
6416                            meta,
6417                            settings.clone(),
6418                            loaded.model.clone(),
6419                            Integrand::ProcessIntegrand(Box::new(process)),
6420                            Some(Complex::new(F(1.0), F(1.0))),
6421                        );
6422                        slot.reference_gaussian = Some(resolved.clone());
6423                        let stopped = havana_integrate(
6424                            HavanaIntegrateRequest {
6425                                slots: vec![slot],
6426                                sampling_correlation_mode: SamplingCorrelationMode::Correlated,
6427                                n_cores: 2,
6428                                state: None,
6429                                workspace: Some(partial.clone()),
6430                                output_control: WorkspaceSnapshotControl::default(),
6431                                batching: IterationBatchingSettings {
6432                                    batch_size: Some(64),
6433                                    batch_timing_seconds: 0.0,
6434                                    ..Default::default()
6435                                },
6436                                view_options: command.build_render_options(&[settings], false),
6437                            },
6438                            |status| {
6439                                if status.kind() == IntegrationStatusKind::Iteration {
6440                                    gammalooprs::request_interrupt();
6441                                }
6442                                Ok(())
6443                            },
6444                        );
6445                        gammalooprs::clear_interrupt_request();
6446                        stopped?;
6447                        let bytes = fs::read(workspace_state_path(&partial))?;
6448                        let (checkpoint, _): (IntegrationState, usize) =
6449                            bincode::decode_from_slice(&bytes, bincode::config::standard())?;
6450                        assert_eq!(checkpoint.iter, 1);
6451                        assert_eq!(checkpoint.num_points, 256);
6452                        // A draw from the trained checkpoint proves that both observables
6453                        // retain actual non-unit grid probabilities exactly once.
6454                        let serialized = serde_json::to_value(&checkpoint)?;
6455                        let mut grid: Grid<F<f64>> = serde_json::from_value(
6456                            serialized["sampling_states"][0]["grid"].clone(),
6457                        )?;
6458                        let mut rng = MonteCarloRng::new(42, 0);
6459                        let mut point = Sample::new();
6460                        grid.sample(&mut rng, &mut point);
6461                        assert!((point.get_weight().0 - 1.0).abs() > 1.0e-6);
6462                        let process = loaded.process_list.get_integrand_mut(0, "default")?;
6463                        let detailed =
6464                            process.evaluate_reference_sample_detailed(&point, &resolved)?;
6465                        let pair = process
6466                            .evaluate_samples_raw(
6467                                EvaluationTarget::Reference(&resolved),
6468                                &[point.clone()],
6469                                0,
6470                                false,
6471                                false,
6472                                Complex::new_zero(),
6473                            )?
6474                            .samples
6475                            .remove(0);
6476                        assert_eq!(pair.integrator_weight, point.get_weight());
6477                        assert!(
6478                            (pair.integrand_result.re.0
6479                                - detailed.evaluation.integrand_result.re.0)
6480                                .abs()
6481                                < 1.0e-12
6482                        );
6483                        assert!(
6484                            (pair.integrand_result.im.0
6485                                - detailed.moments.second_moment.0
6486                                    / resolved.expected_second_moment::<f64>().0)
6487                                .abs()
6488                                < 1.0e-12
6489                        );
6490
6491                        command.workspace_path = Some(partial.clone());
6492                        let resumed = command.run(&mut loaded, &cli)?;
6493                        let actual = &resumed.result.single_slot().unwrap().integral;
6494                        assert_eq!(actual.neval, result.integral.neval);
6495                        assert_eq!(actual.result, result.integral.result);
6496                        assert_eq!(actual.error, result.integral.error);
6497                        assert_eq!(fs::read(&source_path)?, before_source);
6498                        // A mismatch must fail before saved settings are restored.
6499                        loaded
6500                            .process_list
6501                            .get_integrand_mut(0, "default")?
6502                            .get_mut_settings()
6503                            .integrator
6504                            .seed = 19;
6505                        let mut physical = command.clone();
6506                        physical.reference_gaussian = None;
6507                        let unchanged = fs::read(workspace_state_path(&partial))?;
6508                        assert!(physical
6509                            .run(&mut loaded, &cli)
6510                            .unwrap_err()
6511                            .to_string()
6512                            .contains("physical/reference"));
6513                        assert_eq!(
6514                            loaded
6515                                .process_list
6516                                .get_integrand_mut(0, "default")?
6517                                .get_settings()
6518                                .integrator
6519                                .seed,
6520                            19
6521                        );
6522                        assert_eq!(fs::read(workspace_state_path(&partial))?, unchanged);
6523                        command.target = vec!["1,2".into()];
6524                        assert!(command
6525                            .run(&mut loaded, &cli)
6526                            .unwrap_err()
6527                            .to_string()
6528                            .contains("contradictory"));
6529                        Ok(())
6530                    })?
6531                    .join()
6532                    .unwrap()
6533            })?;
6534        }
6535        Ok(())
6536    }
6537
6538    /// Every model handle held by graphs of the state: see
6539    /// [`ProcessList::process_graphs`] for the holders.
6540    fn held_graph_models(state: &State) -> Vec<Arc<Model>> {
6541        state
6542            .process_list
6543            .processes
6544            .iter()
6545            .flat_map(ProcessList::process_graphs)
6546            .map(|graph| Arc::clone(&graph.model))
6547            .collect()
6548    }
6549
6550    fn assert_graphs_share_session_model(state: &State) {
6551        let shared = state.shared_graph_model();
6552        let models = held_graph_models(state);
6553        assert!(models.len() >= 4, "{} graph handles", models.len());
6554        for model in models {
6555            assert!(Arc::ptr_eq(&model, &shared), "graphs must share one model");
6556            assert_eq!(model.fingerprint(), state.model.fingerprint());
6557        }
6558    }
6559
6560    fn card_entries(state: &State) -> BTreeMap<String, Complex<F<f64>>> {
6561        state
6562            .model_parameters
6563            .iter()
6564            .map(|(name, value)| (name.to_string(), *value))
6565            .collect()
6566    }
6567
6568    fn card_with(state: &State, name: &str, value: f64) -> InputParamCard<F<f64>> {
6569        let mut card = state.model_parameters.clone();
6570        card.insert(UFOSymbol::from(name), Complex::new_re(F(value)));
6571        card
6572    }
6573
6574    fn model_value(model: &Model, name: &str) -> f64 {
6575        model.parameter(name).unwrap().value.unwrap().re
6576    }
6577
6578    fn evaluate_first_sample(state: &mut State, name: &str) -> Result<Complex<F<f64>>> {
6579        let model = state.resolve_model_for_integrand(0, name)?;
6580        let integrand = state.process_list.get_integrand_mut(0, name)?;
6581        integrand.warm_up(&model)?;
6582        let result = integrand.evaluate_samples_raw(
6583            EvaluationTarget::Physical(&model),
6584            &[Sample::Continuous(F(1.0), vec![F(0.27), F(0.36), F(0.71)])],
6585            0,
6586            false,
6587            false,
6588            Complex::new_zero(),
6589        )?;
6590        Ok(result.samples[0].integrand_result)
6591    }
6592
6593    fn close(a: &Complex<F<f64>>, b: &Complex<F<f64>>) -> bool {
6594        let scale = a.re.0.abs().max(a.im.0.abs()).max(1e-300);
6595        ((a.re.0 - b.re.0).abs() + (a.im.0 - b.im.0).abs()) / scale < 1e-12
6596    }
6597
6598    fn cheap_generation_settings(check_esurface_at_generation: bool) -> Result<GlobalSettings> {
6599        let mut global: GlobalSettings = toml::from_str(
6600            r#"
6601[n_cores]
6602generate = 1
6603[generation.uv]
6604subtract_uv = false
6605generate_integrated = false
6606[generation.evaluator]
6607compile = false
6608summed = false
6609iterative_orientation_optimization = false
6610"#,
6611        )?;
6612        let thresholds = &mut global.generation.threshold_subtraction;
6613        thresholds.enable_thresholds = true;
6614        thresholds.check_esurface_at_generation = check_esurface_at_generation;
6615        Ok(global)
6616    }
6617
6618    fn import_into(state: &mut State, graphs: Vec<Graph>, process: &str, name: &str) -> Result<()> {
6619        state.import_graphs(
6620            graphs,
6621            GraphImportOptions {
6622                process_name: Some(process.into()),
6623                process_id: None,
6624                process_definition: None,
6625                integrand_name: Some(name.into()),
6626                overwrite: false,
6627                append: false,
6628            },
6629        )
6630    }
6631
6632    /// The scalar bubble generated twice, as integrands "plain" and
6633    /// "overlaid"; the latter overrides `mass_scalar_1` in its settings.
6634    fn generated_scalar_bubble_pair() -> Result<(State, f64)> {
6635        test_initialise()?;
6636        let mut state = State::new_test();
6637        state.model = load_generic_model("scalars");
6638        state.model_parameters = state.model.default_param_card();
6639        let graphs = Graph::from_finalized_runtime_path(
6640            crate::test_workspace_root().join("tests/resources/graphs/scalar_bubble.dot"),
6641            &state.model,
6642        )?;
6643        for name in ["plain", "overlaid"] {
6644            import_into(&mut state, graphs.clone(), "scalar_bubble", name)?;
6645        }
6646        let runtime: RuntimeSettings = toml::from_str(
6647            r#"
6648[kinematics]
6649e_cm = 2.0
6650[kinematics.externals]
6651type = "constant"
6652[kinematics.externals.data]
6653momenta = [[0.5, 0.2, 0.3, 0.1], "dependent"]
6654helicities = [0, 0]
6655"#,
6656        )?;
6657        state.generate_integrands(&cheap_generation_settings(false)?, (&runtime).into())?;
6658        assert_graphs_share_session_model(&state);
6659
6660        let overlay_mass = state.model_parameters[&UFOSymbol::from("mass_scalar_1")]
6661            .re
6662            .0
6663            + 0.25;
6664        state
6665            .process_list
6666            .get_integrand_mut(0, "overlaid")?
6667            .get_mut_settings()
6668            .model
6669            .external_parameters
6670            .insert("mass_scalar_1".into(), (F(overlay_mass), F(0.0)));
6671        Ok((state, overlay_mass))
6672    }
6673
6674    #[test]
6675    fn numeric_model_replacement_rebinds_graphs_and_preserves_overlays() -> Result<()> {
6676        let _guard = crate::LOG_TEST_MUTEX
6677            .lock()
6678            .unwrap_or_else(|err| err.into_inner());
6679        let temp = tempdir()?;
6680        let (mut state, overlay_mass) = generated_scalar_bubble_pair()?;
6681        let mass = UFOSymbol::from("mass_scalar_1");
6682        let plain_before = evaluate_first_sample(&mut state, "plain")?;
6683        let overlaid_before = evaluate_first_sample(&mut state, "overlaid")?;
6684        assert!(
6685            !close(&plain_before, &overlaid_before),
6686            "the overlay must matter"
6687        );
6688
6689        // Import the same records with a genuinely different mass.
6690        let new_mass = state.model_parameters[&mass].re.0 + 0.5;
6691        let mut changed = state.model.clone();
6692        changed.apply_param_card(&card_with(&state, "mass_scalar_1", new_mass))?;
6693        assert_eq!(
6694            changed.structure_fingerprint(),
6695            state.model.structure_fingerprint()
6696        );
6697        let model_path = temp.path().join("scalars_heavier.json");
6698        fs::write(&model_path, changed.to_json()?)?;
6699        let previous = state.shared_graph_model();
6700        state.import_model(&model_path)?;
6701
6702        assert_eq!(state.model_parameters[&mass].re.0, new_mass);
6703        assert_eq!(model_value(&state.model, "mass_scalar_1"), new_mass);
6704        assert_graphs_share_session_model(&state);
6705        assert_eq!(
6706            Arc::strong_count(&previous),
6707            1,
6708            "no graph holder may keep the replaced model"
6709        );
6710        assert_eq!(
6711            state
6712                .process_list
6713                .get_integrand_mut(0, "overlaid")?
6714                .get_settings()
6715                .model
6716                .external_parameters["mass_scalar_1"],
6717            (F(overlay_mass), F(0.0))
6718        );
6719        let plain_after = evaluate_first_sample(&mut state, "plain")?;
6720        let overlaid_after = evaluate_first_sample(&mut state, "overlaid")?;
6721        assert!(
6722            !close(&plain_after, &plain_before),
6723            "the new mass must be used"
6724        );
6725        assert!(
6726            close(&overlaid_after, &overlaid_before),
6727            "the per-integrand overlay must still win"
6728        );
6729
6730        let folder = temp.path().join("state");
6731        state.save(&folder, true, false)?;
6732        let mut loaded = State::load(folder, None, None)?;
6733        loaded.activate_loaded_integrand_backends(false)?;
6734        assert_eq!(loaded.model_parameters[&mass].re.0, new_mass);
6735        assert_graphs_share_session_model(&loaded);
6736        assert!(close(
6737            &evaluate_first_sample(&mut loaded, "plain")?,
6738            &plain_after
6739        ));
6740        assert!(close(
6741            &evaluate_first_sample(&mut loaded, "overlaid")?,
6742            &overlaid_after
6743        ));
6744        Ok(())
6745    }
6746
6747    #[test]
6748    fn replace_model_applies_the_card_to_the_model_it_stores() -> Result<()> {
6749        let _guard = crate::LOG_TEST_MUTEX
6750            .lock()
6751            .unwrap_or_else(|err| err.into_inner());
6752        let temp = tempdir()?;
6753        let (mut state, _) = generated_scalar_bubble_pair()?;
6754        let before = evaluate_first_sample(&mut state, "plain")?;
6755        let new_mass = model_value(&state.model, "mass_scalar_1") + 0.5;
6756        let card = card_with(&state, "mass_scalar_1", new_mass);
6757        let mut expected = state.model.clone();
6758        expected.apply_param_card(&card)?;
6759        let previous = state.shared_graph_model();
6760        let stored_kinematics = |state: &mut State| -> Result<GenerationKinematics> {
6761            Ok(GenerationKinematics::new(
6762                &state
6763                    .process_list
6764                    .get_integrand_mut(0, "plain")?
6765                    .get_settings()
6766                    .kinematics,
6767            ))
6768        };
6769        let kinematics_before = stored_kinematics(&mut state)?;
6770
6771        // The old model with a new card: the card wins.
6772        state.replace_model(state.model.clone(), card)?;
6773        // The generated physical point stays explicit; no defaults are recomputed
6774        // from the new masses.
6775        assert_eq!(stored_kinematics(&mut state)?, kinematics_before);
6776        assert_eq!(model_value(&state.model, "mass_scalar_1"), new_mass);
6777        assert_eq!(state.model.fingerprint(), expected.fingerprint());
6778        assert_eq!(
6779            state.model_parameters[&UFOSymbol::from("mass_scalar_1")]
6780                .re
6781                .0,
6782            new_mass
6783        );
6784        assert_graphs_share_session_model(&state);
6785        assert_eq!(Arc::strong_count(&previous), 1);
6786        let after = evaluate_first_sample(&mut state, "plain")?;
6787        assert!(!close(&after, &before), "the new card value must be used");
6788
6789        let folder = temp.path().join("state");
6790        state.save(&folder, true, false)?;
6791        let mut loaded = State::load(folder, None, None)?;
6792        loaded.activate_loaded_integrand_backends(false)?;
6793        // Saved cards and models round-trip every f64 bit-exactly (see
6794        // `saved_parameter_cards_round_trip_every_f64_bit_exactly`), so the
6795        // stored model, the card and the kinematics all come back identical.
6796        assert_eq!(loaded.model.fingerprint(), state.model.fingerprint());
6797        assert_eq!(model_value(&loaded.model, "mass_scalar_1"), new_mass);
6798        assert_eq!(card_entries(&loaded), card_entries(&state));
6799        assert_graphs_share_session_model(&loaded);
6800        assert!(close(&evaluate_first_sample(&mut loaded, "plain")?, &after));
6801        assert_eq!(stored_kinematics(&mut loaded)?, kinematics_before);
6802        Ok(())
6803    }
6804
6805    #[test]
6806    fn grouped_threshold_amplitude_keeps_every_holder_on_the_session_model() -> Result<()> {
6807        let _guard = crate::LOG_TEST_MUTEX
6808            .lock()
6809            .unwrap_or_else(|err| err.into_inner());
6810        test_initialise()?;
6811        let temp = tempdir()?;
6812        let mut state = State::new_test();
6813        state.model = load_generic_model("scalars");
6814        state.model_parameters = state.model.default_param_card();
6815        let mut graphs = Vec::new();
6816        for (name, group, loop_edge) in [
6817            ("grouped_master", "group_id=0 is_group_master=true", 0),
6818            ("grouped_member", "group_id=0", 1),
6819        ] {
6820            let (first, second) = if loop_edge == 0 {
6821                ("", " lmb_id=0")
6822            } else {
6823                (" lmb_id=0", "")
6824            };
6825            graphs.extend(Graph::import_dot(
6826                &format!(
6827                    "digraph {name} {{
6828                        graph [{group}]
6829                        edge [particle=scalar_0]
6830                        node [num=1]
6831                        e [style=invis]
6832                        e -> A:0 [id=3 particle=scalar_2]
6833                        B:1 -> e [id=2 particle=scalar_2]
6834                        A -> B [id=1{first}]
6835                        A -> B [id=0{second}]
6836                    }}"
6837                ),
6838                &state.model,
6839            )?);
6840        }
6841        import_into(&mut state, graphs, "grouped", "default")?;
6842        let runtime: RuntimeSettings = toml::from_str(
6843            r#"
6844[kinematics]
6845e_cm = 4.0
6846[kinematics.externals]
6847type = "constant"
6848[kinematics.externals.data]
6849momenta = [[4.0, 0.0, 0.0, 0.0], "dependent"]
6850helicities = [0, 0]
6851"#,
6852        )?;
6853        state.generate_integrands(&cheap_generation_settings(false)?, (&runtime).into())?;
6854        let ProcessCollection::Amplitudes(amplitudes) = &state.process_list.processes[0].collection
6855        else {
6856            unreachable!("grouped bubbles are amplitudes")
6857        };
6858        assert!(
6859            amplitudes["default"]
6860                .graphs
6861                .iter()
6862                .any(|graph| graph.derived_data.multi_channeling_setup.is_some()),
6863            "the derived multi-channeling holders must be exercised"
6864        );
6865        assert_graphs_share_session_model(&state);
6866
6867        let previous = state.shared_graph_model();
6868        let new_mass = model_value(&state.model, "mass_scalar_1") + 0.5;
6869        state.replace_model(
6870            state.model.clone(),
6871            card_with(&state, "mass_scalar_1", new_mass),
6872        )?;
6873        assert_graphs_share_session_model(&state);
6874        assert_eq!(Arc::strong_count(&previous), 1);
6875
6876        let folder = temp.path().join("state");
6877        state.save(&folder, true, false)?;
6878        let loaded = State::load(folder, None, None)?;
6879        assert_graphs_share_session_model(&loaded);
6880        assert_eq!(model_value(&loaded.model, "mass_scalar_1"), new_mass);
6881        Ok(())
6882    }
6883
6884    /// The two-loop scalar self-energy cross section imported, ungenerated,
6885    /// as integrand "default" of each of `processes`.
6886    fn threshold_cross_section_state(processes: &[&str]) -> Result<State> {
6887        test_initialise()?;
6888        let mut state = State::new_test();
6889        state.model = Model::from_json(include_str!(
6890            "../../../assets/models/json/scalars/scalars_2p_3p.json"
6891        ))?;
6892        state.model_parameters = state.model.default_param_card();
6893        let mut graphs = Graph::import_dot(
6894            include_str!("../../../tests/resources/graphs/mass_approach_scalar_self_energy.dot"),
6895            &state.model,
6896        )?;
6897        graphs.truncate(1);
6898        for process in processes {
6899            import_into(&mut state, graphs.clone(), process, "default")?;
6900        }
6901        Ok(state)
6902    }
6903
6904    /// The two-loop scalar self-energy cross section, generated with
6905    /// thresholds and the given generation-time existence check.
6906    fn generated_threshold_cross_section(check_esurface_at_generation: bool) -> Result<State> {
6907        let mut state = threshold_cross_section_state(&["self_energy"])?;
6908        state.generate_integrands(
6909            &cheap_generation_settings(check_esurface_at_generation)?,
6910            (&RuntimeSettings::default()).into(),
6911        )?;
6912        let point = state
6913            .recorded_generation_point(0, "default")
6914            .expect("State generation records the generation point");
6915        assert_eq!(point.depends_on_model_values, check_esurface_at_generation);
6916        assert_graphs_share_session_model(&state);
6917        Ok(state)
6918    }
6919
6920    /// A generation which fails after installing some integrands must not
6921    /// leave them with the generation point of their previous build. The
6922    /// interrupt flag is process-global; nextest runs each test in its own
6923    /// process.
6924    #[test]
6925    fn interrupted_rebuild_cannot_keep_a_stale_generation_point() -> Result<()> {
6926        struct InterruptAfterBackend;
6927        impl GenerationProgressObserver for InterruptAfterBackend {
6928            fn backend_finished(&self, _: GenerationProcessKind, _: &str, _: Duration) {
6929                request_interrupt();
6930            }
6931        }
6932
6933        let mut state = threshold_cross_section_state(&["first", "second"])?;
6934        let mut runtime = RuntimeSettings::default();
6935        state.generate_integrands(&cheap_generation_settings(false)?, (&runtime).into())?;
6936        let original_energy = runtime.kinematics.e_cm;
6937        assert!(
6938            !state
6939                .recorded_generation_point(0, "default")
6940                .expect("generation records the point")
6941                .depends_on_model_values
6942        );
6943        runtime.kinematics.e_cm += 0.25;
6944        let observer = GenerationProgressObserverGuard::set(Arc::new(InterruptAfterBackend));
6945        let result =
6946            state.generate_integrands(&cheap_generation_settings(true)?, (&runtime).into());
6947        drop(observer);
6948        let problem = result.expect_err("the second build is interrupted");
6949        assert!(format!("{problem:?}").contains("interrupted"));
6950
6951        // The first integrand was rebuilt, with the check, at the new energy;
6952        // the second keeps its previous payload.
6953        let energy_of = |state: &State, process_id| -> Result<f64> {
6954            Ok(state
6955                .process_list
6956                .get_integrand(process_id, "default")?
6957                .require_generated()?
6958                .get_settings()
6959                .kinematics
6960                .e_cm)
6961        };
6962        assert_eq!(energy_of(&state, 0)?, runtime.kinematics.e_cm);
6963        assert_eq!(energy_of(&state, 1)?, original_energy);
6964        let point = state
6965            .recorded_generation_point(0, "default")
6966            .expect("a rebuilt integrand keeps a generation point");
6967        assert!(point.depends_on_model_values);
6968        assert_eq!(point.kinematics.e_cm, exact_f64(runtime.kinematics.e_cm));
6969        assert_eq!(
6970            point,
6971            &state
6972                .current_generation_point(&IntegrandGenerationSummaryKey {
6973                    process_id: 0,
6974                    integrand_name: "default".to_string(),
6975                })
6976                .expect("a generated integrand has a point"),
6977        );
6978
6979        // The previous payload is held at its own point, conservatively.
6980        let second = state
6981            .recorded_generation_point(1, "default")
6982            .expect("the previous payload keeps a generation point");
6983        assert!(second.depends_on_model_values);
6984        assert_eq!(second.kinematics.e_cm, exact_f64(original_energy));
6985
6986        // The mass change of the generation-point test is refused, and the
6987        // state is unchanged.
6988        let heavy = 10.0 * model_value(&state.model, "mass_scalar_1");
6989        let card = card_with(&state, "mass_scalar_1", heavy);
6990        assert!(state.replace_model(state.model.clone(), card).is_err());
6991        assert_ne!(model_value(&state.model, "mass_scalar_1"), heavy);
6992        Ok(())
6993    }
6994
6995    // Nextest isolates the process-global progress observer and interrupt flag.
6996    #[test]
6997    fn first_checked_install_keeps_its_point_after_a_later_failed_preprocess() -> Result<()> {
6998        struct InterruptAfterBackend;
6999        impl GenerationProgressObserver for InterruptAfterBackend {
7000            fn backend_finished(&self, _: GenerationProcessKind, _: &str, _: Duration) {
7001                request_interrupt();
7002            }
7003        }
7004
7005        struct InterruptSecondPreprocess;
7006        impl GenerationProgressObserver for InterruptSecondPreprocess {
7007            fn begin_phase(
7008                &self,
7009                phase: GenerationProgressPhase,
7010                _: GenerationProcessKind,
7011                process: &str,
7012                _: &str,
7013                _: usize,
7014                _: Option<usize>,
7015            ) {
7016                if phase == GenerationProgressPhase::GraphPreprocessing && process == "second" {
7017                    request_interrupt();
7018                }
7019            }
7020        }
7021
7022        let mut state = threshold_cross_section_state(&["first", "second"])?;
7023        let mut runtime = RuntimeSettings::default();
7024        let energy = runtime.kinematics.e_cm;
7025        let observer = GenerationProgressObserverGuard::set(Arc::new(InterruptAfterBackend));
7026        let result =
7027            state.generate_integrands(&cheap_generation_settings(true)?, (&runtime).into());
7028        drop(observer);
7029        assert!(format!(
7030            "{:?}",
7031            result.expect_err("the second build was interrupted")
7032        )
7033        .contains("interrupted"));
7034        assert!(state
7035            .process_list
7036            .get_integrand(1, "default")?
7037            .integrand
7038            .is_none());
7039
7040        // Preprocessing first completes with the check disabled. The second
7041        // process interrupts before any unchecked replacement can be built.
7042        runtime.kinematics.e_cm += 0.25;
7043        let observer = GenerationProgressObserverGuard::set(Arc::new(InterruptSecondPreprocess));
7044        let result =
7045            state.generate_integrands(&cheap_generation_settings(false)?, (&runtime).into());
7046        drop(observer);
7047        assert!(
7048            format!("{:?}", result.expect_err("preprocessing was interrupted"))
7049                .contains("interrupted")
7050        );
7051        assert!(!state.process_list.processes[0].generation_depends_on_model_values());
7052        let first = state
7053            .process_list
7054            .get_integrand(0, "default")?
7055            .require_generated()?;
7056        assert_eq!(first.get_settings().kinematics.e_cm, energy);
7057
7058        let base_mass = model_value(&state.model, "mass_scalar_1");
7059        let card = card_with(&state, "mass_scalar_1", 10.0 * base_mass);
7060        let error = state
7061            .replace_model(state.model.clone(), card)
7062            .expect_err("the first payload still uses the checked generation point");
7063        let message = format!("{error:?}");
7064        assert!(message.contains("mass_scalar_1"), "{message}");
7065        assert!(message.contains("generation point"), "{message}");
7066        assert_eq!(model_value(&state.model, "mass_scalar_1"), base_mass);
7067
7068        let point = state
7069            .recorded_generation_point(0, "default")
7070            .expect("the partially completed batch recorded its checked payload");
7071        assert!(point.depends_on_model_values);
7072        assert_eq!(point.kinematics.e_cm, exact_f64(energy));
7073
7074        let temp = tempdir()?;
7075        let folder = temp.path().join("state");
7076        state.save(&folder, true, false)?;
7077        let loaded = State::load(folder, None, None)?;
7078        assert_eq!(
7079            loaded.recorded_generation_point(0, "default"),
7080            state.recorded_generation_point(0, "default")
7081        );
7082        Ok(())
7083    }
7084
7085    #[test]
7086    fn duplicates_keep_the_original_generation_point() -> Result<()> {
7087        let _guard = crate::LOG_TEST_MUTEX
7088            .lock()
7089            .unwrap_or_else(|err| err.into_inner());
7090        let temp = tempdir()?;
7091        let mut state = generated_threshold_cross_section(true)?;
7092        state.duplicate_integrand(
7093            Some(&ProcessRef::Name("self_energy".into())),
7094            Some(&"default".to_string()),
7095            "self_energy_copy",
7096            "copy",
7097        )?;
7098        let original = state.recorded_generation_point(0, "default").cloned();
7099        assert!(original.is_some());
7100        assert_eq!(
7101            state.recorded_generation_point(1, "copy").cloned(),
7102            original
7103        );
7104
7105        let folder = temp.path().join("state");
7106        state.save(&folder, true, false)?;
7107        let loaded = State::load(folder.clone(), None, None)?;
7108        assert_eq!(
7109            loaded.recorded_generation_point(0, "default").cloned(),
7110            original
7111        );
7112        assert_eq!(
7113            loaded.recorded_generation_point(1, "copy").cloned(),
7114            original
7115        );
7116
7117        // A changed point is refused for the duplicate as for the original.
7118        let heavy = 10.0 * model_value(&loaded.model, "mass_scalar_1");
7119        let card = card_with(&loaded, "mass_scalar_1", heavy);
7120        for (process_id, name) in [(0, "default"), (1, "copy")] {
7121            let settings = loaded
7122                .process_list
7123                .get_integrand(process_id, name)?
7124                .require_generated()?
7125                .get_settings();
7126            let error = loaded
7127                .ensure_generation_point_kept(process_id, name, &loaded.model, &card, settings)
7128                .expect_err("the duplicate was generated at the original point");
7129            assert!(
7130                format!("{error:?}").contains("regenerate"),
7131                "{name}: {error:?}"
7132            );
7133        }
7134        card.to_file(folder.join("model_parameters.json"), true)?;
7135        assert!(load_error(&folder).contains("no longer matches its generation point"));
7136        Ok(())
7137    }
7138
7139    #[test]
7140    fn value_dependent_copies_only_join_value_dependent_processes() -> Result<()> {
7141        let _guard = crate::LOG_TEST_MUTEX
7142            .lock()
7143            .unwrap_or_else(|err| err.into_inner());
7144        let temp = tempdir()?;
7145        let mut state = threshold_cross_section_state(&["independent", "dependent"])?;
7146        let runtime = RuntimeSettings::default();
7147        for (process_id, check_esurface_at_generation) in [(0, false), (1, true)] {
7148            state.generate_integrand(
7149                &cheap_generation_settings(check_esurface_at_generation)?,
7150                (&runtime).into(),
7151                process_id,
7152                None,
7153            )?;
7154        }
7155        let dependent = ProcessRef::Name("dependent".into());
7156        let source = "default".to_string();
7157
7158        // Into the process whose history records value-independent
7159        // generation, the copy is refused before anything changes.
7160        let names_before = |state: &State| -> Vec<Vec<String>> {
7161            state
7162                .process_list
7163                .processes
7164                .iter()
7165                .map(|process| {
7166                    process
7167                        .collection
7168                        .get_integrand_names()
7169                        .into_iter()
7170                        .map(str::to_owned)
7171                        .collect()
7172                })
7173                .collect()
7174        };
7175        let before = names_before(&state);
7176        let summaries_before = state.generation_summaries.len();
7177        let error = state
7178            .duplicate_integrand(Some(&dependent), Some(&source), "independent", "copy")
7179            .expect_err("the copy would lose its dependence without its summary");
7180        assert!(
7181            format!("{error:?}").contains("Cannot copy integrand"),
7182            "{error:?}"
7183        );
7184        assert_eq!(names_before(&state), before);
7185        assert_eq!(state.generation_summaries.len(), summaries_before);
7186
7187        // Into the dependent process itself and into a new process (which
7188        // inherits the source's history), the copy is accepted.
7189        state.duplicate_integrand(Some(&dependent), Some(&source), "dependent", "copy")?;
7190        state.duplicate_integrand(Some(&dependent), Some(&source), "dependent_copy", "copy")?;
7191        assert!(state
7192            .recorded_generation_point(1, "copy")
7193            .is_some_and(|point| point.depends_on_model_values));
7194        assert!(state
7195            .recorded_generation_point(2, "copy")
7196            .is_some_and(|point| point.depends_on_model_values));
7197
7198        // Without its summary on disk, each copy is refused at load because
7199        // its process still records value-dependent generation.
7200        let folder = temp.path().join("state");
7201        state.save(&folder, true, false)?;
7202        State::load(folder.clone(), None, None)?;
7203        for process_id in [1, 2] {
7204            fs::remove_file(integrand_generation_summary_path(
7205                &folder,
7206                &state.process_list.processes[process_id],
7207                "copy",
7208            ))?;
7209            let error = load_error(&folder);
7210            assert!(
7211                error.contains("generation point was not recorded"),
7212                "{error}"
7213            );
7214            assert!(error.contains("'copy'"), "{error}");
7215            // Restore it for the next copy.
7216            state.save(&folder, true, false)?;
7217        }
7218        Ok(())
7219    }
7220
7221    #[test]
7222    fn constant_internal_parameters_are_generation_inputs() -> Result<()> {
7223        let _guard = crate::LOG_TEST_MUTEX
7224            .lock()
7225            .unwrap_or_else(|err| err.into_inner());
7226        test_initialise()?;
7227        // The scalars model with `mass_scalar_1` turned into an internal
7228        // numeric constant (a value without an expression), scaled by `scale`.
7229        let constant_mass_model = |scale: f64| -> Result<Model> {
7230            let mut definition: JsonValue =
7231                serde_json::from_str(&load_generic_model("scalars").to_json()?)?;
7232            let mass = definition["parameters"]
7233                .as_array_mut()
7234                .and_then(|parameters| {
7235                    parameters
7236                        .iter_mut()
7237                        .find(|parameter| parameter["name"] == "mass_scalar_1")
7238                })
7239                .ok_or_else(|| eyre!("the scalars model defines mass_scalar_1"))?;
7240            mass["nature"] = "internal".into();
7241            mass["expression"] = JsonValue::Null;
7242            let value = mass["value"][0]
7243                .as_f64()
7244                .ok_or_else(|| eyre!("mass_scalar_1 has a real value"))?;
7245            mass["value"][0] = (value * scale + (scale - 1.0)).into();
7246            Ok(Model::from_json(&serde_json::to_string(&definition)?)?)
7247        };
7248        let mut state = State::new_test();
7249        state.model = constant_mass_model(1.0)?;
7250        state.model_parameters = state.model.default_param_card();
7251        assert!(!state
7252            .model_parameters
7253            .contains_key(&UFOSymbol::from("mass_scalar_1")));
7254        let graphs = Graph::from_finalized_runtime_path(
7255            crate::test_workspace_root().join("tests/resources/graphs/scalar_bubble.dot"),
7256            &state.model,
7257        )?;
7258        import_into(&mut state, graphs, "bubble", "default")?;
7259        let runtime: RuntimeSettings = toml::from_str(
7260            r#"
7261[kinematics]
7262e_cm = 2.0
7263[kinematics.externals]
7264type = "constant"
7265[kinematics.externals.data]
7266momenta = [[0.5, 0.2, 0.3, 0.1], "dependent"]
7267helicities = [0, 0]
7268"#,
7269        )?;
7270        state.generate_integrands(&cheap_generation_settings(true)?, (&runtime).into())?;
7271        assert!(state
7272            .recorded_generation_point(0, "default")
7273            .is_some_and(|point| point.input_parameters.contains_key("mass_scalar_1")));
7274
7275        // Unchanged: accepted. A changed constant of the same structure: refused.
7276        state.replace_model(constant_mass_model(1.0)?, state.model_parameters.clone())?;
7277        let heavier = constant_mass_model(10.0)?;
7278        assert_eq!(
7279            heavier.structure_fingerprint(),
7280            state.model.structure_fingerprint()
7281        );
7282        let error = state
7283            .replace_model(heavier, state.model_parameters.clone())
7284            .expect_err("the constant mass decided the generation");
7285        let error = format!("{error:?}");
7286        assert!(error.contains("mass_scalar_1"), "{error}");
7287        assert!(error.contains("regenerate"), "{error}");
7288
7289        // The same constant change as a model override at load is refused too.
7290        let temp = tempdir()?;
7291        let folder = temp.path().join("state");
7292        state.save(&folder, true, false)?;
7293        let override_path = temp.path().join("heavier.json");
7294        fs::write(&override_path, constant_mass_model(10.0)?.to_json()?)?;
7295        let error = match State::load(folder, Some(override_path), None) {
7296            Ok(_) => panic!("a changed constant mass must not load silently"),
7297            Err(error) => format!("{error:?}"),
7298        };
7299        assert!(
7300            error.contains("no longer matches its generation point"),
7301            "{error}"
7302        );
7303        assert!(error.contains("mass_scalar_1"), "{error}");
7304        Ok(())
7305    }
7306
7307    #[test]
7308    fn effective_external_values_count_however_the_card_is_written() -> Result<()> {
7309        let _guard = crate::LOG_TEST_MUTEX
7310            .lock()
7311            .unwrap_or_else(|err| err.into_inner());
7312        let mut state = threshold_cross_section_state(&["self_energy"])?;
7313        // Generate with an empty card: the model's own values are the point.
7314        state.model_parameters = InputParamCard::new();
7315        state.generate_integrands(
7316            &cheap_generation_settings(true)?,
7317            (&RuntimeSettings::default()).into(),
7318        )?;
7319        let mass = model_value(&state.model, "mass_scalar_1");
7320
7321        // A same-structure model with another external mass and again an
7322        // empty card is a different point.
7323        let mut heavier = state.model.clone();
7324        heavier.apply_param_card(&card_with(&state, "mass_scalar_1", 10.0 * mass))?;
7325        let _error = state
7326            .replace_model(heavier, InputParamCard::new())
7327            .expect_err("the effective mass changes");
7328        assert_eq!(model_value(&state.model, "mass_scalar_1"), mass);
7329
7330        // The unchanged model, with an empty or a complete card, is the same point.
7331        state.replace_model(state.model.clone(), InputParamCard::new())?;
7332        state.replace_model(state.model.clone(), state.model.default_param_card())?;
7333        assert_eq!(model_value(&state.model, "mass_scalar_1"), mass);
7334        Ok(())
7335    }
7336
7337    #[test]
7338    fn generation_time_threshold_checks_refuse_a_runtime_model_overlay() -> Result<()> {
7339        let _guard = crate::LOG_TEST_MUTEX
7340            .lock()
7341            .unwrap_or_else(|err| err.into_inner());
7342        for check_esurface_at_generation in [true, false] {
7343            let mut state = threshold_cross_section_state(&["self_energy"])?;
7344            let mut runtime = RuntimeSettings::default();
7345            let overlay = 2.0 * model_value(&state.model, "mass_scalar_1");
7346            runtime
7347                .model
7348                .external_parameters
7349                .insert("mass_scalar_1".into(), (F(overlay), F(0.0)));
7350            let result = state.generate_integrands(
7351                &cheap_generation_settings(check_esurface_at_generation)?,
7352                (&runtime).into(),
7353            );
7354            let generated = state
7355                .process_list
7356                .get_integrand(0, "default")?
7357                .integrand
7358                .is_some();
7359            if check_esurface_at_generation {
7360                let error = format!(
7361                    "{:?}",
7362                    result.expect_err("decisions would use the raw mass")
7363                );
7364                assert!(error.contains("runtime model overlay"), "{error}");
7365                assert!(!generated, "nothing may be built");
7366                assert!(state.generation_summary(0, "default").is_none());
7367            } else {
7368                result?;
7369                assert!(generated);
7370                assert_eq!(
7371                    state
7372                        .process_list
7373                        .get_integrand(0, "default")?
7374                        .require_generated()?
7375                        .get_settings()
7376                        .model
7377                        .external_parameters["mass_scalar_1"],
7378                    (F(overlay), F(0.0))
7379                );
7380            }
7381        }
7382        Ok(())
7383    }
7384
7385    #[test]
7386    fn generation_kinematics_ignore_display_defaults_and_caches() -> Result<()> {
7387        let mut kinematics = RuntimeSettings::default().kinematics;
7388        // The value whose display serialization is skipped by default.
7389        kinematics.e_cm = 64.0;
7390        let point = GenerationKinematics::new(&kinematics);
7391        {
7392            let _show_defaults = ShowDefaultsGuard::new(true);
7393            assert_eq!(GenerationKinematics::new(&kinematics), point);
7394        }
7395        let mut cached = kinematics.clone();
7396        let Externals::Constant { f_64_cache, .. } = &mut cached.externals;
7397        *f_64_cache = Some(Default::default());
7398        assert_ne!(cached, kinematics, "the transient cache is populated");
7399        assert_eq!(GenerationKinematics::new(&cached), point);
7400
7401        // Non-finite values are encoded by their bits and round-trip exactly.
7402        let mut points = Vec::new();
7403        for e_cm in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 64.0] {
7404            kinematics.e_cm = e_cm;
7405            let encoded = GenerationKinematics::new(&kinematics);
7406            let reloaded: GenerationKinematics =
7407                serde_json::from_str(&serde_json::to_string(&encoded)?)?;
7408            assert_eq!(reloaded, encoded);
7409            points.push(encoded);
7410        }
7411        for (index, point) in points.iter().enumerate() {
7412            for other in &points[index + 1..] {
7413                assert_ne!(point, other);
7414            }
7415        }
7416        Ok(())
7417    }
7418
7419    #[test]
7420    fn a_model_override_at_load_is_compared_by_effective_values() -> Result<()> {
7421        let _guard = crate::LOG_TEST_MUTEX
7422            .lock()
7423            .unwrap_or_else(|err| err.into_inner());
7424        let temp = tempdir()?;
7425        let mut state = threshold_cross_section_state(&["self_energy"])?;
7426        // An empty card: the masses come from the model alone.
7427        state.model_parameters = InputParamCard::new();
7428        state.generate_integrands(
7429            &cheap_generation_settings(true)?,
7430            (&RuntimeSettings::default()).into(),
7431        )?;
7432        let folder = temp.path().join("state");
7433        state.save(&folder, true, false)?;
7434        let unchanged = temp.path().join("unchanged.json");
7435        fs::write(&unchanged, state.model.to_json()?)?;
7436        State::load(folder.clone(), Some(unchanged), None)?;
7437
7438        let mut heavier = state.model.clone();
7439        heavier.apply_param_card(&card_with(
7440            &state,
7441            "mass_scalar_1",
7442            10.0 * model_value(&state.model, "mass_scalar_1"),
7443        ))?;
7444        let override_path = temp.path().join("heavier.json");
7445        fs::write(&override_path, heavier.to_json()?)?;
7446        let error = match State::load(folder, Some(override_path), None) {
7447            Ok(_) => panic!("a changed model default must not load silently"),
7448            Err(error) => format!("{error:?}"),
7449        };
7450        assert!(
7451            error.contains("no longer matches its generation point"),
7452            "{error}"
7453        );
7454        assert!(error.contains("mass_scalar_1"), "{error}");
7455        Ok(())
7456    }
7457
7458    #[test]
7459    fn value_changes_require_regeneration_after_generation_time_threshold_checks() -> Result<()> {
7460        let _guard = crate::LOG_TEST_MUTEX
7461            .lock()
7462            .unwrap_or_else(|err| err.into_inner());
7463        let mut state = generated_threshold_cross_section(true)?;
7464        let model_before = state.model.fingerprint();
7465        let card_before = card_entries(&state);
7466        let handle_before = state.shared_graph_model();
7467        let handles_before = Arc::strong_count(&handle_before);
7468        // A tenfold mass closes the thresholds classified at generation.
7469        let heavy = 10.0 * model_value(&state.model, "mass_scalar_1");
7470        let error = state
7471            .replace_model(
7472                state.model.clone(),
7473                card_with(&state, "mass_scalar_1", heavy),
7474            )
7475            .expect_err("generation decided on the old masses");
7476        let error = format!("{error:?}");
7477        assert!(error.contains("regenerate"), "{error}");
7478        assert!(
7479            error.contains("remove processes -p name:self_energy"),
7480            "{error}"
7481        );
7482        assert!(error.contains("the state is unchanged"), "{error}");
7483        assert_eq!(state.model.fingerprint(), model_before);
7484        assert_eq!(card_entries(&state), card_before);
7485        assert!(Arc::ptr_eq(&state.shared_graph_model(), &handle_before));
7486        assert_eq!(Arc::strong_count(&handle_before), handles_before);
7487        assert_graphs_share_session_model(&state);
7488
7489        // Without the generation-time check, the same change only refreshes values.
7490        let temp = tempdir()?;
7491        let mut state = generated_threshold_cross_section(false)?;
7492        let previous = state.shared_graph_model();
7493        let heavy = 10.0 * model_value(&state.model, "mass_scalar_1");
7494        state.replace_model(
7495            state.model.clone(),
7496            card_with(&state, "mass_scalar_1", heavy),
7497        )?;
7498        assert_eq!(model_value(&state.model, "mass_scalar_1"), heavy);
7499        assert_graphs_share_session_model(&state);
7500        assert_eq!(Arc::strong_count(&previous), 1);
7501        let folder = temp.path().join("state");
7502        state.save(&folder, true, false)?;
7503        let loaded = State::load(folder, None, None)?;
7504        assert_graphs_share_session_model(&loaded);
7505        assert_eq!(model_value(&loaded.model, "mass_scalar_1"), heavy);
7506        Ok(())
7507    }
7508
7509    #[test]
7510    fn save_refuses_graphs_of_another_model_before_writing() -> Result<()> {
7511        test_initialise()?;
7512        let temp = tempdir()?;
7513        let mut state = State::new_test();
7514        state.model = load_generic_model("scalars");
7515        state.model_parameters = state.model.default_param_card();
7516        let graphs = Graph::from_finalized_runtime_path(
7517            crate::test_workspace_root().join("tests/resources/graphs/scalar_bubble.dot"),
7518            &state.model,
7519        )?;
7520        import_into(&mut state, graphs, "bubble", "default")?;
7521
7522        // Ungenerated graphs save without any numerical requirement.
7523        state.save(&temp.path().join("graphs_only"), true, false)?;
7524
7525        // A programmatic client replaces the public model field directly.
7526        state.model = state.model.with_restriction(Some("other".into()))?;
7527        let target = temp.path().join("never_written");
7528        let error = state.save(&target, true, false).unwrap_err();
7529        assert!(
7530            format!("{error:?}").contains("do not match its model"),
7531            "{error:?}"
7532        );
7533        assert!(!target.exists(), "nothing may be written");
7534        Ok(())
7535    }
7536
7537    #[test]
7538    fn failed_saved_model_load_preserves_committed_parameter_displays() -> Result<()> {
7539        test_initialise()?;
7540        let temporary = tempdir()?;
7541        let name = "state_load_display_transaction_marker";
7542        let mut definition = serde_json::to_value(Model::empty("display-load"))?;
7543        definition["parameters"] = serde_json::json!([{
7544            "name": name,
7545            "nature": "external",
7546            "parameter_type": "real",
7547            "value": [1.0, 0.0],
7548            "texname": "loaded_before_latex",
7549            "typstname": "loaded_before_typst",
7550            "mathmlname": "<mi>loaded_before_mathml</mi>"
7551        }]);
7552        let mut state = State::new_test();
7553        state.model = Model::from_json(&definition.to_string())?;
7554        state.model_parameters = state.model.default_param_card();
7555        let folder = temporary.path().join("state");
7556        state.save(&folder, true, false)?;
7557        let atom = Atom::var(
7558            Symbol::get_symbol(NamespacedSymbol::parse(&format!("UFO::{name}"))).unwrap(),
7559        );
7560        let expression = &atom * &atom;
7561        let printed = || {
7562            [
7563                PrintOptions::latex(),
7564                PrintOptions::typst(),
7565                PrintOptions::mathml(),
7566            ]
7567            .map(|options| expression.printer(options).to_string())
7568        };
7569        let previous_display = printed();
7570        definition["parameters"][0]["texname"] = "loaded_after_latex".into();
7571        definition["parameters"][0]["typstname"] = "loaded_after_typst".into();
7572        definition["parameters"][0]["mathmlname"] = "<mi>loaded_after_mathml</mi>".into();
7573        fs::write(folder.join("model.json"), definition.to_string())?;
7574
7575        let mut rejected = state.model_parameters.clone();
7576        rejected.insert(
7577            UFOSymbol::from("not_a_display_model_parameter"),
7578            Complex::new_re(F(1.0)),
7579        );
7580        rejected.to_file(folder.join("model_parameters.json"), true)?;
7581        let error = State::load(folder.clone(), None, None)
7582            .err()
7583            .expect("the invalid card must reject this load");
7584        assert!(format!("{error:?}").contains("cannot be applied to the saved model"));
7585        assert_eq!(printed(), previous_display);
7586
7587        state
7588            .model_parameters
7589            .to_file(folder.join("model_parameters.json"), true)?;
7590        let restored = State::load(folder.clone(), None, None)?;
7591        assert_eq!(restored.model.name(), state.model.name());
7592        assert!(printed()[2].contains("loaded_after_mathml"));
7593        assert_ne!(printed(), previous_display);
7594
7595        // A session can still fail after its State loads: its saved settings
7596        // and boot commands are validated by the enclosing application boundary.
7597        let committed_display = printed();
7598        definition["parameters"][0]["mathmlname"] = "<mi>session_after_mathml</mi>".into();
7599        fs::write(folder.join("model.json"), definition.to_string())?;
7600        let runtime_file = folder.join(DEFAULT_RUNTIME_SETTINGS_FILENAME);
7601        fs::write(&runtime_file, "[invalid")?;
7602        let _log_lock = LOG_TEST_MUTEX.lock().unwrap();
7603        assert!(OneShot::new_test(folder.clone()).load().is_err());
7604        assert_eq!(printed(), committed_display);
7605        assert!(StateLoadOption::read_only(folder.clone()).load().is_err());
7606        assert_eq!(printed(), committed_display);
7607        fs::remove_file(runtime_file)?;
7608        StateLoadOption::read_only(folder).load()?;
7609        assert!(printed()[2].contains("session_after_mathml"));
7610        Ok(())
7611    }
7612
7613    #[test]
7614    fn load_reports_a_parameter_card_that_does_not_apply() -> Result<()> {
7615        test_initialise()?;
7616        let temp = tempdir()?;
7617        let mut state = State::new_test();
7618        state.model = load_generic_model("scalars");
7619        state.model_parameters = state.model.default_param_card();
7620        let folder = temp.path().join("state");
7621        state.save(&folder, true, false)?;
7622        let mut card = state.model.default_param_card();
7623        card.insert(
7624            UFOSymbol::from("not_a_model_parameter"),
7625            Complex::new_re(F(1.0)),
7626        );
7627        card.to_file(folder.join("model_parameters.json"), true)?;
7628        let error = match State::load(folder, None, None) {
7629            Ok(_) => panic!("an inapplicable parameter card must not load"),
7630            Err(error) => format!("{error:?}"),
7631        };
7632        assert!(
7633            error.contains("cannot be applied to the saved model"),
7634            "{error}"
7635        );
7636        Ok(())
7637    }
7638
7639    #[test]
7640    fn targeted_overlays_and_kinematics_keep_value_dependent_generation_points() -> Result<()> {
7641        let _guard = crate::LOG_TEST_MUTEX
7642            .lock()
7643            .unwrap_or_else(|err| err.into_inner());
7644        for check_esurface_at_generation in [true, false] {
7645            let mut state = generated_threshold_cross_section(check_esurface_at_generation)?;
7646            let mut cli_settings = CLISettings::default();
7647            let mut default_runtime_settings = RuntimeSettings::default();
7648            let target = ProcessArgs {
7649                process: Some(ProcessRef::Name("self_energy".into())),
7650                integrand_name: Some("default".into()),
7651            };
7652            let settings = |state: &mut State| -> Result<RuntimeSettings> {
7653                Ok(state
7654                    .process_list
7655                    .get_integrand_mut(0, "default")?
7656                    .get_settings()
7657                    .clone())
7658            };
7659            let before = settings(&mut state)?;
7660            let heavy = 10.0 * model_value(&state.model, "mass_scalar_1");
7661            let overlay = Set::Model {
7662                target: target.clone(),
7663                values: vec![ModelSetValue::Assignment(KvPair {
7664                    key: "mass_scalar_1".into(),
7665                    value: heavy.to_string(),
7666                })],
7667            }
7668            .run(&mut state, &mut cli_settings, &mut default_runtime_settings);
7669            let after_overlay = settings(&mut state)?;
7670            let e_cm = 2.0
7671                * state
7672                    .process_list
7673                    .get_integrand_mut(0, "default")?
7674                    .get_settings()
7675                    .kinematics
7676                    .e_cm
7677                + 1.0;
7678            let kinematics = Set::Process {
7679                input: ProcessSetArgs::Kv {
7680                    pairs: vec![KvPair {
7681                        key: "kinematics.e_cm".into(),
7682                        value: e_cm.to_string(),
7683                    }],
7684                },
7685                process: target,
7686            }
7687            .run(&mut state, &mut cli_settings, &mut default_runtime_settings);
7688            if check_esurface_at_generation {
7689                for (change, result) in [("overlay", overlay), ("kinematics", kinematics)] {
7690                    let error = format!(
7691                        "{:?}",
7692                        result.expect_err("generation decided at the generation point")
7693                    );
7694                    assert!(error.contains("regenerate"), "{change}: {error}");
7695                    assert!(error.contains("generation point"), "{change}: {error}");
7696                }
7697                assert_eq!(after_overlay, before);
7698                assert_eq!(settings(&mut state)?, before);
7699            } else {
7700                overlay?;
7701                kinematics?;
7702                assert_ne!(after_overlay, before);
7703                assert_ne!(settings(&mut state)?, after_overlay);
7704            }
7705        }
7706        Ok(())
7707    }
7708
7709    #[test]
7710    fn load_reports_a_card_edited_away_from_the_generation_point() -> Result<()> {
7711        let _guard = crate::LOG_TEST_MUTEX
7712            .lock()
7713            .unwrap_or_else(|err| err.into_inner());
7714        let temp = tempdir()?;
7715        let mut state = generated_threshold_cross_section(true)?;
7716        let folder = temp.path().join("state");
7717        state.save(&folder, true, false)?;
7718
7719        // Unedited, the saved state is exactly at its generation point.
7720        let loaded = State::load(folder.clone(), None, None)?;
7721        assert_eq!(card_bits(&loaded), card_bits(&state));
7722        let settings = loaded
7723            .process_list
7724            .get_integrand(0, "default")?
7725            .require_generated()?
7726            .get_settings();
7727        loaded.ensure_generation_point_kept(
7728            0,
7729            "default",
7730            &loaded.model,
7731            &loaded.model_parameters,
7732            settings,
7733        )?;
7734
7735        // A tenfold mass crosses the thresholds classified at generation.
7736        let heavy = 10.0 * model_value(&state.model, "mass_scalar_1");
7737        card_with(&state, "mass_scalar_1", heavy)
7738            .to_file(folder.join("model_parameters.json"), true)?;
7739        let error = load_error(&folder);
7740        assert!(
7741            error.contains("no longer matches its generation point"),
7742            "{error}"
7743        );
7744        assert!(error.contains("mass_scalar_1"), "{error}");
7745        assert!(error.contains("regenerate"), "{error}");
7746
7747        // Without the record the edit cannot be detected, so the load is
7748        // refused whether or not the card was edited.
7749        strip_generation_point(&folder, &state)?;
7750        for edited in [true, false] {
7751            let value = if edited {
7752                heavy
7753            } else {
7754                model_value(&state.model, "mass_scalar_1")
7755            };
7756            card_with(&state, "mass_scalar_1", value)
7757                .to_file(folder.join("model_parameters.json"), true)?;
7758            let error = load_error(&folder);
7759            assert!(
7760                error.contains("generation point was not recorded"),
7761                "edited: {edited}: {error}"
7762            );
7763            assert!(error.contains("regenerate"), "edited: {edited}: {error}");
7764        }
7765        Ok(())
7766    }
7767
7768    fn card_bits(state: &State) -> BTreeMap<String, [u64; 2]> {
7769        state
7770            .model_parameters
7771            .iter()
7772            .map(|(name, value)| {
7773                (
7774                    name.to_string(),
7775                    [value.re.0.to_bits(), value.im.0.to_bits()],
7776                )
7777            })
7778            .collect()
7779    }
7780
7781    fn load_error(folder: &Path) -> String {
7782        match State::load(folder.to_path_buf(), None, None) {
7783            Ok(_) => panic!("the state must not load"),
7784            Err(error) => format!("{error:?}"),
7785        }
7786    }
7787
7788    /// Remove the recorded generation point of integrand "default" of
7789    /// process 0 from a saved state, as in a state saved before it existed.
7790    fn strip_generation_point(folder: &Path, state: &State) -> Result<()> {
7791        let path =
7792            integrand_generation_summary_path(folder, &state.process_list.processes[0], "default");
7793        let mut summary: JsonValue = serde_json::from_str(&fs::read_to_string(&path)?)?;
7794        summary
7795            .as_object_mut()
7796            .ok_or_else(|| eyre!("a generation summary is a JSON object"))?
7797            .remove("generation_point")
7798            .ok_or_else(|| eyre!("the generation point was recorded"))?;
7799        fs::write(&path, serde_json::to_string_pretty(&summary)?)?;
7800        Ok(())
7801    }
7802
7803    #[test]
7804    fn graph_only_and_value_independent_states_load_without_generation_points() -> Result<()> {
7805        let _guard = crate::LOG_TEST_MUTEX
7806            .lock()
7807            .unwrap_or_else(|err| err.into_inner());
7808        let temp = tempdir()?;
7809
7810        // Generated without generation-time threshold checks: no record needed.
7811        let mut state = generated_threshold_cross_section(false)?;
7812        let folder = temp.path().join("independent");
7813        state.save(&folder, true, false)?;
7814        strip_generation_point(&folder, &state)?;
7815        let heavy = 10.0 * model_value(&state.model, "mass_scalar_1");
7816        card_with(&state, "mass_scalar_1", heavy)
7817            .to_file(folder.join("model_parameters.json"), true)?;
7818        let loaded = State::load(folder, None, None)?;
7819        assert_eq!(model_value(&loaded.model, "mass_scalar_1"), heavy);
7820
7821        // Graphs that were never generated carry no generation decisions.
7822        let mut graphs_only = State::new_test();
7823        graphs_only.model = load_generic_model("scalars");
7824        graphs_only.model_parameters = graphs_only.model.default_param_card();
7825        let graphs = Graph::from_finalized_runtime_path(
7826            crate::test_workspace_root().join("tests/resources/graphs/scalar_bubble.dot"),
7827            &graphs_only.model,
7828        )?;
7829        import_into(&mut graphs_only, graphs, "bubble", "default")?;
7830        let folder = temp.path().join("graphs_only");
7831        graphs_only.save(&folder, true, false)?;
7832        let heavier = model_value(&graphs_only.model, "mass_scalar_1") + 1.0;
7833        card_with(&graphs_only, "mass_scalar_1", heavier)
7834            .to_file(folder.join("model_parameters.json"), true)?;
7835        let loaded = State::load(folder, None, None)?;
7836        assert_eq!(model_value(&loaded.model, "mass_scalar_1"), heavier);
7837        Ok(())
7838    }
7839
7840    #[test]
7841    fn next_representable_changes_leave_value_dependent_generation_points() -> Result<()> {
7842        let _guard = crate::LOG_TEST_MUTEX
7843            .lock()
7844            .unwrap_or_else(|err| err.into_inner());
7845        let mut state = generated_threshold_cross_section(true)?;
7846        let settings = state
7847            .process_list
7848            .get_integrand(0, "default")?
7849            .require_generated()?
7850            .get_settings()
7851            .clone();
7852        let check = |state: &State, card: &InputParamCard<F<f64>>, settings: &RuntimeSettings| {
7853            state.ensure_generation_point_kept(0, "default", &state.model, card, settings)
7854        };
7855        check(&state, &state.model_parameters, &settings)?;
7856
7857        let mass = model_value(&state.model, "mass_scalar_1");
7858        for neighbour in [mass.next_up(), mass.next_down()] {
7859            let card = card_with(&state, "mass_scalar_1", neighbour);
7860            let error = format!("{:?}", check(&state, &card, &settings).unwrap_err());
7861            assert!(error.contains("mass_scalar_1"), "{error}");
7862            assert!(error.contains("regenerate"), "{error}");
7863        }
7864        let card_before = card_bits(&state);
7865        let _error = state
7866            .replace_model(
7867                state.model.clone(),
7868                card_with(&state, "mass_scalar_1", mass.next_up()),
7869            )
7870            .expect_err("one ulp of a classified mass is a different generation point");
7871        assert_eq!(card_bits(&state), card_before);
7872
7873        let mut nudged = settings.clone();
7874        nudged.kinematics.e_cm = nudged.kinematics.e_cm.next_up();
7875        let error = format!(
7876            "{:?}",
7877            check(&state, &state.model_parameters, &nudged).unwrap_err()
7878        );
7879        assert!(error.contains("kinematic settings"), "{error}");
7880
7881        // Signed zeros are distinct inputs.
7882        let with_mass = |value: f64| -> Result<GenerationPoint> {
7883            let mut model = state.model.clone();
7884            model.apply_param_card(&card_with(&state, "mass_scalar_1", value))?;
7885            GenerationPoint::new(&model, &settings, true)
7886        };
7887        let positive = with_mass(0.0)?;
7888        let negative = with_mass(-0.0)?;
7889        assert!(positive.difference(&negative).is_some());
7890        assert!(positive.difference(&positive.clone()).is_none());
7891        Ok(())
7892    }
7893
7894    #[test]
7895    fn saved_parameter_cards_round_trip_every_f64_bit_exactly() -> Result<()> {
7896        test_initialise()?;
7897        let temp = tempdir()?;
7898        let values = [
7899            0.1_f64.next_up(),
7900            1.0 / 3.0,
7901            123_456.0 + 1.0 / 7.0,
7902            f64::MIN_POSITIVE / 3.0,
7903            f64::from_bits(1),
7904            f64::MAX,
7905            -0.0,
7906            0.0,
7907            -2.5e-310,
7908        ];
7909        let mut card = InputParamCard::<F<f64>>::new();
7910        for (index, value) in values.iter().enumerate() {
7911            card.insert(
7912                UFOSymbol::from(format!("round_trip_{index}").as_str()),
7913                Complex::new(F(*value), F(-*value)),
7914            );
7915        }
7916        let path = temp.path().join("model_parameters.json");
7917        card.to_file(&path, true)?;
7918        let reloaded = InputParamCard::<F<f64>>::from_file(&path)?;
7919        for (name, value) in card.iter() {
7920            let other = reloaded
7921                .get(name)
7922                .ok_or_else(|| eyre!("{name} was not reloaded"))?;
7923            assert_eq!(
7924                [value.re.0.to_bits(), value.im.0.to_bits()],
7925                [other.re.0.to_bits(), other.im.0.to_bits()],
7926                "{name}"
7927            );
7928        }
7929        Ok(())
7930    }
7931
7932    #[test]
7933    fn summed_sampling_matches_explicit_canonical_channels() -> Result<()> {
7934        use gammalooprs::{
7935            graph::GroupId,
7936            settings::runtime::{
7937                DiscreteGraphSamplingSettings, DiscreteGraphSamplingType, SamplingSettings,
7938                StabilityLevelSetting,
7939            },
7940        };
7941        use symbolica::numerical_integration::Sample;
7942
7943        use gammalooprs::integrands::evaluation::StabilityStatus;
7944
7945        let _guard = crate::LOG_TEST_MUTEX
7946            .lock()
7947            .unwrap_or_else(|err| err.into_inner());
7948        let mut state = build_generated_scalar_bubble_state_with_external_backend();
7949        state.activate_loaded_integrand_backends(false)?;
7950        let integrand = state.process_list.get_integrand_mut(0, "default")?;
7951        let mut settings: RuntimeSettings = toml::from_str(
7952            r#"
7953[kinematics]
7954e_cm = 2.0
7955[kinematics.externals]
7956type = "constant"
7957[kinematics.externals.data]
7958momenta = [[0.5, 0.2, 0.3, 0.1], "dependent"]
7959helicities = [0, 0]
7960[sampling]
7961graphs = "summed"
7962orientations = "summed"
7963sampling_multichanneling = true
7964sampling_channels = "summed"
7965default_channel_selection = ["auto:lmb"]
7966[stability]
7967rotation_axis = [{type = "x"}, {type = "y"}]
7968"#,
7969        )?;
7970        settings.stability.levels = vec![StabilityLevelSetting::default_double()];
7971        let SamplingSettings::MultiChanneling(multichanneling) = settings.sampling.clone() else {
7972            panic!("expected summed sampling settings");
7973        };
7974        let channel_ids = integrand
7975            .group_sampling_channel_ids(GroupId(0), &multichanneling.parameterization_settings)?;
7976        assert_eq!(
7977            channel_ids.len(),
7978            2,
7979            "bubble must exercise two distinct affine LMB charts"
7980        );
7981        let coordinates = [
7982            vec![F(0.27), F(0.36), F(0.71)],
7983            vec![F(0.62), F(0.24), F(0.53)],
7984        ];
7985        let samples = coordinates
7986            .iter()
7987            .map(|xs| Sample::Continuous(F(1.0), xs.clone()))
7988            .collect::<Vec<_>>();
7989        *integrand.get_mut_settings() = settings.clone();
7990        integrand.warm_up(&state.model)?;
7991        let reference = GaussianReferenceFunction::new(2.0, vec![0.7, -0.4, 0.2])?;
7992        let summed_reference = samples
7993            .iter()
7994            .map(|sample| integrand.evaluate_reference_sample_detailed(sample, &reference))
7995            .collect::<Result<Vec<_>>>()?;
7996        let summed = integrand.evaluate_samples_raw(
7997            EvaluationTarget::Physical(&state.model),
7998            &samples,
7999            0,
8000            false,
8001            false,
8002            Complex::new_zero(),
8003        )?;
8004
8005        settings.sampling = SamplingSettings::DiscreteGraphs(DiscreteGraphSamplingSettings {
8006            sample_orientations: false,
8007            sampling_type: DiscreteGraphSamplingType::SamplingMultiChanneling(
8008                multichanneling.clone(),
8009            ),
8010            ..Default::default()
8011        });
8012        *integrand.get_mut_settings() = settings.clone();
8013        integrand.warm_up(&state.model)?;
8014        let mut expected = vec![Complex::<F<f64>>::new_zero(); coordinates.len()];
8015        let mut expected_reference = vec![(0.0, 0.0); coordinates.len()];
8016        for channel_id in channel_ids {
8017            let samples = coordinates
8018                .iter()
8019                .map(|xs| {
8020                    Sample::Discrete(
8021                        F(1.0),
8022                        0,
8023                        Some(Box::new(Sample::Discrete(
8024                            F(1.0),
8025                            channel_id.0,
8026                            Some(Box::new(Sample::Continuous(F(1.0), xs.clone()))),
8027                        ))),
8028                    )
8029                })
8030                .collect::<Vec<_>>();
8031            for (expected, sample) in expected_reference.iter_mut().zip(&samples) {
8032                let result = integrand.evaluate_reference_sample_detailed(sample, &reference)?;
8033                let jacobian = result.evaluation.parameterization_jacobian.unwrap().0;
8034                expected.0 += result.evaluation.integrand_result.re.0 * jacobian;
8035                expected.1 += result.moments.second_moment.0 * jacobian;
8036            }
8037            let result = integrand.evaluate_samples_raw(
8038                EvaluationTarget::Physical(&state.model),
8039                &samples,
8040                0,
8041                false,
8042                false,
8043                Complex::new_zero(),
8044            )?;
8045            for (total, sample) in expected.iter_mut().zip(result.samples) {
8046                *total +=
8047                    sample.integrand_result * sample.parameterization_jacobian.unwrap_or(F(1.0));
8048            }
8049        }
8050        // Check both ways of summing channels. The physical evaluator and
8051        // stability rotations must see the same maps as explicit MC selections.
8052        settings.sampling = SamplingSettings::DiscreteGraphs(DiscreteGraphSamplingSettings {
8053            sample_orientations: false,
8054            sampling_type: DiscreteGraphSamplingType::MultiChanneling(multichanneling),
8055            ..Default::default()
8056        });
8057        *integrand.get_mut_settings() = settings;
8058        integrand.warm_up(&state.model)?;
8059        let samples = samples
8060            .into_iter()
8061            .map(|sample| Sample::Discrete(F(1.0), 0, Some(Box::new(sample))))
8062            .collect::<Vec<_>>();
8063        let group_summed_reference = samples
8064            .iter()
8065            .map(|sample| integrand.evaluate_reference_sample_detailed(sample, &reference))
8066            .collect::<Result<Vec<_>>>()?;
8067        for results in [summed_reference, group_summed_reference] {
8068            for (result, expected) in results.iter().zip(&expected_reference) {
8069                let jacobian = result.evaluation.parameterization_jacobian.unwrap().0;
8070                for (actual, expected) in [
8071                    (
8072                        result.evaluation.integrand_result.re.0 * jacobian,
8073                        expected.0,
8074                    ),
8075                    (result.moments.second_moment.0 * jacobian, expected.1),
8076                ] {
8077                    assert!(
8078                        (actual - expected).abs() < 1.0e-11 * expected.abs().max(1.0),
8079                        "summed reference {actual} differs from explicit channel sum {expected}"
8080                    );
8081                }
8082            }
8083        }
8084        let group_summed = integrand.evaluate_samples_raw(
8085            EvaluationTarget::Physical(&state.model),
8086            &samples,
8087            0,
8088            false,
8089            false,
8090            Complex::new_zero(),
8091        )?;
8092        for result in [summed, group_summed] {
8093            for (sample, expected) in result.samples.iter().zip(&expected) {
8094                let value =
8095                    sample.integrand_result * sample.parameterization_jacobian.unwrap_or(F(1.0));
8096                let scale = expected.re.0.abs() + expected.im.0.abs();
8097                assert!(
8098                    scale > 1.0e-18 && scale.is_finite(),
8099                    "invalid oracle {expected}"
8100                );
8101                let error = (value - expected).re.0.abs() + (value - expected).im.0.abs();
8102                assert!(
8103                    error < scale * 1.0e-10,
8104                    "summed {value} differs from explicit channels {expected}"
8105                );
8106                assert!(!sample.evaluation_metadata.is_nan);
8107                assert!(
8108                    sample
8109                        .evaluation_metadata
8110                        .stability_results
8111                        .iter()
8112                        .all(|level| matches!(level.status, StabilityStatus::Stable(_))),
8113                    "rotation invariance failed"
8114                );
8115            }
8116        }
8117        // Default selected-LMB sampling must be converted at the same boundary
8118        // as the reference overlay. Compare both targets to an independently
8119        // reconstructed raw point, including the nonzero external shift.
8120        use gammalooprs::{
8121            integrands::process::{
8122                sampling::context::SamplingMapContext, GraphTerm, MomentumSpaceEvaluationInput,
8123                ProcessIntegrand, ProcessIntegrandImpl, SamplingMapComponent,
8124                SamplingMapDefinition, SamplingMapKernel,
8125            },
8126            momentum::ThreeMomentum,
8127        };
8128        let mut settings = integrand.get_settings().clone();
8129        let mut parameterization = settings.sampling.get_parameterization_settings().unwrap();
8130        parameterization
8131            .lmb_basis_ids
8132            .insert("bubble".into(), vec![1]);
8133        parameterization.sampling_channels.default_channel_selection =
8134            vec!["auto:optimized_lmb".into()];
8135        settings.sampling = SamplingSettings::Default(parameterization.clone());
8136        *integrand.get_mut_settings() = settings.clone();
8137        integrand.warm_up(&state.model)?;
8138        let frame = {
8139            let ProcessIntegrand::Amplitude(amplitude) = integrand else {
8140                unreachable!()
8141            };
8142            let term = &amplitude.data.graph_terms[0];
8143            let basis = term.selected_lmb_basis_id(&parameterization)?;
8144            assert_eq!(usize::from(basis), 1);
8145            let externals = settings
8146                .kinematics
8147                .externals
8148                .get_dependent_externals::<f64>(amplitude.get_dependent_momenta_constructor())?;
8149            let externals = externals
8150                .iter()
8151                .map(|p| {
8152                    [
8153                        p.temporal.value.0,
8154                        p.spatial.px.0,
8155                        p.spatial.py.0,
8156                        p.spatial.pz.0,
8157                    ]
8158                })
8159                .collect::<Vec<_>>();
8160            let setup = term.sampling_setup();
8161            setup.lmb_frame_map(&setup.all_bases[basis], &externals)?
8162        };
8163        let kernel = SamplingMapKernel::new(
8164            SamplingMapDefinition::Lmb(vec![0]),
8165            parameterization,
8166            settings.kinematics.e_cm,
8167            1,
8168        )?;
8169        let xs = [0.27, 0.36, 0.71];
8170        let selected =
8171            SamplingMapComponent::forward(&kernel, &xs, &mut SamplingMapContext::detached(&[]))?;
8172        let raw = frame.forward(&selected.point, &mut SamplingMapContext::detached(&[]))?;
8173        let sampling_jacobian = selected.jacobian * raw.jacobian;
8174        let sample = Sample::Continuous(F(1.0), xs.into_iter().map(F).collect());
8175        let reference_result = integrand.evaluate_reference_sample_detailed(&sample, &reference)?;
8176        let distance_squared = raw
8177            .point
8178            .iter()
8179            .zip(reference.center())
8180            .map(|(x, c)| (x - c).powi(2))
8181            .sum::<f64>();
8182        let expected = (-distance_squared / (2.0 * reference.width().powi(2))).exp()
8183            / (2.0 * std::f64::consts::PI * reference.width().powi(2)).powf(1.5);
8184        // X-space results and moments now contain their native Jacobian.
8185        // Undo the independently reconstructed map factor for this raw-frame oracle.
8186        assert_eq!(
8187            reference_result.evaluation.parameterization_jacobian,
8188            Some(F(1.0))
8189        );
8190        assert!(
8191            (reference_result.evaluation.integrand_result.re.0 / sampling_jacobian - expected)
8192                .abs()
8193                < expected * 1.0e-12
8194        );
8195        let radius_squared = raw.point.iter().map(|x| x * x).sum::<f64>();
8196        assert!(
8197            (reference_result.moments.second_moment.0 / sampling_jacobian
8198                - expected * radius_squared)
8199                .abs()
8200                < 1.0e-12
8201        );
8202        let physical = integrand
8203            .evaluate_samples_raw(
8204                EvaluationTarget::Physical(&state.model),
8205                &[sample],
8206                0,
8207                false,
8208                false,
8209                Complex::new_zero(),
8210            )?
8211            .samples
8212            .remove(0);
8213        let raw_result = integrand.evaluate_momentum_configuration(
8214            &state.model,
8215            &MomentumSpaceEvaluationInput {
8216                loop_momenta: raw
8217                    .point
8218                    .as_chunks::<3>()
8219                    .0
8220                    .iter()
8221                    .map(|p| ThreeMomentum {
8222                        px: F(p[0]),
8223                        py: F(p[1]),
8224                        pz: F(p[2]),
8225                    })
8226                    .collect(),
8227                integrator_weight: F(1.0),
8228                graph_id: Some(0),
8229                group_id: None,
8230                orientation: None,
8231                channel_id: None,
8232            },
8233            false,
8234        )?;
8235        assert_eq!(physical.parameterization_jacobian, Some(F(1.0)));
8236        let delta = physical.integrand_result / Complex::new_re(F(sampling_jacobian))
8237            - raw_result.integrand_result;
8238        let scale = raw_result.integrand_result.re.0.abs() + raw_result.integrand_result.im.0.abs();
8239        assert!(scale > 1.0e-18 && scale.is_finite());
8240        assert!(delta.re.0.abs() + delta.im.0.abs() < 1.0e-10 * scale);
8241        Ok(())
8242    }
8243
8244    #[test]
8245    fn resolve_effective_model_parameter_card_overlays_runtime_model_settings() {
8246        let mut state = State::new_test();
8247        state.model = load_generic_model("scalars");
8248        state.model_parameters = state.model.default_param_card();
8249
8250        let mut settings = RuntimeSettings::default();
8251        settings
8252            .model
8253            .external_parameters
8254            .insert("mass_scalar_2".to_string(), (F(7.5), F(0.0)));
8255
8256        let resolved = state
8257            .resolve_effective_model_parameter_card_for_settings(&settings)
8258            .unwrap();
8259
8260        assert_eq!(
8261            resolved[&UFOSymbol::from("mass_scalar_2")],
8262            Complex::new(F(7.5), F(0.0))
8263        );
8264        assert_eq!(
8265            resolved[&UFOSymbol::from("mass_scalar_1")],
8266            state.model_parameters[&UFOSymbol::from("mass_scalar_1")]
8267        );
8268    }
8269
8270    #[test]
8271    fn resolve_effective_model_parameter_card_rejects_non_overridable_parameters() {
8272        let mut state = State::new_test();
8273        state.model = load_generic_model("scalars");
8274        state.model_parameters = state.model.default_param_card();
8275        state
8276            .model_parameters
8277            .remove(&UFOSymbol::from("mass_scalar_2"));
8278
8279        let mut settings = RuntimeSettings::default();
8280        settings
8281            .model
8282            .external_parameters
8283            .insert("mass_scalar_2".to_string(), (F(7.5), F(0.0)));
8284
8285        let err = state
8286            .resolve_effective_model_parameter_card_for_settings(&settings)
8287            .unwrap_err();
8288
8289        assert!(err
8290            .to_string()
8291            .contains("cannot be overridden because it is not present"));
8292    }
8293}
8294
8295#[derive(Args, Debug, Clone)]
8296pub struct ExistingArgs {
8297    pub process_id: u32,
8298    pub name: Option<String>,
8299}