Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/settings-store-selection-refusal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
---

fix(settings): a rejected document no longer swaps the event store

`nostream_config::load` discards the whole user document on any finding and returns the shipped
defaults, and the daemon's gate continued on them. Because the shipped `eventStore.backend` is
`postgres`, one bad field anywhere in `settings.yaml` made an LMDB deployment serve and write into
the old Postgres store while its data directory sat unused.

`LoadOutcome` now records the store the discarded document selected
(`discarded_store_selection`), and the gate refuses to start when the substitution would override
it: a different `eventStore.backend`, or a fault at `eventStore` or below, prints one refusal line
naming the path, the value and the backend that would have served, then exits 2 before any store
is opened. `--check` output is byte-identical; a document that names no store, names the backend
that will serve, or cannot be parsed keeps continue-on-defaults. ADR 0022 records the rule, the
fields that are safe to default, and the unparseable-document limitation. Rust only: no published
package changes, so this entry carries no version bump.
5 changes: 4 additions & 1 deletion crates/nostream-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ pub mod value;

pub use error::ConfigError;
pub use issue::Issue;
pub use load::{LoadOutcome, fit, load, load_defaults, load_document, load_user_settings, merge};
pub use load::{
DiscardedStoreSelection, LoadOutcome, fit, load, load_defaults, load_document,
load_user_settings, merge,
};
pub use paths::SettingsPaths;
pub use settings::Settings;
pub use validate::{validate, validate_document};
73 changes: 68 additions & 5 deletions crates/nostream-config/src/load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
//! The fallback rule is the capture's: a user configuration that cannot be read or does not
//! validate never aborts the process. It is reported as [`Issue`] values and the caller gets
//! the shipped defaults, so a broken `settings.yaml` cannot stop a relay from starting.
//!
//! `load` itself never refuses. On a rejection it also records what store the discarded
//! document selected ([`LoadOutcome::discarded_store_selection`]), so the daemon's gate can
//! refuse a substitution that would override it (ADR 0022).

use std::fs;
use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -375,6 +379,18 @@ fn find_misfit(schema: &Value, candidate: &Value, path: &mut Vec<PathToken>) ->
}
}

/// A store selection the rejected user document made, so the daemon can refuse a
/// substitution that would override it (ADR 0022).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscardedStoreSelection {
/// The dotted path the document set: `eventStore.backend`, or the refused path at
/// `eventStore` or below it.
pub path: String,
/// The scalar at that path rendered as YAML text; `None` when the value there is not a
/// scalar.
pub value: Option<String>,
}

/// The result of loading the effective settings.
#[derive(Debug, Clone)]
pub struct LoadOutcome {
Expand All @@ -384,6 +400,12 @@ pub struct LoadOutcome {
pub issues: Vec<Issue>,
/// Whether the user's document was rejected and the defaults were substituted.
pub used_defaults: bool,
/// What the rejected document selected for the event store, when it selected one.
///
/// `None` on a clean load, when the document names no `eventStore` key, and on the
/// unreadable arm, which has no document to read. It never alters `settings`, `issues`
/// or `used_defaults`.
pub discarded_store_selection: Option<DiscardedStoreSelection>,
}

/// Loads and validates the effective settings, falling back to the defaults on any failure.
Expand All @@ -402,6 +424,7 @@ pub fn load(paths: &SettingsPaths) -> Result<LoadOutcome, ConfigError> {
format!("failed to load user settings: {error}"),
)],
used_defaults: true,
discarded_store_selection: None,
});
}
};
Expand All @@ -411,16 +434,19 @@ pub fn load(paths: &SettingsPaths) -> Result<LoadOutcome, ConfigError> {
settings: defaults_settings,
issues: Vec::new(),
used_defaults: false,
discarded_store_selection: None,
});
};

let merged = merge(&defaults, &user);
let issues = validate_document(&merged, &defaults);
if !issues.is_empty() {
let discarded_store_selection = discarded_store_selection(&user, &issues);
return Ok(LoadOutcome {
settings: defaults_settings,
issues,
used_defaults: true,
discarded_store_selection,
});
}

Expand All @@ -429,12 +455,49 @@ pub fn load(paths: &SettingsPaths) -> Result<LoadOutcome, ConfigError> {
settings,
issues,
used_defaults: false,
discarded_store_selection: None,
}),
Err(issue) => Ok(LoadOutcome {
settings: defaults_settings,
issues: vec![issue],
used_defaults: true,
}),
Err(issue) => {
let discarded_store_selection =
discarded_store_selection(&user, std::slice::from_ref(&issue));
Ok(LoadOutcome {
settings: defaults_settings,
issues: vec![issue],
used_defaults: true,
discarded_store_selection,
})
}
}
}

