pharmsol 0.27.1

Rust library for solving analytic and ode-defined pharmacometric models.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
use std::fmt;
#[cfg(feature = "dsl-aot")]
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
#[cfg(feature = "dsl-aot")]
use std::sync::Arc;

#[cfg(feature = "dsl-aot-load")]
use libloading::{Library, Symbol};
#[cfg(feature = "dsl-aot")]
use rand::RngExt;
#[cfg(feature = "dsl-aot")]
use rand_distr::Alphanumeric;
use serde_json;
use thiserror::Error;

use super::compiled_backend_abi::{
    decode_compiled_model_info, API_VERSION_SYMBOL, DERIVE_SYMBOL, DIFFUSION_SYMBOL, DRIFT_SYMBOL,
    DYNAMICS_SYMBOL, INIT_SYMBOL, MODEL_INFO_JSON_LEN_SYMBOL, MODEL_INFO_JSON_PTR_SYMBOL,
    OUTPUTS_SYMBOL, ROUTE_BIOAVAILABILITY_SYMBOL, ROUTE_LAG_SYMBOL,
};
#[cfg(feature = "dsl-aot-load")]
use super::native::{CompiledNativeModel, DenseKernelFn, NativeExecutionArtifact, NativeModelInfo};
#[cfg(feature = "dsl-aot")]
use super::rust_backend::{emit_rust_backend_source, RustBackendFlavor};
#[cfg(feature = "dsl-aot")]
use crate::build_support::{
    build_cargo_template, create_cargo_template, native_cdylib_filename_for_target,
    write_template_source,
};
#[cfg(all(test, feature = "dsl-aot"))]
use crate::build_support::{rustc_host_target, rustup_installed_targets};
#[cfg(feature = "dsl-aot-load")]
use pharmsol_dsl::ModelKind;
#[cfg(feature = "dsl-aot")]
use pharmsol_dsl::{analyze_module, lower_typed_model, parse_module, ExecutionModel};
use pharmsol_dsl::{Diagnostic, DiagnosticReport, LoweringError, ParseError, SemanticError};

/// ABI version for native AoT artifacts produced by this crate.
pub const AOT_API_VERSION: u32 = 2;

#[cfg(feature = "dsl-aot")]
/// Selects the compilation target for a native ahead-of-time artifact.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum NativeAotTarget {
    /// Compile for the current host toolchain target.
    #[default]
    Host,
    /// Compile for an explicit Rust target triple.
    Triple(String),
}

#[cfg(feature = "dsl-aot")]
impl NativeAotTarget {
    /// Create a target selector for an explicit Rust target triple.
    pub fn triple(target: impl Into<String>) -> Self {
        Self::Triple(target.into())
    }

    fn cargo_target(&self) -> Option<&str> {
        match self {
            Self::Host => None,
            Self::Triple(target) => Some(target.as_str()),
        }
    }
}

#[cfg(feature = "dsl-aot")]
/// Options that control native ahead-of-time artifact export.
///
/// AoT export writes a small template crate under [`template_root`](Self::template_root),
/// builds a native shared library, and then copies the resulting artifact to
/// [`output`](Self::output) or a generated default path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeAotCompileOptions {
    /// Target triple selection for the emitted artifact.
    pub target: NativeAotTarget,
    /// Optional final artifact location.
    pub output: Option<PathBuf>,
    /// Working directory used for the temporary template crate and build output.
    pub template_root: PathBuf,
}

#[cfg(feature = "dsl-aot")]
impl NativeAotCompileOptions {
    /// Create AoT options rooted at a template build directory.
    pub fn new(template_root: PathBuf) -> Self {
        Self {
            target: NativeAotTarget::Host,
            output: None,
            template_root,
        }
    }

    /// Set the final artifact output path.
    pub fn with_output(mut self, output: PathBuf) -> Self {
        self.output = Some(output);
        self
    }

    /// Set the compilation target triple.
    pub fn with_target(mut self, target: NativeAotTarget) -> Self {
        self.target = target;
        self
    }
}

