{"record":{"id":"3ecc6a1e1f8f359a","repo":"tracel-ai/burn","slug":"invalid-regex-pattern-3ecc6a","errorCode":null,"errorMessage":"Invalid regex pattern","messagePattern":"Invalid regex pattern","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/burn-store/src/safetensors/store.rs","lineNumber":322,"sourceCode":"    /// ```rust,no_run\n    /// # use burn_store::SafetensorsStore;\n    /// let store = SafetensorsStore::from_file(\"model.safetensors\")\n    ///     .with_key_remapping(r\"^encoder\\.\", \"transformer.encoder.\")  // encoder.X -> transformer.encoder.X\n    ///     .with_key_remapping(r\"\\.gamma$\", \".weight\");               // X.gamma -> X.weight\n    /// ```\n    #[cfg(feature = \"std\")]\n    pub fn with_key_remapping(\n        mut self,\n        from_pattern: impl AsRef<str>,\n        to_pattern: impl Into<String>,\n    ) -> Self {\n        match &mut self {\n            Self::File(p) => {\n                p.remapper = p\n                    .remapper\n                    .clone()\n                    .add_pattern(from_pattern, to_pattern)\n                    .expect(\"Invalid regex pattern\");\n            }\n            Self::Memory(p) => {\n                p.remapper = p\n                    .remapper\n                    .clone()\n                    .add_pattern(from_pattern, to_pattern)\n                    .expect(\"Invalid regex pattern\");\n            }\n        }\n        self\n    }\n\n    /// Add metadata to be saved with the tensors.\n    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {\n        let key = key.into();\n        let value = value.into();\n        match &mut self {\n            #[cfg(feature = \"std\")]","sourceCodeStart":304,"sourceCodeEnd":340,"githubUrl":"https://github.com/tracel-ai/burn/blob/d16f7ba2ed0d41408189384044cc886fb4c8f957/crates/burn-store/src/safetensors/store.rs#L304-L340","documentation":"`with_key_remapping` compiles the `from_pattern` you pass as a Rust `regex` and panics via `.expect(\"Invalid regex pattern\")` when `Regex::new` fails. The library's builder API is infallible, so a syntactically invalid regex is treated as a programming error and aborts instead of returning `Result`. The panic happens immediately when building the store, before any tensor is loaded or saved.","triggerScenarios":"Calling `SafetensorsStore::from_file(..).with_key_remapping(from, to)` (or on a memory-backed store) where `from` is not a valid regex — e.g. unbalanced `(`, `[`, dangling `*` or `+`, invalid escape like `\\q`, or an overly large pattern that exceeds the regex size limit. The panic fires on the `Self::File` branch at store.rs:322.","commonSituations":"Copying Python `re` syntax that Rust's regex crate rejects (lookaheads `(?=...)`, backreferences `\\1`, possessive quantifiers); typos in hand-written patterns; interpolating user input or dynamically-built strings into the pattern; forgetting to escape a literal dot or parenthesis.","solutions":["Validate the pattern with `regex::Regex::new(from)` before passing it to `with_key_remapping`, and fix any regex syntax error it reports","Replace unsupported regex features (lookarounds, backreferences) with regex-crate-compatible constructs (e.g. capture groups + expansion in `to`)","Escape literal special characters with `regex::escape` for dynamic segments, e.g. `format!(\"{}.*\", regex::escape(prefix))`","If the pattern comes from user config, pre-compile and store the `Regex`, or switch to `with_remapper` with a custom Remapper that handles errors gracefully"],"exampleFix":"// before\nlet store = SafetensorsStore::from_file(\"model.safetensors\")\n    .with_key_remapping(r\"^encoder.(?=.*bn)\", \"transformer.encoder.\"); // panics: lookahead unsupported\n// after\nlet store = SafetensorsStore::from_file(\"model.safetensors\")\n    .with_key_remapping(r\"^encoder\\.\", \"transformer.encoder.\");","handlingStrategy":"validation","validationCode":"use regex::Regex;\nfn valid_pattern(p: &str) -> bool {\n    Regex::new(p).is_ok()\n}\n// before building the store:\nassert!(valid_pattern(r\"^encoder\\.\"), \"invalid remap pattern\");","typeGuard":"fn is_valid_regex(pattern: &str) -> Result<regex::Regex, regex::Error> {\n    regex::Regex::new(pattern)\n}","tryCatchPattern":"// with_key_remapping panics, so validation must happen first;\n// if patterns come from config, do:\nlet re = regex::Regex::new(&cfg.from_pattern)\n    .map_err(|e| anyhow::anyhow!(\"bad remap pattern {:?}: {}\", cfg.from_pattern, e))?;\nlet store = SafetensorsStore::from_file(path).with_key_remapping(cfg.from_pattern, cfg.to_pattern);","preventionTips":["Validate every remap pattern with regex::Regex::new before calling with_key_remapping","Avoid regex features unsupported by the Rust regex crate (lookarounds, backreferences)","Use regex::escape for dynamic or literal segments","Unit-test all remapping patterns with representative tensor names"],"tags":["regex","panic","builder-api","rust"],"backgroundTag":"invalid-regex-pattern","analyzedSha":"d16f7ba2ed0d41408189384044cc886fb4c8f957","analyzedAt":"2026-09-05T13:19:14.260Z","contentChangedAt":"2026-09-05T13:19:14.260Z","schemaVersion":2},"datasetVersion":"2026-09-12T17:17:11.597Z"}