Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(ai-billing): exclude projections from metered usage (#6919)

Will Hutchinsonb42bef3bed61
diff --git a/.sqlx/query-a5e6994cde4e295c582d7ab30fb65595148f6f6932a0b4f4fe1d031477dab1a5.json b/.sqlx/query-a51667f575cf4e79bfb47146b9657f8069857ea4052183dd59b7f0dbb78ed1af.json
similarity index 83%
rename from .sqlx/query-a5e6994cde4e295c582d7ab30fb65595148f6f6932a0b4f4fe1d031477dab1a5.json
rename to .sqlx/query-a51667f575cf4e79bfb47146b9657f8069857ea4052183dd59b7f0dbb78ed1af.json
index 69347bfecb..1972a750ef 100644
--- a/.sqlx/query-a5e6994cde4e295c582d7ab30fb65595148f6f6932a0b4f4fe1d031477dab1a5.json
+++ b/.sqlx/query-a51667f575cf4e79bfb47146b9657f8069857ea4052183dd59b7f0dbb78ed1af.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT user_id, COALESCE(SUM(\n COALESCE(\n total::float8,\n (input_tokens::float8 / 1000000.0) * $4\n + (output_tokens::float8 / 1000000.0) * $5\n )\n ), 0)::float8 AS \"usd!\"\n FROM ai_usage\n WHERE user_id = ANY($1)\n AND created_at >= $2\n AND created_at < $3\n GROUP BY user_id\n ",
+ "query": "\n SELECT user_id, COALESCE(SUM(\n COALESCE(\n total::float8,\n (input_tokens::float8 / 1000000.0) * $4\n + (output_tokens::float8 / 1000000.0) * $5\n )\n ), 0)::float8 AS \"usd!\"\n FROM ai_usage\n WHERE user_id = ANY($1)\n AND created_at >= $2\n AND created_at < $3\n AND feature <> $6\n GROUP BY user_id\n ",
"describe": {
"columns": [
{
@@ -20,7 +20,8 @@
"Timestamptz",
"Timestamptz",
"Float8",
- "Float8"
+ "Float8",
+ "Text"
]
},
"nullable": [
@@ -28,5 +29,5 @@
null
]
},
- "hash": "a5e6994cde4e295c582d7ab30fb65595148f6f6932a0b4f4fe1d031477dab1a5"
+ "hash": "a51667f575cf4e79bfb47146b9657f8069857ea4052183dd59b7f0dbb78ed1af"
}
diff --git a/crates/ai_billing/src/domain/ports.rs b/crates/ai_billing/src/domain/ports.rs
index c2f9a8c42e..cb7c3ed2cd 100644
--- a/crates/ai_billing/src/domain/ports.rs
+++ b/crates/ai_billing/src/domain/ports.rs
@@ -25,9 +25,12 @@ pub trait EntitlementSource: Send + Sync + 'static {
) -> impl Future<Output = Result<Option<String>>> + Send;
}
-/// Reads recorded AI usage at Macro's list rate.
+/// Reads recorded, metered AI usage at Macro's list rate.
pub trait UsageReader: Send + Sync + 'static {
/// List-rate usage for each of `users` within `period`.
+ ///
+ /// AI projections remain in `ai_usage` for cost tracking but do not
+ /// consume a user's allowance, credits, or overage.
fn list_rate_usage_cents_by_user(
&self,
users: &[MacroUserIdStr<'static>],
diff --git a/crates/ai_billing/src/outbound/pg_usage_reader.rs b/crates/ai_billing/src/outbound/pg_usage_reader.rs
index 50c5b9501e..f01f687f0f 100644
--- a/crates/ai_billing/src/outbound/pg_usage_reader.rs
+++ b/crates/ai_billing/src/outbound/pg_usage_reader.rs
@@ -1,6 +1,10 @@
//! Reads recorded AI usage from `ai_usage` at Macro's list rate.
+#[cfg(test)]
+mod test;
+
use crate::domain::{BillingError, BillingPeriod, Result, SeatUsage, UsageReader, list_rate_cents};
+use ai_usage::AiFeature;
use macro_user_id::user_id::MacroUserIdStr;
use sqlx::PgPool;
@@ -50,6 +54,7 @@ impl UsageReader for PgUsageReader {
WHERE user_id = ANY($1)
AND created_at >= $2
AND created_at < $3
+ AND feature <> $6
GROUP BY user_id
"#,
&ids,
@@ -57,6 +62,7 @@ impl UsageReader for PgUsageReader {
period.end,
FALLBACK_PRICE_PER_MILLION_IN,
FALLBACK_PRICE_PER_MILLION_OUT,
+ AiFeature::AiProjection.to_string(),
)
.fetch_all(&self.pool)
.await
diff --git a/crates/ai_billing/src/outbound/pg_usage_reader/test.rs b/crates/ai_billing/src/outbound/pg_usage_reader/test.rs
new file mode 100644
index 0000000000..3196c80b48
--- /dev/null
+++ b/crates/ai_billing/src/outbound/pg_usage_reader/test.rs
@@ -0,0 +1,85 @@
+use super::*;
+use ai_usage::outbound::PgUsageRepo;
+use ai_usage::{
+ CompletionUsage, ModelPricing, Price, Usage, UsageAmount, UsageApiParams, UsageRepo,
+};
+use chrono::{Duration, Utc};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+
+fn completion(
+ user: MacroUserIdStr<'static>,
+ feature: AiFeature,
+ provider_cost_usd: f32,
+) -> CompletionUsage {
+ CompletionUsage {
+ feature,
+ user,
+ entity: None,
+ cost: Usage {
+ amount: UsageAmount::Tokens {
+ input: 1_000_000,
+ output: 0,
+ },
+ model: "test-model".to_string(),
+ price: Some(Price {
+ pricing: ModelPricing::Tokens {
+ input: provider_cost_usd,
+ output: 0.0,
+ },
+ total: provider_cost_usd,
+ }),
+ created_at: Utc::now(),
+ },
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn ai_projection_usage_is_recorded_but_not_metered(pool: PgPool) {
+ let user =
+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let usage_repo = PgUsageRepo::new(pool.clone());
+ usage_repo
+ .insert_usage(&completion(user.clone(), AiFeature::Chat, 4.0))
+ .await
+ .unwrap();
+ usage_repo
+ .insert_usage(&completion(user.clone(), AiFeature::AiProjection, 8.0))
+ .await
+ .unwrap();
+
+ let mut stored_features: Vec<_> = usage_repo
+ .query_usage(&UsageApiParams {
+ include_users: vec![user.clone()],
+ ..Default::default()
+ })
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|usage| usage.feature)
+ .collect();
+ stored_features.sort();
+ assert_eq!(
+ stored_features,
+ vec![AiFeature::Chat, AiFeature::AiProjection]
+ );
+
+ let now = Utc::now();
+ let usage = PgUsageReader::new(pool)
+ .list_rate_usage_cents_by_user(
+ &[user.clone()],
+ BillingPeriod {
+ start: now - Duration::minutes(1),
+ end: now + Duration::minutes(1),
+ },
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ usage,
+ vec![SeatUsage {
+ user,
+ used_cents: 1_000,
+ }]
+ );
+}
diff --git a/crates/github/src/domain/models.rs b/crates/github/src/domain/models.rs
index c7ef8e5e82..453a553413 100644
--- a/crates/github/src/domain/models.rs
+++ b/crates/github/src/domain/models.rs
@@ -3,6 +3,7 @@
#[cfg(test)]
mod test;
+#[cfg(feature = "sync")]
mod app_jwt;
mod installation_state;
mod link;
@@ -10,7 +11,9 @@ mod pull_request;
mod repository;
mod sync;
+#[cfg(feature = "sync")]
pub use app_jwt::AppJwt;
+#[cfg(feature = "sync")]
pub(crate) use app_jwt::app_jwt;
pub use installation_state::{
InstallationState, InstallationStateError, sign_installation_state, verify_installation_state,