flexpool-sim 0.2.0

flexpool replay: bitemporal series with decision-time views, synthetic and imported market days, scenarios and a forward-only test clock. No I/O, no real clock.
Documentation
//! Scenario files: one small TOML file that drives the demo, a test or a bug report.
//!
//! ```toml
//! name = "demo"
//! day  = "2025-10-02"
//! [market]
//! source = "synthetic"   # or "file"
//! seed   = 7
//! [clock]
//! start = "2025-10-01T10:00:00+02:00"   # optional; default 10:00 Berlin on the day before
//! [[fault]]                               # optional, any number: disturb one asset
//! asset = "bess-hamburg-1"
//! kind  = "offline"                       # or "stuck"
//! from  = "2025-10-02T12:00:00+02:00"
//! to    = "2025-10-02T13:00:00+02:00"
//! ```
//!
//! Whether a fault's asset exists is checked against the portfolio by the caller.

use std::path::PathBuf;

use flexpool_core::{AssetId, BusinessDay};
use flexpool_telemetry::sim::{Fault, FaultKind};
use serde::Deserialize;
use time::format_description::well_known::Rfc3339;
use time::{Date, OffsetDateTime};

/// Where the scenario's market data comes from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MarketSource {
    /// The deterministic synthetic generator.
    Synthetic {
        /// Seed.
        seed: u64,
        /// Earlier days generated as history (forecasting), each known from its own publication.
        history_days: u16,
    },
    /// A CSV data file, relative to the scenario file.
    File {
        /// Path as written in the scenario.
        path: PathBuf,
    },
}

/// Earlier synthetic days generated by default (the forecast models' 28-day window).
pub const DEFAULT_HISTORY_DAYS: u16 = 28;
/// At most this many earlier days.
pub const MAX_HISTORY_DAYS: u16 = 60;

/// A validated scenario.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Scenario {
    /// Name.
    pub name: String,
    /// The delivery (business) day replayed.
    pub day: Date,
    /// Market data source.
    pub market: MarketSource,
    /// Where the clock starts.
    pub start: OffsetDateTime,
    /// Where the clock stops.
    pub end: OffsetDateTime,
    /// Planned disturbances of assets, in file order.
    pub faults: Vec<Fault>,
}

/// One problem with a scenario file.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{location}: {message}")]
pub struct ScenarioProblem {
    /// Key or `(file)`.
    pub location: String,
    /// What is wrong.
    pub message: String,
}

#[derive(Deserialize)]
struct Raw {
    name: Option<String>,
    day: Option<toml::Value>,
    market: Option<RawMarket>,
    clock: Option<RawClock>,
    fault: Option<Vec<RawFault>>,
}

#[derive(Deserialize)]
struct RawFault {
    asset: Option<String>,
    kind: Option<String>,
    from: Option<String>,
    to: Option<String>,
}

#[derive(Deserialize)]
struct RawMarket {
    source: Option<String>,
    seed: Option<u64>,
    file: Option<String>,
    history_days: Option<i64>,
}

#[derive(Deserialize)]
struct RawClock {
    start: Option<String>,
    end: Option<String>,
}

const KNOWN: &[(&str, &[&str])] = &[
    ("", &["name", "day", "market", "clock", "fault"]),
    ("market", &["source", "seed", "file", "history_days"]),
    ("clock", &["start", "end"]),
];

/// Every key the format does not know, reported alongside the other problems.
fn unknown_keys(table: &toml::Table) -> Vec<ScenarioProblem> {
    let mut out = Vec::new();
    for (section, keys) in KNOWN {
        let t = if section.is_empty() {
            Some(table)
        } else {
            table.get(*section).and_then(toml::Value::as_table)
        };
        for key in t.into_iter().flat_map(toml::Table::keys) {
            if !keys.contains(&key.as_str()) {
                let location = if section.is_empty() {
                    key.clone()
                } else {
                    format!("{section}.{key}")
                };
                out.push(problem(&location, "unknown key"));
            }
        }
    }
    let faults = table.get("fault").and_then(toml::Value::as_array);
    for (i, f) in faults.into_iter().flatten().enumerate() {
        for key in f.as_table().into_iter().flat_map(toml::Table::keys) {
            if !["asset", "kind", "from", "to"].contains(&key.as_str()) {
                out.push(problem(&format!("fault[{}].{key}", i + 1), "unknown key"));
            }
        }
    }
    out
}

