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
26 changes: 26 additions & 0 deletions .cargo/mutants.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,29 @@
# cargo-mutants settings, used by scripts/mutants.sh.
# Build and test with the lock file, as CI does.
additional_cargo_args = ["--locked"]

# Mutants no test can tell apart from the real code, or that only hang.
exclude_re = [
# crates/bot-core/src/ai_calculator.rs: `index *= 1` never moves the tokenizer forward, so a
# test hangs until the timeout, which costs 2 minutes per mutant and finds nothing. The
# mutant name does not say which `+=` it changes, so this also covers the two `index += 2`
# sites (`**` and `//`), which do not hang. The unspaced `2**3` and `100//3` tests check them.
"replace \\+= with \\*= in tokenize$",
# crates/bot-core/src/bcra.rs: at exactly 100 bps, one decimal prints "100.0", which `trimmed` turns back into "100",
# the same as no decimals. No other value changes.
"replace < with <= in risk_decimals$",
# Moving the parser back makes it read the same operand again, forever.
"replace \\+= with -= in Parser<'a>::parse_(additive|multiplicative|primary)$",
# Without the exponent cap, the tests' large powers run until the timeout: the slow work the
# cap exists to refuse. The tests check the cap's error text where the result is too big.
"replace \\|\\| with && in power$",
# crates/bot-core/src/base_conversion.rs: `value *= target` grows the number forever.
"replace /= with \\*= in convert_base$",
# crates/bot-core/src/command_normalization.rs: `start *= length` stays at 0 forever, and
# `start *= 1` after an ASCII character stays where it is. Both hang the tests.
"replace \\+= with \\*= in romanize_japanese$",
# crates/bot-core/src/polymarket.rs: at exactly 10%, 1 and 2 decimals both print "10".
"replace < with <= in render_elections$",
# crates/bot-core/src/price_queries.rs: the last dot and the last comma are never at the same index.
"replace > with >= in parse_conversion_amount$",
]
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ qrcode = { version = "0.15.0", default-features = false, features = ["image"] }
ib-romaji = "0.2.1"
emojis = "0.9.1"
num-bigint = "0.5.1"
num-integer = "0.1.47"
native-tls = "0.2.18"
postgres = { version = "0.19.14", features = ["with-serde_json-1"] }
postgres-native-tls = "0.5.3"
Expand Down
55 changes: 23 additions & 32 deletions crates/bot-adapters/src/bcra.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::{collections::BTreeMap, io::Cursor, thread, time::Duration};
use bot_core::{
bcra::{BcraBands, BcraSnapshot, BcraVariable, CountryRisk, ItcrmDetails, render_bcra},
cache_policy::request_cache_history_key,
calendar::{checked_days_from_civil, civil_from_days, days_from_civil},
locale::Locale,
};
use calamine::{Data, Reader, Xlsx};
Expand Down Expand Up @@ -180,33 +181,11 @@ fn floor(value: i64, divisor: i64) -> i64 {
if r < 0 { q - 1 } else { q }
}

