From fa9caefe125b6db779caaf00b5fa034baac9e8d3 Mon Sep 17 00:00:00 2001 From: iceteaSA <171169159+iceteaSA@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:59:44 +0000 Subject: [PATCH] test(pricing): cover 30 untested money-path cases (#50) Add 22 exact-value tests for price arithmetic and list valuation in astrocyte-core. Each test passes on the current code and fails on an equality assertion when its case is changed. Test code only; one BROCA test helper takes its measurements and rates as parameters, with the same values. --- .../src/multiplier/shared_valuer_tests.rs | 96 ++++ crates/astrocyte-core/src/pricing.rs | 453 +++++++++++++++++- .../src/pricing_unit_billing_tests.rs | 24 + .../src/report/hourly/valuation/tests.rs | 69 +++ 4 files changed, 628 insertions(+), 14 deletions(-) diff --git a/crates/astrocyte-core/src/multiplier/shared_valuer_tests.rs b/crates/astrocyte-core/src/multiplier/shared_valuer_tests.rs index 5378e90..2fb60bf 100644 --- a/crates/astrocyte-core/src/multiplier/shared_valuer_tests.rs +++ b/crates/astrocyte-core/src/multiplier/shared_valuer_tests.rs @@ -20,6 +20,102 @@ fn shared_event(measurements: &[(&str, &str, i64)]) -> EventTokens { } } +#[test] +fn pricing_batch2_mutation_partial_quantity_precedes_unsupported_unit() { + use crate::valuation::value_event; + let mut event = shared_event(&[("output", "image", 7)]); + event.roles[0].4 = None; + let actual = value_event(None, &event).unwrap(); + let diagnostics: Vec<_> = actual + .unpriced + .iter() + .map(|d| { + ( + d.reason.as_str(), + d.role.as_str(), + d.quantity, + d.measurements.as_slice(), + ) + }) + .collect(); + assert_eq!( + (actual.numerator, diagnostics), + (0, vec![("missing_quantity", "output", 7, &[0][..])]) + ); +} + +#[test] +fn pricing_batch2_mutation_cache_write_rule_does_not_price_missing_output() { + use crate::valuation::{list_value_event, UnvaluedReason}; + let resolution = ModelResolution::Rates(ModelRates { + base: BTreeMap::from([ + ("input".into(), priced(3)), + ( + "cache_write".into(), + RateState::BilledAs { + key: crate::catalog_client::BillingRateKey::Input, + }, + ), + ]), + ..ModelRates::default() + }); + let event = shared_event(&[("cache_write", "token", 7), ("output", "token", 11)]); + let value = list_value_event(Some(&resolution), &event).unwrap(); + assert_eq!( + ( + value.numerator, + value.unvalued.tokens, + value.unvalued.by_reason + ), + (21, 11, BTreeMap::from([(UnvaluedReason::NoRate, 1)])), + ); +} + +#[test] +fn pricing_batch2_mutation_without_cache_write_rule_input_rate_is_not_used() { + use crate::valuation::{list_value_event, UnvaluedReason}; + let resolution = ModelResolution::Rates(ModelRates { + base: BTreeMap::from([("input".into(), priced(3))]), + ..ModelRates::default() + }); + let event = shared_event(&[("input", "token", 11), ("cache_write", "token", 7)]); + let value = list_value_event(Some(&resolution), &event).unwrap(); + assert_eq!( + ( + value.numerator, + value.unvalued.tokens, + value.unvalued.by_reason + ), + (33, 7, BTreeMap::from([(UnvaluedReason::NoRate, 1)])), + ); +} + +#[test] +fn pricing_batch2_mutation_cache_write_rule_uses_stated_mode_input_rate() { + use crate::valuation::list_value_event; + let resolution = ModelResolution::Rates(ModelRates { + base: BTreeMap::from([( + "cache_write".into(), + RateState::BilledAs { + key: crate::catalog_client::BillingRateKey::Input, + }, + )]), + modes: BTreeMap::from([("fast".into(), BTreeMap::from([("input".into(), priced(3))]))]), + ..ModelRates::default() + }); + let mut event = shared_event(&[("cache_write", "token", 7)]); + event.mode = Some("fast".into()); + let value = list_value_event(Some(&resolution), &event).unwrap(); + assert_eq!( + ( + value.numerator, + value.unvalued.tokens, + value.unvalued.by_reason + ), + (21, 0, BTreeMap::new()), + ); +} + #[test] fn shared_valuer_unvalued_tokens_count_only_token_units() { use crate::valuation::{list_value_event, UnvaluedReason}; diff --git a/crates/astrocyte-core/src/pricing.rs b/crates/astrocyte-core/src/pricing.rs index 5d57e3a..481a72f 100644 --- a/crates/astrocyte-core/src/pricing.rs +++ b/crates/astrocyte-core/src/pricing.rs @@ -4897,6 +4897,369 @@ mod tests { ); } + #[test] + fn pricing_batch2_mutation_cache_write_seconds_use_unit_rate() { + let mut conn = conn(); + let event = record( + &mut conn, + "cache-write-seconds", + ChargeBasis::MeteredApi, + Some(700), + vec![unit_billing_measurement("cache_write", "second", 90)], + ); + let catalog = client(FakeCatalog::new(BTreeMap::from([( + "rate.cache_write.per_second".into(), + unit_billing_rate(Some(60), json!({"kind":"none"}), json!({"kind":"none"})), + )]))); + let plan = read_reprice(&conn, &event).unwrap(); + let charge = resolve_reprice(&plan, &catalog).ok().and_then(|resolved| { + match &resolved.measurements[0].decision { + ChargeDecision::Priced { charge_nanos, .. } => Some(*charge_nanos), + _ => None, + } + }); + assert_eq!(charge, Some(6_750_000)); + } + + #[test] + fn pricing_batch2_mutation_zero_minimum_is_invalid() { + let mut conn = conn(); + let event = record( + &mut conn, + "zero-minimum", + ChargeBasis::MeteredApi, + Some(700), + vec![measurement("input", Some(1_000_000))], + ); + let catalog = client(FakeCatalog::new(BTreeMap::from([( + "rate.input".into(), + unit_billing_rate( + None, + json!({"kind":"none"}), + json!({"kind":"minimum","quantity":0}), + ), + )]))); + let plan = read_reprice(&conn, &event).unwrap(); + let actual = match resolve_reprice(&plan, &catalog) { + Err(PricingError::Catalog(CatalogClientError::InvalidRate { reason, .. })) => { + (Some(reason), None) + } + Ok(resolved) => match &resolved.measurements[0].decision { + ChargeDecision::Priced { charge_nanos, .. } => (None, Some(*charge_nanos)), + _ => (None, None), + }, + Err(_) => (None, None), + }; + assert_eq!( + actual, + (Some("token rates must omit per; unit rates require a positive per and positive quantity rules".into()), None), + ); + } + + #[test] + fn pricing_batch2_mutation_request_unit_requires_request_role() { + let mut conn = conn(); + let event = record( + &mut conn, + "invalid-request-role", + ChargeBasis::MeteredApi, + Some(700), + vec![ + unit_billing_measurement("output", "request", 2), + measurement("input", Some(1_000_000)), + ], + ); + let catalog = client(FakeCatalog::new(BTreeMap::from([( + "rate.input".into(), + rate(3_000_000), + )]))); + reprice_event( + &mut conn, + &event, + &catalog, + 1_000, + PricingOrigin::PricingPass, + ) + .unwrap(); + let actual: (Option, Option, Option) = conn + .query_row( + "SELECT charge_nanos,unpriced_reason,catalog_entry FROM priced_charge WHERE role='output'", + [], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .unwrap(); + assert_eq!(actual, (None, Some("no_rate".into()), None)); + } + + #[test] + fn pricing_batch2_mutation_prompt_ignores_non_token_input() { + let mut conn = conn(); + let event = price_against_272k_tier( + &mut conn, + "tier-ignores-input-seconds", + vec![ + measurement("input", Some(10_000)), + unit_billing_measurement("input", "second", 300_000), + ], + ); + let mut charges: Vec<_> = tier_rows(&conn, &event) + .into_iter() + .map(|(reason, _, _, _, charge)| (reason, charge)) + .collect(); + charges.sort(); + assert_eq!( + charges, + [(None, Some(10_000_000)), (Some("no_rate".into()), None)] + ); + } + + #[test] + fn pricing_batch2_mutation_zero_prompt_uses_base_rate() { + let mut conn = conn(); + let event = price_against_272k_tier( + &mut conn, + "tier-known-zero-prompt", + vec![measurement("input", Some(0))], + ); + let actual: Vec<_> = tier_rows(&conn, &event) + .into_iter() + .map(|(reason, _, _, _, charge)| (reason, charge)) + .collect(); + assert_eq!(actual, [(None, Some(0))]); + } + + #[test] + fn pricing_batch2_mutation_token_selector_cannot_claim_cache_lifetime() { + let mut conn = conn(); + let wire = json!({ + "record_id":"token-with-lifetime-label", "principal":"person-a", "job_id":"job-1", + "provider":"provider", "model":"model", "charge_basis":"vendor", "auth_method":"api_key", + "started_at_ms":700, "finished_at_ms":800, "status":"done", + "selectors":{"ttl":"1h"}, + "measurements":[{"role":"cache_write","unit":"token","quantity":"2", + "measure":"billed","source":"vendor_reply"}] + }); + let (request, facts) = crate::media::map_record(&serde_json::from_value(wire).unwrap()) + .unwrap() + .unwrap(); + let tx = conn.transaction().unwrap(); + let event = crate::ingest::record_media_event_in_tx(&tx, &request, &facts, 900) + .unwrap() + .event_id; + tx.commit().unwrap(); + let catalog = client(FakeCatalog::new(BTreeMap::from([( + "rate.cache_write.ttl.1h".into(), + rate(3_000_000), + )]))); + reprice_event( + &mut conn, + &event, + &catalog, + 1_000, + PricingOrigin::PricingPass, + ) + .unwrap(); + let actual: (Option, Option) = conn + .query_row( + "SELECT charge_nanos,unpriced_reason FROM priced_charge", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert_eq!(actual, (None, Some("no_rate".into()))); + } + + #[test] + fn pricing_batch2_mutation_unsupported_output_unit_has_no_catalog_entry() { + let mut conn = conn(); + let event = record( + &mut conn, + "unsupported-output-unit", + ChargeBasis::MeteredApi, + Some(700), + vec![ + unit_billing_measurement("output", "credit", 2), + measurement("input", Some(1_000_000)), + ], + ); + let catalog = client(FakeCatalog::new(BTreeMap::from([( + "rate.input".into(), + rate(3_000_000), + )]))); + reprice_event( + &mut conn, + &event, + &catalog, + 1_000, + PricingOrigin::PricingPass, + ) + .unwrap(); + let actual: (Option, Option, Option) = conn + .query_row( + "SELECT charge_nanos,unpriced_reason,catalog_entry FROM priced_charge WHERE role='output' AND unit='credit'", + [], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .unwrap(); + assert_eq!(actual, (None, Some("no_rate".into()), None)); + } + + #[test] + fn pricing_mutation_fractional_token_uses_quantity_scale() { + let mut conn = conn(); + let mut input = measurement("input", Some(25)); + input.quantity_exponent = Some(-1); + let event_id = record( + &mut conn, + "fractional-quantity-scale", + ChargeBasis::MeteredApi, + Some(700), + vec![input], + ); + let catalog = client(FakeCatalog::new(BTreeMap::from([( + "rate.input".into(), + rate(1_000_000), + )]))); + reprice_event( + &mut conn, + &event_id, + &catalog, + 1_000, + PricingOrigin::PricingPass, + ) + .unwrap(); + assert_eq!( + event_pricing_outcome(&conn, &event_id).unwrap(), + EventPricingOutcome::Priced { + measurement_count: 1, + charge_nanos: 2, + } + ); + } + + #[test] + fn pricing_mutation_negative_token_rate_is_unpriced() { + let mut conn = conn(); + let event_id = record( + &mut conn, + "negative-token-rate", + ChargeBasis::MeteredApi, + Some(700), + vec![measurement("input", Some(1_000_000))], + ); + let catalog = client(FakeCatalog::new(BTreeMap::from([( + "rate.input".into(), + rate(-1), + )]))); + let plan = read_reprice(&conn, &event_id).unwrap(); + let resolved = resolve_reprice(&plan, &catalog).unwrap(); + let actual = match &resolved.measurements[0].decision { + ChargeDecision::Unpriced { reason, .. } => (Some(reason), None), + ChargeDecision::Priced { charge_nanos, .. } => (None, Some(*charge_nanos)), + ChargeDecision::Covered { .. } => (None, None), + }; + assert_eq!(actual, (Some(&UnpricedReason::ArithmeticOutOfRange), None)); + } + + #[test] + fn pricing_mutation_zero_token_quantity_has_zero_charge() { + let mut conn = conn(); + let event_id = record( + &mut conn, + "zero-token-quantity", + ChargeBasis::MeteredApi, + Some(700), + vec![measurement("input", Some(0))], + ); + let catalog = client(FakeCatalog::new(BTreeMap::from([( + "rate.input".into(), + rate(1_000_000), + )]))); + reprice_event( + &mut conn, + &event_id, + &catalog, + 1_000, + PricingOrigin::PricingPass, + ) + .unwrap(); + assert_eq!( + event_pricing_outcome(&conn, &event_id).unwrap(), + EventPricingOutcome::Priced { + measurement_count: 1, + charge_nanos: 0, + } + ); + } + + #[test] + fn pricing_mutation_rounds_just_above_half_a_nano_up() { + let mut conn = conn(); + let mut input = measurement("input", Some(1)); + input.quantity_exponent = Some(-1); + let event_id = record( + &mut conn, + "just-above-half-a-nano", + ChargeBasis::MeteredApi, + Some(700), + vec![input], + ); + let catalog = client(FakeCatalog::new(BTreeMap::from([( + "rate.input".into(), + rate(5_000_002), + )]))); + reprice_event( + &mut conn, + &event_id, + &catalog, + 1_000, + PricingOrigin::PricingPass, + ) + .unwrap(); + assert_eq!( + event_pricing_outcome(&conn, &event_id).unwrap(), + EventPricingOutcome::Priced { + measurement_count: 1, + charge_nanos: 1, + } + ); + } + + #[test] + fn pricing_mutation_fine_rate_and_floor_rescale_exactly() { + let mut conn = conn(); + let event_id = record( + &mut conn, + "fine-rate-and-floor", + ChargeBasis::MeteredApi, + Some(700), + vec![measurement("input", Some(1_000_000))], + ); + let mut value = rate(500); + value["exponent"] = json!(11); + value["floor"] = json!({"kind": "minimum", "units": 700}); + let catalog = client(FakeCatalog::new(BTreeMap::from([( + "rate.input".into(), + value, + )]))); + reprice_event( + &mut conn, + &event_id, + &catalog, + 1_000, + PricingOrigin::PricingPass, + ) + .unwrap(); + let actual: (Option, Option, Option) = conn + .query_row( + "SELECT charge_nanos,rate_units,floor_units FROM priced_charge", + [], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .unwrap(); + assert_eq!(actual, (Some(5), Some(5), Some(7))); + } + /// $0.28 per million output tokens: 42 tokens cost 11,760 nanos, the /// output charge an inclusive 42 would get if its reasoning were not /// taken out. @@ -4914,6 +5277,32 @@ mod tests { output_source: &str, output: i64, reasoning: i64, + ) -> (Connection, String) { + price_broca_measurements( + producer_ref, + provider, + vec![ + MeasurementInput { + source: output_source.into(), + ..measurement("output", Some(output)) + }, + MeasurementInput { + source: "usage.reasoning_tokens".into(), + ..measurement("reasoning", Some(reasoning)) + }, + ], + BTreeMap::from([ + ("rate.output".into(), rate(OUTPUT_RATE)), + ("rate.reasoning".into(), rate(REASONING_RATE)), + ]), + ) + } + + fn price_broca_measurements( + producer_ref: &str, + provider: &str, + measurements: Vec, + facts: BTreeMap, ) -> (Connection, String) { let mut conn = conn(); let event_id = record_event( @@ -4943,26 +5332,13 @@ mod tests { charge_basis_mapping_version: None, charge_basis_overrides: None, charge_basis: ChargeBasis::MeteredApi, - measurements: vec![ - MeasurementInput { - source: output_source.into(), - ..measurement("output", Some(output)) - }, - MeasurementInput { - source: "usage.reasoning_tokens".into(), - ..measurement("reasoning", Some(reasoning)) - }, - ], + measurements, step_detail: Default::default(), }, 900, ) .unwrap() .event_id; - let facts = BTreeMap::from([ - ("rate.output".into(), rate(OUTPUT_RATE)), - ("rate.reasoning".into(), rate(REASONING_RATE)), - ]); let fake = FakeCatalog::new(BTreeMap::new()); fake.response.lock().unwrap().models = BTreeMap::from([(format!("{provider}/model"), facts)]); @@ -5012,6 +5388,55 @@ mod tests { .unwrap() } + #[test] + fn pricing_mutation_broca_fractional_output_keeps_its_quantity() { + let (conn, event_id) = price_broca_measurements( + "inclusive-fractional-output", + "deepseek", + vec![ + MeasurementInput { + source: INCLUSIVE_OUTPUT_SOURCE.into(), + quantity_exponent: Some(-1), + ..measurement("output", Some(42)) + }, + measurement("reasoning", Some(2)), + ], + BTreeMap::from([ + ("rate.output".into(), rate(OUTPUT_RATE)), + ("rate.reasoning".into(), rate(REASONING_RATE)), + ]), + ); + let heads = charge_heads(&conn, &event_id); + assert_eq!((heads[0].0.as_str(), heads[0].2), ("output", Some(1_176))); + } + + #[test] + fn pricing_mutation_broca_unit_output_keeps_its_quantity() { + let (conn, event_id) = price_broca_measurements( + "inclusive-unit-output", + "deepseek", + vec![ + MeasurementInput { + source: INCLUSIVE_OUTPUT_SOURCE.into(), + ..unit_billing_measurement("output", "second", 42) + }, + measurement("reasoning", Some(2)), + ], + BTreeMap::from([ + ( + "rate.output.per_second".into(), + unit_billing_rate(Some(60), json!({"kind":"none"}), json!({"kind":"none"})), + ), + ("rate.reasoning".into(), rate(REASONING_RATE)), + ]), + ); + let heads = charge_heads(&conn, &event_id); + assert_eq!( + (heads[0].0.as_str(), heads[0].2), + ("output", Some(3_150_000)) + ); + } + /// An old BROCA fact stores output with reasoning inside it. Pricing it as /// stored charged the 40 reasoning tokens twice; the output row must /// charge only the 2 tokens that are output proper, while the stored diff --git a/crates/astrocyte-core/src/pricing_unit_billing_tests.rs b/crates/astrocyte-core/src/pricing_unit_billing_tests.rs index 25427bb..305ef96 100644 --- a/crates/astrocyte-core/src/pricing_unit_billing_tests.rs +++ b/crates/astrocyte-core/src/pricing_unit_billing_tests.rs @@ -133,6 +133,30 @@ fn unit_billing_quantum_rounds_quantity_up() { ); } +#[test] +fn pricing_mutation_exact_quantum_does_not_round_up() { + unit_billing_rounding_case( + json!({"kind":"quantum","quantity":60}), + json!({"kind":"none"}), + 60, + 0, + json!({"units":60,"exponent":0}), + 4_500_000, + ); +} + +#[test] +fn pricing_mutation_quantity_equal_to_minimum_keeps_its_scale() { + unit_billing_rounding_case( + json!({"kind":"none"}), + json!({"kind":"minimum","quantity":60}), + 600, + -1, + json!({"units":600,"exponent":-1}), + 4_500_000, + ); +} + #[test] fn unit_billing_minimum_raises_quantity() { unit_billing_rounding_case( diff --git a/crates/astrocyte-core/src/report/hourly/valuation/tests.rs b/crates/astrocyte-core/src/report/hourly/valuation/tests.rs index d9a680c..80bcdb8 100644 --- a/crates/astrocyte-core/src/report/hourly/valuation/tests.rs +++ b/crates/astrocyte-core/src/report/hourly/valuation/tests.rs @@ -374,6 +374,75 @@ fn media_cache_write_report_request() -> ReportRequest { } } +fn image_token_list_value( + rate_key: &str, + rate_timeline: serde_json::Value, + selectors: serde_json::Value, + quantity: &str, +) -> super::surface::ListValue { + let mut conn = conn(); + let history = serde_json::from_value(json!({ + "source":"test","provider_id":"provider","model_id":"media","fact_prefix":"rate.","eras":[], + "served_by_key":{(rate_key):[rate_timeline]} + })) + .unwrap(); + publish( + &conn, + &fetched(history, "provider", "media", None).unwrap(), + 1, + ) + .unwrap(); + record_media_token_usage(&mut conn, 1, selectors, &[("output_image", quantity)]); + spend_report(&conn, &media_cache_write_report_request(), 2 * fees::DAY_MS) + .unwrap() + .rows + .remove(0) + .valuation + .list_value +} + +fn listed_image_token_rate(currency: &str) -> serde_json::Value { + json!({"from_ms":0,"until_ms":null,"state":"value", + "value":{"state":"priced","units":1_000_000,"exponent":9,"currency":currency, + "unit_provenance":{"kind":"stated"}}}) +} + +#[test] +fn pricing_mutation_list_value_keeps_conflicting_mode_aliases_unvalued() { + let value = image_token_list_value( + "rate.output_image.mode.fast", + listed_image_token_rate("USD"), + json!({"mode":"slow","speed_mode":"fast"}), + "2", + ); + assert_eq!( + (value.nanos, value.unvalued.tokens, value.unvalued.by_reason), + ( + 0, + 2, + BTreeMap::from([(crate::valuation::UnvaluedReason::NoRate, 1)]) + ), + ); +} + +#[test] +fn pricing_mutation_list_value_does_not_treat_euros_as_dollars() { + let value = image_token_list_value( + "rate.output_image.quality.high", + listed_image_token_rate("EUR"), + json!({"quality":"high"}), + "2", + ); + assert_eq!( + (value.nanos, value.unvalued.tokens, value.unvalued.by_reason), + ( + 0, + 2, + BTreeMap::from([(crate::valuation::UnvaluedReason::NonUsd, 1)]) + ), + ); +} + #[test] fn spend_report_values_media_cache_writes_billed_as_base_input() { let mut conn = conn();