flow-abi 0.1.0-rc.5

The host boundary's value encoding: the binary encoding and the JSON form, the canonical form and its hash, JSON Schemas, Tool signatures, and the answers a Tool call passes.
Documentation
//! Reading a number builds nothing as large as its value: each test holds
//! the largest integer reading built ([`largest_built`]) to what the limits
//! allow, however large the value its spelling stands for.

use flow_types::Type;

use crate::work::largest_built;
use crate::{Catalog, DecodeError, DecodeErrorKind, Limits, Mode, canonical, decode_text, parse};

fn catalog() -> Catalog {
    Catalog::std(Vec::new()).expect("std's catalog")
}

/// The kind of refusal `result` is.
#[track_caller]
fn kind_of<T: std::fmt::Debug>(result: Result<T, DecodeError>) -> DecodeErrorKind {
    result.expect_err("refused").kind
}

/// `text` read at `ty` as a reply with the minimum limits and written out
/// again, or the path and problem of its refusal; reading builds no integer
/// with more digits than the int limit lets a power of ten have.
#[track_caller]
#[expect(
    clippy::panic_in_result_fn,
    reason = "the result is the reading's; the assertion is the test's own"
)]
fn read(catalog: &Catalog, ty: &Type, text: &str) -> Result<String, (String, String)> {
    let limits = Limits::LANGUAGE;
    let (read, largest) = largest_built(|| decode_text(catalog, ty, text, Mode::Reply, &limits));
    let bound = usize::try_from(limits.int_bits).expect("a limit that fits") + 1;
    assert!(largest <= bound, "{text:.40}… built {largest} digits");
    read.map(|value| canonical(catalog, ty, &value).expect("the value encodes"))
        .map_err(|error| (error.path.to_string(), error.problem))
}

/// The path and problem of reading `text` at `ty`.
#[track_caller]
fn refusal(catalog: &Catalog, ty: &Type, text: &str) -> (String, String) {
    read(catalog, ty, text).expect_err("refused")
}

#[test]
fn a_power_of_ten_past_the_int_limit_is_not_built() {
    let catalog = catalog();
    assert_eq!(
        refusal(&catalog, &Type::Int, "1e9000000").1,
        "is an integer larger than 4096 bits"
    );
}

#[test]
fn a_number_is_measured_by_its_value_before_it_is_built() {
    let catalog = catalog();
    let json = Type::Json;
    let too_large = "is a number too large for this host";
    let past_bits = "is a number whose digits make an integer larger than 4096 bits";
    // Exponents far past any limit, either way, for every number type.
    for spelling in [
        "60E888121000",
        "1e99999999999999999999999",
        "1E9223372036854775807",
        "-1e-9223372036854775808",
        "1e-99999999999999999999999",
        "0.5e-9223372036854775807",
        "5e+9223372036854775807",
    ] {
        for ty in [&Type::Int, &Type::Decimal, &json] {
            let (path, problem) = read(&catalog, ty, spelling).expect_err(spelling);
            assert_eq!(path, "");
            assert!(problem.starts_with(too_large), "{spelling}: {problem}");
        }
    }
    // A long run of significant digits is refused before it is built.
    let long = format!("1{}", "7".repeat(1_000_000));
    for spelling in [
        long.clone(),
        format!("-{long}"),
        format!("0.{long}"),
        format!("{long}e-999999"),
    ] {
        for ty in [&Type::Int, &Type::Decimal, &json] {
            let (_, problem) = read(&catalog, ty, &spelling).expect_err("refused");
            assert!(problem.starts_with(past_bits), "{problem}");
        }
    }
    // Leading zeros of a fraction and trailing zeros anywhere are no
    // coefficient digits: these are read, and written out as long as they
    // were spelled.
    let small = format!("0.{}1", "0".repeat(1_000_000));
    assert_eq!(read(&catalog, &Type::Decimal, &small), Ok(small.clone()));
    assert_eq!(
        read(&catalog, &Type::Int, &small)
            .expect_err("a fraction")
            .1,
        "should be a whole number"
    );
    let round = format!("1{}", "0".repeat(1_000_000));
    assert_eq!(read(&catalog, &Type::Decimal, &round), Ok(round.clone()));
    assert_eq!(
        read(&catalog, &Type::Decimal, &format!("{round}.000")),
        Ok(round.clone())
    );
    assert_eq!(
        read(&catalog, &Type::Int, &round)
            .expect_err("past the limit")
            .1,
        "is an integer larger than 4096 bits"
    );
    assert_eq!(
        read(&catalog, &Type::Decimal, &format!("{small}e1000001")),
        Ok("1".to_owned())
    );
    // Zero is zero under any exponent.
    for spelling in [
        "0e99999999999999999999999",
        "-0.000E-99999999999999999999999",
        "0.0e+7",
    ] {
        assert_eq!(read(&catalog, &Type::Int, spelling), Ok("0".to_owned()));
        assert_eq!(read(&catalog, &json, spelling), Ok("0".to_owned()));
    }
    // A refusal names where the number stands.
    let (path, problem) = read(
        &catalog,
        &Type::list(Type::Decimal),
        "[1, 2e99999999999999999999]",
    )
    .expect_err("refused");
    assert_eq!(
        (path.as_str(), problem.as_str()),
        ("[1]", "is a number too large for this host (at byte 26)")
    );
}

