Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

6.5 KB
Raw Blame
// ©AngelaMos | 2026
// ballot.rs

pub const CHOICE_FIELD: &str = "choice";
pub const FENCE: &str = "```";

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Declined {
    NoBooster,
    BackendUnavailable { detail: String },
    OffBallot { returned: String },
    Empty,
}

impl std::fmt::Display for Declined {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Declined::NoBooster => write!(
                formatter,
                "no booster is configured, so the deterministic answer stands"
            ),
            Declined::BackendUnavailable { detail } => write!(
                formatter,
                "the booster backend is unavailable, so the deterministic answer stands: {detail}"
            ),
            Declined::OffBallot { returned } => write!(
                formatter,
                "the model answered {returned:?}, which was not on the ballot; a choice the caller did not offer is a fabrication and is discarded"
            ),
            Declined::Empty => write!(formatter, "the model returned nothing to adjudicate"),
        }
    }
}

fn strip_fence(text: &str) -> &str {
    let trimmed = text.trim();
    let Some(inner) = trimmed.strip_prefix(FENCE) else {
        return trimmed;
    };
    let inner = inner.strip_suffix(FENCE).unwrap_or(inner);
    match inner.split_once('\n') {
        Some((_language, body)) => body.trim(),
        None => inner.trim(),
    }
}

fn strip_quotes(text: &str) -> &str {
    for quote in ['"', '\''] {
        if let Some(inner) = text.strip_prefix(quote)
            && let Some(inner) = inner.strip_suffix(quote)
        {
            return inner;
        }
    }
    text
}

// The model is asked for a JSON object because a server that honours a schema cannot answer off
// the ballot at all. The raw text is still adjudicated when that object does not arrive, because
// schema support is a property of the server rather than of the protocol, and a booster that
// declines whenever a server is old is a booster nobody can use.
#[must_use]
pub fn extract(raw: &str) -> String {
    let body = strip_fence(raw);
    if let Ok(serde_json::Value::Object(fields)) = serde_json::from_str::<serde_json::Value>(body)
        && let Some(serde_json::Value::String(choice)) = fields.get(CHOICE_FIELD)
    {
        return choice.trim().to_owned();
    }
    strip_quotes(body.trim()).trim().to_owned()
}

// Exact match, and deliberately nothing looser. Every near-miss rule considered here (case
// folding, trailing punctuation, substring containment) turns "the model said something adjacent
// to an option" into "the caller acted on an option", which is the fabrication this whole layer
// exists to prevent. Declining costs a booster suggestion; guessing costs a fabricated crash.
pub fn adjudicate(ballot: &[String], raw: &str) -> Result<String, Declined> {
    let answer = extract(raw);
    if answer.is_empty() {
        return Err(Declined::Empty);
    }
    if ballot.iter().any(|option| option == &answer) {
        return Ok(answer);
    }
    Err(Declined::OffBallot { returned: answer })
}

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

    fn ballot() -> Vec<String> {
        vec![
            "byte_buffer".to_owned(),
            "nul_terminated_string".to_owned(),
            "element_count".to_owned(),
        ]
    }

    #[test]
    fn a_bare_option_is_accepted() {
        assert_eq!(
            adjudicate(&ballot(), "byte_buffer"),
            Ok("byte_buffer".to_owned())
        );
    }

    #[test]
    fn surrounding_whitespace_does_not_change_the_verdict() {
        assert_eq!(
            adjudicate(&ballot(), "\n  element_count \t\n"),
            Ok("element_count".to_owned())
        );
    }

    #[test]
    fn the_schema_object_is_unwrapped_to_its_choice() {
        assert_eq!(
            adjudicate(&ballot(), r#"{"choice":"nul_terminated_string"}"#),
            Ok("nul_terminated_string".to_owned())
        );
    }

    #[test]
    fn a_fenced_schema_object_is_unwrapped_too() {
        let raw = "```json\n{\"choice\": \"byte_buffer\"}\n```";
        assert_eq!(adjudicate(&ballot(), raw), Ok("byte_buffer".to_owned()));
    }

    #[test]
    fn a_quoted_bare_option_is_accepted() {
        assert_eq!(
            adjudicate(&ballot(), "\"byte_buffer\""),
            Ok("byte_buffer".to_owned())
        );
    }

    // The whole point of the layer. An answer the caller never offered is discarded and NAMED,
    // never rounded to the nearest option.
    #[test]
    fn an_answer_that_is_not_on_the_ballot_is_refused_and_reported_verbatim() {
        let got = adjudicate(&ballot(), "size_t");
        assert_eq!(
            got,
            Err(Declined::OffBallot {
                returned: "size_t".to_owned()
            })
        );
    }

    #[test]
    fn a_near_miss_is_still_off_ballot_because_case_is_not_folded() {
        let got = adjudicate(&ballot(), "Byte_Buffer");
        assert_eq!(
            got,
            Err(Declined::OffBallot {
                returned: "Byte_Buffer".to_owned()
            })
        );
    }

    // Prose that CONTAINS an option is not a vote for it. Accepting this is how a model that
    // hedges ("it is not byte_buffer") gets read as having chosen byte_buffer.
    #[test]
    fn prose_containing_an_option_is_not_a_vote_for_it() {
        let got = adjudicate(&ballot(), "It is certainly not byte_buffer here.");
        assert!(
            matches!(got, Err(Declined::OffBallot { .. })),
            "prose was read as a choice: {got:?}"
        );
    }

    #[test]
    fn an_empty_answer_is_named_as_empty_rather_than_off_ballot() {
        assert_eq!(adjudicate(&ballot(), "   \n  "), Err(Declined::Empty));
    }

    #[test]
    fn a_schema_object_carrying_an_invented_choice_is_still_refused() {
        let got = adjudicate(&ballot(), r#"{"choice":"whatever_i_want"}"#);
        assert_eq!(
            got,
            Err(Declined::OffBallot {
                returned: "whatever_i_want".to_owned()
            })
        );
    }

    #[test]
    fn every_declined_variant_says_something_actionable() {
        let variants = [
            Declined::NoBooster,
            Declined::BackendUnavailable {
                detail: "connection refused".to_owned(),
            },
            Declined::OffBallot {
                returned: "nonsense".to_owned(),
            },
            Declined::Empty,
        ];
        for variant in variants {
            assert!(
                variant.to_string().len() > 20,
                "{variant:?} explains nothing"
            );
        }
    }
}