/// Records the store the rejected document selected: `eventStore.backend` when the document
/// states it, otherwise the first refused path at `eventStore` or below it.
fn discarded_store_selection(
document: &Value,
issues: &[Issue],
) -> Option<DiscardedStoreSelection> {
if let Some(value) = lookup(document, "eventStore.backend") {
return Some(DiscardedStoreSelection {
path: "eventStore.backend".to_owned(),
value: yaml_scalar(value),
});
}
let issue = issues
.iter()
.find(|issue| issue.path == "eventStore" || issue.path.starts_with("eventStore."))?;
Some(DiscardedStoreSelection {
path: issue.path.clone(),
value: lookup(document, &issue.path).and_then(yaml_scalar),
})
}

/// Renders a YAML scalar as its text; a mapping, sequence or tagged value is not a scalar.
fn yaml_scalar(value: &Value) -> Option<String> {
match value {
Value::Mapping(_) | Value::Sequence(_) | Value::Tagged(_) => None,
scalar => serde_yaml::to_string(scalar)
.ok()
.map(|text| text.trim_end().to_owned()),
}
}

Expand Down
44 changes: 40 additions & 4 deletions crates/nostreamd/src/settings_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,27 @@
//!
//! A user configuration that cannot be read or does not validate never aborts the process:
//! `nostream_config::load` substitutes the shipped defaults and reports the findings. The
//! serve path logs every finding and continues on the defaults; `--check` is the one place
//! findings are fatal (exit 2), because its whole job is to report them.
//! serve path logs every finding and continues on the defaults, with one exception: when the
//! rejected document selected an event store the substitution would override, the gate
//! refuses to start (exit 2, ADR 0022) before any store is opened. `--check` reports the
//! findings as fatal (exit 2) whether or not a selection was discarded, because its whole job
//! is to report them.
//!
//! This module is also the workspace's one library-position writer to stdout/stderr *outside
//! the `tracing` subscriber*: every other write a library crate makes goes through `tracing`
//! and `telemetry::init`'s `tracing_subscriber::fmt()` layer (whose writer the mode chooses —
//! stdout for the relay path, stderr for `--mcp-stdio` — and whose output the `EnvFilter`
//! governs). These three bypass that filter, so the rule that
//! governs). These writes bypass that filter, so the rule that
//! keeps them honest is worth stating: output belongs to a process's entry point, and a
//! library that writes to a stream the caller does not drain can block it — a per-record
//! write stalls a whole subscription behind a full pipe. These writes are the operator report
//! of a single settings check, reached once from `run` before the relay exists, every one of
//! them newline-terminated (so each flushes per write). Nothing added here may run per
//! request, per message or per streamed record.

use nostream_config::LoadOutcome;
use nostream_config::{DiscardedStoreSelection, LoadOutcome};
use nostream_core::EventStoreBackend;
use nostream_storage::event_store::configured_backend;

use crate::error::DaemonError;

Expand All @@ -38,9 +43,40 @@ pub fn apply_settings_gate(outcome: &LoadOutcome, check: bool) -> Result<(), Dae
count: outcome.issues.len(),
});
}
if let Some(selection) = &outcome.discarded_store_selection {
let backend = configured_backend(&outcome.settings);
if !keeps_backend(selection, backend) {
match &selection.value {
Some(value) => eprintln!(
"nostreamd: refusing to start: the rejected settings document sets {}={value}; the shipped defaults would serve {backend}",
selection.path
),
None => eprintln!(
"nostreamd: refusing to start: the rejected settings document sets {}; the shipped defaults would serve {backend}",
selection.path
),
}
return Err(DaemonError::InvalidSettings {
count: outcome.issues.len(),
});
}
}
eprintln!(
"nostreamd: continuing on the shipped defaults ({} issue(s) in the user settings)",
outcome.issues.len()
);
Ok(())
}

/// Whether the substitution keeps the store backend the discarded document selected.
///
/// Only an explicit `eventStore.backend` naming the backend that will serve can continue; a
/// refused subtree, a value outside the accepted spellings and a different backend all refuse.
fn keeps_backend(selection: &DiscardedStoreSelection, backend: EventStoreBackend) -> bool {
selection.path == "eventStore.backend"
&& selection
.value
.as_deref()
.and_then(EventStoreBackend::parse)
== Some(backend)
}
27 changes: 27 additions & 0 deletions crates/nostreamd/tests/check_flag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,3 +310,30 @@ fn check_reports_nothing_for_the_shipped_defaults() {
assert_eq!(stdout.trim(), "settings valid: 0 issues");
assert_eq!(stderr, "", "the shipped defaults are not a violation");
}

#[test]
fn check_exits_two_on_a_rejected_document_that_selected_lmdb() {
// A discarded store selection refuses the serve path (ADR 0022), but `--check` reported the
// same document before the rule existed: its verdict, its two stderr lines and its empty
// stdout are byte-identical, with no refusal line.
let directory = tempfile::tempdir().expect("tempdir");
std::fs::write(
directory.path().join("settings.yaml"),
"eventStore:\n backend: lmdb\nlimits:\n rateLimiter:\n strategy: random\n",
)
.expect("write");

let config_dir = directory.path().to_string_lossy().into_owned();
let (code, stdout, stderr) = run_check(
Duration::from_secs(30),
&["--check", "--config-dir", &config_dir],
);
assert_eq!(code, Some(2), "exit code");
assert!(stdout.is_empty(), "nothing on stdout: {stdout:?}");
assert_eq!(
stderr.trim(),
"limits.rateLimiter.strategy: strategy must be ewma or sliding_window\n\
settings invalid: 1 issues",
"the check path is byte-identical and prints no refusal"
);
}
108 changes: 108 additions & 0 deletions crates/nostreamd/tests/settings_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,111 @@ fn a_clean_document_passes_the_gate_both_ways() {
assert!(outcome.issues.is_empty());
nostreamd::settings_gate::apply_settings_gate(&outcome, true).expect("check passes");
}