/// Error produced while exporting, reading, or loading a native AoT artifact.
#[derive(Error)]
pub enum AotError {
    #[error(transparent)]
    Io(#[from] io::Error),
    #[error(transparent)]
    Json(#[from] serde_json::Error),
    #[error("failed to parse DSL source: {0}")]
    Parse(#[source] ParseError),
    #[error("failed to analyze DSL source: {0}")]
    Semantic(#[source] SemanticError),
    #[error("failed to lower DSL model: {0}")]
    Lowering(#[source] LoweringError),
    #[error("{0}")]
    ModelSelection(String),
    #[error("AoT artifact API version mismatch: expected {expected}, found {found}")]
    ApiVersionMismatch { expected: u32, found: u32 },
    #[error("missing required AoT symbol `{0}`")]
    MissingSymbol(&'static str),
    #[error("failed to emit AoT library source: {0}")]
    Emit(String),
    #[error("failed to load AoT artifact: {0}")]
    Load(String),
}

impl AotError {
    pub fn diagnostic(&self) -> Option<&Diagnostic> {
        match self {
            Self::Parse(error) => Some(error.diagnostic()),
            Self::Semantic(error) => Some(error.diagnostic()),
            Self::Lowering(error) => Some(error.diagnostic()),
            _ => None,
        }
    }

    pub fn render_diagnostic(&self, src: &str) -> Option<String> {
        self.diagnostic().map(|diagnostic| diagnostic.render(src))
    }

    pub fn diagnostic_report(&self, source_name: impl Into<String>) -> Option<DiagnosticReport> {
        let source_name = source_name.into();
        match self {
            Self::Parse(error) => Some(error.diagnostic_report(source_name)),
            Self::Semantic(error) => Some(error.diagnostic_report(source_name)),
            Self::Lowering(error) => Some(error.diagnostic_report(source_name)),
            _ => None,
        }
    }
}

impl fmt::Debug for AotError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Parse(error) => fmt::Display::fmt(error, f),
            Self::Semantic(error) => fmt::Display::fmt(error, f),
            Self::Lowering(error) => fmt::Display::fmt(error, f),
            _ => fmt::Display::fmt(self, f),
        }
    }
}

#[cfg(feature = "dsl-aot")]
/// Parse DSL source, lower one selected model, and export a native AoT artifact.
///
/// Use this when you want a reusable native artifact that can be loaded later
/// with [`load_aot_model`] or [`crate::dsl::load_runtime_artifact`].
///
/// This function requires the `dsl-aot` feature. Loading the resulting artifact
/// later requires `dsl-aot-load`.
///
/// ```rust,no_run
/// use std::path::PathBuf;
///
/// use pharmsol::dsl::{compile_module_source_to_aot, load_aot_model, NativeAotCompileOptions};
///
/// let source = r#"
/// name = bimodal_ke
/// kind = ode
///
/// params = ke, v
/// states = central
/// outputs = cp
///
/// infusion(iv) -> central
///
/// dx(central) = -ke * central
/// out(cp) = central / v
/// "#;
///
/// let artifact = compile_module_source_to_aot(
///     source,
///     Some("bimodal_ke"),
///     NativeAotCompileOptions::new(PathBuf::from("target/doc-aot-build")),
///     |_, _| {},
/// )?;
/// let loaded = load_aot_model(&artifact)?;
/// # let _ = loaded;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn compile_module_source_to_aot(
    source: &str,
    model_name: Option<&str>,
    options: NativeAotCompileOptions,
    event_callback: impl Fn(String, String) + Send + Sync + 'static,
) -> Result<PathBuf, AotError> {
    let parsed =
        parse_module(source).map_err(|error| AotError::Parse(error.with_source(source)))?;
    let typed =
        analyze_module(&parsed).map_err(|error| AotError::Semantic(error.with_source(source)))?;

    let model = match model_name {
        Some(name) => typed
            .models
            .iter()
            .find(|model| model.name == name)
            .ok_or_else(|| {
                AotError::ModelSelection(format!("model `{name}` not found in module"))
            })?,
        None if typed.models.len() == 1 => &typed.models[0],
        None => {
            return Err(AotError::ModelSelection(
                "module contains multiple models; pass an explicit model name".to_string(),
            ))
        }
    };

    let execution =
        lower_typed_model(model).map_err(|error| AotError::Lowering(error.with_source(source)))?;
    export_execution_model_to_aot(&execution, options, event_callback)
}

#[cfg(feature = "dsl-aot")]
/// Export a lowered execution model as a native AoT artifact.
///
/// Use this lower-level entrypoint when you already own the frontend pipeline
/// and only need artifact generation.
pub fn export_execution_model_to_aot(
    model: &ExecutionModel,
    options: NativeAotCompileOptions,
    event_callback: impl Fn(String, String) + Send + Sync + 'static,
) -> Result<PathBuf, AotError> {
    let event_callback = Arc::new(event_callback);
    let NativeAotCompileOptions {
        target,
        output,
        template_root,
    } = options;
    let cargo_target = target.cargo_target();
    let template_dir = create_cargo_template(template_root.clone(), &aot_template_manifest())?;
    let source = emit_rust_backend_source(
        model,
        RustBackendFlavor::NativeAot {
            api_version: AOT_API_VERSION,
        },
    )
    .map_err(AotError::Emit)?;
    write_template_source(&template_dir, &source)?;

    let dylib_name = native_cdylib_filename_for_target("model_lib", cargo_target);
    let dylib_path = match cargo_target {
        Some(target) => build_cargo_template(
            template_dir,
            event_callback.clone(),
            "native-aot",
            model.name.clone(),
            Some(target),
            &[target, "release", dylib_name.as_str()],
        )?,
        None => build_cargo_template(
            template_dir,
            event_callback.clone(),
            "native-aot",
            model.name.clone(),
            None,
            &["release", dylib_name.as_str()],
        )?,
    };

    let output_path = output.unwrap_or_else(|| default_output_path(&template_root, &target));
    fs::copy(&dylib_path, &output_path)?;
    event_callback(
        "finished".into(),
        format!(
            "Compiled native-aot model `{}` -> {}",
            model.name,
            output_path.display()
        ),
    );
    Ok(output_path)
}

#[cfg(feature = "dsl-aot-load")]
/// Read only the metadata from a native AoT artifact.
///
/// This is useful when you need to inspect model identity, routes, outputs, or
/// buffer sizes without loading the executable kernels.
pub fn read_aot_model_info(path: impl AsRef<Path>) -> Result<NativeModelInfo, AotError> {
    let library = unsafe { Library::new(path.as_ref()) }
        .map_err(|error| AotError::Load(error.to_string()))?;
    let info = unsafe { read_model_info_from_library(&library)? };
    Ok(info)
}

#[cfg(feature = "dsl-aot-load")]
/// Load a native AoT artifact into the native execution runtime.
pub fn load_aot_model(path: impl AsRef<Path>) -> Result<CompiledNativeModel, AotError> {
    let path = path.as_ref();
    let library =
        unsafe { Library::new(path) }.map_err(|error| AotError::Load(error.to_string()))?;

    unsafe { ensure_api_version(&library)? };
    let info = unsafe { read_model_info_from_library(&library)? };
    let model_name = info.name.clone();
    let artifact = unsafe {
        NativeExecutionArtifact::from_library(
            model_name,
            load_optional_kernel(&library, DERIVE_SYMBOL),
            load_optional_kernel(&library, DYNAMICS_SYMBOL),
            load_required_kernel(&library, OUTPUTS_SYMBOL)?,
            load_optional_kernel(&library, INIT_SYMBOL),
            load_optional_kernel(&library, DRIFT_SYMBOL),
            load_optional_kernel(&library, DIFFUSION_SYMBOL),
            load_optional_kernel(&library, ROUTE_LAG_SYMBOL),
            load_optional_kernel(&library, ROUTE_BIOAVAILABILITY_SYMBOL),
            library,
        )
    };

    Ok(match info.kind {
        ModelKind::Ode => CompiledNativeModel::Ode(
            super::NativeOdeModel::new(info, artifact)
                .map_err(|error| AotError::Load(error.to_string()))?,
        ),
        ModelKind::Analytical => CompiledNativeModel::Analytical(
            super::NativeAnalyticalModel::new(info, artifact)
                .map_err(|error| AotError::Load(error.to_string()))?,
        ),
        ModelKind::Sde => CompiledNativeModel::Sde(
            super::NativeSdeModel::new(info, artifact)
                .map_err(|error| AotError::Load(error.to_string()))?,
        ),
    })
}

#[cfg(feature = "dsl-aot")]
fn default_output_path(template_root: &Path, target: &NativeAotTarget) -> PathBuf {
    let random_suffix: String = rand::rng()
        .sample_iter(&Alphanumeric)
        .take(5)
        .map(char::from)
        .collect();
    let target_label = match target {
        NativeAotTarget::Host => default_target_label(),
        NativeAotTarget::Triple(target) => sanitize_target_label(target),
    };
    template_root.join(format!("model_{}_{}.pkm", target_label, random_suffix))
}

#[cfg(feature = "dsl-aot")]
fn default_target_label() -> String {
    sanitize_target_label(&format!(
        "{}-{}",
        std::env::consts::ARCH,
        std::env::consts::OS
    ))
}

#[cfg(feature = "dsl-aot")]
fn sanitize_target_label(target: &str) -> String {
    target
        .chars()
        .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
        .collect()
}

#[cfg(feature = "dsl-aot")]
fn aot_template_manifest() -> String {
    r#"
        [package]
        name = "model_lib"
        version = "0.1.0"
        edition = "2021"

        [lib]
        crate-type = ["cdylib"]

        [workspace]
        "#
    .to_string()
}

#[cfg(feature = "dsl-aot-load")]
unsafe fn ensure_api_version(library: &Library) -> Result<(), AotError> {
    let symbol: Symbol<unsafe extern "C" fn() -> u32> = library
        .get(API_VERSION_SYMBOL.as_bytes())
        .map_err(|_| AotError::MissingSymbol(API_VERSION_SYMBOL))?;
    let found = symbol();
    if found != AOT_API_VERSION {
        return Err(AotError::ApiVersionMismatch {
            expected: AOT_API_VERSION,
            found,
        });
    }
    Ok(())
}

#[cfg(feature = "dsl-aot-load")]
unsafe fn read_model_info_from_library(library: &Library) -> Result<NativeModelInfo, AotError> {
    ensure_api_version(library)?;
    let ptr_symbol: Symbol<unsafe extern "C" fn() -> *const u8> = library
        .get(MODEL_INFO_JSON_PTR_SYMBOL.as_bytes())
        .map_err(|_| AotError::MissingSymbol(MODEL_INFO_JSON_PTR_SYMBOL))?;
    let len_symbol: Symbol<unsafe extern "C" fn() -> usize> = library
        .get(MODEL_INFO_JSON_LEN_SYMBOL.as_bytes())
        .map_err(|_| AotError::MissingSymbol(MODEL_INFO_JSON_LEN_SYMBOL))?;

    let ptr = ptr_symbol();
    let len = len_symbol();
    let bytes = std::slice::from_raw_parts(ptr, len);
    let envelope = decode_compiled_model_info(bytes)?;
    if envelope.abi_version != AOT_API_VERSION {
        return Err(AotError::ApiVersionMismatch {
            expected: AOT_API_VERSION,
            found: envelope.abi_version,
        });
    }
    Ok(envelope.model)
}

#[cfg(feature = "dsl-aot-load")]
unsafe fn load_required_kernel(
    library: &Library,
    name: &'static str,
) -> Result<DenseKernelFn, AotError> {
    let symbol: Symbol<DenseKernelFn> = library
        .get(name.as_bytes())
        .map_err(|_| AotError::MissingSymbol(name))?;
    Ok(*symbol)
}

#[cfg(feature = "dsl-aot-load")]
unsafe fn load_optional_kernel(library: &Library, name: &'static str) -> Option<DenseKernelFn> {
    library
        .get::<DenseKernelFn>(name.as_bytes())
        .ok()
        .map(|symbol| *symbol)
}

#[cfg(all(
    test,
    feature = "dsl-aot",
    feature = "dsl-aot-load",
    feature = "dsl-jit"
))]
mod tests {
    use super::*;
    use crate::dsl::compile_ode_model_to_jit;
    use crate::test_fixtures::STRUCTURED_BLOCK_CORPUS;
    use crate::{Parameters, SubjectBuilderExt};
    use approx::assert_relative_eq;
    use pharmsol_dsl::{DiagnosticPhase, DSL_SEMANTIC_GENERIC};
    use std::sync::{Arc, Mutex};
    use tempfile::tempdir;

