nmbrs-runtime 0.7.1

Workload execution runtime for nmbrs
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! The admission check (SRD-115 ยง4.8): every row a predicated search
//! returns must be a row its predicate admits.
//!
//! Recall says how well a target ranked. It cannot say whether a
//! returned row should have been returned at all: a target that leaks
//! a row its filter excludes still scores recall on the rows it got
//! right. This check is the other half. An op declares it under
//! `evaluations:`:
//!
//! ```yaml
//! evaluations:
//!   admission:
//!     actual: keys          # the result keys, as relevancy's `actual:`
//!     admitted: admitted    # wire: the rows the predicate admits
//! ```
//!
//! `admitted` names a wire of type `admitted_rows` holding the set of
//! base rows the cycle's predicate admits (`admitted_rows_at`). The module holds the block's
//! parsing and the membership test; `validation.rs` runs it after each
//! op and reports a violation as a failed validation.

use polydat::ast::{PortType, Value};
use polydat::dataset_value::DatasetValue;

/// The keys an `admission:` block may carry.
const ADMISSION_VOCAB: &[&str] = &["actual", "admitted"];

/// The param key the workload parser hoists an `admission:` block to.
pub(crate) const PARAM: &str = "admission";

/// The keys of an `admission:` block whose values name wires. The
/// scope synthesizer and the unused-param check read this so the wires
/// the block needs are provisioned and counted as used.
pub(crate) const WIRE_KEYS: &[&str] = &["actual", "admitted"];

/// A parsed `admission:` block.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AdmissionConfig {
    /// Where the returned keys are read from: a result-binding name, a
    /// wire, or a result column, resolved as relevancy's `actual:` is.
    pub actual_field: String,
    /// The `admitted_rows` wire for the cycle's predicate.
    pub admitted_wire: String,
}

/// A wire reference as an op writes it, bare or in the `{name}` form.
fn wire_name(raw: &str) -> String {
    raw.trim()
        .trim_start_matches('{')
        .trim_end_matches('}')
        .trim()
        .to_string()
}

/// Parse the `admission:` block of an op's params.
///
/// Strict, as `relevancy:` is: an unknown key, a missing key, or a
/// value that is not a name is an error naming the op.
pub(crate) fn parse_admission(
    template: &nmbrs_workload::model::ParsedOp,
) -> Result<Option<AdmissionConfig>, String> {
    let Some(block) = template.params.get(PARAM) else {
        return Ok(None);
    };
    let op = &template.name;
    let obj = block.as_object().ok_or_else(|| {
        format!("op '{op}': admission: expected a mapping of `actual` and `admitted`")
    })?;
    for key in obj.keys() {
        if !ADMISSION_VOCAB.contains(&key.as_str()) {
            return Err(format!(
                "op '{op}' admission: unknown key '{key}'. Allowed: [{}]",
                ADMISSION_VOCAB.join(", "),
            ));
        }
    }
    let name_of = |key: &str, what: &str| -> Result<String, String> {
        let name = obj
            .get(key)
            .and_then(|v| v.as_str())
            .map(wire_name)
            .unwrap_or_default();
        if name.is_empty() {
            return Err(format!(
                "op '{op}' admission: missing required field '{key}' ({what})"
            ));
        }
        Ok(name)
    };
    Ok(Some(AdmissionConfig {
        actual_field: name_of("actual", "the result keys")?,
        admitted_wire: name_of("admitted", "the `admitted_rows` wire for the predicate")?,
    }))
}

/// The first returned key the predicate does not admit, if any.
///
/// `admitted` is the dataset's own admitted-row set (SRD-115 D-9,
/// D-15), reached by its declared type. Its membership test is the
/// dataset layer's; this function decides nothing about the set. A
/// negative key names no row and so is never admitted. An error means
/// the wire does not hold an admitted-row set.
pub(crate) fn first_not_admitted(actual: &[i64], admitted: &Value) -> Result<Option<i64>, String> {
    match admitted {
        Value::Dataset(DatasetValue::AdmittedRows(rows)) => Ok(actual
            .iter()
            .copied()
            .find(|&key| u64::try_from(key).map_or(true, |k| !rows.contains(k)))),
        other => Err(format!(
            "holds a {}, not the `admitted_rows` of a query; bind it with `admitted_rows_at`",
            other.type_name()
        )),
    }
}