fn civil(days: i64) -> (i64, i64, i64) {
let z = days + 719_468;
let era = floor(z, 146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let mut year = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = mp + if mp < 10 { 3 } else { -9 };
year += i64::from(month <= 2);
(year, month, day)
}

fn days(year: i64, month: i64, day: i64) -> i64 {
let y = year - i64::from(month <= 2);
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = y - era * 400;
let mp = month + if month > 2 { -3 } else { 9 };
era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + (153 * mp + 2) / 5 + day - 1 - 719_468
}

pub(crate) fn parse_date(value: &str) -> Option<i64> {
let value = value.trim().split(['T', ' ']).next()?;
if let Some((y, rest)) = value.split_once('-') {
let (m, d) = rest.split_once('-')?;
return Some(days(y.parse().ok()?, m.parse().ok()?, d.parse().ok()?));
return checked_days_from_civil(y.parse().ok()?, m.parse().ok()?, d.parse().ok()?);
}
let mut p = value.split('/');
let (d, m, mut y) = (
Expand All @@ -217,22 +196,22 @@ pub(crate) fn parse_date(value: &str) -> Option<i64> {
if y < 100 {
y += 2_000;
}
Some(days(y, m, d))
checked_days_from_civil(y, m, d)
}

pub(crate) fn iso(day: i64) -> String {
let (y, m, d) = civil(day);
let (y, m, d) = civil_from_days(day);
format!("{y:04}-{m:02}-{d:02}")
}
fn display(day: i64) -> String {
let (y, m, d) = civil(day);
let (y, m, d) = civil_from_days(day);
format!("{d:02}/{m:02}/{:02}", y.rem_euclid(100))
}
pub(crate) fn ba_day(now: i64) -> i64 {
floor(now.saturating_sub(10_800), 86_400)
}
fn now_iso(now: i64) -> String {
let (y, m, d) = civil(floor(now, 86_400));
let (y, m, d) = civil_from_days(floor(now, 86_400));
let s = now.rem_euclid(86_400);
format!(
"{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}+00:00",
Expand Down Expand Up @@ -611,7 +590,7 @@ fn risk_label(value: &str) -> Option<String> {
let (h, m) = time.split_once(':')?;
let minutes = h.parse::<i64>().ok()? * 60 + m.parse::<i64>().ok()? - 180;
let adjusted = day + floor(minutes, 1440);
let (_, month, date) = civil(adjusted);
let (_, month, date) = civil_from_days(adjusted);
Some(format!(
"{date:02}/{month:02} {:02}:{:02}",
minutes.rem_euclid(1440) / 60,
Expand Down Expand Up @@ -639,7 +618,7 @@ fn cell_date(value: &Data) -> Option<i64> {
match value {
Data::DateTime(v) => {
let (y, m, d, _, _, _, _) = v.to_ymd_hms_milli();
Some(days(i64::from(y), i64::from(m), i64::from(d)))
Some(days_from_civil(i64::from(y), i64::from(m), i64::from(d)))
}
Data::String(v) | Data::DateTimeIso(v) => parse_date(v),
_ => None,
Expand Down Expand Up @@ -1346,7 +1325,7 @@ mod tests {

#[test]
fn daily_tcrm_uses_only_observations_available_on_the_target_date() {
let now = days(2024, 9, 1) * 86_400 + 15 * 3_600;
let now = days_from_civil(2024, 9, 1) * 86_400 + 15 * 3_600;
let variable = json!({"idVariable":5,"descripcion":"Tipo de cambio mayorista"});
let variables = variable.as_object().into_iter().collect::<Vec<_>>();
let request = BcraRequest::Series { id: 5, limit: 32 };
Expand Down Expand Up @@ -1550,7 +1529,7 @@ mod tests {

#[test]
fn current_itcrm_excludes_future_and_malformed_cached_details() {
let now = days(2024, 9, 1) * 86_400 + 15 * 3600;
let now = days_from_civil(2024, 9, 1) * 86_400 + 15 * 3600;
for latest in [
None,
Some(json!({"date":"2024-09-02","value":250.0})),
Expand Down Expand Up @@ -1588,7 +1567,7 @@ mod tests {

#[test]
fn uncached_itcrm_response_supplies_daily_history_without_a_second_fetch() -> TestResult {
let now = days(2026, 9, 2) * 86_400 + 15 * 3600;
let now = days_from_civil(2026, 9, 2) * 86_400 + 15 * 3600;
let bytes = base64::engine::general_purpose::STANDARD.decode(ITCRM_WORKBOOK)?;
let transport = Transport {
responses: RefCell::new(VecDeque::from([
Expand Down Expand Up @@ -2020,6 +1999,18 @@ mod tests {
fn dates_rows_and_band_descriptions_tolerate_partial_provider_data() {
assert_eq!(parse_date("19/09/2025"), parse_date("19/09/25"));
assert_eq!(parse_date("2025-09-19"), parse_date("19/09/25"));
// Only years below 100 are short years.
assert_eq!(parse_date("01/01/99"), parse_date("2099-01-01"));
assert_eq!(parse_date("01/01/100"), parse_date("100-01-01"));
assert_ne!(parse_date("01/01/100"), parse_date("2100-01-01"));
for date in [
"31/02/2025",
"19/13/2025",
"2025-02-30",
"19/9223372036854775807/2025",
] {
assert_eq!(parse_date(date), None, "{date}");
}
let rows = json!({"results":[{"detalle":[
{"fecha":"2025-09-18","valor":930},
{"fecha":"2025-09-19"},
Expand Down
15 changes: 1 addition & 14 deletions crates/bot-adapters/src/weather.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use std::thread;
use std::time::Duration;

use bot_core::calendar::civil_from_days;
use bot_core::weather::{
DEFAULT_WEATHER_LOCATION, WeatherObservation, search_key, select_forecast_hour,
select_location_candidate,
Expand Down Expand Up @@ -300,20 +301,6 @@ fn location_label(location: &Location) -> String {
parts.join(", ")
}

fn civil_from_days(days: i64) -> (i64, i64, i64) {
let days = days + 719_468;
let era = days.div_euclid(146_097);
let day_of_era = days - era * 146_097;
let year_of_era =
(day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let year = year_of_era + era * 400;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_prime = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * month_prime + 2) / 5 + 1;
let month = month_prime + if month_prime < 10 { 3 } else { -9 };
(year + i64::from(month <= 2), month, day)
}

fn buenos_aires_hour(now_unix: i64) -> String {
let local_seconds = now_unix.saturating_sub(3 * 3_600);
let days = local_seconds.div_euclid(86_400);
Expand Down
1 change: 1 addition & 0 deletions crates/bot-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ deunicode.workspace = true
emojis.workspace = true
ib-romaji.workspace = true
num-bigint.workspace = true
num-integer.workspace = true
regex.workspace = true
serde.workspace = true
serde_json.workspace = true
Expand Down
6 changes: 2 additions & 4 deletions crates/bot-core/src/admin_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,10 +293,8 @@ fn metadata_credit(metadata: &Map<String, Value>, keys: &[&str]) -> i64 {
fn optional_id(metadata: &Map<String, Value>, key: &str, fallback: Option<i64>) -> String {
metadata.get(key).map_or_else(
|| fallback.map_or_else(|| "None".to_owned(), |value| value.to_string()),
|value| match value {
Value::Null => "None".to_owned(),
_ => python_string(Some(value), "None"),
},
// `python_string` also turns a JSON null into "None".
|value| python_string(Some(value), "None"),
)
}

Expand Down
29 changes: 12 additions & 17 deletions crates/bot-core/src/admin_reports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,10 @@ pub fn parse_creditlog_limit(message_text: &str) -> CreditLogLimit {
return CreditLogLimit::UnsupportedNumericInput;
}
let bytes = normalized.as_bytes();
// An underscore must follow a digit and must not end the number. Any other character after
// it makes the parse below fail, so only those two checks are needed here.
let underscores_are_valid = bytes.iter().enumerate().all(|(index, byte)| {
*byte != b'_'
|| (index > 0
&& index + 1 < bytes.len()
&& bytes[index - 1].is_ascii_digit()
&& bytes[index + 1].is_ascii_digit())
*byte != b'_' || (index > 0 && index + 1 < bytes.len() && bytes[index - 1].is_ascii_digit())
});
if !underscores_are_valid {
return CreditLogLimit::Invalid;
Expand All @@ -37,18 +35,11 @@ pub fn parse_creditlog_limit(message_text: &str) -> CreditLogLimit {
let Some(value) = BigInt::parse_bytes(compact.as_bytes(), 10) else {
return CreditLogLimit::Invalid;
};
let minimum = BigInt::from(1_u8);
let maximum = BigInt::from(25_u8);
if value < minimum {
CreditLogLimit::Valid(1)
} else if value > maximum {
CreditLogLimit::Valid(25)
} else {
value
.to_string()
.parse::<usize>()
.map_or(CreditLogLimit::Invalid, CreditLogLimit::Valid)
}
value
.clamp(BigInt::from(1_u8), BigInt::from(25_u8))
.to_string()
.parse::<usize>()
.map_or(CreditLogLimit::Invalid, CreditLogLimit::Valid)
}

/// Truncate a report by Unicode scalar count and append the localized marker.
Expand Down Expand Up @@ -85,6 +76,10 @@ mod tests {
("1", CreditLogLimit::Valid(1)),
("1_0", CreditLogLimit::Valid(10)),
("1__0", CreditLogLimit::Invalid),
("1", CreditLogLimit::Valid(1)),
("25", CreditLogLimit::Valid(25)),
("26", CreditLogLimit::Valid(25)),
("1_a", CreditLogLimit::Invalid),
] {
assert_eq!(parse_creditlog_limit(input), expected, "{input}");
}
Expand Down
36 changes: 16 additions & 20 deletions crates/bot-core/src/ai_calculator.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Safe arithmetic evaluator shared by the AI `calculate` tool.

use num_bigint::BigInt;
use num_integer::Integer;

use crate::locale::Locale;

Expand Down Expand Up @@ -134,8 +135,8 @@ fn tokenize(expression: &str) -> Result<Vec<Token>, CalculationError> {
match chars[index] {
value if value.is_whitespace() => index += 1,
value if value.is_ascii_digit() || value == '.' => {
// The loop takes the first character too: it is a digit or '.'.
let start = index;
index += 1;
while index < chars.len()
&& (chars[index].is_ascii_digit()
|| matches!(chars[index], '.' | 'e' | 'E')
Expand Down Expand Up @@ -353,17 +354,9 @@ fn floor_divide(left: Number, right: Number) -> Result<Number, CalculationError>
return Err(CalculationError::ZeroDivision);
}
match (left, right) {
// Python's `//` rounds toward negative infinity, like `div_floor`.
(Number::Integer(left), Number::Integer(right)) => {
let quotient = &left / &right;
let remainder = &left % &right;
let opposite_signs = (left < BigInt::from(0)) != (right < BigInt::from(0));
Ok(Number::Integer(
if remainder != BigInt::from(0) && opposite_signs {
quotient - 1
} else {
quotient
},
))
Ok(Number::Integer(left.div_floor(&right)))
}
(left, right) => Ok(Number::Float(
(left.as_float()? / right.as_float()?).floor(),
Expand All @@ -376,16 +369,9 @@ fn modulo(left: Number, right: Number) -> Result<Number, CalculationError> {
return Err(CalculationError::ZeroDivision);
}
match (left, right) {
// Python's `%` takes the sign of the divisor, like `mod_floor`.
(Number::Integer(left), Number::Integer(right)) => {
let remainder = &left % &right;
let opposite_signs = (remainder < BigInt::from(0)) != (right < BigInt::from(0));
Ok(Number::Integer(
if remainder != BigInt::from(0) && opposite_signs {
remainder + right
} else {
remainder
},
))
Ok(Number::Integer(left.mod_floor(&right)))
}
(left, right) => {
let left = left.as_float()?;
Expand Down Expand Up @@ -425,6 +411,9 @@ mod tests {
assert_eq!(calculate_expression("2 + 3 * 4", Locale::En), "14");
assert_eq!(calculate_expression("(2 + 3) * 4", Locale::En), "20");
assert_eq!(calculate_expression("2 ** 10", Locale::En), "1024");
// Without spaces, the two-character operators start after index 1.
assert_eq!(calculate_expression("2**3", Locale::En), "8");
assert_eq!(calculate_expression("100//3", Locale::En), "33");
assert_eq!(calculate_expression("2 ** -2", Locale::En), "0.25");
assert_eq!(
calculate_expression("100000000000000000000 + 1", Locale::En),
Expand Down Expand Up @@ -503,6 +492,13 @@ mod tests {
calculate_expression(&"1+".repeat(201), Locale::En),
"expression is too long"
);
// Exactly MAX_SYNTAX_NODES tokens: "-(", 98 times "1+", then "1)".
let longest = format!("-({}1)", "1+".repeat(98));
assert_eq!(calculate_expression(&longest, Locale::En), "-99");
assert_eq!(
calculate_expression(&format!("-{longest}"), Locale::En),
"expression is too long"
);
for expression in ["2 ** 100001", "2 ** 4294967296"] {
assert_eq!(
calculate_expression(expression, Locale::En),
Expand Down
5 changes: 2 additions & 3 deletions crates/bot-core/src/ai_reserve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,9 +170,8 @@ pub fn estimate_transcription_reserve_credit_units(
return Ok(1);
}
let usd_micros = (seconds * usd_micros_per_hour as f64 / 3_600.0).ceil();
if usd_micros > i128::MAX as f64 {
return Err(ReserveEstimateError::Overflow);
}
// `as` saturates at i128::MAX, and a value that large overflows the i64 credit units, so
// `credit_units_from_usd_micros` already returns `Overflow` for it.
Ok(credit_units_from_usd_micros(usd_micros as i128)?.max(1))
}

Expand Down
3 changes: 0 additions & 3 deletions crates/bot-core/src/ai_response_cleanup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,6 @@ fn collapse_double_periods(text: &str) -> String {

#[must_use]
pub fn strip_leading_context(response: &str, contexts: &[Option<String>]) -> String {
if response.is_empty() || contexts.is_empty() {
return response.to_owned();
}
let normalized = contexts
.iter()
.filter_map(|context| context.as_deref().map(str::trim))
Expand Down
Loading