    const CROSS_TARGET_SMOKE_ENV: &str = "PHARMSOL_NATIVE_AOT_SMOKE_TARGET";

    enum CrossTargetSmokeDecision {
        Run(String),
        Skip(String),
    }

    fn load_corpus_model(name: &str) -> ExecutionModel {
        let source = STRUCTURED_BLOCK_CORPUS;
        let parsed = pharmsol_dsl::parse_module(source).expect("parse corpus module");
        let typed = pharmsol_dsl::analyze_module(&parsed).expect("analyze corpus module");
        let model = typed
            .models
            .iter()
            .find(|model| model.name == name)
            .expect("model in corpus module");
        pharmsol_dsl::lower_typed_model(model).expect("lower corpus model")
    }

    fn resolve_cross_target_smoke_target() -> Result<CrossTargetSmokeDecision, String> {
        let requested_target = std::env::var(CROSS_TARGET_SMOKE_ENV)
            .ok()
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty());
        let host_target = rustc_host_target()
            .map_err(|error| format!("failed to detect the Rust host target: {error}"))?;

        let installed_targets = match rustup_installed_targets() {
            Ok(targets) => targets,
            Err(error) if requested_target.is_none() => {
                return Ok(CrossTargetSmokeDecision::Skip(format!(
                    "rustup target discovery is unavailable: {error}"
                )))
            }
            Err(error) => {
                return Err(format!(
                    "{CROSS_TARGET_SMOKE_ENV} is set, but installed targets could not be queried: {error}"
                ))
            }
        };

