Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

fix(ingest): honor explicit data format selections

Rudy Celekli133534e8db74
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3d864085..44d32252 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -46,6 +46,10 @@ All notable changes to Open Ontologies are documented here.
### Fixed
+- Explicit ingest formats are honored by the local CLI and the MCP ingest/map
+ tools rather than silently falling back to filename detection. Omitted formats
+ retain extension detection, and unsupported explicit formats return an error.
+
- **The embedding model is loaded once per process rather than once per HTTP
session** (#262). The HTTP arm hands the same server constructor to
`StreamableHttpService::new` as a per-session factory, so everything that
diff --git a/src/ingest.rs b/src/ingest.rs
index 2f6ed7ad..7ad95e44 100644
--- a/src/ingest.rs
+++ b/src/ingest.rs
@@ -386,7 +386,15 @@ impl DataIngester {
/// Dispatch to the correct parser based on detected format.
/// For text formats, reads the file content first.
pub fn parse_file(path: &str) -> Result<Vec<HashMap<String, String>>> {
- let format = Self::detect_format(path);
+ Self::parse_file_with_format(path, None)
+ }
+
+ /// Parse the explicitly requested format, or infer it from the extension.
+ pub fn parse_file_with_format(
+ path: &str,
+ format: Option<&str>,
+ ) -> Result<Vec<HashMap<String, String>>> {
+ let format = format.unwrap_or_else(|| Self::detect_format(path));
match format {
"csv" => {
let content = Self::read_to_string_capped(path)?;
@@ -410,10 +418,7 @@ impl DataIngester {
}
"xlsx" => Self::parse_xlsx_file(path),
"parquet" => Self::parse_parquet_file(path),
- _ => {
- let content = Self::read_to_string_capped(path)?;
- Self::parse_csv(&content)
- }
+ _ => anyhow::bail!("Unsupported data format: {format}"),
}
}
diff --git a/src/main.rs b/src/main.rs
index e9422b76..544189e9 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -3024,7 +3024,7 @@ async fn async_main() -> anyhow::Result<()> {
}
Commands::Ingest {
path,
- format: _format,
+ format,
mapping,
base_iri,
} => {
@@ -3033,7 +3033,7 @@ async fn async_main() -> anyhow::Result<()> {
let (_db, graph) = setup(&cli.data_dir)?;
let base = base_iri.as_deref().unwrap_or("http://example.org/data/");
- let rows = DataIngester::parse_file(&path)?;
+ let rows = DataIngester::parse_file_with_format(&path, format.as_deref())?;
if rows.is_empty() {
output_json(
diff --git a/src/server.rs b/src/server.rs
index b8a7a197..9318bf6f 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -1029,7 +1029,7 @@ impl OpenOntologiesServer {
let base_iri = input.base_iri.as_deref().unwrap_or("http://example.org/data/");
// Parse data file
- let rows = match DataIngester::parse_file(&input.path) {
+ let rows = match DataIngester::parse_file_with_format(&input.path, input.format.as_deref()) {
Ok(r) => r,
Err(e) => return Self::err_json(format!("Failed to parse {}: {}", input.path, e)),
};
@@ -1310,7 +1310,7 @@ impl OpenOntologiesServer {
use crate::ingest::DataIngester;
use crate::mapping::MappingConfig;
- let rows = match DataIngester::parse_file(&input.data_path) {
+ let rows = match DataIngester::parse_file_with_format(&input.data_path, input.format.as_deref()) {
Ok(r) => r,
Err(e) => return Self::err_json(format!("Failed to parse {}: {}", input.data_path, e)),
};
diff --git a/tests/ingest_format_test.rs b/tests/ingest_format_test.rs
new file mode 100644
index 00000000..12104f88
--- /dev/null
+++ b/tests/ingest_format_test.rs
@@ -0,0 +1,190 @@
+use open_ontologies::ingest::DataIngester;
+use serde_json::{Value, json};
+use std::io::{BufRead, BufReader, Write};
+use std::process::{Child, ChildStdin, Command, Stdio};
+use std::sync::mpsc::{Receiver, channel};
+use std::time::Duration;
+
+#[test]
+fn cli_explicit_json_format_overrides_non_json_extensions() {
+ let dir = tempfile::tempdir().unwrap();
+ for extension in ["data", "csv"] {
+ let file = dir.path().join(format!("records.{extension}"));
+ std::fs::write(&file, r#"[{"id":"b1","name":"Tower Bridge"}]"#).unwrap();
+ let output = Command::new(env!("CARGO_BIN_EXE_open-ontologies"))
+ .args(["--no-connect", "--data-dir"])
+ .arg(dir.path().join(format!("state-{extension}")))
+ .arg("ingest")
+ .arg(&file)
+ .args(["--format", "json"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let result: Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(result["rows"], 1, "{result}");
+ assert_eq!(result["triples_loaded"], 3, "{result}");
+ }
+}
+
+#[test]
+fn omitted_format_keeps_extension_detection_and_csv_fallback() {
+ let dir = tempfile::tempdir().unwrap();
+ let json_file = dir.path().join("records.json");
+ std::fs::write(&json_file, r#"[{"id":"b1","name":"Tower Bridge"}]"#).unwrap();
+ let rows = DataIngester::parse_file(json_file.to_str().unwrap()).unwrap();
+ assert_eq!(rows[0]["name"], "Tower Bridge");
+ let csv_file = dir.path().join("records.data");
+ std::fs::write(&csv_file, "id,name\nb1,Tower Bridge\n").unwrap();
+ let rows = DataIngester::parse_file(csv_file.to_str().unwrap()).unwrap();
+ assert_eq!(rows[0]["name"], "Tower Bridge");
+}
+
+#[test]
+fn explicit_formats_share_the_existing_parsers_and_reject_unknown_formats() {
+ let dir = tempfile::tempdir().unwrap();
+ for (format, content) in [
+ ("json", r#"[{"id":"b1","name":"Tower Bridge"}]"#),
+ ("ndjson", "{\"id\":\"b1\",\"name\":\"Tower Bridge\"}\n"),
+ ("csv", "id,name\nb1,Tower Bridge\n"),
+ ("yaml", "- id: b1\n name: Tower Bridge\n"),
+ (
+ "xml",
+ "<records><record><id>b1</id><name>Tower Bridge</name></record></records>",
+ ),
+ ] {
+ let file = dir.path().join(format!("{format}.data"));
+ std::fs::write(&file, content).unwrap();
+ let rows =
+ DataIngester::parse_file_with_format(file.to_str().unwrap(), Some(format)).unwrap();
+ assert_eq!(rows[0]["id"], "b1");
+ assert_eq!(rows[0]["name"], "Tower Bridge");
+ }
+ let missing = dir.path().join("missing.data");
+ let error = DataIngester::parse_file_with_format(missing.to_str().unwrap(), Some("unknown"))
+ .unwrap_err();
+ assert!(
+ error
+ .to_string()
+ .contains("Unsupported data format: unknown")
+ );
+}
+
+struct McpChild {
+ child: Child,
+ input: ChildStdin,
+ lines: Receiver<String>,
+ reader: Option<std::thread::JoinHandle<()>>,
+}
+
+impl McpChild {
+ fn start(state: &std::path::Path) -> Self {
+ let mut child = Command::new(env!("CARGO_BIN_EXE_open-ontologies"))
+ .args(["--no-connect", "--data-dir"])
+ .arg(state)
+ .arg("serve")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .unwrap();
+ let input = child.stdin.take().unwrap();
+ let stdout = child.stdout.take().unwrap();
+ let (send, lines) = channel();
+ let reader = std::thread::spawn(move || {
+ for line in BufReader::new(stdout).lines() {
+ match line {
+ Ok(line) => {
+ if send.send(line).is_err() {
+ break;
+ }
+ }
+ Err(_) => break,
+ }
+ }
+ });
+ Self {
+ child,
+ input,
+ lines,
+ reader: Some(reader),
+ }
+ }
+
+ fn send(&mut self, message: Value) {
+ writeln!(self.input, "{message}").unwrap();
+ self.input.flush().unwrap();
+ }
+
+ fn request(&mut self, id: u64, method: &str, params: Value) -> Value {
+ self.send(json!({"jsonrpc":"2.0", "id":id, "method":method, "params":params}));
+ loop {
+ let line = self
+ .lines
+ .recv_timeout(Duration::from_secs(10))
+ .expect("MCP response timed out or server exited");
+ let response: Value = serde_json::from_str(&line).unwrap();
+ if response["id"] == id {
+ assert!(response.get("error").is_none(), "{response}");
+ return response["result"].clone();
+ }
+ }
+ }
+
+ fn tool(&mut self, id: u64, name: &str, arguments: Value) -> Value {
+ let result = self.request(
+ id,
+ "tools/call",
+ json!({"name":name, "arguments":arguments}),
+ );
+ serde_json::from_str(result["content"][0]["text"].as_str().unwrap()).unwrap()
+ }
+}
+
+impl Drop for McpChild {
+ fn drop(&mut self) {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ if let Some(reader) = self.reader.take() {
+ let _ = reader.join();
+ }
+ }
+}
+
+#[test]
+fn mcp_ingest_and_map_honor_their_documented_format_field() {
+ let dir = tempfile::tempdir().unwrap();
+ let file = dir.path().join("records.data");
+ std::fs::write(&file, r#"[{"id":"b1","name":"Tower Bridge"}]"#).unwrap();
+ let mut mcp = McpChild::start(&dir.path().join("state"));
+ mcp.request(
+ 1,
+ "initialize",
+ json!({
+ "protocolVersion":"2025-03-26", "capabilities":{},
+ "clientInfo":{"name":"ingest-format-test", "version":"1"}
+ }),
+ );
+ mcp.send(json!({"jsonrpc":"2.0", "method":"notifications/initialized"}));
+ let ingested = mcp.tool(
+ 2,
+ "onto_ingest",
+ json!({
+ "path":file, "format":"json", "base_iri":"https://example.org/"
+ }),
+ );
+ assert_eq!(ingested["rows_processed"], 1, "{ingested}");
+ assert_eq!(ingested["triples_loaded"], 3, "{ingested}");
+ let mapping = mcp.tool(3, "onto_map", json!({"data_path":file, "format":"json"}));
+ assert_eq!(mapping["data_fields"], json!(["id", "name"]));
+ let invalid = mcp.tool(4, "onto_ingest", json!({"path":file, "format":"unknown"}));
+ assert!(
+ invalid["error"]
+ .as_str()
+ .unwrap()
+ .contains("Unsupported data format: unknown")
+ );
+}