/// Loads one `settings.yaml` body into an outcome, the way the daemon's `run` sees it.
fn load_body(body: &str) -> nostream_config::LoadOutcome {
let directory = tempfile::tempdir().expect("tempdir");
fs::write(directory.path().join("settings.yaml"), body).expect("write");
let paths = SettingsPaths::from_config_dir(&workspace_root(), directory.path());
nostream_config::load(&paths).expect("the loader never refuses")
}

#[test]
fn a_rejected_document_that_selected_lmdb_refuses_the_serve_path() {
// The document names the store the deployment runs on and carries one bad field, so the
// substitution would swap LMDB for the shipped Postgres. The gate must refuse it rather
// than serve a store nobody selected (ADR 0022, #1305).
let outcome =
load_body("eventStore:\n backend: lmdb\nlimits:\n rateLimiter:\n strategy: random\n");

assert!(outcome.used_defaults, "the defaults substitute");
let error = nostreamd::settings_gate::apply_settings_gate(&outcome, false)
.expect_err("a discarded lmdb selection refuses the serve path");
assert!(matches!(
error,
nostreamd::DaemonError::InvalidSettings { count: 1 }
));
}

#[test]
fn a_rejected_document_that_keeps_postgres_continues() {
// The substitution keeps the backend the document named, so it is a no-op selection and
// the serve path continues as it always has (ADR 0022's equality arm).
let outcome = load_body(
"eventStore:\n backend: postgres\nlimits:\n rateLimiter:\n strategy: random\n",
);

assert!(outcome.used_defaults, "the defaults substitute");
nostreamd::settings_gate::apply_settings_gate(&outcome, false).expect("serve continues");
assert_eq!(
nostream_storage::event_store::configured_backend(&outcome.settings),
nostream_core::EventStoreBackend::Postgres,
"the shipped backend is the one the document named"
);
}

#[test]
fn a_document_that_cannot_be_parsed_still_serves_on_the_defaults() {
// A document that does not parse has no readable selection, so the deliberate limitation
// stands: it is reported and the daemon serves the shipped defaults (ADR 0022, D5).
let outcome = load_body("eventStore: [\n");

assert!(outcome.used_defaults, "the defaults substitute");
assert_eq!(outcome.issues[0].path, "$", "the whole document failed");
assert!(
outcome.discarded_store_selection.is_none(),
"there is no document to read a selection from"
);
nostreamd::settings_gate::apply_settings_gate(&outcome, false).expect("serve continues");
}

#[test]
fn a_document_that_fails_the_typed_fit_still_refuses_a_discarded_lmdb_selection() {
// `fit` rejects the document after the shape walk approves it, so the selection must be
// recorded on that arm too: otherwise the fit path silently swaps the store (ADR 0022).
let outcome = load_body(
"eventStore:\n backend: lmdb\nlimits:\n event:\n pow:\n periodMs: 1000.5\n",
);

assert!(outcome.used_defaults, "the defaults substitute");
assert_eq!(
outcome
.issues
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>(),
["limits.event.pow.periodMs: must be a whole number"],
"the walk approves the document and the fit names the number"
);
let error = nostreamd::settings_gate::apply_settings_gate(&outcome, false)
.expect_err("the fit arm keeps the discarded selection");
assert!(matches!(
error,
nostreamd::DaemonError::InvalidSettings { count: 1 }
));
}

#[test]
fn the_discarded_selection_names_only_a_selection_the_document_made() {
// The merged document always holds `eventStore.backend: postgres`; the report must hold
// what the operator's file said, so a document that names no store reports `None`.
let without_store = load_body("limits:\n rateLimiter:\n strategy: random\n");
assert!(
without_store.discarded_store_selection.is_none(),
"a document with no eventStore key named no store"
);
nostreamd::settings_gate::apply_settings_gate(&without_store, false).expect("serve continues");

let with_store =
load_body("eventStore:\n backend: lmdb\nlimits:\n rateLimiter:\n strategy: random\n");
let selection = with_store
.discarded_store_selection
.as_ref()
.expect("the document selected a store");
assert_eq!(selection.path, "eventStore.backend");
assert_eq!(selection.value.as_deref(), Some("lmdb"));
assert!(
nostreamd::settings_gate::apply_settings_gate(&with_store, false).is_err(),
"the discarded selection refuses the serve path"
);
}
Loading
Loading