        if let Some(target) = requested_target {
            if target == host_target {
                return Err(format!(
                    "{CROSS_TARGET_SMOKE_ENV} must name a non-host native target, but `{target}` matches the host"
                ));
            }
            if !is_native_target_triple(&target) {
                return Err(format!(
                    "{CROSS_TARGET_SMOKE_ENV} must name a native target triple, but `{target}` is not supported for native AoT"
                ));
            }
            if !installed_targets
                .iter()
                .any(|installed| installed == &target)
            {
                return Err(format!(
                    "{CROSS_TARGET_SMOKE_ENV} requested `{target}`, but it is not installed. Run `rustup target add {target}` first."
                ));
            }
            return Ok(CrossTargetSmokeDecision::Run(target));
        }

        if let Some(target) =
            auto_detect_cross_target_smoke_target(&host_target, &installed_targets)
        {
            return Ok(CrossTargetSmokeDecision::Run(target));
        }

        Ok(CrossTargetSmokeDecision::Skip(format!(
            "no supported non-host native target is installed; set {CROSS_TARGET_SMOKE_ENV} after installing a target and linker"
        )))
    }

    fn auto_detect_cross_target_smoke_target(
        host_target: &str,
        installed_targets: &[String],
    ) -> Option<String> {
        let preferred = match host_target {
            "aarch64-apple-darwin" => &["x86_64-apple-darwin"][..],
            "x86_64-apple-darwin" => &["aarch64-apple-darwin"][..],
            _ => &[][..],
        };

        preferred
            .iter()
            .find(|candidate| {
                installed_targets
                    .iter()
                    .any(|installed| installed == *candidate)
            })
            .map(|candidate| (*candidate).to_string())
    }

    fn is_native_target_triple(target: &str) -> bool {
        !target.starts_with("wasm32-") && !target.starts_with("wasm64-")
    }

    fn render_captured_events(events: &Arc<Mutex<Vec<(String, String)>>>) -> String {
        let events = events
            .lock()
            .expect("cross-target smoke event log mutex poisoned");
        if events.is_empty() {
            return "<no compile events captured>".to_string();
        }

        events
            .iter()
            .map(|(kind, message)| format!("[{kind}] {}", message.trim_end()))
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn aot_ode_artifact_matches_jit_predictions() {
        let model = load_corpus_model("one_cmt_oral_iv");
        let work_dir = tempdir().expect("tempdir");
        let output_path = work_dir.path().join("one_cmt_oral_iv.pkm");

        let jit = compile_ode_model_to_jit(&model).expect("compile jit model");
        export_execution_model_to_aot(
            &model,
            NativeAotCompileOptions::new(work_dir.path().join("build"))
                .with_output(output_path.clone()),
            |_, _| {},
        )
        .expect("export aot model");

        let loaded = load_aot_model(&output_path).expect("load aot model");
        let aot = match loaded {
            CompiledNativeModel::Ode(model) => model,
            other => panic!("expected ode model, got {other:?}"),
        };

        let oral = jit
            .info()
            .routes
            .iter()
            .find(|route| route.name == "oral")
            .map(|route| route.index)
            .expect("jit oral route");
        let iv = jit
            .info()
            .routes
            .iter()
            .find(|route| route.name == "iv")
            .map(|route| route.index)
            .expect("jit iv route");
        let cp = jit
            .info()
            .outputs
            .iter()
            .find(|output| output.name == "cp")
            .map(|output| output.index)
            .expect("jit cp output");
        assert_eq!(
            aot.info()
                .routes
                .iter()
                .find(|route| route.name == "oral")
                .map(|route| route.index),
            Some(oral)
        );
        assert_eq!(
            aot.info()
                .routes
                .iter()
                .find(|route| route.name == "iv")
                .map(|route| route.index),
            Some(iv)
        );
        assert_eq!(
            aot.info()
                .outputs
                .iter()
                .find(|output| output.name == "cp")
                .map(|output| output.index),
            Some(cp)
        );

        let subject = crate::Subject::builder("ode")
            .covariate("wt", 0.0, 70.0)
            .bolus(0.0, 120.0, "oral")
            .infusion(6.0, 60.0, "iv", 2.0)
            .missing_observation(0.5, "cp")
            .missing_observation(1.0, "cp")
            .missing_observation(2.0, "cp")
            .missing_observation(6.0, "cp")
            .missing_observation(7.0, "cp")
            .missing_observation(9.0, "cp")
            .build();

        let support = Parameters::with_model(
            &crate::dsl::CompiledRuntimeModel::Ode(jit.clone()),
            [
                ("ka", 1.2),
                ("cl", 5.0),
                ("v", 40.0),
                ("tlag", 0.5),
                ("f_oral", 0.8),
            ],
        )
        .expect("valid named parameters");
        let jit_predictions = jit
            .estimate_predictions(&subject, &support)
            .expect("jit predictions");
        let aot_predictions = aot
            .estimate_predictions(&subject, &support)
            .expect("aot predictions");

        for (jit_pred, aot_pred) in jit_predictions
            .predictions()
            .iter()
            .zip(aot_predictions.predictions())
        {
            assert_relative_eq!(
                jit_pred.prediction(),
                aot_pred.prediction(),
                max_relative = 1e-4
            );
        }

        let info = read_aot_model_info(&output_path).expect("aot model info");
        assert_eq!(info.name, "one_cmt_oral_iv");
        assert_eq!(info.kind, ModelKind::Ode);
        assert_eq!(info.parameters, vec!["ka", "cl", "v", "tlag", "f_oral"]);
    }

    #[test]
    fn native_cdylib_filename_tracks_requested_target() {
        assert_eq!(
            native_cdylib_filename_for_target("model_lib", Some("x86_64-pc-windows-msvc")),
            "model_lib.dll"
        );
        assert_eq!(
            native_cdylib_filename_for_target("model_lib", Some("aarch64-apple-darwin")),
            "libmodel_lib.dylib"
        );
        assert_eq!(
            native_cdylib_filename_for_target("model_lib", Some("x86_64-unknown-linux-gnu")),
            "libmodel_lib.so"
        );
    }

    #[test]
    fn default_output_path_uses_requested_target_label() {
        let work_dir = tempdir().expect("tempdir");
        let output = default_output_path(
            work_dir.path(),
            &NativeAotTarget::triple("x86_64-pc-windows-msvc"),
        );
        let file_name = output
            .file_name()
            .expect("output file name")
            .to_string_lossy();
        assert!(file_name.starts_with("model_x86_64_pc_windows_msvc_"));
        assert!(file_name.ends_with(".pkm"));
    }

    #[test]
    fn native_aot_compile_options_default_to_host_target() {
        let work_dir = tempdir().expect("tempdir");
        let options = NativeAotCompileOptions::new(work_dir.path().join("build"));
        assert_eq!(options.target, NativeAotTarget::Host);
        assert_eq!(options.output, None);
    }

    #[test]
    fn native_aot_cross_target_smoke_builds_when_supported() {
        let target = match resolve_cross_target_smoke_target() {
            Ok(CrossTargetSmokeDecision::Run(target)) => target,
            Ok(CrossTargetSmokeDecision::Skip(reason)) => {
                eprintln!("skipping Native AoT cross-target smoke test: {reason}");
                return;
            }
            Err(error) => panic!("invalid cross-target smoke configuration: {error}"),
        };

        let model = load_corpus_model("one_cmt_oral_iv");
        let work_dir = tempdir().expect("tempdir");
        let output_path = work_dir.path().join(format!(
            "one_cmt_oral_iv_{}.pkm",
            sanitize_target_label(&target)
        ));
        let events = Arc::new(Mutex::new(Vec::<(String, String)>::new()));
        let captured_events = Arc::clone(&events);

        let result = export_execution_model_to_aot(
            &model,
            NativeAotCompileOptions::new(work_dir.path().join("cross-target-build"))
                .with_target(NativeAotTarget::triple(target.clone()))
                .with_output(output_path.clone()),
            move |kind, message| {
                captured_events
                    .lock()
                    .expect("cross-target smoke event log mutex poisoned")
                    .push((kind, message));
            },
        );

        match result {
            Ok(path) => {
                assert_eq!(path, output_path);
                assert!(path.exists());
            }
            Err(error) => panic!(
                "Native AoT cross-target smoke build failed for `{target}`: {error}\n{}",
                render_captured_events(&events)
            ),
        }
    }

    #[test]
    fn aot_compile_preserves_semantic_diagnostic_structure() {
        let source = r#"
model broken {
  kind ode
  states { central }
  dynamics {
    ddt(central) = rate(oral)
  }
  outputs {
    cp = central
  }
}
"#;
        let work_dir = tempdir().expect("tempdir");
        let error = compile_module_source_to_aot(
            source,
            None,
            NativeAotCompileOptions::new(work_dir.path().join("build")),
            |_, _| {},
        )
        .expect_err("invalid DSL should fail before AoT compilation");

        let diagnostic = error.diagnostic().expect("AoT should expose diagnostic");
        assert_eq!(diagnostic.phase, DiagnosticPhase::Semantic);
        assert_eq!(diagnostic.code, DSL_SEMANTIC_GENERIC);
        assert!(diagnostic.message.contains("unknown route `oral`"));
        let rendered = error
            .render_diagnostic(source)
            .expect("rendered diagnostic");
        assert!(rendered.contains("error[DSL2000]"), "{}", rendered);
        assert!(rendered.contains("unknown route `oral`"), "{}", rendered);
        let debugged = format!("{error:?}");
        assert!(debugged.contains("error[DSL2000]"), "{}", debugged);
        assert!(debugged.contains("unknown route `oral`"), "{}", debugged);
        let report = error
            .diagnostic_report("inline.dsl")
            .expect("diagnostic report");
        assert_eq!(report.source.name, "inline.dsl");
        assert_eq!(report.diagnostics[0].code, "DSL2000");
        assert!(!report.diagnostics[0].labels.is_empty());
    }

    #[test]
    fn aot_compile_preserves_semantic_suggestions() {
        let source = r#"
model broken {
    kind ode
    states { central }
    routes { oral -> central }
    dynamics {
        ddt(central) = rate(orla)
    }
    outputs {
        cp = central
    }
}
"#;
        let work_dir = tempdir().expect("tempdir");
        let error = compile_module_source_to_aot(
            source,
            None,
            NativeAotCompileOptions::new(work_dir.path().join("build-suggestions")),
            |_, _| {},
        )
        .expect_err("invalid DSL should fail before AoT compilation");

        let diagnostic = error.diagnostic().expect("AoT should expose diagnostic");
        assert!(diagnostic
            .suggestions
            .iter()
            .any(|suggestion| suggestion.message.contains("did you mean `oral`?")));

        let rendered = error
            .render_diagnostic(source)
            .expect("rendered diagnostic");
        assert!(
            rendered.contains("suggestion: did you mean `oral`?"),
            "{}",
            rendered
        );
    }
}