/// Check, before any cycle, that the wire an `admission:` block names
/// is declared to carry admitted rows.
pub(crate) fn require_admitted_rows(
    op: &str,
    wire: &str,
    declared: Option<PortType>,
) -> Result<(), String> {
    match declared {
        Some(PortType::AdmittedRows) => Ok(()),
        Some(other) => Err(format!(
            "op '{op}' admission.admitted: wire '{wire}' is a {}, not `admitted_rows`; \
             bind it with `admitted_rows_at`",
            other.to_keyword()
        )),
        // A wire the program does not declare is reported by the
        // pull registration that follows, with the names that exist.
        None => Ok(()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn op_with(block: serde_json::Value) -> nmbrs_workload::model::ParsedOp {
        let mut op = nmbrs_workload::model::ParsedOp::simple("probe", "SELECT key FROM t");
        op.params.insert(PARAM.into(), block);
        op
    }

    fn rows(v: &[u64]) -> Value {
        use polydat::dataset_value::vectordata::ground_truth::OrdinalSet;
        Value::Dataset(DatasetValue::AdmittedRows(std::sync::Arc::new(
            OrdinalSet::from_ordinals(v),
        )))
    }

    #[test]
    fn an_op_without_the_block_has_no_admission_check() {
        let op = nmbrs_workload::model::ParsedOp::simple("probe", "SELECT key FROM t");
        assert_eq!(parse_admission(&op).unwrap(), None);
    }

    #[test]
    fn the_block_names_its_two_wires_bare_or_braced() {
        let cfg = parse_admission(&op_with(serde_json::json!({
            "actual": "keys",
            "admitted": "{admitted_rows}",
        })))
        .unwrap()
        .unwrap();
        assert_eq!(cfg.actual_field, "keys");
        assert_eq!(cfg.admitted_wire, "admitted_rows");
    }

    #[test]
    fn a_missing_or_unknown_key_is_refused_by_name() {
        let missing =
            parse_admission(&op_with(serde_json::json!({ "actual": "keys" }))).unwrap_err();
        assert!(missing.contains("'admitted'"), "{missing}");
        assert!(missing.contains("op 'probe'"), "{missing}");

        let unknown = parse_admission(&op_with(serde_json::json!({
            "actual": "keys",
            "admitted": "rows",
            "admited": "rows",
        })))
        .unwrap_err();
        assert!(unknown.contains("unknown key 'admited'"), "{unknown}");

        let not_a_map = parse_admission(&op_with(serde_json::json!("keys"))).unwrap_err();
        assert!(not_a_map.contains("expected a mapping"), "{not_a_map}");
    }

    #[test]
    fn every_admitted_key_passes() {
        let admitted = rows(&[2, 5, 9, 14, 30]);
        assert_eq!(first_not_admitted(&[14, 2, 30], &admitted), Ok(None));
        assert_eq!(first_not_admitted(&[], &admitted), Ok(None));
    }

    #[test]
    fn the_first_key_outside_the_set_is_named() {
        let admitted = rows(&[2, 5, 9, 14, 30]);
        assert_eq!(first_not_admitted(&[14, 3, 7], &admitted), Ok(Some(3)));
        // Nothing is admitted, so nothing may be returned.
        assert_eq!(first_not_admitted(&[0], &rows(&[])), Ok(Some(0)));
        // A negative key names no row.
        assert_eq!(first_not_admitted(&[-1], &admitted), Ok(Some(-1)));
    }

    #[test]
    fn a_wire_that_is_not_an_admitted_row_set_is_an_error() {
        let err = first_not_admitted(&[1], &Value::U64(7)).unwrap_err();
        assert!(err.contains("admitted_rows_at"), "{err}");
        let list = Value::VecI32(polydat::ast::SliceArc::from_vec(vec![1, 2]));
        assert!(first_not_admitted(&[1], &list).is_err());
    }

    #[test]
    fn the_wire_type_is_checked_before_any_cycle() {
        assert!(require_admitted_rows("probe", "rows", Some(PortType::AdmittedRows)).is_ok());
        assert!(require_admitted_rows("probe", "rows", None).is_ok());
        let err = require_admitted_rows("probe", "rows", Some(PortType::VecI32)).unwrap_err();
        assert!(
            err.contains("op 'probe'") && err.contains("'rows'"),
            "{err}"
        );
        assert!(err.contains("admitted_rows_at"), "{err}");
    }
}