#[test]
fn a_numbers_digits_are_held_to_the_int_limit_exactly_and_counted_before_they_are_built() {
    let five = Limits {
        int_bits: 5,
        ..Limits::LANGUAGE
    };
    let read = |text: &str| parse(text, &five).map(|json| json.canonical());
    // 31 takes five bits, so 3.1, 0.031, 31000 and -31 are within the limit
    // whatever their exponents; 32 takes six.
    for (spelling, canonical) in [
        ("31", "31"),
        ("-31", "-31"),
        ("3.1", "3.1"),
        ("0.031", "0.031"),
        ("31000", "31000"),
        ("3.10e4", "31000"),
        ("310e-4", "0.031"),
    ] {
        assert_eq!(read(spelling).as_deref(), Ok(canonical), "{spelling}");
    }
    for spelling in ["32", "-3.2", "0.032", "32000", "3.20e4", "101"] {
        assert_eq!(
            read(spelling).expect_err(spelling).problem,
            format!(
                "is a number whose digits make an integer larger than 5 bits (at byte {})",
                spelling.len()
            )
        );
    }
    // Zero takes no bits, so even a limit of none holds it, and nothing more.
    let none = Limits {
        int_bits: 0,
        ..Limits::LANGUAGE
    };
    let catalog = catalog();
    let int = |text: &str| decode_text(&catalog, &Type::Int, text, Mode::Reply, &none);
    assert!(int("0").is_ok());
    assert_eq!(
        int("1e0").expect_err("one bit").problem,
        "is a number whose digits make an integer larger than 0 bits (at byte 3)"
    );
    // A host may allow far more; digits that cannot fit are still refused
    // before they are built, which takes time in their square.
    let wide = Limits {
        int_bits: 3_000_000,
        ..Limits::LANGUAGE
    };
    let long = "7".repeat(2_000_000);
    let (read, largest) = largest_built(|| parse(&long, &wide));
    assert_eq!(kind_of(read), DecodeErrorKind::TooLarge);
    assert_eq!(largest, 0, "no integer built");
}

#[test]
fn the_numbers_of_one_text_grow_it_by_no_more_than_the_text_limit_written_out() {
    let catalog = catalog();
    let limits = Limits::LANGUAGE;
    let limit = limits.text_bytes;
    // One number may take the whole limit in plain notation, but two such
    // numbers in one text would take twice it.
    let one = format!("1e{}", limit - 1);
    assert_eq!(parse(&one, &limits).expect("one").canonical().len(), limit);
    let twice = format!("[{one},{one}]");
    let (refused, largest) = largest_built(|| parse(&twice, &limits));
    let refused = refused.expect_err("two");
    assert_eq!(largest, 1, "nothing as long as either number built");
    assert_eq!(refused.path, "[1]");
    assert_eq!(
        refused.problem,
        format!(
            "has numbers that, written out, would lengthen it by more than {limit} characters (at byte {})",
            twice.len() - 1
        )
    );
    // The same at every type that reads a number, a json.Value's included.
    for ty in [Type::list(Type::Int), Type::list(Type::Decimal), Type::Json] {
        let (_, problem) = refusal(&catalog, &ty, &twice);
        assert!(
            problem.starts_with("has numbers that, written out"),
            "{problem}"
        );
    }
    // Many short numbers, each far within the limit, are held to it
    // together, so what is read is never much longer than its spelling.
    let many = format!("[{}]", vec!["9e9999"; 4096].join(","));
    assert_eq!(kind_of(parse(&many, &limits)), DecodeErrorKind::TooLarge);
    let few = format!("[{}]", vec!["9e9999"; 1000].join(","));
    let canonical = parse(&few, &limits).expect("within the limit").canonical();
    assert!(canonical.len() <= few.len() + limit);
    // Growth is counted against the spelling, sign excluded as it is from
    // plain notation: `-1e9` grows by seven characters to `-1000000000`.
    let ten = Limits {
        text_bytes: 10,
        ..limits
    };
    assert!(parse("[-1e9,-1e5]", &ten).is_ok(), "seven and three");
    assert_eq!(
        kind_of(parse("[-1e9,-1e6]", &ten)),
        DecodeErrorKind::TooLarge,
        "seven and four"
    );
    // A number written out takes no more than its spelling, so the
    // canonical text of what was read reads back.
    let half =
        parse(&format!("[1e{},1e{}]", limit / 2, limit / 2 - 10), &limits).expect("half each");
    assert_eq!(parse(&half.canonical(), &limits), Ok(half));
}