fn faults(raw: Vec<RawFault>, problems: &mut Vec<ScenarioProblem>) -> Vec<Fault> {
    let mut out = Vec::new();
    for (i, f) in raw.into_iter().enumerate() {
        let at = |k: &str| format!("fault[{}].{k}", i + 1);
        let asset = match f.asset.map(AssetId::parse) {
            Some(Ok(id)) => Some(id),
            Some(Err(e)) => {
                problems.push(problem(&at("asset"), e.to_string()));
                None
            }
            None => {
                problems.push(problem(&at("asset"), "required"));
                None
            }
        };
        let kind = match f.kind.as_deref() {
            Some("offline") => Some(FaultKind::Offline),
            Some("stuck") => Some(FaultKind::Stuck),
            Some("tripped") => Some(FaultKind::Tripped),
            Some(other) => {
                problems.push(problem(
                    &at("kind"),
                    format!("{other:?} must be \"offline\", \"stuck\" or \"tripped\""),
                ));
                None
            }
            None => {
                problems.push(problem(
                    &at("kind"),
                    "required: \"offline\", \"stuck\" or \"tripped\"",
                ));
                None
            }
        };
        let mut when = |k: &str, v: Option<String>| match v {
            Some(s) => instant(&at(k), &s, problems),
            None => {
                problems.push(problem(&at(k), "required"));
                None
            }
        };
        let (from, to) = (when("from", f.from), when("to", f.to));
        if let (Some(from), Some(to)) = (from, to)
            && to <= from
        {
            problems.push(problem(&at("to"), "must be after from"));
            continue;
        }
        if let (Some(asset), Some(kind), Some(from), Some(to)) = (asset, kind, from, to) {
            out.push(Fault {
                asset,
                kind,
                from: from.unix_timestamp(),
                to: to.unix_timestamp(),
            });
        }
    }
    out
}

/// The data file a scenario names, read best-effort so its problems can be reported even when
/// other fields are invalid.
#[must_use]
pub fn data_file(text: &str) -> Option<PathBuf> {
    let table: toml::Table = text.parse().ok()?;
    let market = table.get("market")?.as_table()?;
    (market.get("source")?.as_str()? == "file")
        .then(|| market.get("file")?.as_str().map(PathBuf::from))?
}

fn problem(location: &str, message: impl Into<String>) -> ScenarioProblem {
    ScenarioProblem {
        location: location.to_owned(),
        message: message.into(),
    }
}

fn instant(location: &str, s: &str, problems: &mut Vec<ScenarioProblem>) -> Option<OffsetDateTime> {
    match OffsetDateTime::parse(s, &Rfc3339) {
        Ok(t) => Some(t.to_offset(time::UtcOffset::UTC)),
        Err(_) => {
            problems.push(problem(
                location,
                format!("{s:?} is not an RFC 3339 instant like 2025-10-01T10:00:00+02:00"),
            ));
            None
        }
    }
}

