Skip to main content

onnx_ir/
pipeline.rs

1//! ONNX to IR conversion pipeline orchestrator
2//!
3//! This module provides the high-level orchestration of the ONNX conversion process.
4//! It clearly shows the entire conversion flow from start to finish.
5//!
6//! # Zero-Copy Loading
7//!
8//! When the `mmap` feature is enabled (default), files are memory-mapped for zero-copy
9//! tensor loading. This significantly reduces memory usage for large models.
10//!
11//! # Usage
12//!
13//! ```ignore
14//! use onnx_ir::OnnxGraphBuilder;
15//!
16//! // Build from file
17//! let graph = OnnxGraphBuilder::new().parse_file("model.onnx")?;
18//!
19//! // Build from bytes
20//! let graph = OnnxGraphBuilder::new().parse_bytes(&bytes)?;
21//!
22//! // Build from reader
23//! let graph = OnnxGraphBuilder::new().parse_reader(file)?;
24//! ```
25
26use std::collections::HashMap;
27use std::io::Read;
28use std::sync::Arc;
29use std::{fmt, fs::File, path::Path};
30
31use protobuf::Message;
32
33use crate::{
34    ir::{NodeType, OnnxGraph},
35    node::custom::{CustomOpInference, HookedCustomProcessor},
36    processor::ProcessError,
37    protos::ModelProto,
38    registry::{ProcessorMethods, ProcessorRegistry},
39};
40
41use super::phases::{
42    finalization, initialization, node_conversion, post_processing, type_inference,
43};
44
45/// Per-parse hook state threaded through the pipeline phases.
46///
47/// The global processor registry cannot carry user hooks (it is a shared
48/// singleton), so the type-inference phase resolves processors through this
49/// overlay instead: `NodeType::Custom` gets the hook-aware processor, every
50/// other node type falls through to the global registry.
51pub(crate) struct PipelineHooks {
52    /// Owns the user hook (`None` = no hooks); the sole storage of the Arc.
53    custom: HookedCustomProcessor,
54}
55
56impl PipelineHooks {
57    pub(crate) fn new(inference: Option<Arc<dyn CustomOpInference>>) -> Self {
58        Self {
59            custom: HookedCustomProcessor::new(inference),
60        }
61    }
62
63    /// The registered inference hook, for capture into `DeferredGraph` (so
64    /// subgraph builds re-enter the pipeline with it).
65    pub(crate) fn inference(&self) -> Option<Arc<dyn CustomOpInference>> {
66        self.custom.hooks()
67    }
68
69    /// Resolution point used by the type-inference phase in place of
70    /// `registry.get(node_type)`.
71    pub(crate) fn resolve<'a>(
72        &'a self,
73        node_type: &NodeType,
74        registry: &'a ProcessorRegistry,
75    ) -> &'a dyn ProcessorMethods {
76        match node_type {
77            NodeType::Custom => &self.custom,
78            other => registry.get(other),
79        }
80    }
81}
82
83/// A custom op present in the model that no registered hook covers.
84#[derive(Debug, Clone)]
85#[non_exhaustive]
86pub struct MissingHook {
87    /// Raw ONNX op_type of the uncovered operator.
88    pub op_type: String,
89    /// Raw ONNX domain ("" = default domain).
90    pub domain: String,
91    /// Number of nodes in the graph using this operator.
92    pub node_count: usize,
93    /// The opset the model imports for the operator's domain.
94    pub model_opset: usize,
95    /// Why the operator is uncovered.
96    pub reason: crate::node::custom::MissingReason,
97}
98
99impl MissingHook {
100    /// Construct a missing-hook diagnostic (the pipeline's coverage pre-pass
101    /// is the normal producer; this is public for tests and tooling).
102    pub fn new(
103        op_type: impl Into<String>,
104        domain: impl Into<String>,
105        node_count: usize,
106        model_opset: usize,
107        reason: crate::node::custom::MissingReason,
108    ) -> Self {
109        Self {
110            op_type: op_type.into(),
111            domain: domain.into(),
112            node_count,
113            model_opset,
114            reason,
115        }
116    }
117}
118
119impl fmt::Display for MissingHook {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        if self.domain.is_empty() {
122            write!(f, "{}", self.op_type)?;
123        } else {
124            write!(f, "{}::{}", self.domain, self.op_type)?;
125        }
126        write!(f, " used by {} node(s)", self.node_count)?;
127        if let crate::node::custom::MissingReason::OpsetMismatch { supported } = &self.reason {
128            write!(
129                f,
130                " (hook covers opsets {supported}, model uses {})",
131                self.model_opset
132            )?;
133        }
134        Ok(())
135    }
136}
137
138/// Errors that can occur when parsing ONNX models
139#[derive(Debug)]
140#[non_exhaustive]
141pub enum Error {
142    /// Failed to open or read the ONNX file
143    Io { path: String, error: std::io::Error },
144
145    /// Failed to parse ONNX protobuf format
146    InvalidFormat { path: Option<String>, error: String },
147
148    /// Model graph nodes are not topologically sorted (ONNX spec violation)
149    InvalidGraphStructure { reason: String },
150
151    /// Model uses default-domain operators without importing the default domain
152    MissingOpsetVersion,
153
154    /// Type inference failed during IR conversion
155    TypeInference(ProcessError),
156
157    /// Generic processing error
158    Processing(ProcessError),
159
160    /// Custom ops present that no registered inference hook covers.
161    ///
162    /// Only raised when hooks are registered (via
163    /// [`OnnxGraphBuilder::with_custom_op_inference`]); a hook-less parse
164    /// keeps the tolerant same-as-input fallback for inspection.
165    MissingCustomOpHooks(Vec<MissingHook>),
166}
167
168impl fmt::Display for Error {
169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170        match self {
171            Error::Io { path, error } => {
172                write!(f, "Failed to open ONNX file '{}': {}", path, error)
173            }
174            Error::InvalidFormat { path, error } => {
175                if let Some(p) = path {
176                    write!(f, "Invalid ONNX format in '{}': {}", p, error)
177                } else {
178                    write!(f, "Invalid ONNX format: {}", error)
179                }
180            }
181            Error::InvalidGraphStructure { reason } => {
182                write!(f, "Invalid ONNX graph structure: {}", reason)
183            }
184            Error::MissingOpsetVersion => {
185                write!(
186                    f,
187                    "ONNX model uses default-domain operators but its opset_import \
188                     declares no version for the default domain (\"\" or \"ai.onnx\")"
189                )
190            }
191            Error::TypeInference(e) => {
192                write!(f, "Type inference failed: {e}")
193            }
194            Error::Processing(e) => {
195                write!(f, "Processing error: {e}")
196            }
197            Error::MissingCustomOpHooks(missing) => {
198                // No trailing "register a hook" instruction: the actionable
199                // hint names an API this layer does not know about, so the
200                // caller appends it (ModelGen points at register_custom_op).
201                write!(
202                    f,
203                    "model contains {} custom op(s) with no covering inference hook:",
204                    missing.len()
205                )?;
206                for hook in missing {
207                    write!(f, "\n  - {hook}")?;
208                }
209                Ok(())
210            }
211        }
212    }
213}
214
215impl std::error::Error for Error {
216    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
217        match self {
218            Error::Io { error, .. } => Some(error),
219            _ => None,
220        }
221    }
222}
223
224impl From<ProcessError> for Error {
225    fn from(error: ProcessError) -> Self {
226        Error::Processing(error)
227    }
228}
229
230/// ONNX IR builder with fluent API
231///
232/// Builds ONNX IR graphs from various sources (files, bytes, readers).
233/// Future configuration options can be added without breaking changes.
234///
235/// # Examples
236///
237/// ```ignore
238/// use onnx_ir::OnnxGraphBuilder;
239///
240/// // Build from file (uses mmap when feature is enabled)
241/// let graph = OnnxGraphBuilder::new().parse_file("model.onnx")?;
242///
243/// // Build from bytes
244/// let graph = OnnxGraphBuilder::new().parse_bytes(&model_bytes)?;
245///
246/// // Build from reader
247/// let graph = OnnxGraphBuilder::new().parse_reader(std::io::Cursor::new(data))?;
248/// ```
249#[derive(Clone)]
250pub struct OnnxGraphBuilder {
251    /// Whether to run graph simplification passes (default: true)
252    simplify: bool,
253    /// Type-inference hooks for custom (non-built-in) operators
254    custom_op_inference: Option<Arc<dyn CustomOpInference>>,
255}
256
257impl fmt::Debug for OnnxGraphBuilder {
258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259        f.debug_struct("OnnxGraphBuilder")
260            .field("simplify", &self.simplify)
261            .field(
262                "custom_op_inference",
263                &self.custom_op_inference.as_ref().map(|_| "<hooks>"),
264            )
265            .finish()
266    }
267}
268
269impl Default for OnnxGraphBuilder {
270    fn default() -> Self {
271        Self {
272            simplify: true,
273            custom_op_inference: None,
274        }
275    }
276}
277
278impl OnnxGraphBuilder {
279    /// Create a new ONNX graph builder with default settings
280    pub fn new() -> Self {
281        Self::default()
282    }
283
284    /// Enable or disable graph simplification passes (default: true)
285    ///
286    /// When enabled, the builder runs optimization passes on the IR graph
287    /// such as dead node elimination, common subexpression elimination, and
288    /// pattern-based simplifications.
289    pub fn simplify(mut self, simplify: bool) -> Self {
290        self.simplify = simplify;
291        self
292    }
293
294    /// Register type-inference hooks for custom (non-built-in) operators.
295    ///
296    /// During type inference, `NodeType::Custom` nodes are resolved through
297    /// the given hooks instead of the best-effort same-as-input fallback.
298    /// Subgraph builds (If/Loop/Scan bodies) inherit the hooks.
299    pub fn with_custom_op_inference(mut self, hooks: Arc<dyn CustomOpInference>) -> Self {
300        self.custom_op_inference = Some(hooks);
301        self
302    }
303
304    /// Parse an ONNX model from a file path
305    ///
306    /// When the `mmap` feature is enabled (default), the file is memory-mapped
307    /// for zero-copy tensor loading, significantly reducing memory usage.
308    ///
309    /// # Errors
310    ///
311    /// Returns an error if:
312    /// - File cannot be opened or read
313    /// - File is not valid ONNX protobuf format
314    /// - Graph nodes are not topologically sorted
315    /// - Type inference fails
316    pub fn parse_file(self, path: impl AsRef<Path>) -> Result<OnnxGraph, Error> {
317        let path = path.as_ref();
318        log::info!("Parsing ONNX file: {}", path.display());
319
320        // Load file contents - mmap when feature is enabled
321        #[cfg(feature = "mmap")]
322        let buffer = {
323            let file = File::open(path).map_err(|error| Error::Io {
324                path: path.display().to_string(),
325                error,
326            })?;
327            // SAFETY: We're mapping a read-only file. The bytes::Bytes keeps
328            // the mmap alive for as long as tensor data references it.
329            let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(|error| Error::Io {
330                path: path.display().to_string(),
331                error,
332            })?;
333            log::debug!("Memory-mapped ONNX file ({} bytes)", mmap.len());
334            bytes::Bytes::from_owner(mmap)
335        };
336
337        #[cfg(not(feature = "mmap"))]
338        let buffer = {
339            let mut file = File::open(path).map_err(|error| Error::Io {
340                path: path.display().to_string(),
341                error,
342            })?;
343            let mut buf = Vec::new();
344            file.read_to_end(&mut buf).map_err(|error| Error::Io {
345                path: path.display().to_string(),
346                error,
347            })?;
348            log::debug!("Read ONNX file into memory ({} bytes)", buf.len());
349            bytes::Bytes::from(buf)
350        };
351
352        self.parse_buffer(buffer, Some(path))
353    }
354
355    /// Parse an ONNX model from a byte slice
356    ///
357    /// Note: This copies the data internally. For large models already in memory
358    /// as `bytes::Bytes`, consider using the internal buffer directly.
359    ///
360    /// # Errors
361    ///
362    /// Returns an error if:
363    /// - Data is not valid ONNX protobuf format
364    /// - Graph nodes are not topologically sorted
365    /// - Type inference fails
366    pub fn parse_bytes(self, data: &[u8]) -> Result<OnnxGraph, Error> {
367        let buffer = bytes::Bytes::copy_from_slice(data);
368        self.parse_buffer(buffer, None)
369    }
370
371    /// Parse an ONNX model from a reader
372    ///
373    /// Reads all data into memory before parsing.
374    ///
375    /// # Errors
376    ///
377    /// Returns an error if:
378    /// - Reading from the reader fails
379    /// - Data is not valid ONNX protobuf format
380    /// - Graph nodes are not topologically sorted
381    /// - Type inference fails
382    pub fn parse_reader<R: Read>(self, mut reader: R) -> Result<OnnxGraph, Error> {
383        let mut buf = Vec::new();
384        reader.read_to_end(&mut buf).map_err(|error| Error::Io {
385            path: "<reader>".to_string(),
386            error,
387        })?;
388        log::debug!("Read ONNX from reader ({} bytes)", buf.len());
389        let buffer = bytes::Bytes::from(buf);
390        self.parse_buffer(buffer, None)
391    }
392
393    /// Internal: Parse from a bytes::Bytes buffer
394    fn parse_buffer(
395        self,
396        buffer: bytes::Bytes,
397        source_path: Option<&Path>,
398    ) -> Result<OnnxGraph, Error> {
399        let path_str = source_path.map(|p| p.display().to_string());
400
401        // Get the base directory for external data resolution
402        let base_path = source_path.and_then(|p| p.parent());
403
404        let model: ModelProto =
405            Message::parse_from_tokio_bytes(&buffer).map_err(|e| Error::InvalidFormat {
406                path: path_str.clone(),
407                error: e.to_string(),
408            })?;
409
410        // ONNX nodes must be topologically sorted per spec:
411        // https://github.com/onnx/onnx/blob/main/docs/IR.md#graphs
412        if !model.graph.node.is_top_sorted() {
413            return Err(Error::InvalidGraphStructure {
414                reason: "Nodes are not topologically sorted (ONNX spec violation)".to_string(),
415            });
416        }
417
418        let hooks = PipelineHooks::new(self.custom_op_inference.clone());
419        let graph = build_graph_with_options(&model, base_path, self.simplify, &hooks)?;
420
421        if let Some(path) = path_str {
422            log::info!("Finished parsing ONNX file: {}", path);
423        } else {
424            log::info!("Finished parsing ONNX from bytes");
425        }
426        Ok(graph)
427    }
428}
429
430/// Build IR graph from ONNX model with base path and simplification option
431fn build_graph_with_options(
432    model: &ModelProto,
433    base_path: Option<&Path>,
434    simplify: bool,
435    hooks: &PipelineHooks,
436) -> Result<OnnxGraph, Error> {
437    let (opset_version, domain_opsets) = extract_opset_versions(model)?;
438    let graph_builder = build_graph_builder_from_proto(
439        &model.graph,
440        opset_version,
441        &domain_opsets,
442        None,
443        base_path,
444        simplify,
445        hooks,
446    )?;
447
448    log::debug!(" PHASE 6: Node Conversion (RawNode -> Node) ");
449    graph_builder
450        .convert_to_graph(opset_version)
451        .map_err(Error::Processing)
452}
453
454/// Build IR graph as OnnxGraphBuilder from ONNX GraphProto
455///
456/// This returns OnnxGraphBuilder which still contains RawNode instances.
457/// Call convert_to_graph() to get the final OnnxGraph with Node enum instances.
458///
459/// # Errors
460///
461/// Returns an error if node conversion or type inference fails
462pub(crate) fn build_graph_builder_from_proto(
463    graph: &crate::protos::GraphProto,
464    opset_version: usize,
465    domain_opsets: &DomainOpsets,
466    name_registry: Option<crate::graph_state::NameRegistry>,
467    base_path: Option<&Path>,
468    simplify: bool,
469    hooks: &PipelineHooks,
470) -> Result<crate::ir::OnnxGraphBuilder, Error> {
471    build_graph_builder_from_proto_with_outer_scope(
472        graph,
473        opset_version,
474        domain_opsets,
475        name_registry,
476        crate::ir::OuterScopeTypes::new(),
477        base_path,
478        simplify,
479        hooks,
480    )
481}
482
483/// Build IR graph as OnnxGraphBuilder with access to outer scope types
484///
485/// This is used for building subgraphs that reference values from parent graphs.
486/// The `outer_scope` map provides types for values that the subgraph references
487/// but doesn't define internally.
488///
489/// The `base_path` is the directory containing the ONNX file, used for resolving
490/// external tensor data paths (for models >2GB).
491///
492/// # Errors
493///
494/// Returns an error if node conversion or type inference fails
495#[allow(clippy::too_many_arguments)] // internal per-parse context, threaded explicitly
496pub(crate) fn build_graph_builder_from_proto_with_outer_scope(
497    graph: &crate::protos::GraphProto,
498    opset_version: usize,
499    domain_opsets: &DomainOpsets,
500    name_registry: Option<crate::graph_state::NameRegistry>,
501    outer_scope: crate::ir::OuterScopeTypes,
502    base_path: Option<&Path>,
503    simplify: bool,
504    hooks: &PipelineHooks,
505) -> Result<crate::ir::OnnxGraphBuilder, Error> {
506    log::debug!(" PHASE 1: Initialization ");
507    let state_rc = initialization::initialize_from_graph_with_registry_and_outer_scope(
508        graph,
509        name_registry,
510        outer_scope,
511        base_path,
512    )
513    .map_err(|error| Error::InvalidFormat { path: None, error })?;
514
515    log::debug!(" PHASE 2: Node Conversion (Proto -> RawNode) ");
516    node_conversion::convert_nodes_from_graph(
517        graph,
518        &state_rc,
519        opset_version,
520        domain_opsets,
521        hooks,
522    )?;
523
524    // Fold constant expressions (Slice, Concat, Unsqueeze, etc.) before type inference.
525    // Models exported from PyTorch often split initializer weights via Slice+Concat+Unsqueeze
526    // chains before feeding them into RNN nodes. Without folding, these remain Dynamic and
527    // block type inference for downstream nodes that need constant weight shapes.
528    log::debug!(" PHASE 2b: Early Constant Folding ");
529    {
530        let mut state = state_rc.borrow_mut();
531        let mut nodes = std::mem::take(&mut state.processed_nodes);
532        drop(state);
533
534        // Run in a fixed-point loop so that Slice -> Concat -> Unsqueeze chains cascade
535        let max_iterations = 10;
536        let mut converged = false;
537        for _ in 0..max_iterations {
538            let const_count_before = nodes
539                .iter()
540                .filter(|n| n.node_type == crate::ir::NodeType::Constant)
541                .count();
542            nodes = crate::simplify::constant_fold::fold_weight_rearrangements(nodes, &state_rc);
543            let const_count_after = nodes
544                .iter()
545                .filter(|n| n.node_type == crate::ir::NodeType::Constant)
546                .count();
547            if const_count_after == const_count_before {
548                converged = true;
549                break;
550            }
551        }
552        if !converged {
553            log::debug!(
554                "Early constant folding: reached max iterations ({max_iterations}) without converging"
555            );
556        }
557
558        let mut state = state_rc.borrow_mut();
559        state.processed_nodes = nodes;
560    }
561
562    // Sequence values have no IR type, so the common SplitToSequence -> SequenceAt
563    // pattern is rewritten into tensor ops before type inference would reject it.
564    // Not gated on `simplify`: without it the model cannot be imported at all.
565    log::debug!(" PHASE 2c: SplitToSequence rewrite ");
566    crate::simplify::split_to_sequence::rewrite_split_to_sequence(&mut state_rc.borrow_mut());
567
568    // Coverage runs before type inference: an uncovered custom op would get
569    // the same-as-input fallback there, and a possibly-wrong guessed type
570    // then fails a *downstream* node with an unrelated cascade error before
571    // any friendly summary could be produced. Hook-less parses skip this and
572    // keep the tolerant fallback (useful for inspection/debugging).
573    if let Some(inference) = hooks.inference() {
574        log::debug!(" PHASE 2d: Custom-op coverage check ");
575        check_custom_op_coverage(&state_rc.borrow().processed_nodes, inference.as_ref())?;
576    }
577
578    log::debug!(" PHASE 3: Type Inference ");
579    type_inference::infer_types(&state_rc, opset_version, hooks).map_err(Error::TypeInference)?;
580
581    log::debug!(" PHASE 4: Post-processing ");
582    let (nodes, inputs, outputs) =
583        post_processing::post_process(&state_rc, simplify, opset_version);
584
585    let (mut nodes, inputs, mut outputs) = if simplify {
586        log::debug!(" PHASE 4b: Simplification ");
587        crate::simplify::simplify_graph(nodes, inputs, outputs, &state_rc, opset_version)
588    } else {
589        (nodes, inputs, outputs)
590    };
591
592    log::debug!(" PHASE 5: Finalization ");
593    Ok(finalization::finalize(
594        &mut nodes,
595        inputs,
596        &mut outputs,
597        state_rc,
598    ))
599}
600
601/// Phase 2d: verify every custom op is covered by the registered hooks.
602///
603/// Aggregates all uncovered `(domain, op_type)` pairs with usage counts so
604/// the user sees the complete list at once instead of failing one op at a
605/// time.
606fn check_custom_op_coverage(
607    nodes: &[crate::ir::RawNode],
608    hooks: &dyn CustomOpInference,
609) -> Result<(), Error> {
610    use std::collections::BTreeMap;
611
612    let mut missing: BTreeMap<(String, String), MissingHook> = BTreeMap::new();
613
614    for node in nodes.iter().filter(|n| n.node_type == NodeType::Custom) {
615        // Same parser invariant custom_node_view enforces: a violated
616        // internal invariant must be loud, not silently skipped (a skipped
617        // node would dodge the coverage gate here and panic later anyway).
618        let identity = node
619            .custom_identity
620            .as_ref()
621            .expect("RawNode with NodeType::Custom must carry a CustomIdentity (parser invariant)");
622        match hooks.coverage(&identity.op_type, &identity.domain, identity.domain_opset) {
623            crate::node::custom::HookCoverage::Covered => {}
624            crate::node::custom::HookCoverage::Missing(reason) => {
625                missing
626                    .entry((identity.domain.clone(), identity.op_type.clone()))
627                    .and_modify(|m| m.node_count += 1)
628                    .or_insert_with(|| MissingHook {
629                        op_type: identity.op_type.clone(),
630                        domain: identity.domain.clone(),
631                        node_count: 1,
632                        model_opset: identity.domain_opset,
633                        reason,
634                    });
635            }
636        }
637    }
638
639    if missing.is_empty() {
640        Ok(())
641    } else {
642        Err(Error::MissingCustomOpHooks(missing.into_values().collect()))
643    }
644}
645
646/// The `ai.onnx` spelling of the default ONNX operator set domain.
647///
648/// ONNX's own `onnx/common/constants.h` documents `""` and `"ai.onnx"` as
649/// "equivalent in an onnx proto representation" and folds the latter into the
650/// former via `NormalizeDomain`. Note that `ai.onnx.ml` is *not* an alias: it
651/// is the separate ONNX-ML operator set with its own opset numbering.
652///
653/// `onnx.checker` does not apply this normalization (it rejects `ai.onnx` node
654/// domains outright); ONNX Runtime does, and so do we.
655const AI_ONNX_DOMAIN: &str = "ai.onnx";
656
657/// Newest default-domain opset this crate implements, used only as the stand-in
658/// for models that import no default domain at all.
659///
660/// Tracks the highest `min_opset` across the node processors (`Swish`, opset
661/// 24). It does not have to be exact: it only has to sit above the version
662/// gates in `extract_config`, so an opset-dependent operator gets current
663/// semantics rather than the opset-1 legacy branch.
664const LATEST_DEFAULT_OPSET: usize = 24;
665
666/// Fold `ai.onnx` onto the canonical empty-string spelling of the default domain.
667///
668/// Public because operator identity is `(op_type, domain)` on both sides of a
669/// custom-op hook: burn-onnx canonicalizes a hook's declared domain with this
670/// so a hook registered for `""` covers a node whose model spells it `ai.onnx`.
671pub fn normalize_domain(domain: &str) -> &str {
672    if domain == AI_ONNX_DOMAIN { "" } else { domain }
673}
674
675/// Opset version for every domain listed in the model's `opset_import`.
676///
677/// ONNX operator identity is `(domain, op_type, opset-for-that-domain)`, so
678/// custom-domain nodes must be tagged with their own domain's opset, not the
679/// default ONNX opset. Wrapped in `Arc` for cheap cloning into `DeferredGraph`
680/// (subgraphs inherit the model-level imports).
681///
682/// `new` guarantees a `""` entry and `opset_for` normalizes lookups, so `""`
683/// and `ai.onnx` always resolve to the same version. That entry is not always a
684/// real import: see `extract_opset_versions` for the models that have none.
685#[derive(Debug, Clone)]
686pub(crate) struct DomainOpsets {
687    versions: Arc<HashMap<String, usize>>,
688    default_opset: usize,
689}
690
691impl DomainOpsets {
692    pub(crate) fn new(mut versions: HashMap<String, usize>, default_opset: usize) -> Self {
693        // Enforce the documented invariant even for hand-built instances
694        // (tests): the default domain is always present.
695        versions.entry(String::new()).or_insert(default_opset);
696        Self {
697            versions: Arc::new(versions),
698            default_opset,
699        }
700    }
701
702    /// Opset version for `domain`, falling back to the default-domain opset.
703    ///
704    /// Per the ONNX spec every domain a node uses must appear in
705    /// `opset_import`; the fallback is robustness against malformed exporters.
706    pub(crate) fn opset_for(&self, domain: &str) -> usize {
707        let domain = normalize_domain(domain);
708        if let Some(version) = self.versions.get(domain) {
709            return *version;
710        }
711        log::warn!(
712            "Domain '{domain}' has no opset_import entry (malformed model); \
713             falling back to default-domain opset {}",
714            self.default_opset
715        );
716        self.default_opset
717    }
718}
719
720/// Returns true if any node in `graph`, or in a nested subgraph, belongs to the
721/// default domain.
722///
723/// Subgraphs normally hang off default-domain control flow (If/Loop/Scan), in
724/// which case the parent node already answers this before the recursion runs.
725/// The recursion is here for the custom-domain op that carries one anyway.
726/// `AttributeProto` reaches a `GraphProto` only through `g` and `graphs`, so
727/// those two cover every subgraph reachable from `graph`.
728fn uses_default_domain(graph: &crate::protos::GraphProto) -> bool {
729    graph.node.iter().any(|node| {
730        normalize_domain(&node.domain).is_empty()
731            || node.attribute.iter().any(|attr| {
732                attr.g.as_ref().is_some_and(uses_default_domain)
733                    || attr.graphs.iter().any(uses_default_domain)
734            })
735    })
736}
737
738/// Per-domain opset versions from `opset_import`, with `ai.onnx` folded onto
739/// the default domain.
740///
741/// Both spellings map to the same key, so a model listing both is merged rather
742/// than resolved by whichever entry protobuf happens to put last.
743fn collect_domain_versions(model: &ModelProto) -> HashMap<String, usize> {
744    let mut versions: HashMap<String, usize> = HashMap::new();
745    for opset in &model.opset_import {
746        let domain = normalize_domain(&opset.domain);
747        let version = opset.version as usize;
748        match versions.get(domain) {
749            Some(&existing) if existing != version => {
750                let kept = existing.max(version);
751                // The default domain reaches here from two spellings as well as
752                // from a plain duplicate, so name the alias only in that case.
753                if domain.is_empty() {
754                    log::warn!(
755                        "The default domain is imported at conflicting opset \
756                         versions {existing} and {version} (\"\" and \"ai.onnx\" \
757                         name the same domain); using {kept}"
758                    );
759                } else {
760                    log::warn!(
761                        "Domain '{domain}' is imported at conflicting opset \
762                         versions {existing} and {version}; using {kept}"
763                    );
764                }
765                versions.insert(domain.to_string(), kept);
766            }
767            Some(_) => {}
768            None => {
769                versions.insert(domain.to_string(), version);
770            }
771        }
772    }
773    versions
774}
775
776/// Extract the model-level opset used to interpret every node, plus the
777/// per-domain map that tags custom-domain nodes with their own domain's opset.
778fn extract_opset_versions(model: &ModelProto) -> Result<(usize, DomainOpsets), Error> {
779    let versions = collect_domain_versions(model);
780
781    let default_opset = match versions.get("") {
782        Some(version) => *version,
783        // Importing the default domain is only required when the model actually
784        // uses default-domain operators, so an ai.onnx.ml-only model (the H2O
785        // export in issue #434) legitimately omits it.
786        //
787        // Stand in with the newest opset rather than anything derived from the
788        // imports. Node specs are validated against this one model-level opset
789        // regardless of domain, and opset numbering is per-domain: ai.onnx.ml
790        // tops out around 5 and contrib domains sit at 1, so borrowing a number
791        // from them would put every version gate in `extract_config` on its
792        // pre-13 legacy branch (Softmax axis default, Squeeze axes-as-attribute,
793        // Pad, Resize). Guessing "current" is the safer direction to be wrong in.
794        None if !uses_default_domain(&model.graph) => {
795            log::warn!(
796                "Model imports no default-domain opset; assuming opset \
797                 {LATEST_DEFAULT_OPSET} for node specs. Operators whose semantics \
798                 depend on the default opset may be interpreted incorrectly."
799            );
800            LATEST_DEFAULT_OPSET
801        }
802        None => return Err(Error::MissingOpsetVersion),
803    };
804
805    Ok((default_opset, DomainOpsets::new(versions, default_opset)))
806}
807
808/// Trait for checking if a list of nodes is topologically sorted
809pub(crate) trait TopologicalSortable {
810    fn is_top_sorted(&self) -> bool;
811}
812
813use crate::protos::NodeProto;
814
815impl TopologicalSortable for Vec<NodeProto> {
816    fn is_top_sorted(&self) -> bool {
817        // Iterate over each node in the vector
818        for (node_position, node) in self.iter().enumerate() {
819            // Iterate over each output of the node
820            for output in &node.output {
821                // If the output is empty, we don't want to check the rest of the graph, inputs and outputs that are optional
822                // can end up as empty strings, so we can't use that as a reason to count the graph as not sorted
823                if output.is_empty() {
824                    continue;
825                }
826                // Iterate over each other node in the vector
827                for (other_node_position, other_node) in self.iter().enumerate() {
828                    // If the other node has an input that matches the current output
829                    if other_node.input.contains(output) {
830                        // If the position of the current node is greater than the position of the other node
831                        if node_position > other_node_position {
832                            // The vector is not topologically sorted
833                            return false;
834                        }
835                    }
836                }
837            }
838        }
839
840        // The vector is topologically sorted
841        true
842    }
843}
844
845#[cfg(test)]
846mod tests {
847    use super::*;
848    use crate::ir::{ArgType, DType, Node};
849    use crate::protos::{
850        GraphProto, ModelProto, NodeProto, OperatorSetIdProto, TypeProto, ValueInfoProto,
851    };
852    use crate::protos::{TensorShapeProto, tensor_shape_proto, type_proto};
853
854    fn tensor_value_info(name: &str, dims: &[i64]) -> ValueInfoProto {
855        let mut shape = TensorShapeProto::new();
856        for d in dims {
857            let mut dim = tensor_shape_proto::Dimension::new();
858            dim.set_dim_value(*d);
859            shape.dim.push(dim);
860        }
861        let mut tensor = type_proto::Tensor::new();
862        tensor.elem_type = 1; // FLOAT
863        tensor.shape = ::protobuf::MessageField::some(shape);
864        let mut ty = TypeProto::new();
865        ty.set_tensor_type(tensor);
866        let mut vi = ValueInfoProto::new();
867        vi.name = name.to_string();
868        vi.type_ = ::protobuf::MessageField::some(ty);
869        vi
870    }
871
872    /// A single-node model: input -> <domain>::<op_type> -> output
873    fn single_node_model(domain: &str, op_type: &str, opset_imports: &[(&str, i64)]) -> Vec<u8> {
874        let mut node = NodeProto::new();
875        node.name = "the_node".to_string();
876        node.op_type = op_type.to_string();
877        node.domain = domain.to_string();
878        node.input.push("input".to_string());
879        node.output.push("output".to_string());
880
881        let mut graph = GraphProto::new();
882        graph.name = "test_graph".to_string();
883        graph.input.push(tensor_value_info("input", &[2, 3]));
884        graph.output.push(tensor_value_info("output", &[2, 3]));
885        graph.node.push(node);
886
887        let mut model = ModelProto::new();
888        model.graph = ::protobuf::MessageField::some(graph);
889        for (domain, version) in opset_imports {
890            let mut op = OperatorSetIdProto::new();
891            op.domain = domain.to_string();
892            op.version = *version;
893            model.opset_import.push(op);
894        }
895        model.write_to_bytes().unwrap()
896    }
897
898    fn parse_single_custom(bytes: &[u8]) -> crate::node::custom::CustomNode {
899        let graph = OnnxGraphBuilder::new().parse_bytes(bytes).unwrap();
900        graph
901            .nodes
902            .iter()
903            .find_map(|n| match n {
904                Node::Custom(c) => Some(c.clone()),
905                _ => None,
906            })
907            .expect("graph should contain a Custom node")
908    }
909
910    #[test]
911    fn custom_domain_node_parses_as_custom() {
912        let bytes = single_node_model(
913            "custom.domain",
914            "FftLike",
915            &[("", 16), ("custom.domain", 2)],
916        );
917        let custom = parse_single_custom(&bytes);
918
919        assert_eq!(custom.op_type, "FftLike");
920        assert_eq!(custom.domain, "custom.domain");
921        // Domain-specific opset, not the default ONNX opset
922        assert_eq!(custom.opset, 2);
923        // Fallback inference: output type mirrors input
924        assert!(matches!(
925            &custom.outputs[0].ty,
926            ArgType::Tensor(t) if t.dtype == DType::F32 && t.rank == 2
927        ));
928    }
929
930    #[test]
931    fn unknown_default_domain_op_parses_as_custom() {
932        let bytes = single_node_model("", "TotallyUnknownOp", &[("", 16)]);
933        let custom = parse_single_custom(&bytes);
934
935        assert_eq!(custom.op_type, "TotallyUnknownOp");
936        assert_eq!(custom.domain, "");
937        assert_eq!(custom.opset, 16);
938    }
939
940    #[test]
941    fn builtin_name_in_custom_domain_stays_custom() {
942        // ONNX identity is (domain, op_type): my.domain::MatMul is NOT the
943        // built-in MatMul and must not silently get default-domain semantics.
944        let bytes = single_node_model("my.domain", "MatMul", &[("", 16), ("my.domain", 5)]);
945        let custom = parse_single_custom(&bytes);
946
947        assert_eq!(custom.op_type, "MatMul");
948        assert_eq!(custom.domain, "my.domain");
949        assert_eq!(custom.opset, 5);
950    }
951
952    #[test]
953    fn missing_domain_import_falls_back_to_default_opset() {
954        // Malformed model: the node's domain has no opset_import entry.
955        let bytes = single_node_model("no.import.domain", "SomeOp", &[("", 16)]);
956        let custom = parse_single_custom(&bytes);
957
958        assert_eq!(custom.opset, 16);
959    }
960
961    #[test]
962    fn builtin_op_still_resolves_normally() {
963        let bytes = single_node_model("", "Relu", &[("", 16)]);
964        let graph = OnnxGraphBuilder::new().parse_bytes(&bytes).unwrap();
965        assert!(graph.nodes.iter().any(|n| matches!(n, Node::Relu(_))));
966        assert!(!graph.nodes.iter().any(|n| matches!(n, Node::Custom(_))));
967    }
968
969    #[test]
970    fn ai_onnx_import_is_the_default_domain() {
971        // "" and "ai.onnx" name the same operator set, so an "ai.onnx" entry
972        // satisfies a default-domain node's need for an opset.
973        let bytes = single_node_model("", "Relu", &[("ai.onnx", 16)]);
974        let graph = OnnxGraphBuilder::new().parse_bytes(&bytes).unwrap();
975        assert!(graph.nodes.iter().any(|n| matches!(n, Node::Relu(_))));
976
977        // Relu's spec is opset-permissive, so also pin that the version itself
978        // came out of the "ai.onnx" entry rather than a fallback.
979        let bytes = single_node_model("no.import.domain", "SomeOp", &[("ai.onnx", 16)]);
980        assert_eq!(parse_single_custom(&bytes).opset, 16);
981    }
982
983    #[test]
984    fn duplicate_default_domain_spellings_merge_by_max() {
985        // onnx.checker accepts a model importing both spellings at different
986        // versions. Folding them into one key must not leave the answer up to
987        // whichever entry protobuf happens to put last.
988        for imports in [[("", 13), ("ai.onnx", 17)], [("ai.onnx", 17), ("", 13)]] {
989            let bytes = single_node_model("no.import.domain", "SomeOp", &imports);
990            assert_eq!(
991                parse_single_custom(&bytes).opset,
992                17,
993                "import order {imports:?} changed the resolved opset"
994            );
995        }
996    }
997
998    #[test]
999    fn duplicate_non_default_domain_imports_merge_by_max() {
1000        // Not an alias collision, just a model importing one domain twice.
1001        // onnx.checker accepts it, and it takes the same merge path.
1002        for imports in [
1003            [("", 16), ("custom.domain", 2), ("custom.domain", 5)],
1004            [("", 16), ("custom.domain", 5), ("custom.domain", 2)],
1005        ] {
1006            let bytes = single_node_model("custom.domain", "SomeOp", &imports);
1007            assert_eq!(
1008                parse_single_custom(&bytes).opset,
1009                5,
1010                "import order {imports:?} changed the resolved opset"
1011            );
1012        }
1013    }
1014
1015    #[test]
1016    fn no_imports_at_all_uses_the_latest_opset() {
1017        // Degenerate but reachable: nothing to derive a version from, and the
1018        // stand-in must not land on the opset-1 legacy branch.
1019        let bytes = single_node_model("custom.domain", "SomeOp", &[]);
1020        assert_eq!(parse_single_custom(&bytes).opset, LATEST_DEFAULT_OPSET);
1021    }
1022
1023    #[test]
1024    fn ai_onnx_node_domain_gets_the_default_opset() {
1025        let bytes = single_node_model("ai.onnx", "TotallyUnknownOp", &[("", 16)]);
1026        let custom = parse_single_custom(&bytes);
1027
1028        // No spurious "domain has no opset_import entry" fallback: "ai.onnx"
1029        // resolves through the default domain's entry.
1030        assert_eq!(custom.opset, 16);
1031        // Identity is canonicalized, so a hook registered for the default
1032        // domain covers this node.
1033        assert_eq!(custom.domain, "");
1034    }
1035
1036    #[test]
1037    fn ml_only_model_needs_no_default_domain_import() {
1038        // The OnnxMLTools H2O export in issue #434 imports only ai.onnx.ml,
1039        // its graph using no default-domain operators. onnx.checker accepts
1040        // that, so parsing must not demand a default-domain opset.
1041        let bytes = single_node_model("ai.onnx.ml", "TreeEnsembleRegressor", &[("ai.onnx.ml", 1)]);
1042        let custom = parse_single_custom(&bytes);
1043
1044        assert_eq!(custom.op_type, "TreeEnsembleRegressor");
1045        assert_eq!(custom.domain, "ai.onnx.ml");
1046        assert_eq!(custom.opset, 1);
1047    }
1048
1049    #[test]
1050    fn default_domain_node_without_import_errors() {
1051        // Genuinely malformed: guessing an opset here would silently pick the
1052        // wrong schema version for the operator.
1053        let bytes = single_node_model("", "Relu", &[("ai.onnx.ml", 1)]);
1054        let err = OnnxGraphBuilder::new().parse_bytes(&bytes).unwrap_err();
1055
1056        assert!(matches!(err, Error::MissingOpsetVersion), "got: {err}");
1057    }
1058
1059    /// A custom-domain node carrying a subgraph whose body holds a
1060    /// default-domain Relu, attached via either the `g` or the `graphs` field.
1061    fn subgraph_model(use_graphs_field: bool, opset_imports: &[(&str, i64)]) -> Vec<u8> {
1062        let mut inner_node = NodeProto::new();
1063        inner_node.name = "inner".to_string();
1064        inner_node.op_type = "Relu".to_string();
1065        inner_node.input.push("input".to_string());
1066        inner_node.output.push("inner_output".to_string());
1067
1068        let mut inner_graph = GraphProto::new();
1069        inner_graph.name = "inner_graph".to_string();
1070        inner_graph.node.push(inner_node);
1071
1072        let mut attr = crate::protos::AttributeProto::new();
1073        attr.name = "body".to_string();
1074        if use_graphs_field {
1075            attr.type_ = ::protobuf::EnumOrUnknown::new(
1076                crate::protos::attribute_proto::AttributeType::GRAPHS,
1077            );
1078            attr.graphs.push(inner_graph);
1079        } else {
1080            attr.type_ = ::protobuf::EnumOrUnknown::new(
1081                crate::protos::attribute_proto::AttributeType::GRAPH,
1082            );
1083            attr.g = ::protobuf::MessageField::some(inner_graph);
1084        }
1085
1086        let mut node = NodeProto::new();
1087        node.name = "outer".to_string();
1088        node.op_type = "SomeOp".to_string();
1089        node.domain = "custom.domain".to_string();
1090        node.input.push("input".to_string());
1091        node.output.push("output".to_string());
1092        node.attribute.push(attr);
1093
1094        let mut graph = GraphProto::new();
1095        graph.name = "test_graph".to_string();
1096        graph.input.push(tensor_value_info("input", &[2, 3]));
1097        graph.output.push(tensor_value_info("output", &[2, 3]));
1098        graph.node.push(node);
1099
1100        let mut model = ModelProto::new();
1101        model.graph = ::protobuf::MessageField::some(graph);
1102        for (domain, version) in opset_imports {
1103            let mut op = OperatorSetIdProto::new();
1104            op.domain = domain.to_string();
1105            op.version = *version;
1106            model.opset_import.push(op);
1107        }
1108        model.write_to_bytes().unwrap()
1109    }
1110
1111    #[test]
1112    fn default_domain_node_nested_in_subgraph_errors() {
1113        // The outer node's domain alone would clear the guard. Without the
1114        // recursion the model parses and the nested Relu gets interpreted at
1115        // a guessed opset instead of being rejected.
1116        for use_graphs_field in [false, true] {
1117            let bytes = subgraph_model(use_graphs_field, &[("custom.domain", 3)]);
1118            let err = OnnxGraphBuilder::new().parse_bytes(&bytes).unwrap_err();
1119
1120            assert!(
1121                matches!(err, Error::MissingOpsetVersion),
1122                "graphs field: {use_graphs_field}, got: {err}"
1123            );
1124        }
1125    }
1126
1127    #[test]
1128    fn custom_domain_subgraph_without_default_domain_nodes_parses() {
1129        // Same shape, but the subgraph holds no default-domain node, so the
1130        // guard must not fire. Pins that the recursion checks node domains
1131        // rather than merely the presence of a subgraph.
1132        for use_graphs_field in [false, true] {
1133            let bytes = subgraph_model(use_graphs_field, &[("custom.domain", 3), ("", 16)]);
1134            let graph = OnnxGraphBuilder::new().parse_bytes(&bytes).unwrap();
1135
1136            assert!(graph.nodes.iter().any(|n| matches!(n, Node::Custom(_))));
1137        }
1138    }
1139
1140    /// Hook that gives every custom op a fixed F64 rank-3 output type.
1141    struct RankThreeInference;
1142
1143    impl crate::node::custom::CustomOpInference for RankThreeInference {
1144        fn coverage(
1145            &self,
1146            _op_type: &str,
1147            _domain: &str,
1148            _opset: usize,
1149        ) -> crate::node::custom::HookCoverage {
1150            crate::node::custom::HookCoverage::Covered
1151        }
1152
1153        fn infer(
1154            &self,
1155            node: &crate::node::custom::CustomNode,
1156        ) -> Result<Option<Vec<ArgType>>, ProcessError> {
1157            Ok(Some(vec![
1158                ArgType::Tensor(crate::ir::TensorType::new(
1159                    DType::F64,
1160                    3,
1161                    None
1162                ));
1163                node.outputs.len()
1164            ]))
1165        }
1166    }
1167
1168    #[test]
1169    fn registered_inference_hook_overrides_fallback() {
1170        let bytes = single_node_model(
1171            "custom.domain",
1172            "FftLike",
1173            &[("", 16), ("custom.domain", 2)],
1174        );
1175        // Simplify off: the graph output type check would reject the
1176        // rank change against the declared rank-2 graph output otherwise.
1177        let graph = OnnxGraphBuilder::new()
1178            .simplify(false)
1179            .with_custom_op_inference(Arc::new(RankThreeInference))
1180            .parse_bytes(&bytes)
1181            .unwrap();
1182
1183        let custom = graph
1184            .nodes
1185            .iter()
1186            .find_map(|n| match n {
1187                Node::Custom(c) => Some(c),
1188                _ => None,
1189            })
1190            .expect("graph should contain a Custom node");
1191
1192        // Hook-provided type, not the same-as-input (F32 rank-2) fallback
1193        assert!(matches!(
1194            &custom.outputs[0].ty,
1195            ArgType::Tensor(t) if t.dtype == DType::F64 && t.rank == 3
1196        ));
1197    }
1198
1199    /// Inference with no coverage for anything (empty registry equivalent).
1200    struct NoCoverageInference;
1201
1202    impl crate::node::custom::CustomOpInference for NoCoverageInference {
1203        fn coverage(
1204            &self,
1205            _op_type: &str,
1206            _domain: &str,
1207            _opset: usize,
1208        ) -> crate::node::custom::HookCoverage {
1209            crate::node::custom::HookCoverage::Missing(crate::node::custom::MissingReason::NoHook)
1210        }
1211
1212        fn infer(
1213            &self,
1214            _node: &crate::node::custom::CustomNode,
1215        ) -> Result<Option<Vec<ArgType>>, ProcessError> {
1216            Ok(None)
1217        }
1218    }
1219
1220    #[test]
1221    fn coverage_pre_pass_reports_uncovered_ops() {
1222        let bytes = single_node_model(
1223            "custom.domain",
1224            "FftLike",
1225            &[("", 16), ("custom.domain", 2)],
1226        );
1227        let err = OnnxGraphBuilder::new()
1228            .with_custom_op_inference(Arc::new(NoCoverageInference))
1229            .parse_bytes(&bytes)
1230            .unwrap_err();
1231
1232        assert!(matches!(err, Error::MissingCustomOpHooks(_)));
1233        let msg = format!("{err}");
1234        assert!(msg.contains("custom.domain::FftLike"), "got: {msg}");
1235        assert!(msg.contains("used by 1 node(s)"), "got: {msg}");
1236        // The actionable "register a hook via ..." hint belongs to the caller
1237        // (ModelGen appends it); this layer only reports what is missing.
1238        assert!(!msg.contains("register"), "got: {msg}");
1239        assert!(msg.trim_end() == msg, "message must not end in whitespace");
1240    }
1241
1242    #[test]
1243    fn coverage_pre_pass_reports_opset_mismatch() {
1244        struct MismatchInference;
1245
1246        impl crate::node::custom::CustomOpInference for MismatchInference {
1247            fn coverage(
1248                &self,
1249                _op_type: &str,
1250                _domain: &str,
1251                _opset: usize,
1252            ) -> crate::node::custom::HookCoverage {
1253                crate::node::custom::HookCoverage::Missing(
1254                    crate::node::custom::MissingReason::OpsetMismatch {
1255                        supported: crate::node::custom::OpsetRange {
1256                            min: 1,
1257                            max: Some(1),
1258                        },
1259                    },
1260                )
1261            }
1262
1263            fn infer(
1264                &self,
1265                _node: &crate::node::custom::CustomNode,
1266            ) -> Result<Option<Vec<ArgType>>, ProcessError> {
1267                Ok(None)
1268            }
1269        }
1270
1271        let bytes = single_node_model(
1272            "custom.domain",
1273            "FftLike",
1274            &[("", 16), ("custom.domain", 3)],
1275        );
1276        let err = OnnxGraphBuilder::new()
1277            .with_custom_op_inference(Arc::new(MismatchInference))
1278            .parse_bytes(&bytes)
1279            .unwrap_err();
1280
1281        let msg = format!("{err}");
1282        assert!(
1283            msg.contains("hook covers opsets 1..=1, model uses 3"),
1284            "got: {msg}"
1285        );
1286    }
1287
1288    #[test]
1289    fn hookless_parse_skips_coverage_pre_pass() {
1290        // No hooks registered: custom ops keep the tolerant fallback so the
1291        // graph stays inspectable (PR 1 behavior).
1292        let bytes = single_node_model(
1293            "custom.domain",
1294            "FftLike",
1295            &[("", 16), ("custom.domain", 2)],
1296        );
1297        assert!(OnnxGraphBuilder::new().parse_bytes(&bytes).is_ok());
1298    }
1299
1300    #[test]
1301    fn hook_error_fails_the_parse() {
1302        struct FailingInference;
1303
1304        impl crate::node::custom::CustomOpInference for FailingInference {
1305            fn coverage(
1306                &self,
1307                _op_type: &str,
1308                _domain: &str,
1309                _opset: usize,
1310            ) -> crate::node::custom::HookCoverage {
1311                crate::node::custom::HookCoverage::Covered
1312            }
1313
1314            fn infer(
1315                &self,
1316                _node: &crate::node::custom::CustomNode,
1317            ) -> Result<Option<Vec<ArgType>>, ProcessError> {
1318                Err(ProcessError::MissingAttribute("n_fft".to_string()))
1319            }
1320        }
1321
1322        let bytes = single_node_model(
1323            "custom.domain",
1324            "FftLike",
1325            &[("", 16), ("custom.domain", 2)],
1326        );
1327        let err = OnnxGraphBuilder::new()
1328            .with_custom_op_inference(Arc::new(FailingInference))
1329            .parse_bytes(&bytes)
1330            .unwrap_err();
1331
1332        let msg = format!("{err}");
1333        assert!(msg.contains("n_fft"), "got: {msg}");
1334    }
1335
1336    /// Reshape(x: f32[2, 3], s: i64[?]) -> `output`, where the length of the runtime shape
1337    /// input `s` is unknown, so the output rank can only come from the declared output type.
1338    fn runtime_reshape_model(output: ValueInfoProto) -> Vec<u8> {
1339        let mut node = NodeProto::new();
1340        node.name = "reshape".to_string();
1341        node.op_type = "Reshape".to_string();
1342        node.input.push("x".to_string());
1343        node.input.push("s".to_string());
1344        node.output.push(output.name.clone());
1345
1346        let mut s_dim = tensor_shape_proto::Dimension::new();
1347        s_dim.set_dim_param("N".to_string());
1348        let mut s_shape = TensorShapeProto::new();
1349        s_shape.dim.push(s_dim);
1350        let mut s_tensor = type_proto::Tensor::new();
1351        s_tensor.elem_type = 7; // INT64
1352        s_tensor.shape = ::protobuf::MessageField::some(s_shape);
1353        let mut s_ty = TypeProto::new();
1354        s_ty.set_tensor_type(s_tensor);
1355        let mut s = ValueInfoProto::new();
1356        s.name = "s".to_string();
1357        s.type_ = ::protobuf::MessageField::some(s_ty);
1358
1359        let mut graph = GraphProto::new();
1360        graph.name = "test_graph".to_string();
1361        graph.input.push(tensor_value_info("x", &[2, 3]));
1362        graph.input.push(s);
1363        graph.output.push(output);
1364        graph.node.push(node);
1365
1366        let mut model = ModelProto::new();
1367        model.graph = ::protobuf::MessageField::some(graph);
1368        let mut op = OperatorSetIdProto::new();
1369        op.version = 16;
1370        model.opset_import.push(op);
1371        model.write_to_bytes().unwrap()
1372    }
1373
1374    /// Regression test for https://github.com/tracel-ai/burn-onnx/issues/565: a graph output
1375    /// whose name changes under sanitization ("Mean" -> "mean") still seeds the Reshape output
1376    /// with its declared rank.
1377    #[test]
1378    fn runtime_reshape_uses_declared_rank_of_sanitized_output() {
1379        let bytes = runtime_reshape_model(tensor_value_info("Mean", &[3, 2]));
1380        let graph = OnnxGraphBuilder::new().parse_bytes(&bytes).unwrap();
1381
1382        assert!(
1383            matches!(&graph.outputs[0].ty, ArgType::Tensor(t) if t.rank == 2),
1384            "got: {:?}",
1385            graph.outputs[0].ty
1386        );
1387    }
1388
1389    /// An output declared with a tensor type but no shape has unknown rank. It must not be
1390    /// read as a scalar declaration.
1391    #[test]
1392    fn runtime_reshape_with_shapeless_output_declaration_errors() {
1393        let mut output = tensor_value_info("y", &[]);
1394        output
1395            .type_
1396            .mut_or_insert_default()
1397            .mut_tensor_type()
1398            .shape
1399            .clear();
1400
1401        let err = OnnxGraphBuilder::new()
1402            .parse_bytes(&runtime_reshape_model(output))
1403            .unwrap_err();
1404
1405        let msg = format!("{err}");
1406        assert!(
1407            msg.contains("output rank cannot be determined"),
1408            "got: {msg}"
1409        );
1410    }
1411}