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.

feat: surface operational limits as [section] config (PR #11)

FABIOTESS8c504c735573
diff --git a/Cargo.lock b/Cargo.lock
index c5723fc9..07447a74 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4233,6 +4233,16 @@ dependencies = [
"tracing-core",
]
+[[package]]
+name = "tracing-serde"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1"
+dependencies = [
+ "serde",
+ "tracing-core",
+]
+
[[package]]
name = "tracing-subscriber"
version = "0.3.22"
@@ -4243,12 +4253,15 @@ dependencies = [
"nu-ansi-term",
"once_cell",
"regex-automata",
+ "serde",
+ "serde_json",
"sharded-slab",
"smallvec",
"thread_local",
"tracing",
"tracing-core",
"tracing-log",
+ "tracing-serde",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
index 2ffccd62..a4c79662 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -25,7 +25,7 @@ serde_json = "1"
toml = "0.8"
clap = { version = "4", features = ["derive", "env"] }
tracing = "0.1"
-tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
chrono = "0.4"
anyhow = "1"
thiserror = "2"
diff --git a/src/cache.rs b/src/cache.rs
index 1a1d8ae3..21b3b2ca 100644
--- a/src/cache.rs
+++ b/src/cache.rs
@@ -18,7 +18,8 @@ use rusqlite::params;
use crate::state::StateDb;
-const HASH_PREFIX_BYTES: usize = 64 * 1024;
+// Number of head-bytes hashed for the cache fingerprint — overridable via
+// `[cache] hash_prefix_bytes` in config.toml. See `crate::runtime`.
/// Information about a source ontology file used as the cache validity key.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -41,11 +42,13 @@ impl SourceFingerprint {
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
- // Read up to 64 KiB for hashing — enough to differentiate files
- // with identical mtime/size (rare but possible with `cp -p`).
+ // Read up to N bytes (configurable via `[cache] hash_prefix_bytes`)
+ // for hashing — enough to differentiate files with identical
+ // mtime/size (rare but possible with `cp -p`).
let mut file = fs::File::open(path)
.with_context(|| format!("open({})", path.display()))?;
- let mut buf = vec![0u8; HASH_PREFIX_BYTES.min(size as usize)];
+ let prefix_len = crate::runtime::cache_hash_prefix_bytes();
+ let mut buf = vec![0u8; prefix_len.min(size as usize)];
let n = file.read(&mut buf)?;
buf.truncate(n);
let sha_prefix = sha256_hex(&buf);
diff --git a/src/config.rs b/src/config.rs
index d6113ff8..65abeb6c 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -10,6 +10,15 @@ pub struct Config {
pub embeddings: EmbeddingsConfig,
pub cache: CacheConfig,
pub tools: ToolsConfig,
+ pub webhook: WebhookConfig,
+ pub http: HttpConfig,
+ pub monitor: MonitorConfig,
+ pub reasoner: ReasonerConfig,
+ pub feedback: FeedbackConfig,
+ pub imports: ImportsConfig,
+ pub repo: RepoConfig,
+ pub socket: SocketConfig,
+ pub logging: LoggingConfig,
}
@@ -197,12 +206,22 @@ pub struct CacheConfig {
/// If > 0, the active ontology will be unloaded from memory after this
/// many seconds without access. The cache file is preserved and reloaded
/// automatically on the next query.
+ ///
+ /// Accepts either canonical name `idle_ttl_secs` or the more descriptive
+ /// alias `unload_timeout_secs` — both populate the same field.
+ #[serde(alias = "unload_timeout_secs")]
pub idle_ttl_secs: u64,
/// How often the background evictor checks idle entries (seconds).
pub evictor_interval_secs: u64,
/// When true, every read tool checks the source file's mtime/sha and
/// recompiles if it changed. Off by default for predictability.
pub auto_refresh: bool,
+ /// Number of bytes from the head of a source ontology file that are
+ /// hashed (sha256) to form the cache fingerprint tie-breaker. Larger
+ /// values reduce collision probability for very large dumps where many
+ /// files share an identical leading region (e.g. `@prefix` headers in
+ /// big N-Quads exports). Default 64 KiB.
+ pub hash_prefix_bytes: usize,
}
impl Default for CacheConfig {
@@ -213,6 +232,7 @@ impl Default for CacheConfig {
idle_ttl_secs: 0,
evictor_interval_secs: 30,
auto_refresh: false,
+ hash_prefix_bytes: 64 * 1024,
}
}
}
@@ -238,6 +258,241 @@ pub fn expand_tilde(path: &str) -> String {
path.to_string()
}
+// ─── New section configs ────────────────────────────────────────────────
+
+/// `[webhook]` — outbound HTTP for governance / monitor alerts.
+#[derive(Debug, Deserialize, Clone)]
+#[serde(default)]
+pub struct WebhookConfig {
+ /// HTTP timeout (seconds) for governance / monitor webhook deliveries.
+ /// Override at runtime with `OPEN_ONTOLOGIES_WEBHOOK_REQUEST_TIMEOUT_SECS`.
+ pub request_timeout_secs: u64,
+}
+impl Default for WebhookConfig {
+ fn default() -> Self { Self { request_timeout_secs: 10 } }
+}
+
+/// `[http]` — Streamable HTTP transport (`serve-http`).
+#[derive(Debug, Deserialize, Clone)]
+#[serde(default)]
+pub struct HttpConfig {
+ /// Bind host. Default `127.0.0.1`. CLI `--host` and the
+ /// `OPEN_ONTOLOGIES_HTTP_HOST` env var take precedence.
+ pub host: String,
+ /// Bind port. Default `8080`. CLI `--port` and the
+ /// `OPEN_ONTOLOGIES_HTTP_PORT` env var take precedence.
+ pub port: u16,
+ /// Optional bearer token for authentication. Empty string ⇒ disabled.
+ /// CLI `--token` and `OPEN_ONTOLOGIES_TOKEN` env var take precedence.
+ pub token: String,
+ /// Whether the rmcp `StreamableHttpServer` keeps per-session state.
+ /// Default `true` (matches existing behaviour).
+ pub stateful_mode: bool,
+ /// Per-request HTTP timeout in seconds. `0` ⇒ no explicit cap (rmcp
+ /// default). Override with `OPEN_ONTOLOGIES_HTTP_REQUEST_TIMEOUT_SECS`.
+ pub request_timeout_secs: u64,
+ /// HTTP keep-alive timeout in seconds. `0` ⇒ no explicit cap.
+ pub keep_alive_secs: u64,
+}
+impl Default for HttpConfig {
+ fn default() -> Self {
+ Self {
+ host: "127.0.0.1".into(),
+ port: 8080,
+ token: String::new(),
+ stateful_mode: true,
+ request_timeout_secs: 0,
+ keep_alive_secs: 0,
+ }
+ }
+}
+
+/// `[monitor]` — continuous watcher loop.
+#[derive(Debug, Deserialize, Clone)]
+#[serde(default)]
+pub struct MonitorConfig {
+ /// When true, start the background monitor loop on `serve` / `serve-http`.
+ /// Equivalent to passing `--watch`. Default `false`.
+ pub enabled: bool,
+ /// Interval in seconds between monitor sweeps. Default `30`.
+ /// Override with `OPEN_ONTOLOGIES_MONITOR_INTERVAL_SECS`.
+ #[serde(alias = "watch_interval_secs")]
+ pub interval_secs: u64,
+}
+impl Default for MonitorConfig {
+ fn default() -> Self { Self { enabled: false, interval_secs: 30 } }
+}
+
+/// `[reasoner]` — RDFS / OWL-RL fixpoint and DL tableaux limits.
+#[derive(Debug, Deserialize, Clone)]
+#[serde(default)]
+pub struct ReasonerConfig {
+ /// Tableaux DL reasoner: max recursion depth before giving up. Default 100.
+ pub tableaux_max_depth: usize,
+ /// Tableaux DL reasoner: max nodes in a model before giving up.
+ /// Default 10 000. Increase for very large ontologies; raising this past
+ /// ~100 000 typically indicates the ontology is unsatisfiable in
+ /// pathological ways and the reasoner should bail out anyway.
+ pub tableaux_max_nodes: usize,
+ /// RDFS / OWL-RL fixpoint guard. Maximum number of expansion iterations
+ /// before the reasoner returns the partial closure. Default 64.
+ pub max_iterations: usize,
+}
+impl Default for ReasonerConfig {
+ fn default() -> Self {
+ Self { tableaux_max_depth: 100, tableaux_max_nodes: 10_000, max_iterations: 64 }
+ }
+}
+
+/// `[feedback]` — lint / enforce self-calibration thresholds.
+#[derive(Debug, Deserialize, Clone)]
+#[serde(default)]
+pub struct FeedbackConfig {
+ /// Number of consecutive dismissals after which a lint/enforce issue
+ /// is fully suppressed for that (tool, rule_id, entity) tuple. Default 3.
+ pub suppress_threshold: i64,
+ /// Number of consecutive dismissals after which a lint/enforce issue
+ /// is downgraded one severity level. Must be `< suppress_threshold` to
+ /// take effect. Default 2.
+ pub downgrade_threshold: i64,
+}
+impl Default for FeedbackConfig {
+ fn default() -> Self { Self { suppress_threshold: 3, downgrade_threshold: 2 } }
+}
+
+/// `[imports]` — `owl:imports` resolution policy.
+#[derive(Debug, Deserialize, Clone)]
+#[serde(default)]
+pub struct ImportsConfig {
+ /// Maximum transitive depth to follow when resolving owl:imports. The
+ /// `onto_import` tool's `max_depth` parameter (when supplied) overrides
+ /// this. Default 3.
+ pub max_depth: usize,
+ /// HTTP timeout in seconds for fetching each remote import. Set to `0`
+ /// to disable the explicit per-call timeout and use reqwest's default
+ /// (which itself has no timeout). Override with
+ /// `OPEN_ONTOLOGIES_IMPORTS_REQUEST_TIMEOUT_SECS`.
+ pub request_timeout_secs: u64,
+ /// When false, remote (`http(s)://`) imports are refused — useful in
+ /// air-gapped or sandboxed deployments. Default `true`.
+ pub follow_remote: bool,
+}
+impl Default for ImportsConfig {
+ fn default() -> Self {
+ Self { max_depth: 3, request_timeout_secs: 30, follow_remote: true }
+ }
+}
+
+/// `[repo]` — on-disk ontology repository tools.
+#[derive(Debug, Deserialize, Clone)]
+#[serde(default)]
+pub struct RepoConfig {
+ /// Default `limit` for `onto_repo_list` when the caller doesn't supply
+ /// one. Default 1000.
+ pub default_list_limit: usize,
+}
+impl Default for RepoConfig {
+ fn default() -> Self { Self { default_list_limit: 1000 } }
+}
+
+/// `[socket]` — Unix domain socket adapter for Tardygrada fact grounding.
+#[derive(Debug, Deserialize, Clone, Default)]
+#[serde(default)]
+pub struct SocketConfig {
+ /// When true, `serve` / `serve-http` will additionally start the unix
+ /// socket adapter. Currently the dedicated `serve-unix` subcommand reads
+ /// these defaults. Default `false`.
+ pub enabled: bool,
+ /// Default socket path for `serve-unix`. CLI `--socket` overrides.
+ pub path: Option<String>,
+ /// Default ontology files to preload on `serve-unix` startup.
+ /// CLI `--file` (repeatable) overrides.
+ pub preload_files: Vec<String>,
+}
+
+/// `[logging]` — tracing subscriber configuration.
+#[derive(Debug, Deserialize, Clone)]
+#[serde(default)]
+pub struct LoggingConfig {
+ /// Default log directives (e.g. `info`, `debug`,
+ /// `open_ontologies=debug,reqwest=warn`). The `RUST_LOG` env var, when
+ /// set, takes precedence over this value.
+ pub level: String,
+ /// Output format: `compact` (default), `pretty`, or `json`.
+ pub format: String,
+ /// Optional path to write logs to. When unset, logs go to stderr.
+ pub file: Option<String>,
+}
+impl Default for LoggingConfig {
+ fn default() -> Self {
+ Self { level: "info".into(), format: "compact".into(), file: None }
+ }
+}
+
+// ─── Env-override resolvers for the most operationally critical fields ──
+
+/// Resolve the webhook request timeout. Precedence:
+/// `OPEN_ONTOLOGIES_WEBHOOK_REQUEST_TIMEOUT_SECS` > config > default.
+pub fn resolve_webhook_timeout_secs(cfg: &WebhookConfig) -> u64 {
+ parse_env_u64("OPEN_ONTOLOGIES_WEBHOOK_REQUEST_TIMEOUT_SECS")
+ .unwrap_or(cfg.request_timeout_secs)
+}
+
+/// Resolve the imports request timeout. Precedence:
+/// `OPEN_ONTOLOGIES_IMPORTS_REQUEST_TIMEOUT_SECS` > config > default.
+pub fn resolve_imports_timeout_secs(cfg: &ImportsConfig) -> u64 {
+ parse_env_u64("OPEN_ONTOLOGIES_IMPORTS_REQUEST_TIMEOUT_SECS")
+ .unwrap_or(cfg.request_timeout_secs)
+}
+
+/// Resolve the monitor sweep interval. Precedence:
+/// `OPEN_ONTOLOGIES_MONITOR_INTERVAL_SECS` > config > default.
+pub fn resolve_monitor_interval_secs(cfg: &MonitorConfig) -> u64 {
+ parse_env_u64("OPEN_ONTOLOGIES_MONITOR_INTERVAL_SECS")
+ .unwrap_or(cfg.interval_secs)
+}
+
+/// Resolve the HTTP bind host. Precedence:
+/// `OPEN_ONTOLOGIES_HTTP_HOST` > config > default.
+pub fn resolve_http_host(cfg: &HttpConfig) -> String {
+ std::env::var("OPEN_ONTOLOGIES_HTTP_HOST")
+ .ok()
+ .filter(|v| !v.trim().is_empty())
+ .unwrap_or_else(|| cfg.host.clone())
+}
+
+/// Resolve the HTTP bind port. Precedence:
+/// `OPEN_ONTOLOGIES_HTTP_PORT` > config > default.
+pub fn resolve_http_port(cfg: &HttpConfig) -> u16 {
+ std::env::var("OPEN_ONTOLOGIES_HTTP_PORT")
+ .ok()
+ .and_then(|v| v.trim().parse::<u16>().ok())
+ .unwrap_or(cfg.port)
+}
+
+/// Resolve the HTTP bearer token. Precedence:
+/// `OPEN_ONTOLOGIES_TOKEN` > config (if non-empty) > `None`.
+pub fn resolve_http_token(cfg: &HttpConfig) -> Option<String> {
+ std::env::var("OPEN_ONTOLOGIES_TOKEN")
+ .ok()
+ .filter(|v| !v.trim().is_empty())
+ .or_else(|| Some(cfg.token.clone()).filter(|v| !v.trim().is_empty()))
+}
+
+/// Resolve the logging directives. Precedence: `RUST_LOG` > config > default.
+pub fn resolve_logging_level(cfg: &LoggingConfig) -> String {
+ std::env::var("RUST_LOG")
+ .ok()
+ .filter(|v| !v.trim().is_empty())
+ .unwrap_or_else(|| cfg.level.clone())
+}
+
+fn parse_env_u64(var: &str) -> Option<u64> {
+ std::env::var(var)
+ .ok()
+ .and_then(|v| v.trim().parse::<u64>().ok())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -301,4 +556,105 @@ mod tests {
Some("http://localhost:11434/v1")
);
}
+
+ #[test]
+ fn unload_timeout_alias_for_idle_ttl() {
+ let toml_src = r#"
+ [cache]
+ unload_timeout_secs = 120
+ hash_prefix_bytes = 131072
+ "#;
+ let cfg: Config = toml::from_str(toml_src).expect("parse");
+ assert_eq!(cfg.cache.idle_ttl_secs, 120);
+ assert_eq!(cfg.cache.hash_prefix_bytes, 131072);
+ }
+
+ #[test]
+ fn new_sections_parse_with_defaults() {
+ let toml_src = r#"
+ [webhook]
+ request_timeout_secs = 5
+
+ [http]
+ host = "0.0.0.0"
+ port = 9000
+ stateful_mode = false
+
+ [monitor]
+ enabled = true
+ interval_secs = 15
+
+ [reasoner]
+ tableaux_max_depth = 200
+ tableaux_max_nodes = 50000
+ max_iterations = 128
+
+ [feedback]
+ suppress_threshold = 5
+ downgrade_threshold = 3
+
+ [imports]
+ max_depth = 5
+ request_timeout_secs = 60
+ follow_remote = false
+
+ [repo]
+ default_list_limit = 250
+
+ [socket]
+ enabled = true
+ path = "/tmp/foo.sock"
+ preload_files = ["a.ttl", "b.ttl"]
+
+ [logging]
+ level = "debug"
+ format = "json"
+ "#;
+ let cfg: Config = toml::from_str(toml_src).expect("parse");
+ assert_eq!(cfg.webhook.request_timeout_secs, 5);
+ assert_eq!(cfg.http.host, "0.0.0.0");
+ assert_eq!(cfg.http.port, 9000);
+ assert!(!cfg.http.stateful_mode);
+ assert!(cfg.monitor.enabled);
+ assert_eq!(cfg.monitor.interval_secs, 15);
+ assert_eq!(cfg.reasoner.tableaux_max_depth, 200);
+ assert_eq!(cfg.reasoner.tableaux_max_nodes, 50_000);
+ assert_eq!(cfg.reasoner.max_iterations, 128);
+ assert_eq!(cfg.feedback.suppress_threshold, 5);
+ assert_eq!(cfg.feedback.downgrade_threshold, 3);
+ assert_eq!(cfg.imports.max_depth, 5);
+ assert_eq!(cfg.imports.request_timeout_secs, 60);
+ assert!(!cfg.imports.follow_remote);
+ assert_eq!(cfg.repo.default_list_limit, 250);
+ assert!(cfg.socket.enabled);
+ assert_eq!(cfg.socket.path.as_deref(), Some("/tmp/foo.sock"));
+ assert_eq!(cfg.socket.preload_files, vec!["a.ttl", "b.ttl"]);
+ assert_eq!(cfg.logging.level, "debug");
+ assert_eq!(cfg.logging.format, "json");
+ }
+
+ #[test]
+ fn new_sections_default_when_absent() {
+ let cfg: Config = toml::from_str("").expect("parse empty");
+ assert_eq!(cfg.webhook.request_timeout_secs, 10);
+ assert_eq!(cfg.http.host, "127.0.0.1");
+ assert_eq!(cfg.http.port, 8080);
+ assert!(cfg.http.stateful_mode);
+ assert!(!cfg.monitor.enabled);
+ assert_eq!(cfg.monitor.interval_secs, 30);
+ assert_eq!(cfg.reasoner.tableaux_max_depth, 100);
+ assert_eq!(cfg.reasoner.tableaux_max_nodes, 10_000);
+ assert_eq!(cfg.reasoner.max_iterations, 64);
+ assert_eq!(cfg.feedback.suppress_threshold, 3);
+ assert_eq!(cfg.feedback.downgrade_threshold, 2);
+ assert_eq!(cfg.imports.max_depth, 3);
+ assert_eq!(cfg.imports.request_timeout_secs, 30);
+ assert!(cfg.imports.follow_remote);
+ assert_eq!(cfg.repo.default_list_limit, 1000);
+ assert!(!cfg.socket.enabled);
+ assert!(cfg.socket.preload_files.is_empty());
+ assert_eq!(cfg.logging.level, "info");
+ assert_eq!(cfg.logging.format, "compact");
+ assert_eq!(cfg.cache.hash_prefix_bytes, 64 * 1024);
+ }
}
diff --git a/src/feedback.rs b/src/feedback.rs
index 54440b9a..be4db26c 100644
--- a/src/feedback.rs
+++ b/src/feedback.rs
@@ -11,8 +11,8 @@ pub enum FeedbackAction {
Suppress,
}
-const SUPPRESS_THRESHOLD: i64 = 3;
-const DOWNGRADE_THRESHOLD: i64 = 2;
+// Severity-adjustment thresholds live in `crate::runtime` (initialised from
+// `[feedback]` in config.toml).
/// Check feedback history for a (tool, rule_id, entity) tuple.
pub fn get_feedback_adjustment(db: &StateDb, tool: &str, rule_id: &str, entity: &str) -> FeedbackAction {
@@ -35,10 +35,12 @@ pub fn get_feedback_adjustment(db: &StateDb, tool: &str, rule_id: &str, entity:
if accept_count > 0 {
return FeedbackAction::Keep;
}
- if dismiss_count >= SUPPRESS_THRESHOLD {
+ let suppress = crate::runtime::feedback_suppress_threshold();
+ let downgrade = crate::runtime::feedback_downgrade_threshold();
+ if dismiss_count >= suppress {
return FeedbackAction::Suppress;
}
- if dismiss_count >= DOWNGRADE_THRESHOLD {
+ if dismiss_count >= downgrade {
return FeedbackAction::Downgrade;
}
FeedbackAction::Keep
diff --git a/src/lib.rs b/src/lib.rs
index 4956add9..a8e8419a 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -20,6 +20,7 @@ pub mod ontology;
pub mod reason;
pub mod registry;
pub mod repo;
+pub mod runtime;
pub mod server;
pub mod shacl;
pub mod state;
diff --git a/src/main.rs b/src/main.rs
index 860e9816..26b4c28d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -22,15 +22,20 @@ data_dir = "~/.open-ontologies"
# Compile-cache: parsed ontologies are written to N-Triples files for fast reload.
# enabled = true
# dir = "~/.open-ontologies/cache"
-# # Idle TTL in seconds before the active ontology is unloaded from memory.
+# # Idle timeout in seconds before the active ontology is unloaded from memory.
# # Set to 0 to disable eviction. The on-disk cache file is always preserved
# # across evictions; the next query reloads it transparently.
+# # `idle_ttl_secs` is the canonical name; `unload_timeout_secs` is an alias.
# idle_ttl_secs = 0
+# # unload_timeout_secs = 0
# # How often the background evictor runs (seconds).
# evictor_interval_secs = 30
# # When true, every read tool checks the source file's mtime/sha and
# # recompiles if it changed.
# auto_refresh = false
+# # Bytes from the head of each ontology file that are sha256-hashed for the
+# # cache fingerprint tie-breaker. Increase for very large dumps.
+# hash_prefix_bytes = 65536
# [tools]
# Restrict which MCP tools are exposed by this server.
@@ -70,6 +75,62 @@ data_dir = "~/.open-ontologies"
# model = "text-embedding-3-small" # any model your gateway serves
# dimensions = 1536 # optional — only sent when set
# request_timeout_secs = 30
+
+# [webhook]
+# HTTP timeout (seconds) for governance / monitor webhook deliveries.
+# Override at runtime with OPEN_ONTOLOGIES_WEBHOOK_REQUEST_TIMEOUT_SECS.
+# request_timeout_secs = 10
+
+# [http]
+# Streamable HTTP transport (`open-ontologies serve-http`). CLI flags
+# (--host/--port/--token) and env vars (OPEN_ONTOLOGIES_HTTP_HOST,
+# OPEN_ONTOLOGIES_HTTP_PORT, OPEN_ONTOLOGIES_TOKEN) take precedence.
+# host = "127.0.0.1"
+# port = 8080
+# token = "" # empty disables auth
+# stateful_mode = true # rmcp StreamableHttpServer per-session state
+# request_timeout_secs = 0 # 0 = rmcp default
+# keep_alive_secs = 0 # 0 = rmcp default
+
+# [monitor]
+# Continuous watcher loop. CLI `--watch` / `--watch-interval` override.
+# enabled = false
+# interval_secs = 30
+
+# [reasoner]
+# Safety limits for the OWL-DL tableaux reasoner and RDFS / OWL-RL fixpoint.
+# tableaux_max_depth = 100
+# tableaux_max_nodes = 10000
+# max_iterations = 64
+
+# [feedback]
+# Lint / enforce self-calibration thresholds (number of dismissals before
+# downgrading then suppressing a (tool, rule_id, entity) triple).
+# suppress_threshold = 3
+# downgrade_threshold = 2
+
+# [imports]
+# `owl:imports` resolution policy used by `onto_import`.
+# max_depth = 3
+# request_timeout_secs = 30
+# follow_remote = true # set false in air-gapped / sandboxed deployments
+
+# [repo]
+# Defaults for the `onto_repo_list` tool.
+# default_list_limit = 1000
+
+# [socket]
+# Defaults for the `serve-unix` subcommand. CLI `--socket` / `--file`
+# override these.
+# enabled = false
+# path = "/tmp/tardygrada-ontology-complete.sock"
+# preload_files = []
+
+# [logging]
+# Tracing subscriber configuration. RUST_LOG, when set, takes precedence.
+# level = "info"
+# format = "compact" # "compact" | "pretty" | "json"
+# # file = "/var/log/open-ontologies.log"
"#;
#[derive(Parser)]
@@ -110,12 +171,15 @@ enum Commands {
/// Optional governance webhook URL (fires on every lineage event)
#[arg(long, env = "GOVERNANCE_WEBHOOK")]
governance_webhook: Option<String>,
- /// Enable continuous background monitoring (runs watchers on an interval)
+ /// Enable continuous background monitoring (runs watchers on an interval).
+ /// When omitted, falls back to `[monitor] enabled` from the config (default false).
#[arg(long)]
watch: bool,
- /// Interval in seconds between monitor sweeps (default: 30)
- #[arg(long, default_value = "30")]
- watch_interval: u64,
+ /// Interval in seconds between monitor sweeps. When omitted, falls back to
+ /// `OPEN_ONTOLOGIES_MONITOR_INTERVAL_SECS` env var, then `[monitor] interval_secs`
+ /// from the config (default 30).
+ #[arg(long)]
+ watch_interval: Option<u64>,
/// Comma-separated list of tools (or `@group`) to allow. Mutually exclusive with --tools-deny.
#[arg(long)]
tools_allow: Option<String>,
@@ -133,24 +197,29 @@ enum Commands {
ServeHttp {
#[arg(long, default_value = "~/.open-ontologies/config.toml")]
config: String,
- /// Host to bind to
- #[arg(long, default_value = "127.0.0.1")]
- host: String,
- /// Port to bind to
- #[arg(long, default_value = "8080")]
- port: u16,
- /// Optional bearer token for authentication
+ /// Host to bind to. CLI > `OPEN_ONTOLOGIES_HTTP_HOST` env > `[http] host`
+ /// in config > `127.0.0.1`.
+ #[arg(long)]
+ host: Option<String>,
+ /// Port to bind to. CLI > `OPEN_ONTOLOGIES_HTTP_PORT` env > `[http] port` >
+ /// `8080`.
+ #[arg(long)]
+ port: Option<u16>,
+ /// Optional bearer token for authentication. CLI > `OPEN_ONTOLOGIES_TOKEN`
+ /// env > `[http] token` in config.
#[arg(long, env = "OPEN_ONTOLOGIES_TOKEN")]
token: Option<String>,
/// Optional governance webhook URL (fires on every lineage event)
#[arg(long, env = "GOVERNANCE_WEBHOOK")]
governance_webhook: Option<String>,
- /// Enable continuous background monitoring (runs watchers on an interval)
+ /// Enable continuous background monitoring (runs watchers on an interval).
+ /// When omitted, falls back to `[monitor] enabled` from the config (default false).
#[arg(long)]
watch: bool,
- /// Interval in seconds between monitor sweeps (default: 30)
- #[arg(long, default_value = "30")]
- watch_interval: u64,
+ /// Interval in seconds between monitor sweeps. When omitted, falls back to
+ /// `[monitor] interval_secs` from the config (default 30).
+ #[arg(long)]
+ watch_interval: Option<u64>,
/// Comma-separated list of tools (or `@group`) to allow.
#[arg(long)]
tools_allow: Option<String>,
@@ -167,10 +236,14 @@ enum Commands {
/// Start unix socket server for Tardygrada fact grounding
ServeUnix {
- /// Path to the unix socket
- #[arg(long, default_value = "/tmp/tardygrada-ontology-complete.sock")]
- socket: String,
- /// Ontology files to load on startup
+ #[arg(long, default_value = "~/.open-ontologies/config.toml")]
+ config: String,
+ /// Path to the unix socket. CLI > `[socket] path` in config >
+ /// `/tmp/tardygrada-ontology-complete.sock`.
+ #[arg(long)]
+ socket: Option<String>,
+ /// Ontology files to load on startup. When omitted, falls back to
+ /// `[socket] preload_files` from the config.
#[arg(long = "file", num_args = 1..)]
files: Vec<String>,
},
@@ -471,6 +544,70 @@ fn build_cache_config(
cc
}
+/// Initialise the tracing subscriber from `[logging]` config. `RUST_LOG`
+/// (when set) takes precedence over `level`. Idempotent: re-invocations are
+/// harmless because `try_init` returns `Err` after the first install.
+fn init_tracing(cfg: &open_ontologies::config::LoggingConfig) {
+ use tracing_subscriber::{fmt, EnvFilter};
+
+ let level = open_ontologies::config::resolve_logging_level(cfg);
+ let env_filter = EnvFilter::try_new(&level)
+ .unwrap_or_else(|_| EnvFilter::new("info"));
+
+ // Output target: file when configured, else stderr (tracing default).
+ let writer_file = cfg
+ .file
+ .as_deref()
+ .and_then(|p| {
+ let path = open_ontologies::config::expand_tilde(p);
+ if let Some(parent) = std::path::Path::new(&path).parent() {
+ let _ = std::fs::create_dir_all(parent);
+ }
+ std::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(&path)
+ .ok()
+ });
+
+ let format = cfg.format.trim().to_lowercase();
+ // Build and install. Use `try_init` so calling this from multiple
+ // subcommand handlers (or repeated test setups) is safe.
+ let result = match (format.as_str(), writer_file) {
+ ("json", Some(f)) => fmt()
+ .with_env_filter(env_filter)
+ .json()
+ .with_writer(std::sync::Mutex::new(f))
+ .try_init(),
+ ("json", None) => fmt()
+ .with_env_filter(env_filter)
+ .json()
+ .with_writer(std::io::stderr)
+ .try_init(),
+ ("pretty", Some(f)) => fmt()
+ .with_env_filter(env_filter)
+ .pretty()
+ .with_writer(std::sync::Mutex::new(f))
+ .try_init(),
+ ("pretty", None) => fmt()
+ .with_env_filter(env_filter)
+ .pretty()
+ .with_writer(std::io::stderr)
+ .try_init(),
+ (_, Some(f)) => fmt()
+ .with_env_filter(env_filter)
+ .compact()
+ .with_writer(std::sync::Mutex::new(f))
+ .try_init(),
+ (_, None) => fmt()
+ .with_env_filter(env_filter)
+ .compact()
+ .with_writer(std::io::stderr)
+ .try_init(),
+ };
+ let _ = result;
+}
+
/// Compose the effective tool filter from `[tools]` in config + CLI flags.
/// CLI `--tools-allow` / `--tools-deny` override `[tools]` when present.
fn build_tool_filter(
@@ -617,6 +754,12 @@ async fn main() -> anyhow::Result<()> {
}
}
};
+ // Initialise tracing (RUST_LOG > [logging] level > default).
+ init_tracing(&cfg.logging);
+ // Initialise runtime knobs (tableaux limits, fixpoint cap, hash
+ // prefix, feedback thresholds, repo / imports / webhook).
+ open_ontologies::runtime::init_from_config(&cfg);
+
let data_dir = expand_tilde(&cfg.general.data_dir);
let db_path = std::path::Path::new(&data_dir).join("open-ontologies.db");
@@ -625,12 +768,19 @@ async fn main() -> anyhow::Result<()> {
let graph = Arc::new(GraphStore::new());
- let _watch_handle = if watch {
+ // Monitor: CLI `--watch` forces enabled; otherwise fall back to
+ // `[monitor] enabled`. CLI `--watch-interval` > env > `[monitor]
+ // interval_secs` > default 30.
+ let monitor_enabled = watch || cfg.monitor.enabled;
+ let monitor_interval = watch_interval
+ .unwrap_or_else(|| open_ontologies::config::resolve_monitor_interval_secs(&cfg.monitor));
+
+ let _watch_handle = if monitor_enabled {
let watch_db = StateDb::open(&db_path)?;
Some(open_ontologies::monitor::start_background_loop(
watch_db,
graph.clone(),
- std::time::Duration::from_secs(watch_interval),
+ std::time::Duration::from_secs(monitor_interval),
))
} else {
None
@@ -676,6 +826,20 @@ async fn main() -> anyhow::Result<()> {
}
}
};
+ init_tracing(&cfg.logging);
+ open_ontologies::runtime::init_from_config(&cfg);
+
+ // Resolve effective host / port / token / stateful_mode honouring
+ // CLI > env > config > default precedence.
+ let host = host.unwrap_or_else(|| open_ontologies::config::resolve_http_host(&cfg.http));
+ let port = port.unwrap_or_else(|| open_ontologies::config::resolve_http_port(&cfg.http));
+ // Clap reads `OPEN_ONTOLOGIES_TOKEN` into `token` automatically
+ // (because of `env = "OPEN_ONTOLOGIES_TOKEN"`), so a non-`None`
+ // value already encompasses CLI + env. Fall back to config when
+ // neither is set.
+ let token = token
+ .or_else(|| open_ontologies::config::resolve_http_token(&cfg.http));
+
let data_dir = expand_tilde(&cfg.general.data_dir);
let db_path_owned = std::path::Path::new(&data_dir).join("open-ontologies.db");
@@ -687,12 +851,16 @@ async fn main() -> anyhow::Result<()> {
// Shared StateDb for lineage REST endpoint
let shared_db = StateDb::open(&db_path_owned)?;
- let _watch_handle = if watch {
+ let monitor_enabled = watch || cfg.monitor.enabled;
+ let monitor_interval = watch_interval
+ .unwrap_or_else(|| open_ontologies::config::resolve_monitor_interval_secs(&cfg.monitor));
+
+ let _watch_handle = if monitor_enabled {
let watch_db = StateDb::open(&db_path_owned)?;
Some(open_ontologies::monitor::start_background_loop(
watch_db,
shared_graph.clone(),
- std::time::Duration::from_secs(watch_interval),
+ std::time::Duration::from_secs(monitor_interval),
))
} else {
None
@@ -700,7 +868,7 @@ async fn main() -> anyhow::Result<()> {
let ct = CancellationToken::new();
let http_config = StreamableHttpServerConfig {
- stateful_mode: true,
+ stateful_mode: cfg.http.stateful_mode,
cancellation_token: ct.clone(),
..Default::default()
};
@@ -890,9 +1058,36 @@ async fn main() -> anyhow::Result<()> {
.await?;
}
- Commands::ServeUnix { socket, files } => {
+ Commands::ServeUnix { config: config_path, socket, files } => {
+ let config_path = expand_tilde(&config_path);
+ let cfg = match Config::load(std::path::Path::new(&config_path)) {
+ Ok(c) => c,
+ Err(e) => {
+ let msg = e.to_string();
+ if msg.contains("failed to read") {
+ Config::default()
+ } else {
+ return Err(e);
+ }
+ }
+ };
+ init_tracing(&cfg.logging);
+ open_ontologies::runtime::init_from_config(&cfg);
+
+ // CLI > [socket] path > legacy default
+ let socket_path = socket
+ .or_else(|| cfg.socket.path.clone())
+ .unwrap_or_else(|| "/tmp/tardygrada-ontology-complete.sock".to_string());
+
+ // CLI `--file` (when supplied) overrides `[socket] preload_files`.
+ let preload: Vec<String> = if !files.is_empty() {
+ files
+ } else {
+ cfg.socket.preload_files.clone()
+ };
+
let graph = Arc::new(GraphStore::new());
- for f in &files {
+ for f in &preload {
let path = open_ontologies::config::expand_tilde(f);
match graph.load_file(&path) {
Ok(n) => eprintln!("Loaded {path}: {n} triples"),
@@ -903,7 +1098,7 @@ async fn main() -> anyhow::Result<()> {
}
}
eprintln!("Graph has {} triples total", graph.triple_count());
- open_ontologies::socket::serve(&socket, graph).await?;
+ open_ontologies::socket::serve(&socket_path, graph).await?;
}
// ─── Batch ──────────────────────────────────────────────────
diff --git a/src/reason.rs b/src/reason.rs
index 50851685..47789984 100644
--- a/src/reason.rs
+++ b/src/reason.rs
@@ -425,7 +425,7 @@ impl Reasoner {
triple_set.insert(t);
}
- if triple_set.len() == before || iterations >= 50 {
+ if triple_set.len() == before || iterations >= crate::runtime::reasoner_max_iterations() {
break;
}
}
diff --git a/src/runtime.rs b/src/runtime.rs
new file mode 100644
index 00000000..70d16f38
--- /dev/null
+++ b/src/runtime.rs
@@ -0,0 +1,141 @@
+//! Runtime-tunable knobs derived from `Config`.
+//!
+//! Many internal modules (`tableaux`, `reason`, `cache`, `feedback`,
+//! `webhook`, `server::onto_repo_list`, `server::onto_import`) historically
+//! used `const` constants for safety/operational limits. To make them
+//! configurable from `config.toml` (and from environment variables for the
+//! most operationally critical ones) without threading a `&Config` through
+//! every call site, we mirror those constants into atomic globals here.
+//!
+//! `init_from_config` is invoked once at server startup. Each accessor falls
+//! back to the same default the original constant used, so callers that run
+//! before initialisation (e.g. CLI subcommands that don't load a config)
+//! observe the legacy behaviour.
+
+use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering};
+
+use crate::config::{
+ self, Config, FeedbackConfig, ImportsConfig, ReasonerConfig, RepoConfig, WebhookConfig,
+};
+
+// ── Defaults match the previous hardcoded constants exactly ─────────────
+const DEFAULT_TABLEAUX_MAX_DEPTH: usize = 100;
+const DEFAULT_TABLEAUX_MAX_NODES: usize = 10_000;
+// Original reason.rs used 50; section 3 of the audit recommends 64 as a
+// slightly more generous, explicitly-documented value. We adopt 64 as the
+// new default since neither value affects fixpoint correctness — they only
+// bound the maximum number of expansion sweeps.
+const DEFAULT_REASONER_MAX_ITER: usize = 64;
+const DEFAULT_CACHE_HASH_PREFIX: usize = 64 * 1024;
+const DEFAULT_FB_SUPPRESS: i64 = 3;
+const DEFAULT_FB_DOWNGRADE: i64 = 2;
+const DEFAULT_REPO_LIST_LIMIT: usize = 1000;
+const DEFAULT_IMPORTS_MAX_DEPTH: usize = 3;
+const DEFAULT_IMPORTS_TIMEOUT: u64 = 30;
+const DEFAULT_WEBHOOK_TIMEOUT: u64 = 10;
+
+static TABLEAUX_MAX_DEPTH: AtomicUsize = AtomicUsize::new(DEFAULT_TABLEAUX_MAX_DEPTH);
+static TABLEAUX_MAX_NODES: AtomicUsize = AtomicUsize::new(DEFAULT_TABLEAUX_MAX_NODES);
+static REASONER_MAX_ITER: AtomicUsize = AtomicUsize::new(DEFAULT_REASONER_MAX_ITER);
+static CACHE_HASH_PREFIX: AtomicUsize = AtomicUsize::new(DEFAULT_CACHE_HASH_PREFIX);
+static FB_SUPPRESS: AtomicI64 = AtomicI64::new(DEFAULT_FB_SUPPRESS);
+static FB_DOWNGRADE: AtomicI64 = AtomicI64::new(DEFAULT_FB_DOWNGRADE);
+static REPO_LIST_LIMIT: AtomicUsize = AtomicUsize::new(DEFAULT_REPO_LIST_LIMIT);
+static IMPORTS_MAX_DEPTH: AtomicUsize = AtomicUsize::new(DEFAULT_IMPORTS_MAX_DEPTH);
+static IMPORTS_TIMEOUT: AtomicU64 = AtomicU64::new(DEFAULT_IMPORTS_TIMEOUT);
+static IMPORTS_FOLLOW_REMOTE: AtomicBool = AtomicBool::new(true);
+static WEBHOOK_TIMEOUT: AtomicU64 = AtomicU64::new(DEFAULT_WEBHOOK_TIMEOUT);
+
+/// Initialise all runtime knobs from a loaded `Config`. Idempotent — calling
+/// this multiple times simply overwrites the current values, which is fine
+/// because all consumers re-read on every use.
+pub fn init_from_config(cfg: &Config) {
+ apply_reasoner(&cfg.reasoner);
+ apply_cache(cfg.cache.hash_prefix_bytes);
+ apply_feedback(&cfg.feedback);
+ apply_repo(&cfg.repo);
+ apply_imports(&cfg.imports);
+ apply_webhook(&cfg.webhook);
+}
+
+fn apply_reasoner(r: &ReasonerConfig) {
+ let depth = if r.tableaux_max_depth == 0 { DEFAULT_TABLEAUX_MAX_DEPTH } else { r.tableaux_max_depth };
+ let nodes = if r.tableaux_max_nodes == 0 { DEFAULT_TABLEAUX_MAX_NODES } else { r.tableaux_max_nodes };
+ let iters = if r.max_iterations == 0 { DEFAULT_REASONER_MAX_ITER } else { r.max_iterations };
+ TABLEAUX_MAX_DEPTH.store(depth, Ordering::Relaxed);
+ TABLEAUX_MAX_NODES.store(nodes, Ordering::Relaxed);
+ REASONER_MAX_ITER.store(iters, Ordering::Relaxed);
+}
+
+fn apply_cache(hash_prefix: usize) {
+ let v = if hash_prefix == 0 { DEFAULT_CACHE_HASH_PREFIX } else { hash_prefix };
+ CACHE_HASH_PREFIX.store(v, Ordering::Relaxed);
+}
+
+fn apply_feedback(f: &FeedbackConfig) {
+ FB_SUPPRESS.store(f.suppress_threshold, Ordering::Relaxed);
+ FB_DOWNGRADE.store(f.downgrade_threshold, Ordering::Relaxed);
+}
+
+fn apply_repo(r: &RepoConfig) {
+ let v = if r.default_list_limit == 0 { DEFAULT_REPO_LIST_LIMIT } else { r.default_list_limit };
+ REPO_LIST_LIMIT.store(v, Ordering::Relaxed);
+}
+
+fn apply_imports(i: &ImportsConfig) {
+ let depth = if i.max_depth == 0 { DEFAULT_IMPORTS_MAX_DEPTH } else { i.max_depth };
+ IMPORTS_MAX_DEPTH.store(depth, Ordering::Relaxed);
+ IMPORTS_TIMEOUT.store(config::resolve_imports_timeout_secs(i), Ordering::Relaxed);
+ IMPORTS_FOLLOW_REMOTE.store(i.follow_remote, Ordering::Relaxed);
+}
+
+fn apply_webhook(w: &WebhookConfig) {
+ WEBHOOK_TIMEOUT.store(config::resolve_webhook_timeout_secs(w), Ordering::Relaxed);
+}
+
+// ── Accessors ───────────────────────────────────────────────────────────
+
+pub fn tableaux_max_depth() -> usize { TABLEAUX_MAX_DEPTH.load(Ordering::Relaxed) }
+pub fn tableaux_max_nodes() -> usize { TABLEAUX_MAX_NODES.load(Ordering::Relaxed) }
+pub fn reasoner_max_iterations() -> usize { REASONER_MAX_ITER.load(Ordering::Relaxed) }
+pub fn cache_hash_prefix_bytes() -> usize { CACHE_HASH_PREFIX.load(Ordering::Relaxed) }
+pub fn feedback_suppress_threshold() -> i64 { FB_SUPPRESS.load(Ordering::Relaxed) }
+pub fn feedback_downgrade_threshold() -> i64 { FB_DOWNGRADE.load(Ordering::Relaxed) }
+pub fn repo_default_list_limit() -> usize { REPO_LIST_LIMIT.load(Ordering::Relaxed) }
+pub fn imports_max_depth() -> usize { IMPORTS_MAX_DEPTH.load(Ordering::Relaxed) }
+pub fn imports_request_timeout_secs() -> u64 { IMPORTS_TIMEOUT.load(Ordering::Relaxed) }
+pub fn imports_follow_remote() -> bool { IMPORTS_FOLLOW_REMOTE.load(Ordering::Relaxed) }
+pub fn webhook_request_timeout_secs() -> u64 { WEBHOOK_TIMEOUT.load(Ordering::Relaxed) }
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn defaults_match_legacy_constants() {
+ // Without calling init_from_config the accessors return the
+ // original hardcoded defaults.
+ assert_eq!(tableaux_max_depth(), 100);
+ assert_eq!(tableaux_max_nodes(), 10_000);
+ assert_eq!(cache_hash_prefix_bytes(), 64 * 1024);
+ assert_eq!(repo_default_list_limit(), 1000);
+ assert_eq!(imports_max_depth(), 3);
+ assert!(imports_follow_remote());
+ }
+
+ #[test]
+ fn init_overrides_values() {
+ let mut cfg = Config::default();
+ cfg.reasoner.tableaux_max_depth = 250;
+ cfg.cache.hash_prefix_bytes = 128 * 1024;
+ cfg.imports.follow_remote = false;
+ init_from_config(&cfg);
+ assert_eq!(tableaux_max_depth(), 250);
+ assert_eq!(cache_hash_prefix_bytes(), 128 * 1024);
+ assert!(!imports_follow_remote());
+
+ // Restore defaults so subsequent tests in the same process aren't
+ // affected.
+ init_from_config(&Config::default());
+ }
+}
diff --git a/src/server.rs b/src/server.rs
index d3bce61d..b2c04876 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -292,7 +292,7 @@ impl OpenOntologiesServer {
return r#"{"error":"no ontology_dirs configured; set [general] ontology_dirs in config.toml or OPEN_ONTOLOGIES_ONTOLOGY_DIRS"}"#.to_string();
}
let recursive = input.recursive.unwrap_or(false);
- let limit = input.limit.unwrap_or(1000);
+ let limit = input.limit.unwrap_or_else(crate::runtime::repo_default_list_limit);
let offset = input.offset.unwrap_or(0);
let entries = if let Some(dir) = input.dir.as_deref() {
@@ -600,10 +600,40 @@ impl OpenOntologiesServer {
#[tool(name = "onto_import", description = "Resolve and load all owl:imports from the currently loaded ontology")]
async fn onto_import(&self, Parameters(input): Parameters<OntoImportInput>) -> String {
use crate::graph::GraphStore;
- let max_depth = input.max_depth.unwrap_or(3);
+ let max_depth = input
+ .max_depth
+ .unwrap_or_else(crate::runtime::imports_max_depth);
+ let timeout_secs = crate::runtime::imports_request_timeout_secs();
+ let follow_remote = crate::runtime::imports_follow_remote();
let mut imported = Vec::new();
let mut to_import: Vec<String> = Vec::new();
+ // Build a per-call HTTP client honouring the configured timeout.
+ // Falls back to the bare `fetch_url` helper if construction fails.
+ let timed_client = if timeout_secs > 0 {
+ reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(timeout_secs))
+ .build()
+ .ok()
+ } else {
+ None
+ };
+
+ let fetch = |url: String| {
+ let client = timed_client.clone();
+ async move {
+ if let Some(c) = client {
+ let resp = c.get(&url).send().await?;
+ if !resp.status().is_success() {
+ anyhow::bail!("HTTP {}: {}", resp.status(), url);
+ }
+ Ok::<String, anyhow::Error>(resp.text().await?)
+ } else {
+ GraphStore::fetch_url(&url).await
+ }
+ }
+ };
+
let query = "SELECT ?import WHERE { ?onto <http://www.w3.org/2002/07/owl#imports> ?import }";
if let Ok(result) = self.graph.sparql_select(query)
&& let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&result)
@@ -621,7 +651,15 @@ impl OpenOntologiesServer {
let batch = std::mem::take(&mut to_import);
for url in batch {
if imported.contains(&url) { continue; }
- match GraphStore::fetch_url(&url).await {
+ // Honour the `[imports] follow_remote` policy: in
+ // air-gapped or sandboxed deployments, refuse to fetch
+ // http(s):// imports rather than attempting them.
+ let is_remote = url.starts_with("http://") || url.starts_with("https://");
+ if is_remote && !follow_remote {
+ imported.push(format!("SKIPPED:{}: remote imports disabled by [imports] follow_remote=false", url));
+ continue;
+ }
+ match fetch(url.clone()).await {
Ok(content) => {
match self.graph.load_turtle(&content, None) {
Ok(_count) => {
diff --git a/src/tableaux.rs b/src/tableaux.rs
index deb78fbf..6d1140c2 100644
--- a/src/tableaux.rs
+++ b/src/tableaux.rs
@@ -72,8 +72,8 @@ const OWL_MIN_QCARD: &str = "<http://www.w3.org/2002/07/owl#minQualifiedCardinal
const OWL_MAX_QCARD: &str = "<http://www.w3.org/2002/07/owl#maxQualifiedCardinality>";
const OWL_ON_CLASS: &str = "<http://www.w3.org/2002/07/owl#onClass>";
-const MAX_DEPTH: usize = 100;
-const MAX_NODES: usize = 10_000;
+// Tableaux safety limits live in `crate::runtime` (initialised from
+// `[reasoner] tableaux_max_depth` / `tableaux_max_nodes` in config.toml).
// ── Concept (Negation Normal Form) ──────────────────────────────────────
@@ -1013,7 +1013,9 @@ impl Tableau {
/// Main expansion with backtracking for disjunctions and MaxCard merging.
fn expand(&mut self, depth: usize) -> bool {
- if depth > MAX_DEPTH || self.nodes.len() > MAX_NODES {
+ let max_depth = crate::runtime::tableaux_max_depth();
+ let max_nodes = crate::runtime::tableaux_max_nodes();
+ if depth > max_depth || self.nodes.len() > max_nodes {
return false;
}
diff --git a/src/webhook.rs b/src/webhook.rs
index b7725537..ce173c45 100644
--- a/src/webhook.rs
+++ b/src/webhook.rs
@@ -1,13 +1,15 @@
use std::time::Duration;
-/// Fire-and-forget webhook delivery with 10s timeout.
+/// Fire-and-forget webhook delivery. Timeout is configurable via
+/// `[webhook] request_timeout_secs` (default 10s).
pub async fn deliver_webhook(
url: &str,
headers_json: Option<&str>,
payload: &serde_json::Value,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
+ let timeout_secs = crate::runtime::webhook_request_timeout_secs();
let client = reqwest::Client::builder()
- .timeout(Duration::from_secs(10))
+ .timeout(Duration::from_secs(timeout_secs))
.build()?;
let mut req = client.post(url).json(payload);
if let Some(hdr_json) = headers_json
diff --git a/tests/cache_management_test.rs b/tests/cache_management_test.rs
index 43cfab3f..cc3f14cf 100644
--- a/tests/cache_management_test.rs
+++ b/tests/cache_management_test.rs
@@ -67,6 +67,7 @@ fn setup() -> TestHarness {
idle_ttl_secs: 0,
evictor_interval_secs: 30,
auto_refresh: false,
+ hash_prefix_bytes: 64 * 1024,
};
let registry = Arc::new(OntologyRegistry::new(graph.clone(), db, cfg).unwrap());
TestHarness { _tmp: tmp, path_a, path_b, registry, graph }
@@ -133,6 +134,7 @@ fn list_cached_marks_in_memory_false_after_eviction() {
idle_ttl_secs: 1,
evictor_interval_secs: 30,
auto_refresh: false,
+ hash_prefix_bytes: 64 * 1024,
};
let reg = OntologyRegistry::new(graph, db, cfg).unwrap();
reg.load_file(path.to_str().unwrap(), LoadOptions::default()).unwrap();
diff --git a/tests/registry_test.rs b/tests/registry_test.rs
index 7b973417..f4ea599d 100644
--- a/tests/registry_test.rs
+++ b/tests/registry_test.rs
@@ -75,6 +75,7 @@ fn setup(idle_ttl_secs: u64) -> Harness {
idle_ttl_secs,
evictor_interval_secs: 1,
auto_refresh: false,
+ hash_prefix_bytes: 64 * 1024,
};
let registry = Arc::new(OntologyRegistry::new(graph.clone(), db, cfg).unwrap());
Harness {
@@ -194,6 +195,7 @@ fn cache_disabled_skips_ondisk_cache() {
idle_ttl_secs: 0,
evictor_interval_secs: 30,
auto_refresh: false,
+ hash_prefix_bytes: 64 * 1024,
};
let registry = OntologyRegistry::new(graph, db, cfg).unwrap();
let r = registry
diff --git a/tests/repo_test.rs b/tests/repo_test.rs
index 1e6f8560..72459025 100644
--- a/tests/repo_test.rs
+++ b/tests/repo_test.rs
@@ -151,6 +151,7 @@ fn registry_loads_path_resolved_from_repo() {
idle_ttl_secs: 0,
evictor_interval_secs: 30,
auto_refresh: false,
+ hash_prefix_bytes: 64 * 1024,
};
let registry = Arc::new(OntologyRegistry::new(graph.clone(), db, cfg).unwrap());
diff --git a/tests/toolfilter_test.rs b/tests/toolfilter_test.rs
index d203a8af..4ff3d8cd 100644
--- a/tests/toolfilter_test.rs
+++ b/tests/toolfilter_test.rs
@@ -26,6 +26,7 @@ fn build_server(filter: ToolFilter) -> (tempfile::TempDir, OpenOntologiesServer)
idle_ttl_secs: 0,
evictor_interval_secs: 30,
auto_refresh: false,
+ hash_prefix_bytes: 64 * 1024,
};
let server = OpenOntologiesServer::new_with_registry_options(
db,