impl Scenario {
    /// Parses scenario TOML, collecting every problem. File existence is the caller's concern.
    ///
    /// # Errors
    /// Every problem, each with its key.
    pub fn parse(text: &str) -> Result<Self, Vec<ScenarioProblem>> {
        let table: toml::Table = text.parse().map_err(|e: toml::de::Error| {
            let at = e.span().map_or_else(
                || "(file)".into(),
                |s| format!("(file) at byte {}", s.start),
            );
            vec![problem(&at, e.message())]
        })?;
        // Unknown keys are problems like any other, not an abort: every problem in one run.
        let mut problems = unknown_keys(&table);
        let raw: Raw = match toml::Value::Table(table).try_into() {
            Ok(raw) => raw,
            Err(e) => {
                problems.push(problem("(file)", e.message()));
                return Err(problems);
            }
        };
        let name = raw.name.unwrap_or_else(|| {
            problems.push(problem("name", "required"));
            String::new()
        });
        let date_fmt = time::macros::format_description!("[year]-[month]-[day]");
        let day = match raw.day {
            None => {
                problems.push(problem("day", "required, e.g. day = \"2025-10-02\""));
                None
            }
            Some(toml::Value::Datetime(d)) => {
                Date::parse(&d.to_string(), date_fmt).ok().or_else(|| {
                    problems.push(problem("day", format!("{d} is not a calendar date")));
                    None
                })
            }
            Some(toml::Value::String(s)) => Date::parse(&s, date_fmt).ok().or_else(|| {
                problems.push(problem(
                    "day",
                    format!("{s:?} is not a date like 2025-10-02"),
                ));
                None
            }),
            Some(other) => {
                problems.push(problem("day", format!("{other} is not a date")));
                None
            }
        };
        let business = day.and_then(|d| match BusinessDay::new(d) {
            Ok(b) => Some(b),
            Err(e) => {
                problems.push(problem("day", e.to_string()));
                None
            }
        });
        let market = match raw.market {
            None => {
                problems.push(problem(
                    "market",
                    "required: [market] source = \"synthetic\" or \"file\"",
                ));
                None
            }
            Some(m) => match (m.source.as_deref(), m.seed, m.file) {
                (Some("synthetic"), Some(seed), None) => match m.history_days {
                    None => Some(MarketSource::Synthetic {
                        seed,
                        history_days: DEFAULT_HISTORY_DAYS,
                    }),
                    Some(d) => match u16::try_from(d).ok().filter(|d| *d <= MAX_HISTORY_DAYS) {
                        Some(history_days) => Some(MarketSource::Synthetic { seed, history_days }),
                        None => {
                            problems.push(problem(
                                "market.history_days",
                                format!("{d} must be 0–{MAX_HISTORY_DAYS}"),
                            ));
                            None
                        }
                    },
                },
                (Some("synthetic"), None, None) => {
                    problems.push(problem(
                        "market.seed",
                        "required for source = \"synthetic\"",
                    ));
                    None
                }
                (Some("file"), None, Some(_)) if m.history_days.is_some() => {
                    problems.push(problem(
                        "market.history_days",
                        "applies to source = \"synthetic\" only; a data file holds one day",
                    ));
                    None
                }
                (Some("file"), None, Some(file)) => Some(MarketSource::File {
                    path: PathBuf::from(file),
                }),
                (Some("file"), None, None) => {
                    problems.push(problem("market.file", "required for source = \"file\""));
                    None
                }
                (Some(s @ ("synthetic" | "file")), _, _) => {
                    problems.push(problem(
                        "market",
                        format!(
                            "source = {s:?} takes {} only",
                            if s == "file" { "file" } else { "seed" }
                        ),
                    ));
                    None
                }
                (other, _, _) => {
                    problems.push(problem(
                        "market.source",
                        format!("{other:?} must be \"synthetic\" or \"file\""),
                    ));
                    None
                }
            },
        };
        let clock = raw.clock.unwrap_or(RawClock {
            start: None,
            end: None,
        });
        let start = clock
            .start
            .as_deref()
            .and_then(|s| instant("clock.start", s, &mut problems));
        let end = clock
            .end
            .as_deref()
            .and_then(|s| instant("clock.end", s, &mut problems));
        let faults = faults(raw.fault.unwrap_or_default(), &mut problems);
        let (Some(business), Some(market)) = (business, market) else {
            return Err(problems);
        };
        // Default start: 10:00 Berlin on the day before delivery = 2 h before the day-ahead gate.
        let start = start.unwrap_or_else(|| business.start() - time::Duration::hours(14));
        let end = end.unwrap_or_else(|| business.end());
        if end <= start {
            problems.push(problem("clock.end", "must be after clock.start"));
        }
        if !problems.is_empty() {
            return Err(problems);
        }
        Ok(Self {
            name,
            day: business.date(),
            market,
            start,
            end,
            faults,
        })
    }
}