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.

feat(ai): track provider usage and add billing foundations (#7130)

Will Hutchinsonb91d99d44e18
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 9f123eb094..098897f641 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -1471,11 +1471,23 @@
],
"anthropic": [
"crates/ai_toolset",
+ "crates/ai_usage",
"crates/anthropic",
+ "crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/genai_telemetry",
+ "crates/harness_id",
+ "crates/harness_token",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_env",
"crates/macro_env_var",
"crates/macro_user_id",
+ "crates/macro_uuid",
+ "crates/model-error-response",
+ "crates/model_user",
+ "crates/remote_env_var",
"crates/workspace-hack"
],
"attachment": [
diff --git a/.sqlx/query-0422664f350ca0e137794470cf510befb8632f7f02035d3463b9c4ca386365de.json b/.sqlx/query-0422664f350ca0e137794470cf510befb8632f7f02035d3463b9c4ca386365de.json
new file mode 100644
index 0000000000..bdf9a2ff9f
--- /dev/null
+++ b/.sqlx/query-0422664f350ca0e137794470cf510befb8632f7f02035d3463b9c4ca386365de.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT (\n EXISTS(SELECT 1 FROM ai_billing_period_allowance WHERE user_id = $1 AND period_start = $2 AND $3 = ANY(billed_users))\n OR EXISTS(SELECT 1 FROM ai_overage_charge WHERE user_id = $1 AND period_start = $2 AND accounting_policy = 'legacy')\n OR EXISTS(SELECT 1 FROM ai_credit_ledger WHERE user_id = $1 AND period_start = $2 AND kind = 'consumption' AND funding_invocation_id IS NULL)\n ) AS \"used!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "used!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "0422664f350ca0e137794470cf510befb8632f7f02035d3463b9c4ca386365de"
+}
diff --git a/.sqlx/query-19aac9e8697e9913351702c92e2adf5e285d37891fe9bfe3426795fbb27c2b4c.json b/.sqlx/query-19aac9e8697e9913351702c92e2adf5e285d37891fe9bfe3426795fbb27c2b4c.json
new file mode 100644
index 0000000000..b5ca923b74
--- /dev/null
+++ b/.sqlx/query-19aac9e8697e9913351702c92e2adf5e285d37891fe9bfe3426795fbb27c2b4c.json
@@ -0,0 +1,19 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_billing_usage_period (user_id, payer_id, subscription_id, period_start, period_end, policy)\n VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Timestamptz",
+ "Timestamptz",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "19aac9e8697e9913351702c92e2adf5e285d37891fe9bfe3426795fbb27c2b4c"
+}
diff --git a/.sqlx/query-1fcfec153c06c1a248dff8dcd9cfe7303db4d591af1141c6dc9a5d27e4ac930b.json b/.sqlx/query-1fcfec153c06c1a248dff8dcd9cfe7303db4d591af1141c6dc9a5d27e4ac930b.json
new file mode 100644
index 0000000000..8e1cb0defe
--- /dev/null
+++ b/.sqlx/query-1fcfec153c06c1a248dff8dcd9cfe7303db4d591af1141c6dc9a5d27e4ac930b.json
@@ -0,0 +1,19 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_financial_rate\n (version, provider, model, effective_at, valid_until, publication)\n VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Timestamptz",
+ "Timestamptz",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1fcfec153c06c1a248dff8dcd9cfe7303db4d591af1141c6dc9a5d27e4ac930b"
+}
diff --git a/.sqlx/query-20f5acd27c33c121b7df74843febf9774859e94c3f1b86446b3f33cf4ec133b9.json b/.sqlx/query-20f5acd27c33c121b7df74843febf9774859e94c3f1b86446b3f33cf4ec133b9.json
new file mode 100644
index 0000000000..e0d7deea51
--- /dev/null
+++ b/.sqlx/query-20f5acd27c33c121b7df74843febf9774859e94c3f1b86446b3f33cf4ec133b9.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COALESCE(SUM(actual_public), 0)::bigint AS \"used!\" FROM ai_funding_reservation\n WHERE payer_id = $1 AND user_id = $2 AND period_start = $3 AND allocated",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "used!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "20f5acd27c33c121b7df74843febf9774859e94c3f1b86446b3f33cf4ec133b9"
+}
diff --git a/.sqlx/query-24da96efa6de9c9d56f6d363d941acbc4327ecd3fe11fbcb3bb63a67fd55bc4b.json b/.sqlx/query-24da96efa6de9c9d56f6d363d941acbc4327ecd3fe11fbcb3bb63a67fd55bc4b.json
new file mode 100644
index 0000000000..87abf6d5f4
--- /dev/null
+++ b/.sqlx/query-24da96efa6de9c9d56f6d363d941acbc4327ecd3fe11fbcb3bb63a67fd55bc4b.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT finalization AS \"finalization: Json<StateData>\"\n FROM ai_usage_observation WHERE invocation_id = $1 FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "finalization: Json<StateData>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "24da96efa6de9c9d56f6d363d941acbc4327ecd3fe11fbcb3bb63a67fd55bc4b"
+}
diff --git a/.sqlx/query-27289fa131cd5a458ef1f6f79b6424fcf6551590934d3201ce5ab67b2c750f6f.json b/.sqlx/query-27289fa131cd5a458ef1f6f79b6424fcf6551590934d3201ce5ab67b2c750f6f.json
new file mode 100644
index 0000000000..997cd41e33
--- /dev/null
+++ b/.sqlx/query-27289fa131cd5a458ef1f6f79b6424fcf6551590934d3201ce5ab67b2c750f6f.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT COALESCE(SUM(amount_cents), 0)::bigint AS \"charged!\"\n FROM ai_overage_charge\n WHERE user_id = $1\n AND period_start = $2\n AND accounting_policy = 'legacy'\n AND (status <> 'failed' OR stripe_invoice_id IS NOT NULL)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "charged!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "27289fa131cd5a458ef1f6f79b6424fcf6551590934d3201ce5ab67b2c750f6f"
+}
diff --git a/.sqlx/query-280f5030ca080b15d7221c09d4ecc4e603af3894aff05adf0853496b617af3ab.json b/.sqlx/query-280f5030ca080b15d7221c09d4ecc4e603af3894aff05adf0853496b617af3ab.json
new file mode 100644
index 0000000000..75d6bec97e
--- /dev/null
+++ b/.sqlx/query-280f5030ca080b15d7221c09d4ecc4e603af3894aff05adf0853496b617af3ab.json
@@ -0,0 +1,42 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT j.request AS \"request: Json<RequestData>\",\n r.publication AS \"publication: Json<RateData>\",\n j.funding AS \"funding: Json<FundingData>\",\n j.finalization AS \"finalization: Json<StateData>\"\n FROM ai_financial_invocation j JOIN ai_financial_rate r ON r.version = j.rate_version\n WHERE j.funding IS NOT NULL AND (j.recovery_required OR NOT j.funding_acknowledged)\n AND ($1::uuid IS NULL OR j.invocation_id > $1) AND j.occurred_at < $2\n ORDER BY j.invocation_id LIMIT $3",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "request: Json<RequestData>",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 1,
+ "name": "publication: Json<RateData>",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 2,
+ "name": "funding: Json<FundingData>",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 3,
+ "name": "finalization: Json<StateData>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "280f5030ca080b15d7221c09d4ecc4e603af3894aff05adf0853496b617af3ab"
+}
diff --git a/.sqlx/query-2ed3112c95f3ad29410270186f31e701f7dcb2368d1c17222a5b952039f996f4.json b/.sqlx/query-2ed3112c95f3ad29410270186f31e701f7dcb2368d1c17222a5b952039f996f4.json
new file mode 100644
index 0000000000..a73d262c76
--- /dev/null
+++ b/.sqlx/query-2ed3112c95f3ad29410270186f31e701f7dcb2368d1c17222a5b952039f996f4.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_credit_ledger (id, user_id, kind, delta_cents, period_start, funding_invocation_id, note)\n VALUES ($1, $2, 'consumption', $3, $4, $5, 'Authorized public-rate AI usage') ON CONFLICT (funding_invocation_id) DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Int8",
+ "Timestamptz",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2ed3112c95f3ad29410270186f31e701f7dcb2368d1c17222a5b952039f996f4"
+}
diff --git a/.sqlx/query-2f3df79e6958deadbb7fe5bdef538c7def1d7bf10d77bab8e53e39fec3c1bc15.json b/.sqlx/query-2f3df79e6958deadbb7fe5bdef538c7def1d7bf10d77bab8e53e39fec3c1bc15.json
new file mode 100644
index 0000000000..9e8288525b
--- /dev/null
+++ b/.sqlx/query-2f3df79e6958deadbb7fe5bdef538c7def1d7bf10d77bab8e53e39fec3c1bc15.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE ai_financial_invocation SET finalization = $2,\n recovery_required = $3, finalized_at = now() WHERE invocation_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb",
+ "Bool"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2f3df79e6958deadbb7fe5bdef538c7def1d7bf10d77bab8e53e39fec3c1bc15"
+}
diff --git a/.sqlx/query-30a38c7a082413ceecc45d5aa3f8c4613780722361fede37fb79ebe3639439f7.json b/.sqlx/query-30a38c7a082413ceecc45d5aa3f8c4613780722361fede37fb79ebe3639439f7.json
new file mode 100644
index 0000000000..cd5b41bc0a
--- /dev/null
+++ b/.sqlx/query-30a38c7a082413ceecc45d5aa3f8c4613780722361fede37fb79ebe3639439f7.json
@@ -0,0 +1,31 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT facts AS \"facts: Json<SeatPeriodObservation>\", decision AS \"decision: Json<PeriodDecision>\"\n FROM ai_billing_usage_observation WHERE event_id = $1 AND user_id = $2 AND subscription_id = $3 AND item_id = $4",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "facts: Json<SeatPeriodObservation>",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 1,
+ "name": "decision: Json<PeriodDecision>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "30a38c7a082413ceecc45d5aa3f8c4613780722361fede37fb79ebe3639439f7"
+}
diff --git a/.sqlx/query-32769e980bd65abeb0e8810499490deddbc73c6850576c5106b0c30efa5002f3.json b/.sqlx/query-32769e980bd65abeb0e8810499490deddbc73c6850576c5106b0c30efa5002f3.json
new file mode 100644
index 0000000000..9be60df46f
--- /dev/null
+++ b/.sqlx/query-32769e980bd65abeb0e8810499490deddbc73c6850576c5106b0c30efa5002f3.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM ai_financial_rate WHERE version = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "32769e980bd65abeb0e8810499490deddbc73c6850576c5106b0c30efa5002f3"
+}
diff --git a/.sqlx/query-336e25150643939eed2d3b63e27dfef8bcb272e8cbc58edc6aa60d08dd1ec090.json b/.sqlx/query-336e25150643939eed2d3b63e27dfef8bcb272e8cbc58edc6aa60d08dd1ec090.json
new file mode 100644
index 0000000000..241e70cf79
--- /dev/null
+++ b/.sqlx/query-336e25150643939eed2d3b63e27dfef8bcb272e8cbc58edc6aa60d08dd1ec090.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_billing_account (user_id) VALUES ($1) ON CONFLICT DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "336e25150643939eed2d3b63e27dfef8bcb272e8cbc58edc6aa60d08dd1ec090"
+}
diff --git a/.sqlx/query-3cbc947ef08f79a6832f9cc05b22417ebf390b2776a1f75856e00089e5dd3358.json b/.sqlx/query-3cbc947ef08f79a6832f9cc05b22417ebf390b2776a1f75856e00089e5dd3358.json
new file mode 100644
index 0000000000..eb97915186
--- /dev/null
+++ b/.sqlx/query-3cbc947ef08f79a6832f9cc05b22417ebf390b2776a1f75856e00089e5dd3358.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_funding_prepaid_release (payer_id, sequence, through_sequence, units) VALUES ($1,$2,$3,$4) ON CONFLICT DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Int8",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3cbc947ef08f79a6832f9cc05b22417ebf390b2776a1f75856e00089e5dd3358"
+}
diff --git a/.sqlx/query-46f00e9f6f28a586aab06bd62938c813f46f6b259880942a7efc79042f7d39c7.json b/.sqlx/query-46f00e9f6f28a586aab06bd62938c813f46f6b259880942a7efc79042f7d39c7.json
new file mode 100644
index 0000000000..9ff776423d
--- /dev/null
+++ b/.sqlx/query-46f00e9f6f28a586aab06bd62938c813f46f6b259880942a7efc79042f7d39c7.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT user_id FROM ai_billing_account WHERE user_id = $1 FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "46f00e9f6f28a586aab06bd62938c813f46f6b259880942a7efc79042f7d39c7"
+}
diff --git a/.sqlx/query-47a63d040f2c46b77091eacf0da4e91ab30230de0812ad8ba6c2d346b3b2f257.json b/.sqlx/query-47a63d040f2c46b77091eacf0da4e91ab30230de0812ad8ba6c2d346b3b2f257.json
new file mode 100644
index 0000000000..eac028b7ea
--- /dev/null
+++ b/.sqlx/query-47a63d040f2c46b77091eacf0da4e91ab30230de0812ad8ba6c2d346b3b2f257.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT invocation_id FROM ai_funding_reservation WHERE NOT allocated AND created_at < $1\n AND ($2::uuid IS NULL OR invocation_id > $2) ORDER BY invocation_id LIMIT $3",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "invocation_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Timestamptz",
+ "Uuid",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "47a63d040f2c46b77091eacf0da4e91ab30230de0812ad8ba6c2d346b3b2f257"
+}
diff --git a/.sqlx/query-497b6f9620162618496bac7fc86c7233bda6fe16c7cf8d3bf05f36a3b0c0257d.json b/.sqlx/query-497b6f9620162618496bac7fc86c7233bda6fe16c7cf8d3bf05f36a3b0c0257d.json
new file mode 100644
index 0000000000..fdb02a6cee
--- /dev/null
+++ b/.sqlx/query-497b6f9620162618496bac7fc86c7233bda6fe16c7cf8d3bf05f36a3b0c0257d.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_funding_state (user_id) VALUES ($1) ON CONFLICT DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "497b6f9620162618496bac7fc86c7233bda6fe16c7cf8d3bf05f36a3b0c0257d"
+}
diff --git a/.sqlx/query-4e5a63007bc391d03ec6a6b1a4c9a618781ee3486f1a0f4ada3454319324043a.json b/.sqlx/query-4e5a63007bc391d03ec6a6b1a4c9a618781ee3486f1a0f4ada3454319324043a.json
new file mode 100644
index 0000000000..0a278654e4
--- /dev/null
+++ b/.sqlx/query-4e5a63007bc391d03ec6a6b1a4c9a618781ee3486f1a0f4ada3454319324043a.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE ai_funding_state SET watermark = watermark + 1, prepaid_remainder = $2 WHERE user_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "4e5a63007bc391d03ec6a6b1a4c9a618781ee3486f1a0f4ada3454319324043a"
+}
diff --git a/.sqlx/query-53908392b5b0672b2fcc4cf2506e508939bd5318c6729535d80fc026d117e90c.json b/.sqlx/query-53908392b5b0672b2fcc4cf2506e508939bd5318c6729535d80fc026d117e90c.json
new file mode 100644
index 0000000000..b138956834
--- /dev/null
+++ b/.sqlx/query-53908392b5b0672b2fcc4cf2506e508939bd5318c6729535d80fc026d117e90c.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE ai_funding_intent SET denied = TRUE WHERE invocation_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "53908392b5b0672b2fcc4cf2506e508939bd5318c6729535d80fc026d117e90c"
+}
diff --git a/.sqlx/query-54668a2405ce35f89ff7be09e0f0bc188879c5beba015ed27d8b5e3ee21f8827.json b/.sqlx/query-54668a2405ce35f89ff7be09e0f0bc188879c5beba015ed27d8b5e3ee21f8827.json
new file mode 100644
index 0000000000..acc0ad39ce
--- /dev/null
+++ b/.sqlx/query-54668a2405ce35f89ff7be09e0f0bc188879c5beba015ed27d8b5e3ee21f8827.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT identity, denied FROM ai_funding_intent WHERE invocation_id = $1 FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "identity",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 1,
+ "name": "denied",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "54668a2405ce35f89ff7be09e0f0bc188879c5beba015ed27d8b5e3ee21f8827"
+}
diff --git a/.sqlx/query-5a28e11d69dd37dbc63881772fb3ece9fedce2ceb6263bf5a7fb3145502cd3c1.json b/.sqlx/query-5a28e11d69dd37dbc63881772fb3ece9fedce2ceb6263bf5a7fb3145502cd3c1.json
new file mode 100644
index 0000000000..7153d2a390
--- /dev/null
+++ b/.sqlx/query-5a28e11d69dd37dbc63881772fb3ece9fedce2ceb6263bf5a7fb3145502cd3c1.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE ai_financial_invocation SET funding = $2 WHERE invocation_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5a28e11d69dd37dbc63881772fb3ece9fedce2ceb6263bf5a7fb3145502cd3c1"
+}
diff --git a/.sqlx/query-5c1390339a382278471343f73b60614ba9fea72013ed7f38c7d18cdea39d91fb.json b/.sqlx/query-5c1390339a382278471343f73b60614ba9fea72013ed7f38c7d18cdea39d91fb.json
new file mode 100644
index 0000000000..b94bc8d5ee
--- /dev/null
+++ b/.sqlx/query-5c1390339a382278471343f73b60614ba9fea72013ed7f38c7d18cdea39d91fb.json
@@ -0,0 +1,52 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT included_public, extra_public, prepaid, reclaimed_prepaid, postpaid, macro_absorbed\n FROM ai_funding_reservation WHERE invocation_id = $1 AND allocated",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "included_public",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "extra_public",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 2,
+ "name": "prepaid",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "reclaimed_prepaid",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 4,
+ "name": "postpaid",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 5,
+ "name": "macro_absorbed",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "5c1390339a382278471343f73b60614ba9fea72013ed7f38c7d18cdea39d91fb"
+}
diff --git a/.sqlx/query-619e374061fd7560c09d3831e7ba51d0bc2224de8f48ef6abbc3f3021932c06e.json b/.sqlx/query-619e374061fd7560c09d3831e7ba51d0bc2224de8f48ef6abbc3f3021932c06e.json
new file mode 100644
index 0000000000..1833aabf1c
--- /dev/null
+++ b/.sqlx/query-619e374061fd7560c09d3831e7ba51d0bc2224de8f48ef6abbc3f3021932c06e.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT publication AS \"publication: Json<RateData>\"\n FROM ai_financial_rate\n WHERE provider = $1 AND model = $2 AND effective_at <= $3\n ORDER BY effective_at DESC LIMIT 1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "publication: Json<RateData>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "619e374061fd7560c09d3831e7ba51d0bc2224de8f48ef6abbc3f3021932c06e"
+}
diff --git a/.sqlx/query-61af8cd8a106bf80fe1f065134f7e7625a9e968b59757dbc564b68dc7a29aa85.json b/.sqlx/query-61af8cd8a106bf80fe1f065134f7e7625a9e968b59757dbc564b68dc7a29aa85.json
new file mode 100644
index 0000000000..d452700540
--- /dev/null
+++ b/.sqlx/query-61af8cd8a106bf80fe1f065134f7e7625a9e968b59757dbc564b68dc7a29aa85.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM ai_funding_prepaid_release WHERE payer_id = $1 AND through_sequence <= $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "61af8cd8a106bf80fe1f065134f7e7625a9e968b59757dbc564b68dc7a29aa85"
+}
diff --git a/.sqlx/query-6471b41967948f44f0bc8c2df2bcfd3673ae7d74dc032ab4ba6d1addb2d0f109.json b/.sqlx/query-6471b41967948f44f0bc8c2df2bcfd3673ae7d74dc032ab4ba6d1addb2d0f109.json
new file mode 100644
index 0000000000..09a72ad822
--- /dev/null
+++ b/.sqlx/query-6471b41967948f44f0bc8c2df2bcfd3673ae7d74dc032ab4ba6d1addb2d0f109.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT admission AS \"admission: Json<AdmissionData>\" FROM ai_funding_reservation WHERE invocation_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "admission: Json<AdmissionData>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "6471b41967948f44f0bc8c2df2bcfd3673ae7d74dc032ab4ba6d1addb2d0f109"
+}
diff --git a/.sqlx/query-6a3b43433310b498c8eb24ebf0870ff6017a7491c1f0491d75c56735977812a3.json b/.sqlx/query-6a3b43433310b498c8eb24ebf0870ff6017a7491c1f0491d75c56735977812a3.json
new file mode 100644
index 0000000000..19323b7bf6
--- /dev/null
+++ b/.sqlx/query-6a3b43433310b498c8eb24ebf0870ff6017a7491c1f0491d75c56735977812a3.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT user_id FROM ai_billing_usage_period WHERE user_id = ANY($1)\n AND policy = 'public_allowance_v1' AND period_start < $3 AND period_end > $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "6a3b43433310b498c8eb24ebf0870ff6017a7491c1f0491d75c56735977812a3"
+}
diff --git a/.sqlx/query-6cc9118255c2d9e7c04094ebed34e1641069fb2ad8be27c8d1513b20a031b914.json b/.sqlx/query-6cc9118255c2d9e7c04094ebed34e1641069fb2ad8be27c8d1513b20a031b914.json
new file mode 100644
index 0000000000..d479c2aed6
--- /dev/null
+++ b/.sqlx/query-6cc9118255c2d9e7c04094ebed34e1641069fb2ad8be27c8d1513b20a031b914.json
@@ -0,0 +1,19 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_billing_usage_period (user_id, payer_id, subscription_id, period_start, period_end, policy)\n VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Timestamptz",
+ "Timestamptz",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "6cc9118255c2d9e7c04094ebed34e1641069fb2ad8be27c8d1513b20a031b914"
+}
diff --git a/.sqlx/query-6f05a75418c6fb961c199a48e86707c04e9f91952080c5fd3f28a983b7d9cd2a.json b/.sqlx/query-6f05a75418c6fb961c199a48e86707c04e9f91952080c5fd3f28a983b7d9cd2a.json
new file mode 100644
index 0000000000..c20698f8ff
--- /dev/null
+++ b/.sqlx/query-6f05a75418c6fb961c199a48e86707c04e9f91952080c5fd3f28a983b7d9cd2a.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE ai_usage_observation SET finalization = $2, finalized_at = now()\n WHERE invocation_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "6f05a75418c6fb961c199a48e86707c04e9f91952080c5fd3f28a983b7d9cd2a"
+}
diff --git a/.sqlx/query-74476621882c558774449b191be0247686be4cbf3abf133b48bfd6ca1f4ea9a8.json b/.sqlx/query-74476621882c558774449b191be0247686be4cbf3abf133b48bfd6ca1f4ea9a8.json
new file mode 100644
index 0000000000..9563dc0dbd
--- /dev/null
+++ b/.sqlx/query-74476621882c558774449b191be0247686be4cbf3abf133b48bfd6ca1f4ea9a8.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE ai_financial_invocation SET finalization = NULL, finalized_at = NULL WHERE invocation_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "74476621882c558774449b191be0247686be4cbf3abf133b48bfd6ca1f4ea9a8"
+}
diff --git a/.sqlx/query-7724f36f7904253f6bccd8db3b5d2eb180669cc5363bf47875bb22c64312731b.json b/.sqlx/query-7724f36f7904253f6bccd8db3b5d2eb180669cc5363bf47875bb22c64312731b.json
new file mode 100644
index 0000000000..354eede8e1
--- /dev/null
+++ b/.sqlx/query-7724f36f7904253f6bccd8db3b5d2eb180669cc5363bf47875bb22c64312731b.json
@@ -0,0 +1,41 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, amount_cents, stripe_invoice_id, status::text AS \"status!\"\n FROM ai_overage_charge\n WHERE user_id = $1\n AND period_start = $2\n AND accounting_policy = 'legacy'\n AND (\n status = 'failed'\n OR (\n status = 'pending'\n AND stripe_invoice_id IS NULL\n AND updated_at < NOW() - INTERVAL '10 minutes'\n )\n )\n ORDER BY created_at\n FOR UPDATE\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "amount_cents",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 2,
+ "name": "stripe_invoice_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "status!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ null
+ ]
+ },
+ "hash": "7724f36f7904253f6bccd8db3b5d2eb180669cc5363bf47875bb22c64312731b"
+}
diff --git a/.sqlx/query-786dd4d53269c55a1865fedd231901cff70a3fe3a814eaeb3883e038e53c086e.json b/.sqlx/query-786dd4d53269c55a1865fedd231901cff70a3fe3a814eaeb3883e038e53c086e.json
new file mode 100644
index 0000000000..417b14c176
--- /dev/null
+++ b/.sqlx/query-786dd4d53269c55a1865fedd231901cff70a3fe3a814eaeb3883e038e53c086e.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_overage_charge (id, user_id, period_start, amount_cents, status, accounting_policy)\n VALUES ($1, $2, $3, 105, 'paid', 'public_allowance_v1')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "786dd4d53269c55a1865fedd231901cff70a3fe3a814eaeb3883e038e53c086e"
+}
diff --git a/.sqlx/query-7cbcbc3617689c95be4b5c3caf6d27ea7846645f94eee38fc23f035d520b2e3c.json b/.sqlx/query-7cbcbc3617689c95be4b5c3caf6d27ea7846645f94eee38fc23f035d520b2e3c.json
new file mode 100644
index 0000000000..8890af70ea
--- /dev/null
+++ b/.sqlx/query-7cbcbc3617689c95be4b5c3caf6d27ea7846645f94eee38fc23f035d520b2e3c.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS(SELECT 1 FROM ai_billing_usage_period\n WHERE user_id = $1 AND period_start < $3 AND period_end > $2) AS \"exists!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "7cbcbc3617689c95be4b5c3caf6d27ea7846645f94eee38fc23f035d520b2e3c"
+}
diff --git a/.sqlx/query-7dbe1525e041dd133ca8e665d9ce2c580e5df3d1d4ec0e40f8dbd211a1203af2.json b/.sqlx/query-7dbe1525e041dd133ca8e665d9ce2c580e5df3d1d4ec0e40f8dbd211a1203af2.json
new file mode 100644
index 0000000000..8021e9baef
--- /dev/null
+++ b/.sqlx/query-7dbe1525e041dd133ca8e665d9ce2c580e5df3d1d4ec0e40f8dbd211a1203af2.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE ai_funding_reservation SET allocated = TRUE, included_public = $2, extra_public = $3,\n prepaid = $4, reclaimed_prepaid = $5, postpaid = $6, macro_absorbed = $7 WHERE invocation_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8",
+ "Int8",
+ "Int8",
+ "Int8",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "7dbe1525e041dd133ca8e665d9ce2c580e5df3d1d4ec0e40f8dbd211a1203af2"
+}
diff --git a/.sqlx/query-80ab02c43d201cf0a703fcea5e8d137329942dc7fabecce1cfbeb06c82e05130.json b/.sqlx/query-80ab02c43d201cf0a703fcea5e8d137329942dc7fabecce1cfbeb06c82e05130.json
new file mode 100644
index 0000000000..4310dc968b
--- /dev/null
+++ b/.sqlx/query-80ab02c43d201cf0a703fcea5e8d137329942dc7fabecce1cfbeb06c82e05130.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT publication AS \"publication: Json<RateData>\"\n FROM ai_financial_rate WHERE version = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "publication: Json<RateData>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "80ab02c43d201cf0a703fcea5e8d137329942dc7fabecce1cfbeb06c82e05130"
+}
diff --git a/.sqlx/query-85a0dea7efa1b0f59b36afe382544e36beb1737c14cb9fc3ad0868bb747abdc4.json b/.sqlx/query-85a0dea7efa1b0f59b36afe382544e36beb1737c14cb9fc3ad0868bb747abdc4.json
new file mode 100644
index 0000000000..d592696be5
--- /dev/null
+++ b/.sqlx/query-85a0dea7efa1b0f59b36afe382544e36beb1737c14cb9fc3ad0868bb747abdc4.json
@@ -0,0 +1,19 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_billing_usage_observation (event_id, user_id, subscription_id, item_id, facts, decision)\n VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Jsonb",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "85a0dea7efa1b0f59b36afe382544e36beb1737c14cb9fc3ad0868bb747abdc4"
+}
diff --git a/.sqlx/query-884f5823f4f66eb6ef85dd767fd36dbab7fe8412b0c3ef0e2d54cfc09c8d077c.json b/.sqlx/query-884f5823f4f66eb6ef85dd767fd36dbab7fe8412b0c3ef0e2d54cfc09c8d077c.json
new file mode 100644
index 0000000000..b62c6d9771
--- /dev/null
+++ b/.sqlx/query-884f5823f4f66eb6ef85dd767fd36dbab7fe8412b0c3ef0e2d54cfc09c8d077c.json
@@ -0,0 +1,42 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT\n COALESCE(SUM(actual_public) FILTER (WHERE allocated AND user_id = $2), 0)::bigint AS \"used!\",\n COALESCE(SUM(included_hold) FILTER (WHERE NOT allocated AND user_id = $2), 0)::bigint AS \"included_held!\",\n COALESCE(SUM(postpaid) FILTER (WHERE allocated), 0)::bigint AS \"postpaid!\",\n COALESCE(SUM(postpaid_hold) FILTER (WHERE NOT allocated), 0)::bigint AS \"postpaid_held!\"\n FROM ai_funding_reservation WHERE payer_id = $1 AND period_start = $3",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "used!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "included_held!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 2,
+ "name": "postpaid!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "postpaid_held!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null,
+ null,
+ null,
+ null
+ ]
+ },
+ "hash": "884f5823f4f66eb6ef85dd767fd36dbab7fe8412b0c3ef0e2d54cfc09c8d077c"
+}
diff --git a/.sqlx/query-8d449867fb53f9637e9f6d370d79c6783b02df65f47e724826f7929f2321a520.json b/.sqlx/query-8d449867fb53f9637e9f6d370d79c6783b02df65f47e724826f7929f2321a520.json
new file mode 100644
index 0000000000..9e321c43f5
--- /dev/null
+++ b/.sqlx/query-8d449867fb53f9637e9f6d370d79c6783b02df65f47e724826f7929f2321a520.json
@@ -0,0 +1,46 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT a.overage_enabled, a.overage_limit_cents, a.overage_suspended_at, a.authorization_revision,\n f.next_sequence FROM ai_billing_account a JOIN ai_funding_state f USING (user_id) WHERE a.user_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "overage_enabled",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "overage_limit_cents",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 2,
+ "name": "overage_suspended_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 3,
+ "name": "authorization_revision",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 4,
+ "name": "next_sequence",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "8d449867fb53f9637e9f6d370d79c6783b02df65f47e724826f7929f2321a520"
+}
diff --git a/.sqlx/query-928cb329088ea58f1d95f4b6a8d67ff1e160773a15198159a00656b3f8f5d827.json b/.sqlx/query-928cb329088ea58f1d95f4b6a8d67ff1e160773a15198159a00656b3f8f5d827.json
new file mode 100644
index 0000000000..f81824c3e4
--- /dev/null
+++ b/.sqlx/query-928cb329088ea58f1d95f4b6a8d67ff1e160773a15198159a00656b3f8f5d827.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_funding_reservation (invocation_id, authorization_id, payer_id, sequence, user_id, period_start,\n admission, included_hold, prepaid_hold, postpaid_hold) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) ON CONFLICT DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Int8",
+ "Text",
+ "Timestamptz",
+ "Jsonb",
+ "Int8",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "928cb329088ea58f1d95f4b6a8d67ff1e160773a15198159a00656b3f8f5d827"
+}
diff --git a/.sqlx/query-966d5a2784b4f2b966b4eacacf66610395f955db52f8b8f52a00448162f5aa02.json b/.sqlx/query-966d5a2784b4f2b966b4eacacf66610395f955db52f8b8f52a00448162f5aa02.json
new file mode 100644
index 0000000000..fa619e1e9a
--- /dev/null
+++ b/.sqlx/query-966d5a2784b4f2b966b4eacacf66610395f955db52f8b8f52a00448162f5aa02.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_billing_usage_rollout (policy, configuration) VALUES ('public_allowance_v1', $1) ON CONFLICT DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "966d5a2784b4f2b966b4eacacf66610395f955db52f8b8f52a00448162f5aa02"
+}
diff --git a/.sqlx/query-96db76be911fb6d927bf56c94054f02e0172cc4031f8e1822053c3745d2672e8.json b/.sqlx/query-96db76be911fb6d927bf56c94054f02e0172cc4031f8e1822053c3745d2672e8.json
new file mode 100644
index 0000000000..024cdd3ee5
--- /dev/null
+++ b/.sqlx/query-96db76be911fb6d927bf56c94054f02e0172cc4031f8e1822053c3745d2672e8.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_funding_intent (invocation_id, identity) VALUES ($1, $2) ON CONFLICT DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "96db76be911fb6d927bf56c94054f02e0172cc4031f8e1822053c3745d2672e8"
+}
diff --git a/.sqlx/query-9caa00338d5f998133f6af3af66c96938c488b90cf441b79dd806bee80fa9041.json b/.sqlx/query-9caa00338d5f998133f6af3af66c96938c488b90cf441b79dd806bee80fa9041.json
new file mode 100644
index 0000000000..6c67ef2f47
--- /dev/null
+++ b/.sqlx/query-9caa00338d5f998133f6af3af66c96938c488b90cf441b79dd806bee80fa9041.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_billing_usage_eligibility (user_id, subscription_id, item_id, identity, state)\n VALUES ($1,$2,$3,$4,$5) ON CONFLICT (user_id, subscription_id, item_id) DO UPDATE SET state = EXCLUDED.state",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Jsonb",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9caa00338d5f998133f6af3af66c96938c488b90cf441b79dd806bee80fa9041"
+}
diff --git a/.sqlx/query-9d7b3c808b6a8786431fb21520308c90c3bb34d4ac49d7a0f337a751d2ae2211.json b/.sqlx/query-9d7b3c808b6a8786431fb21520308c90c3bb34d4ac49d7a0f337a751d2ae2211.json
new file mode 100644
index 0000000000..a6826f0a7a
--- /dev/null
+++ b/.sqlx/query-9d7b3c808b6a8786431fb21520308c90c3bb34d4ac49d7a0f337a751d2ae2211.json
@@ -0,0 +1,53 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT user_id, payer_id, subscription_id, period_start, period_end, policy FROM ai_billing_usage_period\n WHERE user_id = $1 AND period_start <= $2 AND period_end > $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "payer_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "subscription_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "period_start",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 4,
+ "name": "period_end",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "policy",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "9d7b3c808b6a8786431fb21520308c90c3bb34d4ac49d7a0f337a751d2ae2211"
+}
diff --git a/.sqlx/query-9db8784c9154097ffdc92e816bc629cc83da88cb39f177178a986ebbe9601283.json b/.sqlx/query-9db8784c9154097ffdc92e816bc629cc83da88cb39f177178a986ebbe9601283.json
new file mode 100644
index 0000000000..40273c0b49
--- /dev/null
+++ b/.sqlx/query-9db8784c9154097ffdc92e816bc629cc83da88cb39f177178a986ebbe9601283.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE ai_funding_prepaid_release SET units = units - $3 WHERE payer_id = $1 AND sequence = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9db8784c9154097ffdc92e816bc629cc83da88cb39f177178a986ebbe9601283"
+}
diff --git a/.sqlx/query-9e630408ab64e086f3d05ce57b9e612cc71856aa421640675dedb7fae95c2c09.json b/.sqlx/query-9e630408ab64e086f3d05ce57b9e612cc71856aa421640675dedb7fae95c2c09.json
new file mode 100644
index 0000000000..ef38737f9e
--- /dev/null
+++ b/.sqlx/query-9e630408ab64e086f3d05ce57b9e612cc71856aa421640675dedb7fae95c2c09.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT finalization AS \"finalization: Json<StateData>\" FROM ai_usage_observation WHERE invocation_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "finalization: Json<StateData>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "9e630408ab64e086f3d05ce57b9e612cc71856aa421640675dedb7fae95c2c09"
+}
diff --git a/.sqlx/query-9ebf8f16483066f181f617ec1cee7907f4a9c1141bd45c8c5c4851e9c9d77281.json b/.sqlx/query-9ebf8f16483066f181f617ec1cee7907f4a9c1141bd45c8c5c4851e9c9d77281.json
new file mode 100644
index 0000000000..762b304e58
--- /dev/null
+++ b/.sqlx/query-9ebf8f16483066f181f617ec1cee7907f4a9c1141bd45c8c5c4851e9c9d77281.json
@@ -0,0 +1,30 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT identity, state AS \"state: Json<EligibilityState>\" FROM ai_billing_usage_eligibility\n WHERE user_id = $1 AND subscription_id = $2 AND item_id = $3",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "identity",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 1,
+ "name": "state: Json<EligibilityState>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "9ebf8f16483066f181f617ec1cee7907f4a9c1141bd45c8c5c4851e9c9d77281"
+}
diff --git a/.sqlx/query-a4ad80f1fba67280db263dc839150756f5b4f640d9212918eec8116c26138425.json b/.sqlx/query-a4ad80f1fba67280db263dc839150756f5b4f640d9212918eec8116c26138425.json
new file mode 100644
index 0000000000..4d360d4577
--- /dev/null
+++ b/.sqlx/query-a4ad80f1fba67280db263dc839150756f5b4f640d9212918eec8116c26138425.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT configuration AS \"configuration: Json<UsageRollout>\" FROM ai_billing_usage_rollout WHERE policy = 'public_allowance_v1'",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "configuration: Json<UsageRollout>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "a4ad80f1fba67280db263dc839150756f5b4f640d9212918eec8116c26138425"
+}
diff --git a/.sqlx/query-a90ce080fa5c03ee3f9a9ac5053610a439192f2e9359fb52f1d5ab4a7a5c9ad6.json b/.sqlx/query-a90ce080fa5c03ee3f9a9ac5053610a439192f2e9359fb52f1d5ab4a7a5c9ad6.json
new file mode 100644
index 0000000000..22f74cd8bd
--- /dev/null
+++ b/.sqlx/query-a90ce080fa5c03ee3f9a9ac5053610a439192f2e9359fb52f1d5ab4a7a5c9ad6.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT j.request AS \"request: Json<RequestData>\",\n r.publication AS \"publication: Json<RateData>\",\n j.funding AS \"funding: Json<FundingData>\",\n j.finalization AS \"finalization: Json<StateData>\"\n FROM ai_financial_invocation j JOIN ai_financial_rate r ON r.version = j.rate_version\n WHERE j.invocation_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "request: Json<RequestData>",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 1,
+ "name": "publication: Json<RateData>",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 2,
+ "name": "funding: Json<FundingData>",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 3,
+ "name": "finalization: Json<StateData>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "a90ce080fa5c03ee3f9a9ac5053610a439192f2e9359fb52f1d5ab4a7a5c9ad6"
+}
diff --git a/.sqlx/query-acbfde5ceed9ad24f4a14c231f29cd3ee1509cf21ebd4b6201f52135ee53c91f.json b/.sqlx/query-acbfde5ceed9ad24f4a14c231f29cd3ee1509cf21ebd4b6201f52135ee53c91f.json
new file mode 100644
index 0000000000..fae72596c9
--- /dev/null
+++ b/.sqlx/query-acbfde5ceed9ad24f4a14c231f29cd3ee1509cf21ebd4b6201f52135ee53c91f.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT count(*) FROM ai_financial_invocation",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "acbfde5ceed9ad24f4a14c231f29cd3ee1509cf21ebd4b6201f52135ee53c91f"
+}
diff --git a/.sqlx/query-adf44cbb3d760af4502a9a46e4ac7936fead71ffe6cb571dbe7ef8fccdf50d83.json b/.sqlx/query-adf44cbb3d760af4502a9a46e4ac7936fead71ffe6cb571dbe7ef8fccdf50d83.json
new file mode 100644
index 0000000000..2641e4a598
--- /dev/null
+++ b/.sqlx/query-adf44cbb3d760af4502a9a46e4ac7936fead71ffe6cb571dbe7ef8fccdf50d83.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE ai_financial_rate SET model = 'mutated' WHERE version = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "adf44cbb3d760af4502a9a46e4ac7936fead71ffe6cb571dbe7ef8fccdf50d83"
+}
diff --git a/.sqlx/query-b553087fb1cd8ad735f479822df14d802bc2e5dfa58fd653448473517298ee41.json b/.sqlx/query-b553087fb1cd8ad735f479822df14d802bc2e5dfa58fd653448473517298ee41.json
new file mode 100644
index 0000000000..ba79575c8b
--- /dev/null
+++ b/.sqlx/query-b553087fb1cd8ad735f479822df14d802bc2e5dfa58fd653448473517298ee41.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT j.request AS \"request: Json<RequestData>\",\n r.publication AS \"publication: Json<RateData>\",\n j.funding AS \"funding: Json<FundingData>\",\n j.finalization AS \"finalization: Json<StateData>\"\n FROM ai_financial_invocation j JOIN ai_financial_rate r ON r.version = j.rate_version\n WHERE j.invocation_id = $1 FOR UPDATE OF j",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "request: Json<RequestData>",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 1,
+ "name": "publication: Json<RateData>",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 2,
+ "name": "funding: Json<FundingData>",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 3,
+ "name": "finalization: Json<StateData>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "b553087fb1cd8ad735f479822df14d802bc2e5dfa58fd653448473517298ee41"
+}
diff --git a/.sqlx/query-bb237f2550e3837f292dbb66ccc8cf198d6ca6f0928a31372d48c4a2d81ebc13.json b/.sqlx/query-bb237f2550e3837f292dbb66ccc8cf198d6ca6f0928a31372d48c4a2d81ebc13.json
new file mode 100644
index 0000000000..df48b417d0
--- /dev/null
+++ b/.sqlx/query-bb237f2550e3837f292dbb66ccc8cf198d6ca6f0928a31372d48c4a2d81ebc13.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_financial_invocation (invocation_id, rate_version, occurred_at, request)\n VALUES ($1, $2, $3, $4) ON CONFLICT (invocation_id) DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Timestamptz",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "bb237f2550e3837f292dbb66ccc8cf198d6ca6f0928a31372d48c4a2d81ebc13"
+}
diff --git a/.sqlx/query-bd362b7bde0271e53c2e9d10f9597cc8e8e05fd48832d0c4727e8f61c92e50aa.json b/.sqlx/query-bd362b7bde0271e53c2e9d10f9597cc8e8e05fd48832d0c4727e8f61c92e50aa.json
new file mode 100644
index 0000000000..b4b8ca2d65
--- /dev/null
+++ b/.sqlx/query-bd362b7bde0271e53c2e9d10f9597cc8e8e05fd48832d0c4727e8f61c92e50aa.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT sequence, units FROM ai_funding_prepaid_release WHERE payer_id = $1 AND through_sequence >= $2 ORDER BY sequence",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "sequence",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "units",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "bd362b7bde0271e53c2e9d10f9597cc8e8e05fd48832d0c4727e8f61c92e50aa"
+}
diff --git a/.sqlx/query-c51f26f7fd7b06ac8db307bb6fabc8be0aefdeb9e64d58ada66c8fc143139fbc.json b/.sqlx/query-c51f26f7fd7b06ac8db307bb6fabc8be0aefdeb9e64d58ada66c8fc143139fbc.json
new file mode 100644
index 0000000000..69a167a0ae
--- /dev/null
+++ b/.sqlx/query-c51f26f7fd7b06ac8db307bb6fabc8be0aefdeb9e64d58ada66c8fc143139fbc.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT COALESCE(-SUM(delta_cents), 0)::bigint AS \"consumed!\"\n FROM ai_credit_ledger\n WHERE user_id = $1 AND kind = 'consumption' AND period_start = $2\n AND funding_invocation_id IS NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "consumed!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "c51f26f7fd7b06ac8db307bb6fabc8be0aefdeb9e64d58ada66c8fc143139fbc"
+}
diff --git a/.sqlx/query-cbeb3e4d4021cdfd6f3f24d389c00f4b0b7c3c6b1c1e2c6fecabad8ac8172c37.json b/.sqlx/query-cbeb3e4d4021cdfd6f3f24d389c00f4b0b7c3c6b1c1e2c6fecabad8ac8172c37.json
new file mode 100644
index 0000000000..66529c958c
--- /dev/null
+++ b/.sqlx/query-cbeb3e4d4021cdfd6f3f24d389c00f4b0b7c3c6b1c1e2c6fecabad8ac8172c37.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE ai_funding_state SET next_sequence = next_sequence + 1 WHERE user_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "cbeb3e4d4021cdfd6f3f24d389c00f4b0b7c3c6b1c1e2c6fecabad8ac8172c37"
+}
diff --git a/.sqlx/query-cc4f754e35a3d3bfcd58fb3e5f98fce7aab8bdeeaa6419ce2a98b52ff4c3b107.json b/.sqlx/query-cc4f754e35a3d3bfcd58fb3e5f98fce7aab8bdeeaa6419ce2a98b52ff4c3b107.json
new file mode 100644
index 0000000000..47da2adcc0
--- /dev/null
+++ b/.sqlx/query-cc4f754e35a3d3bfcd58fb3e5f98fce7aab8bdeeaa6419ce2a98b52ff4c3b107.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT count(*) FROM ai_usage",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "cc4f754e35a3d3bfcd58fb3e5f98fce7aab8bdeeaa6419ce2a98b52ff4c3b107"
+}
diff --git a/.sqlx/query-d024840942fdd0c664ff6233fd8f42bdcddc37bd76b8e54fe0dc5b7543b5bdc5.json b/.sqlx/query-d024840942fdd0c664ff6233fd8f42bdcddc37bd76b8e54fe0dc5b7543b5bdc5.json
new file mode 100644
index 0000000000..5546bd6c3f
--- /dev/null
+++ b/.sqlx/query-d024840942fdd0c664ff6233fd8f42bdcddc37bd76b8e54fe0dc5b7543b5bdc5.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM ai_funding_prepaid_release WHERE payer_id = $1 AND sequence = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "d024840942fdd0c664ff6233fd8f42bdcddc37bd76b8e54fe0dc5b7543b5bdc5"
+}
diff --git a/.sqlx/query-d17c1df5dfcdd5efd7024810961350e86dd88214e54bd428e992d602f25a7b18.json b/.sqlx/query-d17c1df5dfcdd5efd7024810961350e86dd88214e54bd428e992d602f25a7b18.json
new file mode 100644
index 0000000000..92917b2e64
--- /dev/null
+++ b/.sqlx/query-d17c1df5dfcdd5efd7024810961350e86dd88214e54bd428e992d602f25a7b18.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE ai_financial_invocation SET request = '{}'::jsonb WHERE invocation_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "d17c1df5dfcdd5efd7024810961350e86dd88214e54bd428e992d602f25a7b18"
+}
diff --git a/.sqlx/query-d65ad3ed3df0b01dc736a93b85bb049d9cc652f9751aa6d8a88d259b2f5f9784.json b/.sqlx/query-d65ad3ed3df0b01dc736a93b85bb049d9cc652f9751aa6d8a88d259b2f5f9784.json
new file mode 100644
index 0000000000..041512cc9d
--- /dev/null
+++ b/.sqlx/query-d65ad3ed3df0b01dc736a93b85bb049d9cc652f9751aa6d8a88d259b2f5f9784.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT completion FROM ai_funding_reservation WHERE invocation_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "completion",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "d65ad3ed3df0b01dc736a93b85bb049d9cc652f9751aa6d8a88d259b2f5f9784"
+}
diff --git a/.sqlx/query-d6824a4120b55bbcc1fdeab6de7a4b4b16aeef095755bb06bdc428d50539f5fa.json b/.sqlx/query-d6824a4120b55bbcc1fdeab6de7a4b4b16aeef095755bb06bdc428d50539f5fa.json
new file mode 100644
index 0000000000..3c8630e30d
--- /dev/null
+++ b/.sqlx/query-d6824a4120b55bbcc1fdeab6de7a4b4b16aeef095755bb06bdc428d50539f5fa.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO ai_usage_observation (invocation_id, occurred_at, request)\n VALUES ($1, $2, $3) ON CONFLICT (invocation_id) DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "d6824a4120b55bbcc1fdeab6de7a4b4b16aeef095755bb06bdc428d50539f5fa"
+}
diff --git a/.sqlx/query-d81a0f98a2299337971e33f3299709237742b6be8c777181f54e2c056d9c3491.json b/.sqlx/query-d81a0f98a2299337971e33f3299709237742b6be8c777181f54e2c056d9c3491.json
new file mode 100644
index 0000000000..43dbb6e867
--- /dev/null
+++ b/.sqlx/query-d81a0f98a2299337971e33f3299709237742b6be8c777181f54e2c056d9c3491.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COUNT(*) FROM ai_billing_usage_observation",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "d81a0f98a2299337971e33f3299709237742b6be8c777181f54e2c056d9c3491"
+}
diff --git a/.sqlx/query-db61b9a88aa49b17468a21a7bc5e9f93f14e687cff2e8b6e1826670127bfb49d.json b/.sqlx/query-db61b9a88aa49b17468a21a7bc5e9f93f14e687cff2e8b6e1826670127bfb49d.json
new file mode 100644
index 0000000000..8543bada6b
--- /dev/null
+++ b/.sqlx/query-db61b9a88aa49b17468a21a7bc5e9f93f14e687cff2e8b6e1826670127bfb49d.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS(SELECT 1 FROM ai_billing_usage_period\n WHERE user_id = $1 AND (period_start > $2 OR (period_start < $3 AND period_end > $2))) AS \"exists!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "db61b9a88aa49b17468a21a7bc5e9f93f14e687cff2e8b6e1826670127bfb49d"
+}
diff --git a/.sqlx/query-ddb2f5c62dac93c10ba5ef65cf9ab60ea9d0f55b145f17fde2ba0ba55374a62b.json b/.sqlx/query-ddb2f5c62dac93c10ba5ef65cf9ab60ea9d0f55b145f17fde2ba0ba55374a62b.json
new file mode 100644
index 0000000000..9c60073246
--- /dev/null
+++ b/.sqlx/query-ddb2f5c62dac93c10ba5ef65cf9ab60ea9d0f55b145f17fde2ba0ba55374a62b.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT request AS \"request: Json<ObservationData>\"\n FROM ai_usage_observation WHERE invocation_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "request: Json<ObservationData>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "ddb2f5c62dac93c10ba5ef65cf9ab60ea9d0f55b145f17fde2ba0ba55374a62b"
+}
diff --git a/.sqlx/query-e2de8b07a51abdfacd6fc02bfd7bce17fd60bd8c8d43e540a8f7b81f0cfe2427.json b/.sqlx/query-e2de8b07a51abdfacd6fc02bfd7bce17fd60bd8c8d43e540a8f7b81f0cfe2427.json
new file mode 100644
index 0000000000..4d26d08dd1
--- /dev/null
+++ b/.sqlx/query-e2de8b07a51abdfacd6fc02bfd7bce17fd60bd8c8d43e540a8f7b81f0cfe2427.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT\n COALESCE((SELECT prepaid_remainder FROM ai_funding_state WHERE user_id = $1), 0) AS \"remainder!\",\n COALESCE((SELECT SUM(prepaid_hold)::bigint FROM ai_funding_reservation WHERE payer_id = $1 AND NOT allocated), 0) AS \"held!\",\n COALESCE((SELECT SUM(units)::bigint FROM ai_funding_prepaid_release WHERE payer_id = $1), 0) AS \"released!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "remainder!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "held!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 2,
+ "name": "released!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null,
+ null,
+ null
+ ]
+ },
+ "hash": "e2de8b07a51abdfacd6fc02bfd7bce17fd60bd8c8d43e540a8f7b81f0cfe2427"
+}
diff --git a/.sqlx/query-e3e7916bee59f69a354f3fb4ac16217884e7368fb1825ec71d814671a675cf0a.json b/.sqlx/query-e3e7916bee59f69a354f3fb4ac16217884e7368fb1825ec71d814671a675cf0a.json
new file mode 100644
index 0000000000..36227ff67c
--- /dev/null
+++ b/.sqlx/query-e3e7916bee59f69a354f3fb4ac16217884e7368fb1825ec71d814671a675cf0a.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE ai_funding_reservation SET completion = $2, actual_public = $3 WHERE invocation_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e3e7916bee59f69a354f3fb4ac16217884e7368fb1825ec71d814671a675cf0a"
+}
diff --git a/.sqlx/query-e55efb52bfded98e5a4110a80e6a14e7fc295825e86e48d93c49f282b2f7d73d.json b/.sqlx/query-e55efb52bfded98e5a4110a80e6a14e7fc295825e86e48d93c49f282b2f7d73d.json
new file mode 100644
index 0000000000..a137078f40
--- /dev/null
+++ b/.sqlx/query-e55efb52bfded98e5a4110a80e6a14e7fc295825e86e48d93c49f282b2f7d73d.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COALESCE(SUM(CASE WHEN allocated THEN postpaid ELSE postpaid_hold END), 0)::bigint AS \"amount!\"\n FROM ai_funding_reservation WHERE payer_id = $1 AND period_start = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "amount!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "e55efb52bfded98e5a4110a80e6a14e7fc295825e86e48d93c49f282b2f7d73d"
+}
diff --git a/.sqlx/query-e73d7bbbdae1fb4b6d943bb83ac4c8925c6731052f9b2b8ec4e6534e221e3b5a.json b/.sqlx/query-e73d7bbbdae1fb4b6d943bb83ac4c8925c6731052f9b2b8ec4e6534e221e3b5a.json
new file mode 100644
index 0000000000..874a764ef4
--- /dev/null
+++ b/.sqlx/query-e73d7bbbdae1fb4b6d943bb83ac4c8925c6731052f9b2b8ec4e6534e221e3b5a.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT pg_advisory_xact_lock(hashtextextended($1, 7404))",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "pg_advisory_xact_lock",
+ "type_info": "Void"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "e73d7bbbdae1fb4b6d943bb83ac4c8925c6731052f9b2b8ec4e6534e221e3b5a"
+}
diff --git a/.sqlx/query-e7cece8828345e0d4a0849e036843da3f11cb2777063e6f10b1cdad4b4929e08.json b/.sqlx/query-e7cece8828345e0d4a0849e036843da3f11cb2777063e6f10b1cdad4b4929e08.json
new file mode 100644
index 0000000000..e31cd2d0b3
--- /dev/null
+++ b/.sqlx/query-e7cece8828345e0d4a0849e036843da3f11cb2777063e6f10b1cdad4b4929e08.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT\n COALESCE((SELECT SUM(delta_cents)::bigint FROM ai_credit_ledger WHERE user_id = $1), 0) AS \"balance!\",\n COALESCE((SELECT SUM(amount_cents)::bigint FROM ai_overage_charge WHERE user_id = $1 AND period_start = $2\n AND accounting_policy = 'legacy' AND (status <> 'failed' OR stripe_invoice_id IS NOT NULL)), 0) AS \"charged!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "balance!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "charged!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null,
+ null
+ ]
+ },
+ "hash": "e7cece8828345e0d4a0849e036843da3f11cb2777063e6f10b1cdad4b4929e08"
+}
diff --git a/.sqlx/query-ed760b649317df1bd483f90cae420305a2961192cbc3103c4eb328c3389b02d1.json b/.sqlx/query-ed760b649317df1bd483f90cae420305a2961192cbc3103c4eb328c3389b02d1.json
new file mode 100644
index 0000000000..0604d7f3d1
--- /dev/null
+++ b/.sqlx/query-ed760b649317df1bd483f90cae420305a2961192cbc3103c4eb328c3389b02d1.json
@@ -0,0 +1,64 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT r.invocation_id, r.sequence, r.user_id, r.period_start, r.actual_public,\n r.admission AS \"admission: Json<AdmissionData>\", f.next_sequence, f.prepaid_remainder\n FROM ai_funding_state f JOIN ai_funding_reservation r ON r.payer_id = f.user_id AND r.sequence = f.watermark\n WHERE f.user_id = $1 AND NOT r.allocated",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "invocation_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "sequence",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 2,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "period_start",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 4,
+ "name": "actual_public",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 5,
+ "name": "admission: Json<AdmissionData>",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 6,
+ "name": "next_sequence",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 7,
+ "name": "prepaid_remainder",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "ed760b649317df1bd483f90cae420305a2961192cbc3103c4eb328c3389b02d1"
+}
diff --git a/.sqlx/query-2016dc9632410a432574b78d49f6e6cc14f87d8fe948ce7adb937a4f021d5ca9.json b/.sqlx/query-f286e281c3f1b8f7ba3c6f948f8d422807b3155f4a562b81df9fe642572611c1.json
similarity index 53%
rename from .sqlx/query-2016dc9632410a432574b78d49f6e6cc14f87d8fe948ce7adb937a4f021d5ca9.json
rename to .sqlx/query-f286e281c3f1b8f7ba3c6f948f8d422807b3155f4a562b81df9fe642572611c1.json
index 5d3591e8b7..b83ed48645 100644
--- a/.sqlx/query-2016dc9632410a432574b78d49f6e6cc14f87d8fe948ce7adb937a4f021d5ca9.json
+++ b/.sqlx/query-f286e281c3f1b8f7ba3c6f948f8d422807b3155f4a562b81df9fe642572611c1.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO ai_billing_account (user_id, period_start, period_end)\n VALUES ($1, $2, $3)\n ON CONFLICT (user_id) DO UPDATE\n SET period_start = EXCLUDED.period_start,\n period_end = EXCLUDED.period_end,\n updated_at = NOW()\n ",
+ "query": "\n INSERT INTO ai_billing_account (user_id, period_start, period_end)\n VALUES ($1, $2, $3)\n ON CONFLICT (user_id) DO UPDATE\n SET period_start = EXCLUDED.period_start,\n period_end = EXCLUDED.period_end,\n updated_at = NOW()\n WHERE ai_billing_account.period_start IS NULL\n OR (EXCLUDED.period_start > ai_billing_account.period_start\n AND EXCLUDED.period_start >= ai_billing_account.period_end)\n OR (EXCLUDED.period_start = ai_billing_account.period_start\n AND EXCLUDED.period_end > EXCLUDED.period_start)\n ",
"describe": {
"columns": [],
"parameters": {
@@ -12,5 +12,5 @@
},
"nullable": []
},
- "hash": "2016dc9632410a432574b78d49f6e6cc14f87d8fe948ce7adb937a4f021d5ca9"
+ "hash": "f286e281c3f1b8f7ba3c6f948f8d422807b3155f4a562b81df9fe642572611c1"
}
diff --git a/.sqlx/query-f5c1386cfd11007775b9c25a833794479adebbe0ccc71f539994003d0179942d.json b/.sqlx/query-f5c1386cfd11007775b9c25a833794479adebbe0ccc71f539994003d0179942d.json
new file mode 100644
index 0000000000..a17448cdcb
--- /dev/null
+++ b/.sqlx/query-f5c1386cfd11007775b9c25a833794479adebbe0ccc71f539994003d0179942d.json
@@ -0,0 +1,42 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT j.request AS \"request: Json<RequestData>\",\n r.publication AS \"publication: Json<RateData>\",\n j.funding AS \"funding: Json<FundingData>\",\n j.finalization AS \"finalization: Json<StateData>\"\n FROM ai_financial_invocation j JOIN ai_financial_rate r ON r.version = j.rate_version\n WHERE j.funding IS NULL\n AND ($1::uuid IS NULL OR j.invocation_id > $1) AND j.occurred_at < $2\n ORDER BY j.invocation_id LIMIT $3",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "request: Json<RequestData>",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 1,
+ "name": "publication: Json<RateData>",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 2,
+ "name": "funding: Json<FundingData>",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 3,
+ "name": "finalization: Json<StateData>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "f5c1386cfd11007775b9c25a833794479adebbe0ccc71f539994003d0179942d"
+}
diff --git a/.sqlx/query-f83c33d84756507f9c8710ea899f1469e13dac2072c3f48390f60139607636b4.json b/.sqlx/query-f83c33d84756507f9c8710ea899f1469e13dac2072c3f48390f60139607636b4.json
new file mode 100644
index 0000000000..9874804142
--- /dev/null
+++ b/.sqlx/query-f83c33d84756507f9c8710ea899f1469e13dac2072c3f48390f60139607636b4.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE ai_financial_invocation SET funding_acknowledged = true\n WHERE invocation_id = $1 AND finalization IS NOT NULL",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f83c33d84756507f9c8710ea899f1469e13dac2072c3f48390f60139607636b4"
+}
diff --git a/.sqlx/query-fb949ebb5ca9376c2f531ce34432689901ce74bd8b15d19d30fbb31585039893.json b/.sqlx/query-fb949ebb5ca9376c2f531ce34432689901ce74bd8b15d19d30fbb31585039893.json
new file mode 100644
index 0000000000..4f9c8b65d9
--- /dev/null
+++ b/.sqlx/query-fb949ebb5ca9376c2f531ce34432689901ce74bd8b15d19d30fbb31585039893.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT payer_id, admission AS \"admission: Json<AdmissionData>\" FROM ai_funding_reservation WHERE invocation_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "payer_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "admission: Json<AdmissionData>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "fb949ebb5ca9376c2f531ce34432689901ce74bd8b15d19d30fbb31585039893"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 1a1fd10194..1e8d4e2e75 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -143,6 +143,8 @@ dependencies = [
"async-stream",
"async-trait",
"attachment",
+ "bytes",
+ "chrono",
"futures",
"genai_telemetry",
"macro_env_var",
@@ -153,6 +155,7 @@ dependencies = [
"opentelemetry_sdk",
"prompt",
"regex",
+ "reqwest 0.13.4",
"rig-agent",
"rig-core",
"schemars 1.2.1",
@@ -1086,6 +1089,7 @@ name = "anthropic"
version = "0.2.0"
dependencies = [
"ai_toolset",
+ "ai_usage",
"anyhow",
"async-openai",
"async-stream",
diff --git a/crates/agent/Cargo.toml b/crates/agent/Cargo.toml
index 139e5b0aaa..0de18d46c8 100644
--- a/crates/agent/Cargo.toml
+++ b/crates/agent/Cargo.toml
@@ -12,8 +12,11 @@ anyhow = { workspace = true }
async-openai = { workspace = true }
async-stream = { workspace = true }
async-trait = { workspace = true }
+bytes = { workspace = true }
+chrono = { workspace = true }
futures = { workspace = true }
regex = { workspace = true }
+reqwest = { workspace = true }
rig-core = "0.41.0"
rig-agent = "0.41.0"
schemars = { workspace = true }
@@ -35,6 +38,7 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
tokio-util.workspace = true
[dev-dependencies]
+tokio = { workspace = true, features = ["test-util"] }
model-entity = { path = "../model-entity" }
non_empty = { path = "../non_empty" }
opentelemetry = { workspace = true, features = ["trace"] }
diff --git a/crates/agent/src/agent_loop.rs b/crates/agent/src/agent_loop.rs
index 47cc8048fd..7b2a0d0ae2 100644
--- a/crates/agent/src/agent_loop.rs
+++ b/crates/agent/src/agent_loop.rs
@@ -2,6 +2,7 @@
use crate::error::AgentError;
use crate::hook::{BridgeInputs, RegisterFn, ToolRouter, UserToolFinisher};
use crate::model::PredefinedModel;
+use crate::model::metering::MeteringContext;
use crate::model::router::{ModelRouter, ProviderAgent};
use crate::stream::ChatCompletionStream;
use crate::telemetry::GenAiContext;
@@ -47,8 +48,9 @@ impl AgentLoop {
/// Create an `AgentLoop` with provider clients from `APP_SECRETS_JSON` or the environment and
/// the default model (Opus 4.7).
///
- /// `recorder` is the [`UsageRecorder`] every session created from this loop
- /// logs token usage to — it is required so that no AI call goes unrecorded.
+ /// Sessions log legacy aggregates through `recorder`. When its separate
+ /// tracking capability is present, they also bind observational per-attempt
+ /// scopes; analytics injection alone is not proof of attempt coverage.
///
/// `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` are required.
pub fn new(recorder: Arc<dyn UsageRecorder>) -> Self {
@@ -311,6 +313,7 @@ impl AgentLoop {
telemetry.clone(),
);
+ let financial_context = MeteringContext::for_operation(self.recorder.as_ref(), &usage_ctx);
Session {
agent,
history: Vec::new(),
@@ -326,6 +329,7 @@ impl AgentLoop {
model: self.model.clone(),
request_context,
telemetry,
+ financial_context,
}
}
@@ -372,6 +376,7 @@ pub struct Session {
model: String,
request_context: RequestContext,
telemetry: GenAiContext,
+ financial_context: Option<MeteringContext>,
}
impl Session {
@@ -421,8 +426,23 @@ impl Session {
)
};
let telemetry = self.telemetry.clone();
- let result = self
- .send_message_in(messages)
+ // A newly activated turn may replace the construction-time scope, but
+ // observational/legacy callers must never downgrade an activated session.
+ let current = MeteringContext::current();
+ let financial_context = if current.as_ref().is_some_and(MeteringContext::activated) {
+ current
+ } else if self
+ .financial_context
+ .as_ref()
+ .is_some_and(MeteringContext::activated)
+ {
+ self.financial_context.clone()
+ } else if current.is_some() {
+ MeteringContext::for_operation(self.recorder.as_ref(), &self.usage_ctx)
+ } else {
+ self.financial_context.clone()
+ };
+ let result = MeteringContext::carry(financial_context, self.send_message_in(messages))
.instrument(span.clone())
.await;
if let Err(error) = &result {
@@ -441,6 +461,8 @@ impl Session {
&mut self,
messages: Vec<Message>,
) -> Result<ChatCompletionStream<'_>, AgentError> {
+ MeteringContext::require_usage(&self.usage_ctx)
+ .map_err(|error| AgentError::Other(error.into()))?;
self.history = messages;
let Some((prompt, history)) = self.history.split_last() else {
diff --git a/crates/agent/src/completion.rs b/crates/agent/src/completion.rs
index f5ac2810e6..584f7cfc76 100644
--- a/crates/agent/src/completion.rs
+++ b/crates/agent/src/completion.rs
@@ -5,6 +5,7 @@
#[cfg(test)]
mod test;
+use crate::model::metering::MeteringContext;
use crate::model::router::{ModelRouter, RoutedModel};
use crate::telemetry::{ChatSpanHook, GenAiContext, TracedModel};
use ai_usage::{UsageContext, UsageRecorder};
@@ -23,8 +24,10 @@ const ONE_SHOT_MAX_TOKENS: u64 = 16_000;
/// summarization. `model` is anything stringifiable to an api id — an
/// [`AgentModel`](crate::AgentModel) or a raw string from the frontend.
///
-/// Token usage is recorded against `ctx` via `recorder` once the completion
-/// returns. Recording is best-effort and never affects the result.
+/// Aggregate analytics are recorded against `ctx` on success. A recorder's optional
+/// tracking capability binds observational HTTP-attempt recording automatically.
+/// Activated traffic must run inside a [`MeteringContext::scope`]; each attempt is authorized
+/// and its evidence persisted before SDK or structured-output parsing.
#[tracing::instrument(skip(model, system_prompt, user_message, recorder, ctx), err)]
pub async fn complete<M: ToString>(
model: M,
@@ -33,49 +36,54 @@ pub async fn complete<M: ToString>(
recorder: &dyn UsageRecorder,
ctx: UsageContext,
) -> anyhow::Result<String> {
- let model = model.to_string();
- let routed = ModelRouter::shared()?.route_or_default(&model);
- let telemetry = telemetry_for(&ctx, &routed);
- let response = match routed {
- RoutedModel::Anthropic(m) => {
- prompt_once(
- TracedModel::new(m.completion(), telemetry.clone()),
- system_prompt,
- user_message,
- telemetry,
- )
- .await?
- }
- RoutedModel::Gemini(m) => {
- prompt_once(
- TracedModel::new(m.completion(), telemetry.clone()),
- system_prompt,
- user_message,
- telemetry,
- )
- .await?
- }
- RoutedModel::OpenAiChatCompletions(m) => {
- prompt_once(
- TracedModel::new(m.completion(), telemetry.clone()),
- system_prompt,
- user_message,
- telemetry,
- )
- .await?
- }
- RoutedModel::OpenAiResponses(m) => {
- prompt_once(
- TracedModel::new(m.completion(), telemetry.clone()),
- system_prompt,
- user_message,
- telemetry,
- )
- .await?
- }
- };
- record(recorder, ctx, model, &response);
- Ok(response.output)
+ MeteringContext::require_usage(&ctx)?;
+ let metering = MeteringContext::for_operation(recorder, &ctx);
+ MeteringContext::carry(metering, async {
+ let model = model.to_string();
+ let routed = ModelRouter::shared()?.route_or_default(&model);
+ let telemetry = telemetry_for(&ctx, &routed);
+ let response = match routed {
+ RoutedModel::Anthropic(m) => {
+ prompt_once(
+ TracedModel::new(m.completion(), telemetry.clone()),
+ system_prompt,
+ user_message,
+ telemetry,
+ )
+ .await?
+ }
+ RoutedModel::Gemini(m) => {
+ prompt_once(
+ TracedModel::new(m.completion(), telemetry.clone()),
+ system_prompt,
+ user_message,
+ telemetry,
+ )
+ .await?
+ }
+ RoutedModel::OpenAiChatCompletions(m) => {
+ prompt_once(
+ TracedModel::new(m.completion(), telemetry.clone()),
+ system_prompt,
+ user_message,
+ telemetry,
+ )
+ .await?
+ }
+ RoutedModel::OpenAiResponses(m) => {
+ prompt_once(
+ TracedModel::new(m.completion(), telemetry.clone()),
+ system_prompt,
+ user_message,
+ telemetry,
+ )
+ .await?
+ }
+ };
+ record(recorder, ctx, model, &response);
+ Ok(response.output)
+ })
+ .await
}
/// Send a system prompt + conversation history and return the model's text
@@ -90,49 +98,54 @@ pub async fn complete_with_history<M: ToString>(
recorder: &dyn UsageRecorder,
ctx: UsageContext,
) -> anyhow::Result<String> {
- let model = model.to_string();
- let routed = ModelRouter::shared()?.route_or_default(&model);
- let telemetry = telemetry_for(&ctx, &routed);
- let response = match routed {
- RoutedModel::Anthropic(m) => {
- prompt_with_history(
- TracedModel::new(m.completion(), telemetry.clone()),
- system_prompt,
- messages,
- telemetry,
- )
- .await?
- }
- RoutedModel::Gemini(m) => {
- prompt_with_history(
- TracedModel::new(m.completion(), telemetry.clone()),
- system_prompt,
- messages,
- telemetry,
- )
- .await?
- }
- RoutedModel::OpenAiChatCompletions(m) => {
- prompt_with_history(
- TracedModel::new(m.completion(), telemetry.clone()),
- system_prompt,
- messages,
- telemetry,
- )
- .await?
- }
- RoutedModel::OpenAiResponses(m) => {
- prompt_with_history(
- TracedModel::new(m.completion(), telemetry.clone()),
- system_prompt,
- messages,
- telemetry,
- )
- .await?
- }
- };
- record(recorder, ctx, model, &response);
- Ok(response.output)
+ MeteringContext::require_usage(&ctx)?;
+ let metering = MeteringContext::for_operation(recorder, &ctx);
+ MeteringContext::carry(metering, async {
+ let model = model.to_string();
+ let routed = ModelRouter::shared()?.route_or_default(&model);
+ let telemetry = telemetry_for(&ctx, &routed);
+ let response = match routed {
+ RoutedModel::Anthropic(m) => {
+ prompt_with_history(
+ TracedModel::new(m.completion(), telemetry.clone()),
+ system_prompt,
+ messages,
+ telemetry,
+ )
+ .await?
+ }
+ RoutedModel::Gemini(m) => {
+ prompt_with_history(
+ TracedModel::new(m.completion(), telemetry.clone()),
+ system_prompt,
+ messages,
+ telemetry,
+ )
+ .await?
+ }
+ RoutedModel::OpenAiChatCompletions(m) => {
+ prompt_with_history(
+ TracedModel::new(m.completion(), telemetry.clone()),
+ system_prompt,
+ messages,
+ telemetry,
+ )
+ .await?
+ }
+ RoutedModel::OpenAiResponses(m) => {
+ prompt_with_history(
+ TracedModel::new(m.completion(), telemetry.clone()),
+ system_prompt,
+ messages,
+ telemetry,
+ )
+ .await?
+ }
+ };
+ record(recorder, ctx, model, &response);
+ Ok(response.output)
+ })
+ .await
}
/// Ask `model` to answer `instruction` about one image and return its text.
@@ -187,7 +200,7 @@ fn telemetry_for(ctx: &UsageContext, routed: &RoutedModel<'_>) -> GenAiContext {
telemetry
}
-/// Record the usage of a one-shot completion.
+/// Record aggregate analytics only, never financial evidence.
fn record(
recorder: &dyn UsageRecorder,
ctx: UsageContext,
diff --git a/crates/agent/src/completion/test.rs b/crates/agent/src/completion/test.rs
index 3c2f800650..1ad628e443 100644
--- a/crates/agent/src/completion/test.rs
+++ b/crates/agent/src/completion/test.rs
@@ -146,3 +146,41 @@ fn image_user_message_rejects_bytes_that_are_not_an_image() {
image_user_message("Describe this image.", b"not an image".to_vec())
.expect_err("non-image bytes");
}
+
+#[tokio::test]
+async fn activated_one_shots_fail_before_routing_without_financial_capability() {
+ use ai_usage::financial::{FinancialCapability, FinancialMode};
+ use ai_usage::{AiFeature, NoOpUsageRecorder};
+
+ let usage = UsageContext::system(AiFeature::DynamicCompletionsApi);
+ let metering = MeteringContext::new(
+ FinancialMode::Activated,
+ FinancialCapability::Unavailable,
+ usage.clone(),
+ vec![],
+ );
+ metering
+ .scope(async {
+ let error = complete(
+ "unknown/model",
+ "system",
+ "hello",
+ &NoOpUsageRecorder,
+ usage.clone(),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(error.to_string(), "financial capability unavailable");
+ let error = complete_with_history(
+ "unknown/model",
+ "system",
+ vec![Message::user("hello")],
+ &NoOpUsageRecorder,
+ usage,
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(error.to_string(), "financial capability unavailable");
+ })
+ .await;
+}
diff --git a/crates/agent/src/lib.rs b/crates/agent/src/lib.rs
index 6a7f59def6..cccdf225b9 100644
--- a/crates/agent/src/lib.rs
+++ b/crates/agent/src/lib.rs
@@ -26,6 +26,7 @@ pub use convert::{merge_consecutive_parts, to_rig_messages};
pub use error::AgentError;
pub use hook::{FinishedUserTool, PendingUserTool, UserToolFinisher};
pub use model::PredefinedModel;
+pub use model::metering::{MeteringContext, MeteringError, ProviderSupport, WireProtocol};
pub use stream::{ChatCompletionStream, McpInfo, StreamPart, ToolCall, ToolResponse, Usage};
pub use tool_adapter::{DynToolSetAdapter, ToolsetToolAdapter, normalize_request_schema};
diff --git a/crates/agent/src/model/anthropic.rs b/crates/agent/src/model/anthropic.rs
index 53a45b529a..a79ca52a6b 100644
--- a/crates/agent/src/model/anthropic.rs
+++ b/crates/agent/src/model/anthropic.rs
@@ -1,5 +1,5 @@
use crate::model::types::Model;
-use rig_core::{client::CompletionClient, providers::anthropic};
+use rig_core::{client::CompletionClient, http_client::HttpClientExt, providers::anthropic};
use std::sync::Arc;
/// A Claude model bound to the native Anthropic client that serves it.
@@ -7,14 +7,14 @@ use std::sync::Arc;
/// Carries the parsed [`Model`] id and a shared client. Which provider an id
/// belongs to is decided by routing (the `anthropic/…` segment), so there is no
/// id classification here.
-pub struct AnthropicModel<'a> {
+pub struct AnthropicModel<'a, H = rig_core::http_client::ReqwestClient> {
model: Model<'a>,
- client: Arc<anthropic::Client>,
+ client: Arc<anthropic::Client<H>>,
}
-impl<'a> AnthropicModel<'a> {
+impl<'a, H: HttpClientExt + Clone + Default + 'static> AnthropicModel<'a, H> {
/// Bind `model` to the client that serves it.
- pub fn new(model: Model<'a>, client: Arc<anthropic::Client>) -> Self {
+ pub fn new(model: Model<'a>, client: Arc<anthropic::Client<H>>) -> Self {
Self { model, client }
}
@@ -25,7 +25,7 @@ impl<'a> AnthropicModel<'a> {
/// The rig completion model for this id. The id is passed verbatim to the
/// Anthropic API.
- pub fn completion(&self) -> anthropic::completion::CompletionModel {
+ pub fn completion(&self) -> anthropic::completion::CompletionModel<H> {
self.client.completion_model(self.model.name().to_string())
}
diff --git a/crates/agent/src/model/gemini.rs b/crates/agent/src/model/gemini.rs
index e4c426ff5c..aba273cd5d 100644
--- a/crates/agent/src/model/gemini.rs
+++ b/crates/agent/src/model/gemini.rs
@@ -1,5 +1,5 @@
use crate::model::types::Model;
-use rig_core::{client::CompletionClient, providers::gemini};
+use rig_core::{client::CompletionClient, http_client::HttpClientExt, providers::gemini};
use std::sync::Arc;
/// A Gemini model bound to the native GenerateContent client that serves it.
@@ -8,14 +8,14 @@ use std::sync::Arc;
/// turn. The OpenAI-compatible Chat Completions adapter drops that field, so
/// Google ids route here rather than through
/// [`super::openai::OpenAiChatCompletionsModel`].
-pub struct GeminiModel<'a> {
+pub struct GeminiModel<'a, H = rig_core::http_client::ReqwestClient> {
model: Model<'a>,
- client: Arc<gemini::Client>,
+ client: Arc<gemini::Client<H>>,
}
-impl<'a> GeminiModel<'a> {
+impl<'a, H: HttpClientExt + Clone + 'static> GeminiModel<'a, H> {
/// Bind `model` to the client that serves it.
- pub fn new(model: Model<'a>, client: Arc<gemini::Client>) -> Self {
+ pub fn new(model: Model<'a>, client: Arc<gemini::Client<H>>) -> Self {
Self { model, client }
}
@@ -26,7 +26,7 @@ impl<'a> GeminiModel<'a> {
/// The rig completion model for this id. The id is passed verbatim to the
/// Gemini API.
- pub fn completion(&self) -> gemini::completion::CompletionModel {
+ pub fn completion(&self) -> gemini::completion::CompletionModel<H> {
self.client.completion_model(self.model.name().to_string())
}
diff --git a/crates/agent/src/model/metering.rs b/crates/agent/src/model/metering.rs
new file mode 100644
index 0000000000..df56e32c9b
--- /dev/null
+++ b/crates/agent/src/model/metering.rs
@@ -0,0 +1,493 @@
+//! Per-operation tracking/financial context, separate from GenAI telemetry and analytics.
+//!
+//! Public completion/session entry points bridge observational recorder injection
+//! into a scope. Activated financial mode must instead be selected explicitly from
+//! trusted policy facts. Raw unscoped HTTP calls retain legacy behavior and are NOT
+//! covered producers. Spawned tasks must explicitly carry the scope.
+
+use std::future::Future;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+
+use ai_usage::financial::{
+ BeginInvocation, FinalizeInvocation, FinancialCapability, FinancialError, FinancialMode,
+ InvocationId, ProviderModel, ProviderOutcome, ProviderRequestId, RunId, TrustedTokenUsage,
+ UnresolvedReason, UsageEvidence, WriteDisposition,
+};
+use ai_usage::{FinancialUsage, TrackedInvocation, UsageContext, UsageRecorder, UsageTracking};
+use chrono::Utc;
+use serde_json::Value;
+
+#[cfg(test)]
+mod test;
+
+tokio::task_local! {
+ static REQUEST: MeteringContext;
+}
+
+/// Provider wire semantics, not the provider's commercial identity.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum WireProtocol {
+ /// Native Anthropic Messages.
+ Anthropic,
+ /// OpenAI Responses.
+ Responses,
+ /// A reviewed OpenAI-compatible Chat Completions provider.
+ ChatCompletions,
+ /// Native Gemini GenerateContent.
+ Gemini,
+}
+
+/// A host-reviewed activation gate for one exact provider/API model.
+///
+/// Do not populate this from user input or analytics pricing. The host must verify
+/// token-only pricing, usage semantics (including omitted optional counters), and
+/// the provider-enforced input/context ceiling. Multimodal pricing, server tools,
+/// cache TTL variants and unbounded execution require separate review. No built-in
+/// profiles are enabled by this crate; missing support fails before network I/O.
+#[derive(Debug, Clone)]
+pub struct ProviderSupport {
+ /// Exact wire model, including account prefixes for compatible providers.
+ pub model: ProviderModel,
+ /// Verified wire protocol.
+ pub protocol: WireProtocol,
+ /// Provider-enforced upper bound for every input/cache dimension.
+ pub input_token_ceiling: u64,
+ /// Maximum generated tokens, enforced on the outgoing request.
+ pub output_token_ceiling: u64,
+ /// Some compatible endpoints report an all-zero sentinel rather than usage.
+ pub zero_usage_is_missing: bool,
+}
+
+impl ProviderSupport {
+ pub(crate) fn constrain(&self, body: &mut Value) -> Result<TrustedTokenUsage, MeteringError> {
+ if self.input_token_ceiling == 0 || self.output_token_ceiling == 0 {
+ return Err(MeteringError::Unsupported);
+ }
+ if unsupported_content(body)
+ || body.get("prediction").is_some()
+ || body
+ .get("service_tier")
+ .is_some_and(|tier| tier != "default")
+ || body.get("speed").is_some()
+ || body.get("n").is_some_and(|n| n.as_u64() != Some(1))
+ || body
+ .pointer("/generationConfig/candidateCount")
+ .is_some_and(|n| n.as_u64() != Some(1))
+ {
+ return Err(MeteringError::Unsupported);
+ }
+ // Built-in provider tools can have non-token charges. Only client-side
+ // function tools belong to these profiles.
+ if let Some(tools) = body.get("tools").and_then(Value::as_array) {
+ for tool in tools {
+ let supported = match self.protocol {
+ WireProtocol::Anthropic => tool.get("type").is_none_or(|t| t == "custom"),
+ WireProtocol::Responses | WireProtocol::ChatCompletions => {
+ tool.get("type").is_some_and(|t| t == "function")
+ }
+ WireProtocol::Gemini => tool.as_object().is_some_and(|t| {
+ t.get("functionDeclarations").is_some_and(Value::is_array)
+ && t.iter().all(|(key, value)| {
+ key == "functionDeclarations" || value.is_null()
+ })
+ }),
+ };
+ if !supported {
+ return Err(MeteringError::Unsupported);
+ }
+ }
+ }
+ // Rig 0.41 ignores generic max_tokens when Gemini generation_config is
+ // absent. Install the verified ceiling on the actual wire request.
+ if self.protocol == WireProtocol::Gemini {
+ let object = body.as_object_mut().ok_or(MeteringError::Unsupported)?;
+ let config = object
+ .entry("generationConfig")
+ .or_insert_with(|| serde_json::json!({}));
+ if config.is_null() {
+ *config = serde_json::json!({});
+ }
+ config
+ .as_object_mut()
+ .ok_or(MeteringError::Unsupported)?
+ .entry("maxOutputTokens")
+ .or_insert(Value::from(self.output_token_ceiling));
+ }
+ let pointer = match self.protocol {
+ WireProtocol::Anthropic => "/max_tokens",
+ WireProtocol::Responses => "/max_output_tokens",
+ WireProtocol::ChatCompletions if body.get("max_completion_tokens").is_some() => {
+ "/max_completion_tokens"
+ }
+ WireProtocol::ChatCompletions => "/max_tokens",
+ WireProtocol::Gemini => "/generationConfig/maxOutputTokens",
+ };
+ let limit = body
+ .pointer_mut(pointer)
+ .ok_or(MeteringError::Unsupported)?;
+ let output = limit
+ .as_u64()
+ .filter(|n| *n > 0)
+ .ok_or(MeteringError::Unsupported)?
+ .min(self.output_token_ceiling);
+ *limit = Value::from(output);
+ if body
+ .pointer("/thinking/budget_tokens")
+ .and_then(Value::as_u64)
+ .is_some_and(|thinking| thinking >= output)
+ {
+ return Err(MeteringError::Unsupported);
+ }
+ // Reserve conservative independent maxima. Actual normalized counters are
+ // disjoint; unused capacity is released by the funding owner, not here.
+ Ok(TrustedTokenUsage::from_disjoint(
+ self.input_token_ceiling,
+ output,
+ self.input_token_ceiling,
+ self.input_token_ceiling,
+ output,
+ ))
+ }
+}
+
+/// Multimodal and alternate-TTL requests require different rate provenance.
+/// Inspect content envelopes, not user text, function arguments or tool schemas.
+fn unsupported_content(value: &Value) -> bool {
+ match value {
+ Value::Array(values) => values.iter().any(unsupported_content),
+ Value::Object(object) => {
+ if matches!(
+ object.get("type").and_then(Value::as_str),
+ Some(
+ "image"
+ | "image_url"
+ | "input_image"
+ | "document"
+ | "input_file"
+ | "audio"
+ | "input_audio"
+ )
+ ) || object.contains_key("inlineData")
+ || object.contains_key("fileData")
+ || value
+ .pointer("/cache_control/ttl")
+ .is_some_and(|ttl| ttl != "5m")
+ {
+ return true;
+ }
+ [
+ "messages",
+ "contents",
+ "content",
+ "parts",
+ "system",
+ "systemInstruction",
+ ]
+ .into_iter()
+ .any(|key| object.get(key).is_some_and(unsupported_content))
+ || (object.get("type").is_none()
+ && object.get("input").is_some_and(unsupported_content))
+ }
+ _ => false,
+ }
+}
+
+/// Immutable attribution and capability for one logical run. Clones share only a
+/// fail-closed latch, never mutable payer/model attribution on a shared router.
+#[derive(Clone)]
+pub struct MeteringContext {
+ run_id: RunId,
+ mode: FinancialMode,
+ capability: FinancialCapability,
+ tracking: Option<Arc<dyn UsageTracking>>,
+ usage: UsageContext,
+ support: Arc<Vec<ProviderSupport>>,
+ stopped: Arc<AtomicBool>,
+}
+
+impl MeteringContext {
+ /// Bind trusted attribution and activation facts before entering an AI call.
+ pub fn new(
+ mode: FinancialMode,
+ capability: FinancialCapability,
+ usage: UsageContext,
+ support: Vec<ProviderSupport>,
+ ) -> Self {
+ Self {
+ run_id: RunId::new(),
+ mode,
+ capability,
+ tracking: None,
+ usage,
+ support: Arc::new(support),
+ stopped: Arc::new(AtomicBool::new(false)),
+ }
+ }
+
+ /// Bind observational recording to immutable, trusted operation attribution.
+ /// No funding service or provider budget/profile is required or consulted.
+ pub fn tracking_only(tracking: Arc<dyn UsageTracking>, usage: UsageContext) -> Self {
+ let mut context = Self::new(
+ FinancialMode::TrackingOnly,
+ FinancialCapability::Unavailable,
+ usage,
+ vec![],
+ );
+ context.tracking = Some(tracking);
+ context
+ }
+
+ /// Bridge analytics injection to per-attempt tracking. Financial scopes remain
+ /// strict; observational child operations bind their own user/feature/entity.
+ pub fn for_operation(recorder: &dyn UsageRecorder, usage: &UsageContext) -> Option<Self> {
+ if let Some(current) = Self::current() {
+ if current.activated() {
+ return Some(current);
+ }
+ if let Some(tracking) = &current.tracking {
+ if current.usage.user == usage.user
+ && current.usage.feature == usage.feature
+ && current.usage.entity == usage.entity
+ {
+ return Some(current);
+ }
+ let tracking = recorder.tracking().unwrap_or_else(|| tracking.clone());
+ return Some(Self::tracking_only(tracking, usage.clone()));
+ }
+ }
+ recorder
+ .tracking()
+ .map(|tracking| Self::tracking_only(tracking, usage.clone()))
+ }
+
+ /// Run a completion, structured generation or session operation in this scope.
+ /// This does not automatically propagate into arbitrary `tokio::spawn` calls.
+ pub async fn scope<F: Future>(&self, future: F) -> F::Output {
+ REQUEST.scope(self.clone(), future).await
+ }
+
+ pub(crate) fn require_usage(usage: &UsageContext) -> Result<(), MeteringError> {
+ if let Some(context) = Self::current().filter(Self::activated) {
+ context.capability.for_mode(context.mode)?;
+ if context.usage.user != usage.user
+ || context.usage.feature != usage.feature
+ || context.usage.entity != usage.entity
+ {
+ return Err(MeteringError::AttributionMismatch);
+ }
+ }
+ Ok(())
+ }
+
+ /// Capture an immutable scope before spawning a task.
+ pub fn current() -> Option<Self> {
+ REQUEST.try_with(Clone::clone).ok()
+ }
+
+ /// Explicitly carry a captured scope across task boundaries. Construct transport
+ /// calls inside the scoped async block: they can capture context at creation.
+ pub async fn carry<F: Future>(context: Option<Self>, future: F) -> F::Output {
+ match context {
+ Some(context) => context.scope(future).await,
+ None => future.await,
+ }
+ }
+
+ pub(crate) fn activated(&self) -> bool {
+ self.mode == FinancialMode::Activated
+ }
+
+ pub(crate) fn enabled(&self) -> bool {
+ self.activated() || self.tracking.is_some()
+ }
+
+ pub(crate) async fn begin(
+ &self,
+ model: ProviderModel,
+ protocol: WireProtocol,
+ body: &mut Value,
+ ) -> Result<Attempt, MeteringError> {
+ if let Some(service) = &self.tracking {
+ let request = TrackedInvocation {
+ run_id: self.run_id,
+ invocation_id: InvocationId::new(),
+ user: self.usage.user.clone(),
+ feature: self.usage.feature,
+ entity: self.usage.entity,
+ model,
+ occurred_at: Utc::now(),
+ };
+ let _ = service.begin(request.clone()).await.inspect_err(|error| {
+ tracing::error!(invocation_id = ?request.invocation_id, error = ?error, "observation begin failed; provider execution continues");
+ });
+ return Ok(Attempt {
+ id: request.invocation_id,
+ service: AttemptRecorder::Tracking {
+ service: service.clone(),
+ request,
+ },
+ context: self.clone(),
+ protocol,
+ // Unreviewed compatible endpoints may return zero sentinels.
+ zero_usage_is_missing: protocol == WireProtocol::ChatCompletions,
+ });
+ }
+ if self.stopped.load(Ordering::Acquire) {
+ return Err(MeteringError::Stopped);
+ }
+ self.capability.for_mode(self.mode)?;
+ let FinancialCapability::Available(service) = &self.capability else {
+ return Err(FinancialError::CapabilityUnavailable.into());
+ };
+ let support = self
+ .support
+ .iter()
+ .find(|p| p.model == model && p.protocol == protocol)
+ .ok_or(MeteringError::Unsupported)?
+ .clone();
+ let token_budget = support.constrain(body)?;
+ let request = BeginInvocation {
+ run_id: self.run_id,
+ invocation_id: InvocationId::new(),
+ user: self.usage.user.clone(),
+ feature: self.usage.feature,
+ entity: self.usage.entity,
+ model,
+ occurred_at: Utc::now(),
+ token_budget,
+ };
+ let result = service.begin(request.clone()).await;
+ let admission = result.inspect_err(|_| self.stopped.store(true, Ordering::Release))?;
+ if admission.disposition != WriteDisposition::Inserted {
+ self.stopped.store(true, Ordering::Release);
+ return Err(MeteringError::Replayed);
+ }
+ request.check_replay(&admission.value.request)?;
+ admission.value.rate.require_model(&request.model)?;
+ if admission.value.funding.invocation_id != request.invocation_id
+ || admission.value.rate.tokens.price(token_budget)?
+ > admission.value.funding.maximum_public_usage
+ {
+ self.stopped.store(true, Ordering::Release);
+ return Err(MeteringError::Unsupported);
+ }
+ Ok(Attempt {
+ id: request.invocation_id,
+ service: AttemptRecorder::Financial(service.clone()),
+ context: self.clone(),
+ protocol: support.protocol,
+ zero_usage_is_missing: support.zero_usage_is_missing,
+ })
+ }
+}
+
+enum AttemptRecorder {
+ Financial(Arc<dyn FinancialUsage>),
+ Tracking {
+ service: Arc<dyn UsageTracking>,
+ request: TrackedInvocation,
+ },
+}
+
+pub(crate) struct Attempt {
+ pub(crate) id: InvocationId,
+ service: AttemptRecorder,
+ context: MeteringContext,
+ pub(crate) protocol: WireProtocol,
+ pub(crate) zero_usage_is_missing: bool,
+}
+
+impl Attempt {
+ pub(crate) fn activated(&self) -> bool {
+ self.context.activated()
+ }
+
+ /// Spawn before awaiting so cancellation of the consumer cannot cancel delivery
+ /// of evidence already observed. Delivery retries reuse the entire immutable
+ /// value; HTTP executions always obtain a fresh invocation ID instead.
+ pub(crate) async fn finish(
+ self,
+ outcome: ProviderOutcome,
+ usage: UsageEvidence,
+ provider_request_id: Option<ProviderRequestId>,
+ ) -> Result<(), MeteringError> {
+ if self.context.activated()
+ && matches!(
+ usage,
+ UsageEvidence::Missing(
+ UnresolvedReason::UnsupportedDimensions | UnresolvedReason::UsageNotReported
+ )
+ )
+ {
+ self.context.stopped.store(true, Ordering::Release);
+ }
+ let evidence = FinalizeInvocation {
+ invocation_id: self.id,
+ occurred_at: Utc::now(),
+ provider_request_id,
+ outcome,
+ usage,
+ };
+ let activated = self.context.activated();
+ let delivered = tokio::spawn(async move {
+ for retry in 0..3 {
+ let result = match &self.service {
+ AttemptRecorder::Financial(service) => service.finalize(evidence.clone()).await.map(|_| ()),
+ AttemptRecorder::Tracking { service, request } => {
+ // Retry begin as well: a lost acknowledgement must not lose
+ // the subsequent evidence or generate another execution ID.
+ match service.begin(request.clone()).await {
+ Ok(_) => service.finalize(evidence.clone()).await.map(|_| ()),
+ Err(error) => Err(error),
+ }
+ }
+ };
+ match result {
+ Ok(()) => return Ok(()),
+ Err(error) => {
+ tracing::error!(invocation_id = ?self.id, error = ?error, "provider evidence delivery failed");
+ if retry == 2 {
+ if !self.context.activated() {
+ // Error logs above explicitly report failed persistence.
+ // Observations must never become a provider denial.
+ return Ok(());
+ }
+ self.context.stopped.store(true, Ordering::Release);
+ return Err(MeteringError::Financial(error));
+ }
+ }
+ }
+ }
+ unreachable!("bounded delivery loop always returns")
+ }).await;
+ match delivered {
+ Ok(result) => result,
+ Err(error) if !activated => {
+ tracing::error!(error = ?error, "observation delivery task failed; persistence not acknowledged");
+ Ok(())
+ }
+ Err(_) => Err(MeteringError::Stopped),
+ }
+ }
+}
+
+/// Financial failures must propagate, unlike best-effort analytics failures.
+#[derive(Debug, thiserror::Error)]
+pub enum MeteringError {
+ /// Failure from the financial domain, including exhausted funding.
+ #[error(transparent)]
+ Financial(#[from] FinancialError),
+ /// Missing reviewed provider semantics or an enforceable execution budget.
+ #[error("provider usage or execution budget support is not verified")]
+ Unsupported,
+ /// A previous admission may already have executed; never execute it again.
+ #[error("replayed financial admission cannot execute the provider again")]
+ Replayed,
+ /// A previous financial failure prevents further attempts in this run.
+ #[error("financial run stopped")]
+ Stopped,
+ /// The caller's attribution does not match the immutable financial scope.
+ #[error("financial request attribution mismatch")]
+ AttributionMismatch,
+}
diff --git a/crates/agent/src/model/metering/test.rs b/crates/agent/src/model/metering/test.rs
new file mode 100644
index 0000000000..5bf69c67d1
--- /dev/null
+++ b/crates/agent/src/model/metering/test.rs
@@ -0,0 +1,107 @@
+use super::*;
+use serde_json::json;
+
+fn profile(protocol: WireProtocol) -> ProviderSupport {
+ ProviderSupport {
+ model: ProviderModel::new("test", "model").unwrap(),
+ protocol,
+ input_token_ceiling: 100,
+ output_token_ceiling: 20,
+ zero_usage_is_missing: false,
+ }
+}
+
+#[test]
+fn clamps_wire_output_limit_before_authorization() {
+ for (protocol, mut body, pointer) in [
+ (
+ WireProtocol::Anthropic,
+ json!({"max_tokens": 50}),
+ "/max_tokens",
+ ),
+ (
+ WireProtocol::Responses,
+ json!({"max_output_tokens": 50}),
+ "/max_output_tokens",
+ ),
+ (
+ WireProtocol::ChatCompletions,
+ json!({"max_tokens": 50}),
+ "/max_tokens",
+ ),
+ (
+ WireProtocol::Gemini,
+ json!({"generationConfig": {"maxOutputTokens": 50}}),
+ "/generationConfig/maxOutputTokens",
+ ),
+ ] {
+ let budget = profile(protocol).constrain(&mut body).unwrap();
+ assert_eq!(body.pointer(pointer).unwrap(), 20);
+ assert_eq!(budget.input(), 100);
+ assert_eq!(budget.output(), 20);
+ }
+}
+
+#[test]
+fn unsupported_multiplicity_and_missing_limits_fail_closed() {
+ let support = profile(WireProtocol::ChatCompletions);
+ assert!(
+ support
+ .constrain(&mut json!({"max_tokens": 20, "n": 2}))
+ .is_err()
+ );
+ assert!(support.constrain(&mut json!({})).is_err());
+ assert!(support.constrain(&mut json!({"max_tokens": 0})).is_err());
+}
+
+#[tokio::test]
+async fn request_scopes_do_not_share_attribution() {
+ let first = MeteringContext::new(
+ FinancialMode::Activated,
+ FinancialCapability::Unavailable,
+ UsageContext::system(ai_usage::AiFeature::Chat),
+ vec![],
+ );
+ let second = MeteringContext::new(
+ FinancialMode::Legacy,
+ FinancialCapability::Unavailable,
+ UsageContext::system(ai_usage::AiFeature::Memory),
+ vec![],
+ );
+ let a = first.run_id;
+ let b = second.run_id;
+ tokio::join!(
+ first.scope(async {
+ tokio::task::yield_now().await;
+ assert_eq!(MeteringContext::current().unwrap().run_id, a);
+ }),
+ second.scope(async {
+ tokio::task::yield_now().await;
+ assert_eq!(MeteringContext::current().unwrap().run_id, b);
+ })
+ );
+ assert!(MeteringContext::current().is_none());
+}
+
+#[test]
+fn gemini_installs_the_limit_rig_omits_without_generation_config() {
+ let mut body = json!({"generationConfig": null, "tools": [{"functionDeclarations": [], "codeExecution": null}]});
+ profile(WireProtocol::Gemini).constrain(&mut body).unwrap();
+ assert_eq!(body["generationConfig"]["maxOutputTokens"], 20);
+}
+
+#[test]
+fn unverified_modalities_server_tools_and_cache_ttls_fail_closed() {
+ for mut body in [
+ json!({"max_tokens": 20, "messages": [{"content": [{"type":"image","source":{}}]}]}),
+ json!({"max_tokens": 20, "tools": [{"type":"web_search_20250305"}]}),
+ json!({"max_tokens": 20, "system": [{"type":"text","text":"hello","cache_control":{"type":"ephemeral","ttl":"1h"}}]}),
+ json!({"max_tokens": 20, "thinking": {"budget_tokens": 25}}),
+ ] {
+ assert!(
+ profile(WireProtocol::Anthropic)
+ .constrain(&mut body)
+ .is_err()
+ );
+ }
+}
diff --git a/crates/agent/src/model/metering_http.rs b/crates/agent/src/model/metering_http.rs
new file mode 100644
index 0000000000..186e331c4b
--- /dev/null
+++ b/crates/agent/src/model/metering_http.rs
@@ -0,0 +1,691 @@
+//! Rig 0.41's public HTTP extension point. Its completion stream's inner stream
+//! is private, and accepted-turn hooks miss invalid-tool recovery. Intercepting
+//! each send here also accounts for `GenericEventSource` reconnect executions.
+//! No GenAI spans or aggregate analytics are emitted by this adapter.
+
+use std::time::Duration;
+
+use ai_usage::financial::{
+ ProviderModel, ProviderOutcome, ProviderRequestId, TrustedTokenUsage, UnresolvedReason,
+ UsageEvidence,
+};
+use bytes::Bytes;
+use futures::StreamExt;
+use rig_core::http_client::{
+ self, HttpClientExt, LazyBody, MultipartForm, Request, Response, StreamingResponse,
+};
+use serde_json::Value;
+
+use super::metering::{Attempt, MeteringContext, MeteringError, WireProtocol};
+
+#[cfg(test)]
+mod test;
+
+/// Maximum time to drain a provider execution after its consumer disappears.
+const DRAIN_TIMEOUT: Duration = Duration::from_secs(300);
+/// Bound transient SSE parsing memory; never retain or journal model content.
+const MAX_EVENT_BYTES: usize = 1024 * 1024;
+
+/// HTTP adapter installed when building a Rig provider client. Attribution is
+/// obtained from the request scope, never stored on this shared client.
+#[derive(Debug, Clone)]
+pub struct MeteredHttpClient<H = http_client::ReqwestClient> {
+ inner: H,
+ provider: String,
+ protocol: WireProtocol,
+}
+
+// Required by Rig's CompletionModel bounds, even for explicitly built clients.
+// An unconfigured default must fail closed for activated traffic.
+impl<H: Default> Default for MeteredHttpClient<H> {
+ fn default() -> Self {
+ Self::new(H::default(), "", WireProtocol::Responses)
+ }
+}
+
+impl<H> MeteredHttpClient<H> {
+ /// Wrap a transport with no hidden execution retries. Rig retries above this
+ /// boundary are supported; retries inside `inner` would bypass authorization.
+ pub fn new(inner: H, provider: impl Into<String>, protocol: WireProtocol) -> Self {
+ Self {
+ inner,
+ provider: provider.into(),
+ protocol,
+ }
+ }
+
+ async fn prepare(
+ &self,
+ request: Request<Bytes>,
+ ) -> http_client::Result<(Request<Bytes>, Option<Attempt>)> {
+ let Some(context) = MeteringContext::current().filter(MeteringContext::enabled) else {
+ return Ok((request, None));
+ };
+ let parsed = (|| {
+ let body: Value =
+ serde_json::from_slice(request.body()).map_err(|_| MeteringError::Unsupported)?;
+ let model = if self.protocol == WireProtocol::Gemini {
+ request
+ .uri()
+ .path()
+ .split_once("/models/")
+ .and_then(|(_, model)| model.split_once(':').map(|(model, _)| model))
+ } else {
+ body.get("model").and_then(Value::as_str)
+ }
+ .ok_or(MeteringError::Unsupported)?;
+ let model = ProviderModel::new(self.provider.clone(), model)?;
+ Ok::<_, MeteringError>((body, model))
+ })();
+ let (mut body, model) = match parsed {
+ Ok(parsed) => parsed,
+ Err(error) if !context.activated() => {
+ tracing::error!(error = ?error, "cannot identify provider attempt; observation not persisted");
+ return Ok((request, None));
+ }
+ Err(error) => return Err(http_error(error)),
+ };
+ let attempt = context
+ .begin(model, self.protocol, &mut body)
+ .await
+ .map_err(http_error)?;
+ if !context.activated() {
+ // Preserve the exact body and headers, including all request budgets.
+ return Ok((request, Some(attempt)));
+ }
+ let (parts, _) = request.into_parts();
+ let mut request = Request::from_parts(
+ parts,
+ Bytes::from(
+ serde_json::to_vec(&body).map_err(|_| http_error(MeteringError::Unsupported))?,
+ ),
+ );
+ // The adapter changed max tokens; let the transport compute the length.
+ request.headers_mut().remove("content-length");
+ Ok((request, Some(attempt)))
+ }
+}
+
+fn http_error(error: MeteringError) -> http_client::Error {
+ http_client::Error::Instance(Box::new(error))
+}
+
+fn request_id(headers: &http_client::HeaderMap) -> Option<ProviderRequestId> {
+ ["request-id", "x-request-id", "x-goog-request-id"]
+ .into_iter()
+ .find_map(|name| {
+ headers
+ .get(name)
+ .and_then(|id| id.to_str().ok())
+ .and_then(|id| ProviderRequestId::new(id).ok())
+ })
+}
+
+impl<H: HttpClientExt + Clone + 'static> HttpClientExt for MeteredHttpClient<H> {
+ fn send<T, U>(
+ &self,
+ request: Request<T>,
+ ) -> impl Future<Output = http_client::Result<Response<LazyBody<U>>>> + Send + 'static
+ where
+ T: Into<Bytes> + Send,
+ U: From<Bytes> + Send + 'static,
+ {
+ let client = self.clone();
+ let request = request.map(Into::into);
+ let context = MeteringContext::current();
+ async move {
+ MeteringContext::carry(context, async move {
+ let (request, attempt) = client.prepare(request).await?;
+ let Some(attempt) = attempt else {
+ return client.inner.send(request).await;
+ };
+ // Complete the provider/evidence exchange independently of caller
+ // cancellation, before Rig can reject tool arguments or JSON.
+ let (caller_alive, cancelled) = tokio::sync::oneshot::channel::<()>();
+ let result = tokio::spawn(async move {
+ let result = drain_after_cancellation(
+ async {
+ let response = client.inner.send::<_, Bytes>(request).await?;
+ let (parts, body) = response.into_parts();
+ Ok::<_, http_client::Error>((parts, body.await?))
+ },
+ cancelled,
+ )
+ .await;
+ match result {
+ Ok(Ok((parts, bytes))) => {
+ let mut facts = Facts::new(
+ attempt.protocol,
+ attempt.zero_usage_is_missing,
+ request_id(&parts.headers),
+ );
+ facts.response(&bytes);
+ attempt
+ .finish(facts.outcome, facts.evidence(), facts.request_id)
+ .await
+ .map_err(http_error)?;
+ let body: LazyBody<U> = Box::pin(async move { Ok(U::from(bytes)) });
+ Ok(Response::from_parts(parts, body))
+ }
+ other => {
+ let error = match other {
+ Ok(Err(error)) => error,
+ _ => http_error(MeteringError::Stopped),
+ };
+ finish_failure(attempt, &error).await?;
+ Err(error)
+ }
+ }
+ })
+ .await
+ .map_err(|_| http_error(MeteringError::Stopped))?;
+ // Keep this guard until the await completes; dropping the caller
+ // future instead closes the channel and starts detached draining.
+ drop(caller_alive);
+ result
+ })
+ .await
+ }
+ }
+
+ fn send_multipart<U>(
+ &self,
+ request: Request<MultipartForm>,
+ ) -> impl Future<Output = http_client::Result<Response<LazyBody<U>>>> + Send + 'static
+ where
+ U: From<Bytes> + Send + 'static,
+ {
+ let context = MeteringContext::current();
+ let activated = context.as_ref().is_some_and(MeteringContext::activated);
+ if context.as_ref().is_some_and(MeteringContext::enabled) && !activated {
+ tracing::warn!("multipart provider attempt is not covered by observational metering");
+ }
+ let inner = self.inner.clone();
+ async move {
+ if activated {
+ return Err(http_error(MeteringError::Unsupported));
+ }
+ inner.send_multipart(request).await
+ }
+ }
+
+ async fn send_streaming<T>(&self, request: Request<T>) -> http_client::Result<StreamingResponse>
+ where
+ T: Into<Bytes> + Send,
+ {
+ let (request, attempt) = self.prepare(request.map(Into::into)).await?;
+ let Some(attempt) = attempt else {
+ return self.inner.send_streaming(request).await;
+ };
+ let inner = self.inner.clone();
+ // Keep connection establishment alive too: a timeout after provider
+ // execution is unresolved evidence, not permission to release the hold.
+ let (caller_alive, cancelled) = tokio::sync::oneshot::channel::<()>();
+ let result = tokio::spawn(async move {
+ let mut drain_deadline = None;
+ let response = drain_after_cancellation(inner.send_streaming(request), async {
+ let _ = cancelled.await;
+ drain_deadline = Some(tokio::time::Instant::now() + DRAIN_TIMEOUT);
+ })
+ .await;
+ let response = match response {
+ Ok(Ok(response)) => response,
+ other => {
+ let error = match other {
+ Ok(Err(error)) => error,
+ _ => http_error(MeteringError::Stopped),
+ };
+ finish_failure(attempt, &error).await?;
+ return Err(error);
+ }
+ };
+ let (parts, mut body) = response.into_parts();
+ let mut facts = Facts::new(
+ attempt.protocol,
+ attempt.zero_usage_is_missing,
+ request_id(&parts.headers),
+ );
+ let (tx, mut rx) = tokio::sync::mpsc::channel(8);
+ tokio::spawn(async move {
+ let mut attempt = Some(attempt);
+ let mut decoder = SseDecoder::default();
+ let drain = async {
+ while let Some(chunk) = body.next().await {
+ match &chunk {
+ Ok(bytes) => {
+ decoder.push(bytes, &mut facts);
+ if facts.terminal
+ && let Some(attempt) = attempt.take()
+ && let Err(error) = attempt
+ .finish(
+ facts.outcome,
+ facts.evidence(),
+ facts.request_id.clone(),
+ )
+ .await
+ {
+ let _ = tx.send(Err(http_error(error))).await;
+ return;
+ }
+ }
+ Err(_) => {
+ let _ = tx.send(chunk).await;
+ break;
+ }
+ }
+ // When Rig rejects an invalid tool call, or the user drops
+ // the stream, continue bounded draining for terminal usage.
+ let _ = tx.send(chunk).await;
+ }
+ };
+ // Cancellation during connection establishment and body drain
+ // share one budget, rather than resetting it after headers.
+ let _ = match drain_deadline {
+ Some(deadline) => tokio::time::timeout_at(deadline, drain).await,
+ None => drain_after_cancellation(drain, tx.closed()).await,
+ };
+ if let Some(attempt) = attempt {
+ let activated = attempt.activated();
+ let result = attempt
+ .finish(
+ ProviderOutcome::Unknown,
+ UsageEvidence::Missing(UnresolvedReason::Interrupted),
+ facts.request_id,
+ )
+ .await;
+ if let Err(error) = result {
+ let _ = tx.send(Err(http_error(error))).await;
+ } else if activated {
+ let _ = tx.send(Err(http_error(MeteringError::Stopped))).await;
+ }
+ }
+ });
+ let stream = async_stream::stream! {
+ while let Some(chunk) = rx.recv().await { yield chunk; }
+ };
+ Ok(Response::from_parts(
+ parts,
+ Box::pin(stream) as http_client::sse::BoxedStream,
+ ))
+ })
+ .await
+ .map_err(|_| http_error(MeteringError::Stopped))?;
+ drop(caller_alive);
+ result
+ }
+}
+
+/// Live consumers have no metering deadline. Only detached work is bounded.
+async fn drain_after_cancellation<F: Future, C: Future>(
+ execution: F,
+ cancelled: C,
+) -> Result<F::Output, tokio::time::error::Elapsed> {
+ tokio::pin!(execution);
+ tokio::select! {
+ result = &mut execution => Ok(result),
+ _ = cancelled => tokio::time::timeout(DRAIN_TIMEOUT, execution).await,
+ }
+}
+
+/// Rig exposes non-success response bodies through this public error variant.
+/// Retain reported usage even when HTTP status prevents SDK response parsing.
+async fn finish_failure(attempt: Attempt, error: &http_client::Error) -> http_client::Result<()> {
+ let mut facts = Facts::new(attempt.protocol, attempt.zero_usage_is_missing, None);
+ let mut outcome = ProviderOutcome::Unknown;
+ let mut evidence = UsageEvidence::Missing(UnresolvedReason::Interrupted);
+ if let http_client::Error::InvalidStatusCodeWithMessage(_, body) = error {
+ facts.response(body.as_bytes());
+ outcome = ProviderOutcome::Failed;
+ if facts.usage.is_some() {
+ evidence = facts.evidence();
+ }
+ }
+ attempt
+ .finish(outcome, evidence, facts.request_id)
+ .await
+ .map_err(http_error)
+}
+
+/// Raw provider facts: never use Rig's generic Usage defaults, which replace
+/// absent counters with zeros and overlap cache/reasoning totals.
+struct Facts {
+ protocol: WireProtocol,
+ zero_usage_is_missing: bool,
+ request_id: Option<ProviderRequestId>,
+ usage: Option<Value>,
+ terminal: bool,
+ invalid: bool,
+ outcome: ProviderOutcome,
+}
+
+impl Facts {
+ fn new(
+ protocol: WireProtocol,
+ zero_usage_is_missing: bool,
+ request_id: Option<ProviderRequestId>,
+ ) -> Self {
+ Self {
+ protocol,
+ zero_usage_is_missing,
+ request_id,
+ usage: None,
+ terminal: false,
+ invalid: false,
+ outcome: ProviderOutcome::Succeeded,
+ }
+ }
+
+ fn identify(&mut self, value: &Value) {
+ if self.request_id.is_none() {
+ self.request_id = value
+ .get("id")
+ .or_else(|| value.get("responseId"))
+ .and_then(Value::as_str)
+ .and_then(|id| ProviderRequestId::new(id).ok());
+ }
+ }
+
+ fn response(&mut self, bytes: &[u8]) {
+ match serde_json::from_slice::<Value>(bytes) {
+ Ok(value) => {
+ self.identify(&value);
+ self.usage = value
+ .get(if self.protocol == WireProtocol::Gemini {
+ "usageMetadata"
+ } else {
+ "usage"
+ })
+ .cloned();
+ if value.get("error").is_some_and(|e| !e.is_null())
+ || value.get("status").is_some_and(|s| s == "failed")
+ {
+ self.outcome = ProviderOutcome::Failed;
+ }
+ self.terminal = true;
+ }
+ Err(_) => self.invalid = true,
+ }
+ }
+
+ fn event(&mut self, data: &[u8]) {
+ if self.terminal {
+ return;
+ }
+ if data == b"[DONE]" {
+ // Only a usage-only Chat Completions event is a reliable final
+ // snapshot. Earlier per-chunk counters may be incomplete.
+ self.usage = None;
+ self.terminal = true;
+ return;
+ }
+ let Ok(value) = serde_json::from_slice::<Value>(data) else {
+ self.invalid = true;
+ return;
+ };
+ match self.protocol {
+ WireProtocol::Anthropic => match value.get("type").and_then(Value::as_str) {
+ Some("message_start") => {
+ self.identify(&value["message"]);
+ self.usage = value.pointer("/message/usage").cloned();
+ if let Some(usage) = self.usage.as_mut().and_then(Value::as_object_mut) {
+ // message_start output is provisional, not final usage.
+ usage.remove("output_tokens");
+ }
+ }
+ Some("message_delta") => {
+ // Cumulative counters, not deltas. Some endpoints include
+ // zero input/cache placeholders here: preserve start counts.
+ if let Some(update) = value.get("usage").and_then(Value::as_object)
+ && let Some(usage) = self.usage.as_mut().and_then(Value::as_object_mut)
+ {
+ for (key, value) in update {
+ if !value.is_null()
+ && (key == "output_tokens" || value.as_u64() != Some(0))
+ {
+ usage.insert(key.clone(), value.clone());
+ }
+ }
+ }
+ }
+ Some("message_stop") => self.terminal = true,
+ Some("error") => {
+ self.outcome = ProviderOutcome::Failed;
+ self.usage = None;
+ self.terminal = true;
+ }
+ _ => {}
+ },
+ WireProtocol::Responses => {
+ if let Some(response) = value.get("response") {
+ self.identify(response);
+ }
+ if matches!(
+ value.get("type").and_then(Value::as_str),
+ Some("response.completed" | "response.incomplete" | "response.failed")
+ ) {
+ self.usage = value.pointer("/response/usage").cloned();
+ self.terminal = true;
+ if value["type"] == "response.failed" {
+ self.outcome = ProviderOutcome::Failed;
+ }
+ }
+ }
+ WireProtocol::ChatCompletions => {
+ self.identify(&value);
+ // The include_usage event is a cumulative, final snapshot. A
+ // repeated snapshot is never added a second time.
+ if value.get("usage").is_some_and(Value::is_object) {
+ self.usage = value.get("usage").cloned();
+ self.terminal = value
+ .get("choices")
+ .and_then(Value::as_array)
+ .is_some_and(Vec::is_empty);
+ }
+ }
+ WireProtocol::Gemini => {
+ self.identify(&value);
+ if let Some(usage) = value.get("usageMetadata") {
+ self.usage = Some(usage.clone());
+ }
+ if value.pointer("/candidates/0/finishReason").is_some() {
+ // Earlier chunks are cumulative but not necessarily complete.
+ self.usage = value.get("usageMetadata").cloned();
+ self.terminal = true;
+ }
+ }
+ }
+ }
+
+ fn evidence(&self) -> UsageEvidence {
+ if self.invalid {
+ return UsageEvidence::Missing(UnresolvedReason::UnsupportedDimensions);
+ }
+ if !self.terminal {
+ return UsageEvidence::Missing(UnresolvedReason::Interrupted);
+ }
+ let Some(usage) = &self.usage else {
+ return UsageEvidence::Missing(UnresolvedReason::UsageNotReported);
+ };
+ match normalize(self.protocol, usage) {
+ Some(tokens)
+ if !(self.zero_usage_is_missing
+ && tokens == TrustedTokenUsage::from_disjoint(0, 0, 0, 0, 0)) =>
+ {
+ UsageEvidence::Reported(tokens)
+ }
+ _ => UsageEvidence::Missing(UnresolvedReason::UnsupportedDimensions),
+ }
+ }
+}
+
+fn count(value: &Value, key: &str) -> Option<u64> {
+ value.get(key)?.as_u64()
+}
+
+// Omitted optional counters have zero semantics only for reviewed profiles.
+// Required totals always retain absence, including SDK zero-default sentinels.
+fn optional_count(value: &Value, key: &str) -> Option<u64> {
+ match value.as_object()?.get(key) {
+ None => Some(0),
+ Some(value) => value.as_u64(),
+ }
+}
+
+// Anthropic models these optional cache fields as nullable as well as omittable.
+fn anthropic_optional_count(value: &Value, key: &str) -> Option<u64> {
+ if value.get(key).is_some_and(Value::is_null) {
+ return Some(0);
+ }
+ optional_count(value, key)
+}
+
+fn normalize(protocol: WireProtocol, usage: &Value) -> Option<TrustedTokenUsage> {
+ let tokens = match protocol {
+ WireProtocol::Anthropic => {
+ // Anthropic input excludes cache reads/writes; output already bills
+ // thinking at the output rate without a separate reasoning counter.
+ if let Some(cache) = usage.get("cache_creation").filter(|cache| !cache.is_null())
+ && anthropic_optional_count(cache, "ephemeral_1h_input_tokens")? != 0
+ {
+ return None;
+ }
+ Some(TrustedTokenUsage::from_disjoint(
+ count(usage, "input_tokens")?,
+ count(usage, "output_tokens")?,
+ anthropic_optional_count(usage, "cache_read_input_tokens")?,
+ anthropic_optional_count(usage, "cache_creation_input_tokens")?,
+ 0,
+ ))
+ }
+ WireProtocol::Responses | WireProtocol::ChatCompletions => {
+ let (input, output, input_details, output_details) =
+ if protocol == WireProtocol::Responses {
+ (
+ "input_tokens",
+ "output_tokens",
+ "input_tokens_details",
+ "output_tokens_details",
+ )
+ } else {
+ (
+ "prompt_tokens",
+ "completion_tokens",
+ "prompt_tokens_details",
+ "completion_tokens_details",
+ )
+ };
+ let cached = usage
+ .get(input_details)
+ .map_or(Some(0), |v| optional_count(v, "cached_tokens"))?;
+ let reasoning = usage
+ .get(output_details)
+ .map_or(Some(0), |v| optional_count(v, "reasoning_tokens"))?;
+ // Audio and prediction tokens need different rate provenance.
+ for details in [input_details, output_details] {
+ if let Some(object) = usage.get(details).and_then(Value::as_object)
+ && object.iter().any(|(key, value)| {
+ key != "cached_tokens"
+ && key != "reasoning_tokens"
+ && value.as_u64() != Some(0)
+ })
+ {
+ return None;
+ }
+ }
+ TrustedTokenUsage::from_inclusive_totals(
+ count(usage, input)?,
+ count(usage, output)?,
+ cached,
+ 0,
+ reasoning,
+ )
+ .ok()
+ }
+ WireProtocol::Gemini => {
+ // Gemini candidates EXCLUDE thoughts; prompt INCLUDES cache reads.
+ // Server tool-use tokens do not belong to this token-only profile.
+ if optional_count(usage, "toolUsePromptTokenCount")? != 0 {
+ return None;
+ }
+ let cached = optional_count(usage, "cachedContentTokenCount")?;
+ Some(TrustedTokenUsage::from_disjoint(
+ count(usage, "promptTokenCount")?.checked_sub(cached)?,
+ count(usage, "candidatesTokenCount")?,
+ cached,
+ 0,
+ optional_count(usage, "thoughtsTokenCount")?,
+ ))
+ }
+ }?;
+ let total_key = if protocol == WireProtocol::Gemini {
+ "totalTokenCount"
+ } else {
+ "total_tokens"
+ };
+ if let Some(total) = usage.get(total_key) {
+ let total = total.as_u64()?;
+ // Some APIs/SDKs use zero for an absent total. Never replace explicit
+ // dimensions with that sentinel, or invent a missing dimension from it.
+ let disjoint_total = [
+ tokens.input(),
+ tokens.output(),
+ tokens.cache_read(),
+ tokens.cache_write(),
+ tokens.reasoning(),
+ ]
+ .into_iter()
+ .try_fold(0_u64, u64::checked_add)?;
+ if total != 0 && total != disjoint_total {
+ return None;
+ }
+ }
+ Some(tokens)
+}
+
+#[derive(Default)]
+struct SseDecoder {
+ line: Vec<u8>,
+ data: Vec<u8>,
+ oversized: bool,
+}
+
+impl SseDecoder {
+ fn push(&mut self, bytes: &[u8], facts: &mut Facts) {
+ if self.oversized || facts.terminal {
+ return;
+ }
+ for byte in bytes {
+ if self.line.len() + self.data.len() >= MAX_EVENT_BYTES {
+ self.oversized = true;
+ facts.invalid = true;
+ self.line.clear();
+ self.data.clear();
+ return;
+ }
+ if *byte != b'\n' {
+ self.line.push(*byte);
+ continue;
+ }
+ if self.line.last() == Some(&b'\r') {
+ self.line.pop();
+ }
+ if self.line.is_empty() {
+ if !self.data.is_empty() {
+ if self.data.last() == Some(&b'\n') {
+ self.data.pop();
+ }
+ facts.event(&self.data);
+ }
+ self.data.clear();
+ if facts.terminal {
+ return;
+ }
+ } else if let Some(data) = self.line.strip_prefix(b"data:") {
+ let data = data.strip_prefix(b" ").unwrap_or(data);
+ self.data.extend_from_slice(data);
+ self.data.push(b'\n');
+ }
+ self.line.clear();
+ }
+ }
+}
diff --git a/crates/agent/src/model/metering_http/test.rs b/crates/agent/src/model/metering_http/test.rs
new file mode 100644
index 0000000000..52a905d384
--- /dev/null
+++ b/crates/agent/src/model/metering_http/test.rs
@@ -0,0 +1,851 @@
+mod review;
+mod tracking;
+
+use super::super::metering::ProviderSupport;
+use super::*;
+use ai_usage::financial::*;
+use ai_usage::{AiFeature, FinancialFuture, FinancialUsage, UsageContext};
+use serde_json::json;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+
+#[derive(Default)]
+struct Journal {
+ begins: Mutex<Vec<BeginInvocation>>,
+ finals: Mutex<Vec<FinalizeInvocation>>,
+ deliveries: Mutex<Vec<FinalizeInvocation>>,
+ deny_after: Option<usize>,
+ lose_ack: bool,
+ replay_begin: bool,
+}
+
+impl FinancialUsage for Journal {
+ fn begin(
+ &self,
+ request: BeginInvocation,
+ ) -> FinancialFuture<'_, Recorded<AuthorizedInvocation>> {
+ Box::pin(async move {
+ let mut begins = self.begins.lock().unwrap();
+ if self.deny_after.is_some_and(|n| begins.len() >= n) {
+ return Err(FinancialError::FundingDenied);
+ }
+ begins.push(request.clone());
+ Ok(Recorded {
+ value: admission(request),
+ disposition: if self.replay_begin {
+ WriteDisposition::Replayed
+ } else {
+ WriteDisposition::Inserted
+ },
+ })
+ })
+ }
+ fn finalize(
+ &self,
+ evidence: FinalizeInvocation,
+ ) -> FinancialFuture<'_, Recorded<InvocationRecord>> {
+ Box::pin(async move {
+ let mut deliveries = self.deliveries.lock().unwrap();
+ deliveries.push(evidence.clone());
+ let mut finals = self.finals.lock().unwrap();
+ let disposition = if let Some(previous) = finals
+ .iter()
+ .find(|p| p.invocation_id == evidence.invocation_id)
+ {
+ previous.check_replay(&evidence)?;
+ WriteDisposition::Replayed
+ } else {
+ finals.push(evidence.clone());
+ WriteDisposition::Inserted
+ };
+ if self.lose_ack && deliveries.len() == 1 {
+ return Err(FinancialError::CapabilityUnavailable);
+ }
+ let request = self
+ .begins
+ .lock()
+ .unwrap()
+ .iter()
+ .find(|b| b.invocation_id == evidence.invocation_id)
+ .unwrap()
+ .clone();
+ let admission = admission(request);
+ let state = match evidence.usage {
+ UsageEvidence::Reported(usage) => InvocationState::Priced {
+ public_usage: admission.rate.tokens.price(usage)?,
+ evidence,
+ },
+ UsageEvidence::Missing(_) => InvocationState::Unresolved { evidence },
+ };
+ Ok(Recorded {
+ value: InvocationRecord { admission, state },
+ disposition,
+ })
+ })
+ }
+ fn get(&self, _: InvocationId) -> FinancialFuture<'_, Option<InvocationRecord>> {
+ Box::pin(async { Ok(None) })
+ }
+ fn pending(&self, _: PendingInvocations) -> FinancialFuture<'_, Vec<InvocationRecord>> {
+ Box::pin(async { Ok(vec![]) })
+ }
+}
+
+fn admission(request: BeginInvocation) -> AuthorizedInvocation {
+ let rate = RateSnapshot {
+ version: RateVersion::new(),
+ model: request.model.clone(),
+ effective_at: request.occurred_at,
+ tokens: TokenRates {
+ input: 1,
+ output: 1,
+ cache_read: 1,
+ cache_write: 1,
+ reasoning: 1,
+ },
+ };
+ let funding = FundingAuthorization {
+ id: FundingAuthorizationId::new(),
+ invocation_id: request.invocation_id,
+ maximum_public_usage: rate.tokens.price(request.token_budget).unwrap(),
+ };
+ AuthorizedInvocation {
+ request,
+ rate,
+ funding,
+ }
+}
+
+#[derive(Clone, Debug, Default)]
+struct Transport {
+ calls: Arc<AtomicUsize>,
+ bodies: Arc<Mutex<Vec<Value>>>,
+ response: Bytes,
+ remaining: Arc<Mutex<std::collections::VecDeque<Bytes>>>,
+ fail: bool,
+ stall: bool,
+ connect_delay: Duration,
+}
+
+impl Transport {
+ fn new(response: impl Into<Bytes>) -> Self {
+ Self {
+ calls: Arc::default(),
+ bodies: Arc::default(),
+ response: response.into(),
+ ..Default::default()
+ }
+ }
+ fn next_response(&self) -> Bytes {
+ self.remaining
+ .lock()
+ .unwrap()
+ .pop_front()
+ .unwrap_or_else(|| self.response.clone())
+ }
+
+ fn called<T: Into<Bytes>>(&self, request: Request<T>) {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ self.bodies
+ .lock()
+ .unwrap()
+ .push(serde_json::from_slice(&request.into_body().into()).unwrap());
+ }
+}
+
+impl HttpClientExt for Transport {
+ fn send<T, U>(
+ &self,
+ request: Request<T>,
+ ) -> impl Future<Output = http_client::Result<Response<LazyBody<U>>>> + Send + 'static
+ where
+ T: Into<Bytes> + Send,
+ U: From<Bytes> + Send + 'static,
+ {
+ self.called(request);
+ let response = self.next_response();
+ let fail = self.fail;
+ let stall = self.stall;
+ async move {
+ if fail {
+ return Err(http_client::Error::StreamEnded);
+ }
+ let body: LazyBody<U> = Box::pin(async move {
+ if stall {
+ tokio::time::sleep(DRAIN_TIMEOUT * 2).await;
+ }
+ Ok(U::from(response))
+ });
+ Ok(Response::builder()
+ .header("x-request-id", "req-1")
+ .body(body)
+ .unwrap())
+ }
+ }
+ fn send_multipart<U>(
+ &self,
+ _: Request<MultipartForm>,
+ ) -> impl Future<Output = http_client::Result<Response<LazyBody<U>>>> + Send + 'static
+ where
+ U: From<Bytes> + Send + 'static,
+ {
+ std::future::ready(Err(http_client::Error::StreamEnded))
+ }
+ async fn send_streaming<T>(&self, request: Request<T>) -> http_client::Result<StreamingResponse>
+ where
+ T: Into<Bytes> + Send,
+ {
+ self.called(request);
+ if !self.connect_delay.is_zero() {
+ tokio::time::sleep(self.connect_delay).await;
+ }
+ let bytes = self.next_response();
+ // Exercise arbitrary byte boundaries, including UTF-8 and CRLF.
+ let chunks: Vec<_> = bytes
+ .chunks(7)
+ .map(|chunk| Ok(Bytes::copy_from_slice(chunk)))
+ .collect();
+ let stall = self.stall;
+ let stream = async_stream::stream! {
+ if stall {
+ tokio::time::sleep(DRAIN_TIMEOUT * 2).await;
+ }
+ for chunk in chunks {
+ yield chunk;
+ }
+ };
+ Ok(Response::builder()
+ .header("content-type", "text/event-stream")
+ .body(Box::pin(stream) as http_client::sse::BoxedStream)
+ .unwrap())
+ }
+}
+
+fn context(
+ journal: Arc<Journal>,
+ protocol: WireProtocol,
+ provider: &str,
+ model: &str,
+) -> MeteringContext {
+ MeteringContext::new(
+ FinancialMode::Activated,
+ FinancialCapability::Available(journal),
+ UsageContext::system(AiFeature::Chat),
+ vec![ProviderSupport {
+ model: ProviderModel::new(provider, model).unwrap(),
+ protocol,
+ input_token_ceiling: 100,
+ output_token_ceiling: 20,
+ zero_usage_is_missing: false,
+ }],
+ )
+}
+
+fn request() -> Request<Bytes> {
+ Request::builder()
+ .uri("https://example.test/v1/messages")
+ .body(Bytes::from_static(br#"{"model":"model","max_tokens":50}"#))
+ .unwrap()
+}
+
+fn anthropic_response() -> Bytes {
+ Bytes::from_static(br#"{"id":"msg-1","content":[{"text":"not JSON"}],"usage":{"input_tokens":10,"output_tokens":5,"cache_read_input_tokens":2,"cache_creation_input_tokens":3}}"#)
+}
+
+#[test]
+fn provider_semantics_are_disjoint() {
+ let cases = [
+ (
+ WireProtocol::Anthropic,
+ json!({"input_tokens":10,"output_tokens":5,"cache_read_input_tokens":2,"cache_creation_input_tokens":3}),
+ TrustedTokenUsage::from_disjoint(10, 5, 2, 3, 0),
+ ),
+ (
+ WireProtocol::Responses,
+ json!({"input_tokens":10,"output_tokens":5,"input_tokens_details":{"cached_tokens":2},"output_tokens_details":{"reasoning_tokens":3}}),
+ TrustedTokenUsage::from_disjoint(8, 2, 2, 0, 3),
+ ),
+ (
+ WireProtocol::ChatCompletions,
+ json!({"prompt_tokens":10,"completion_tokens":5,"prompt_tokens_details":{"cached_tokens":2},"completion_tokens_details":{"reasoning_tokens":3}}),
+ TrustedTokenUsage::from_disjoint(8, 2, 2, 0, 3),
+ ),
+ (
+ WireProtocol::Gemini,
+ json!({"promptTokenCount":10,"candidatesTokenCount":5,"cachedContentTokenCount":2,"thoughtsTokenCount":3}),
+ TrustedTokenUsage::from_disjoint(8, 5, 2, 0, 3),
+ ),
+ ];
+ for (protocol, usage, expected) in cases {
+ assert_eq!(normalize(protocol, &usage), Some(expected));
+ }
+}
+
+#[test]
+fn absent_inconsistent_and_unsupported_counters_are_not_zero() {
+ assert_eq!(
+ normalize(
+ WireProtocol::Gemini,
+ &json!({"promptTokenCount":10,"candidatesTokenCount":5,"thoughtsTokenCount":3,"totalTokenCount":0})
+ ),
+ Some(TrustedTokenUsage::from_disjoint(10, 5, 0, 0, 3))
+ );
+ assert!(
+ normalize(
+ WireProtocol::Gemini,
+ &json!({"promptTokenCount":10,"candidatesTokenCount":5,"totalTokenCount":18})
+ )
+ .is_none()
+ );
+ assert!(normalize(WireProtocol::Responses, &json!({"input_tokens":0})).is_none());
+ assert!(
+ normalize(
+ WireProtocol::Gemini,
+ &json!({"promptTokenCount":-1,"candidatesTokenCount":2})
+ )
+ .is_none()
+ );
+ assert!(
+ normalize(
+ WireProtocol::Responses,
+ &json!({"input_tokens":1,"output_tokens":1,"input_tokens_details":{"cached_tokens":2}})
+ )
+ .is_none()
+ );
+ assert!(normalize(WireProtocol::Anthropic, &json!({"input_tokens":1,"output_tokens":1,"cache_creation":{"ephemeral_1h_input_tokens":1}})).is_none());
+ let mut facts = Facts::new(WireProtocol::ChatCompletions, true, None);
+ facts.response(br#"{"usage":{"prompt_tokens":0,"completion_tokens":0}}"#);
+ assert!(matches!(facts.evidence(), UsageEvidence::Missing(_)));
+ facts.zero_usage_is_missing = false;
+ assert_eq!(
+ facts.evidence(),
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(0, 0, 0, 0, 0))
+ );
+}
+
+#[test]
+fn repeated_cumulative_sse_counters_and_zero_placeholders_are_not_added() {
+ let mut facts = Facts::new(WireProtocol::Anthropic, false, None);
+ facts.event(br#"{"type":"message_start","message":{"id":"msg","usage":{"input_tokens":10,"output_tokens":1,"cache_read_input_tokens":2}}}"#);
+ for _ in 0..2 {
+ facts.event(br#"{"type":"message_delta","usage":{"input_tokens":0,"output_tokens":7,"cache_read_input_tokens":0}}"#);
+ }
+ assert_eq!(
+ facts.evidence(),
+ UsageEvidence::Missing(UnresolvedReason::Interrupted)
+ );
+ facts.event(br#"{"type":"message_stop"}"#);
+ assert_eq!(
+ facts.evidence(),
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(10, 7, 2, 0, 0))
+ );
+}
+
+#[tokio::test]
+async fn funding_is_awaited_and_limits_are_enforced_before_transport() {
+ let journal = Arc::new(Journal::default());
+ let transport = Transport::new(anthropic_response());
+ let client = MeteredHttpClient::new(transport.clone(), "anthropic", WireProtocol::Anthropic);
+ context(
+ journal.clone(),
+ WireProtocol::Anthropic,
+ "anthropic",
+ "model",
+ )
+ .scope(async {
+ client.send::<_, Bytes>(request()).await.unwrap();
+ })
+ .await;
+ assert_eq!(transport.calls.load(Ordering::SeqCst), 1);
+ assert_eq!(transport.bodies.lock().unwrap()[0]["max_tokens"], 20);
+ assert_eq!(journal.begins.lock().unwrap().len(), 1);
+ assert_eq!(
+ journal.finals.lock().unwrap()[0]
+ .provider_request_id
+ .as_ref()
+ .unwrap()
+ .as_str(),
+ "req-1"
+ );
+}
+
+#[tokio::test]
+async fn multiround_partial_failure_preserves_completed_round_and_stops_retries() {
+ let journal = Arc::new(Journal {
+ deny_after: Some(1),
+ ..Default::default()
+ });
+ let transport = Transport::new(anthropic_response());
+ let client = MeteredHttpClient::new(transport.clone(), "anthropic", WireProtocol::Anthropic);
+ context(
+ journal.clone(),
+ WireProtocol::Anthropic,
+ "anthropic",
+ "model",
+ )
+ .scope(async {
+ client.send::<_, Bytes>(request()).await.unwrap();
+ assert!(client.send::<_, Bytes>(request()).await.is_err());
+ assert!(client.send::<_, Bytes>(request()).await.is_err());
+ })
+ .await;
+ assert_eq!(transport.calls.load(Ordering::SeqCst), 1);
+ assert_eq!(journal.finals.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn distinct_executions_have_distinct_ids_but_lost_ack_reuses_evidence() {
+ let journal = Arc::new(Journal {
+ lose_ack: true,
+ ..Default::default()
+ });
+ let client = MeteredHttpClient::new(
+ Transport::new(anthropic_response()),
+ "anthropic",
+ WireProtocol::Anthropic,
+ );
+ context(
+ journal.clone(),
+ WireProtocol::Anthropic,
+ "anthropic",
+ "model",
+ )
+ .scope(async {
+ for _ in 0..2 {
+ client.send::<_, Bytes>(request()).await.unwrap();
+ }
+ })
+ .await;
+ let begins = journal.begins.lock().unwrap();
+ assert_ne!(begins[0].invocation_id, begins[1].invocation_id);
+ assert_eq!(begins[0].run_id, begins[1].run_id);
+ let deliveries = journal.deliveries.lock().unwrap();
+ assert_eq!(deliveries[0], deliveries[1]);
+ assert_eq!(journal.finals.lock().unwrap().len(), 2);
+}
+
+#[tokio::test]
+async fn structured_parse_failure_is_after_evidence_persistence() {
+ let journal = Arc::new(Journal::default());
+ let client = MeteredHttpClient::new(
+ Transport::new(anthropic_response()),
+ "anthropic",
+ WireProtocol::Anthropic,
+ );
+ context(
+ journal.clone(),
+ WireProtocol::Anthropic,
+ "anthropic",
+ "model",
+ )
+ .scope(async {
+ let response = client
+ .send::<_, Bytes>(request())
+ .await
+ .unwrap()
+ .into_body()
+ .await
+ .unwrap();
+ let value: Value = serde_json::from_slice(&response).unwrap();
+ assert!(
+ serde_json::from_str::<Value>(value["content"][0]["text"].as_str().unwrap()).is_err()
+ );
+ assert_eq!(journal.finals.lock().unwrap().len(), 1);
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn cancellation_or_invalid_tool_consumer_does_not_discard_terminal_evidence() {
+ let journal = Arc::new(Journal::default());
+ let sse = concat!(
+ "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg\",\"usage\":{\"input_tokens\":10,\"output_tokens\":1}}}\r\n\r\n",
+ "data: {\"type\":\"message_delta\",\"usage\":{\"output_tokens\":7}}\n\n",
+ "data: {\"type\":\"message_stop\"}\n\n"
+ );
+ let client = MeteredHttpClient::new(Transport::new(sse), "anthropic", WireProtocol::Anthropic);
+ context(
+ journal.clone(),
+ WireProtocol::Anthropic,
+ "anthropic",
+ "model",
+ )
+ .scope(async {
+ // Drop before reading any body; the provider's completed round still lands.
+ drop(client.send_streaming(request()).await.unwrap());
+ })
+ .await;
+ tokio::time::timeout(Duration::from_secs(2), async {
+ loop {
+ if !journal.finals.lock().unwrap().is_empty() {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .unwrap();
+ assert_eq!(
+ journal.finals.lock().unwrap()[0].usage,
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(10, 7, 0, 0, 0))
+ );
+}
+
+#[tokio::test]
+async fn lost_transport_after_execution_stays_unresolved() {
+ let journal = Arc::new(Journal::default());
+ let transport = Transport {
+ fail: true,
+ ..Transport::new("")
+ };
+ let client = MeteredHttpClient::new(transport.clone(), "anthropic", WireProtocol::Anthropic);
+ context(
+ journal.clone(),
+ WireProtocol::Anthropic,
+ "anthropic",
+ "model",
+ )
+ .scope(async {
+ assert!(client.send::<_, Bytes>(request()).await.is_err());
+ })
+ .await;
+ assert_eq!(transport.calls.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ journal.finals.lock().unwrap()[0].usage,
+ UsageEvidence::Missing(UnresolvedReason::Interrupted)
+ );
+}
+
+#[tokio::test]
+async fn absent_support_is_an_activation_gate_not_an_exemption() {
+ let journal = Arc::new(Journal::default());
+ let transport = Transport::new(anthropic_response());
+ let client = MeteredHttpClient::new(transport.clone(), "anthropic", WireProtocol::Anthropic);
+ context(
+ journal,
+ WireProtocol::Anthropic,
+ "anthropic",
+ "different-model",
+ )
+ .scope(async {
+ assert!(client.send::<_, Bytes>(request()).await.is_err());
+ })
+ .await;
+ assert_eq!(transport.calls.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test(start_paused = true)]
+async fn live_nonstream_request_outlives_the_cancelled_drain_budget() {
+ let journal = Arc::new(Journal::default());
+ let transport = Transport {
+ stall: true,
+ ..Transport::new(anthropic_response())
+ };
+ let client = MeteredHttpClient::new(transport.clone(), "anthropic", WireProtocol::Anthropic);
+ context(
+ journal.clone(),
+ WireProtocol::Anthropic,
+ "anthropic",
+ "model",
+ )
+ .scope(async {
+ client.send::<_, Bytes>(request()).await.unwrap();
+ })
+ .await;
+ assert_eq!(transport.calls.load(Ordering::SeqCst), 1);
+ let finals = journal.finals.lock().unwrap();
+ assert_eq!(finals[0].outcome, ProviderOutcome::Succeeded);
+ assert!(matches!(finals[0].usage, UsageEvidence::Reported(_)));
+}
+
+#[tokio::test]
+async fn rig_invalid_tool_retry_is_two_authorized_executions() {
+ use crate::{AgentLoop, StreamPart};
+ use ai_toolset::AsyncToolCollection;
+ use ai_usage::NoOpUsageRecorder;
+ use rig_core::client::CompletionClient;
+ use rig_core::providers::gemini;
+
+ let journal = Arc::new(Journal::default());
+ let bad = json!({"responseId":"bad", "candidates":[{"content":{"role":"model","parts":[{"functionCall":{"name":"unknown_tool","args":{}}}]},"finishReason":"STOP"}], "usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":2}});
+ let good = json!({"responseId":"good", "candidates":[{"content":{"role":"model","parts":[{"text":"done"}]},"finishReason":"STOP"}], "usageMetadata":{"promptTokenCount":12,"candidatesTokenCount":3}});
+ let transport = Transport::default();
+ transport
+ .remaining
+ .lock()
+ .unwrap()
+ .extend([bad, good].map(|event| Bytes::from(format!("data: {event}\n\n"))));
+ let client = gemini::Client::builder()
+ .api_key("test")
+ .http_client(MeteredHttpClient::new(
+ transport.clone(),
+ "google",
+ WireProtocol::Gemini,
+ ))
+ .build()
+ .unwrap();
+ let agent = AgentLoop::new(Arc::new(NoOpUsageRecorder)).with_max_tokens(20);
+ let mut session = context(journal.clone(), WireProtocol::Gemini, "google", "model")
+ .scope(agent.test_session(
+ Arc::new(AsyncToolCollection::<()>::new()),
+ Arc::new(()),
+ "system",
+ UsageContext::system(AiFeature::Chat),
+ client.completion_model("model"),
+ ))
+ .await;
+ // The session and its spawned driver retain the scope after construction.
+ let mut stream = session
+ .send_message(vec![rig_core::message::Message::user("hello")])
+ .await
+ .unwrap();
+ let mut output = String::new();
+ while let Some(item) = stream.next().await {
+ if let StreamPart::Content(text) = item.unwrap() {
+ output.push_str(&text);
+ }
+ }
+ assert_eq!(output, "done");
+ assert_eq!(transport.calls.load(Ordering::SeqCst), 2);
+ let finals = journal.finals.lock().unwrap();
+ assert_eq!(finals.len(), 2);
+ assert_ne!(finals[0].invocation_id, finals[1].invocation_id);
+ assert_eq!(
+ finals[0].usage,
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(10, 2, 0, 0, 0))
+ );
+}
+
+#[tokio::test]
+async fn routing_fallback_is_attributed_to_actual_provider_and_wire_model() {
+ use crate::model::router::{ModelRouter, RoutedModel};
+ use rig_agent::agent::AgentBuilder;
+ use rig_agent::completion::Prompt;
+ use rig_core::providers::{anthropic, openai};
+
+ let journal = Arc::new(Journal::default());
+ let transport = Transport::new(anthropic_response());
+ let anthropic = anthropic::Client::builder()
+ .api_key("test")
+ .http_client(MeteredHttpClient::new(
+ transport.clone(),
+ "anthropic",
+ WireProtocol::Anthropic,
+ ))
+ .build()
+ .unwrap();
+ let openai = openai::Client::builder()
+ .api_key("test")
+ .http_client(MeteredHttpClient::new(
+ transport.clone(),
+ "openai",
+ WireProtocol::Responses,
+ ))
+ .build()
+ .unwrap();
+ let router = ModelRouter::new(anthropic, openai);
+ let routed = router.route_or_default("unknown/model");
+ let model = routed.model_name().to_owned();
+ let RoutedModel::Anthropic(routed) = routed else {
+ panic!("expected native fallback")
+ };
+ context(
+ journal.clone(),
+ WireProtocol::Anthropic,
+ "anthropic",
+ &model,
+ )
+ .scope(async {
+ // Deliberately malformed SDK response, but wire usage is persisted first.
+ let agent = AgentBuilder::new(routed.completion())
+ .max_tokens(20)
+ .build();
+ let _ = agent.prompt("hello").await;
+ })
+ .await;
+ let begins = journal.begins.lock().unwrap();
+ assert_eq!(begins.len(), 1);
+ assert_eq!(
+ begins[0].model,
+ ProviderModel::new("anthropic", model).unwrap()
+ );
+ assert_eq!(journal.finals.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn responses_sdk_uses_the_capped_wire_budget_and_preserves_usage_on_parse_error() {
+ use rig_agent::agent::AgentBuilder;
+ use rig_agent::completion::Prompt;
+ use rig_core::client::CompletionClient;
+ use rig_core::providers::openai;
+
+ let journal = Arc::new(Journal::default());
+ let transport = Transport::new(Bytes::from(
+ json!({"usage": {
+ "input_tokens": 10, "output_tokens": 5, "input_tokens_details": {"cached_tokens": 2},
+ "output_tokens_details": {"reasoning_tokens": 3}
+ }})
+ .to_string(),
+ ));
+ let client = openai::Client::builder()
+ .api_key("test")
+ .http_client(MeteredHttpClient::new(
+ transport.clone(),
+ "openai",
+ WireProtocol::Responses,
+ ))
+ .build()
+ .unwrap();
+ let agent = AgentBuilder::new(client.completion_model("model"))
+ .max_tokens(50)
+ .build();
+ context(journal.clone(), WireProtocol::Responses, "openai", "model")
+ .scope(async {
+ assert!(agent.prompt("hello").await.is_err());
+ })
+ .await;
+ assert_eq!(transport.bodies.lock().unwrap()[0]["max_output_tokens"], 20);
+ assert_eq!(
+ journal.finals.lock().unwrap()[0].usage,
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(8, 2, 2, 0, 3))
+ );
+}
+
+#[tokio::test]
+async fn compatible_sdk_authorizes_the_account_qualified_wire_model() {
+ use crate::model::openai::OpenAiChatCompletionsModel;
+ use crate::model::types::Model;
+ use rig_agent::agent::AgentBuilder;
+ use rig_agent::completion::Prompt;
+ use rig_core::providers::openai;
+
+ let journal = Arc::new(Journal::default());
+ let transport = Transport::new(Bytes::from(json!({"usage": {
+ "prompt_tokens": 10, "completion_tokens": 5, "prompt_tokens_details": {"cached_tokens": 2},
+ "completion_tokens_details": {"reasoning_tokens": 3}
+ }}).to_string()));
+ let client = openai::CompletionsClient::builder()
+ .api_key("test")
+ .http_client(MeteredHttpClient::new(
+ transport.clone(),
+ "fireworks",
+ WireProtocol::ChatCompletions,
+ ))
+ .build()
+ .unwrap();
+ let model = OpenAiChatCompletionsModel::new(
+ Model::try_from("fireworks/kimi").unwrap(),
+ Arc::new(client),
+ );
+ let agent = AgentBuilder::new(model.completion()).max_tokens(50).build();
+ context(
+ journal.clone(),
+ WireProtocol::ChatCompletions,
+ "fireworks",
+ "accounts/fireworks/models/kimi",
+ )
+ .scope(async {
+ assert!(agent.prompt("hello").await.is_err());
+ })
+ .await;
+ assert_eq!(transport.bodies.lock().unwrap()[0]["max_tokens"], 20);
+ assert_eq!(
+ journal.begins.lock().unwrap()[0].model.model(),
+ "accounts/fireworks/models/kimi"
+ );
+ assert_eq!(
+ journal.finals.lock().unwrap()[0].usage,
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(8, 2, 2, 0, 3))
+ );
+}
+
+#[test]
+fn incomplete_stream_snapshots_are_never_promoted_to_final_usage() {
+ let mut gemini = Facts::new(WireProtocol::Gemini, false, None);
+ gemini.event(br#"{"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":2}}"#);
+ gemini.event(br#"{"candidates":[{"finishReason":"STOP"}]}"#);
+ assert!(matches!(gemini.evidence(), UsageEvidence::Missing(_)));
+ let mut anthropic = Facts::new(WireProtocol::Anthropic, false, None);
+ anthropic.event(
+ br#"{"type":"message_start","message":{"usage":{"input_tokens":10,"output_tokens":1}}}"#,
+ );
+ anthropic.event(br#"{"type":"error"}"#);
+ assert!(matches!(anthropic.evidence(), UsageEvidence::Missing(_)));
+ let mut chat = Facts::new(WireProtocol::ChatCompletions, false, None);
+ chat.event(br#"{"choices":[{}],"usage":{"prompt_tokens":10,"completion_tokens":2}}"#);
+ chat.event(b"[DONE]");
+ assert!(matches!(chat.evidence(), UsageEvidence::Missing(_)));
+}
+
+#[tokio::test]
+async fn replayed_admission_never_executes_again() {
+ let journal = Arc::new(Journal {
+ replay_begin: true,
+ ..Default::default()
+ });
+ let transport = Transport::new(anthropic_response());
+ let client = MeteredHttpClient::new(transport.clone(), "anthropic", WireProtocol::Anthropic);
+ context(journal, WireProtocol::Anthropic, "anthropic", "model")
+ .scope(async {
+ assert!(client.send::<_, Bytes>(request()).await.is_err());
+ })
+ .await;
+ assert_eq!(transport.calls.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn non_success_http_status_still_retains_reported_usage() {
+ let journal = Arc::new(Journal::default());
+ let context = context(
+ journal.clone(),
+ WireProtocol::Anthropic,
+ "anthropic",
+ "model",
+ );
+ let attempt = context
+ .begin(
+ ProviderModel::new("anthropic", "model").unwrap(),
+ WireProtocol::Anthropic,
+ &mut json!({"max_tokens":20}),
+ )
+ .await
+ .unwrap();
+ let error = http_client::Error::InvalidStatusCodeWithMessage(
+ reqwest::StatusCode::INTERNAL_SERVER_ERROR,
+ String::from_utf8(anthropic_response().to_vec()).unwrap(),
+ );
+ finish_failure(attempt, &error).await.unwrap();
+ let finals = journal.finals.lock().unwrap();
+ assert_eq!(finals[0].outcome, ProviderOutcome::Failed);
+ assert!(matches!(finals[0].usage, UsageEvidence::Reported(_)));
+ assert_eq!(
+ finals[0].provider_request_id.as_ref().unwrap().as_str(),
+ "msg-1"
+ );
+}
+
+#[tokio::test]
+async fn provider_excess_is_not_clipped_to_the_authorized_budget() {
+ let journal = Arc::new(Journal::default());
+ let transport = Transport::new(Bytes::from(
+ json!({"usage":{"input_tokens":10,"output_tokens":1000}}).to_string(),
+ ));
+ let client = MeteredHttpClient::new(transport, "anthropic", WireProtocol::Anthropic);
+ context(
+ journal.clone(),
+ WireProtocol::Anthropic,
+ "anthropic",
+ "model",
+ )
+ .scope(async {
+ client.send::<_, Bytes>(request()).await.unwrap();
+ })
+ .await;
+ assert_eq!(journal.begins.lock().unwrap()[0].token_budget.output(), 20);
+ // The funding domain needs the full excess to classify Macro-absorbed usage;
+ // the producer must neither truncate it nor invent customer liability.
+ assert_eq!(
+ journal.finals.lock().unwrap()[0].usage,
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(10, 1000, 0, 0, 0))
+ );
+}
diff --git a/crates/agent/src/model/metering_http/test/review.rs b/crates/agent/src/model/metering_http/test/review.rs
new file mode 100644
index 0000000000..d949a0a32f
--- /dev/null
+++ b/crates/agent/src/model/metering_http/test/review.rs
@@ -0,0 +1,203 @@
+use super::*;
+
+#[test]
+fn nullable_anthropic_counters_are_absent_but_required_and_malformed_counts_are_not() {
+ assert_eq!(
+ normalize(
+ WireProtocol::Anthropic,
+ &json!({
+ "input_tokens": 10, "output_tokens": 2, "cache_creation": null,
+ "cache_read_input_tokens": null, "cache_creation_input_tokens": null
+ })
+ ),
+ Some(TrustedTokenUsage::from_disjoint(10, 2, 0, 0, 0))
+ );
+ for usage in [
+ json!({"input_tokens": 10}),
+ json!({"input_tokens": 10, "output_tokens": null}),
+ json!({"input_tokens": 10, "output_tokens": 2, "cache_creation": 3}),
+ json!({"input_tokens": 10, "output_tokens": 2, "cache_read_input_tokens": -1}),
+ json!({"input_tokens": 10, "output_tokens": 2, "cache_creation_input_tokens": "3"}),
+ ] {
+ assert!(normalize(WireProtocol::Anthropic, &usage).is_none());
+ }
+ let mut facts = Facts::new(WireProtocol::Anthropic, false, None);
+ facts.event(br#"{"type":"message_start","message":{"usage":{"input_tokens":10,"cache_read_input_tokens":3,"cache_creation_input_tokens":2}}}"#);
+ facts.event(br#"{"type":"message_delta","usage":{"input_tokens":null,"output_tokens":7,"cache_read_input_tokens":null,"cache_creation_input_tokens":null,"cache_creation":null}}"#);
+ facts.event(br#"{"type":"message_delta","usage":{"output_tokens":null}}"#);
+ facts.event(br#"{"type":"message_stop"}"#);
+ assert_eq!(
+ facts.evidence(),
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(10, 7, 3, 2, 0))
+ );
+}
+
+const SSE: &str = concat!(
+ "data: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":10}}}\n\n",
+ "data: {\"type\":\"message_delta\",\"usage\":{\"output_tokens\":7}}\n\n",
+ "data: {\"type\":\"message_stop\"}\n\n",
+);
+
+#[tokio::test(start_paused = true)]
+async fn live_stream_outlives_drain_budget_without_truncation() {
+ let journal = Arc::new(Journal::default());
+ let client = MeteredHttpClient::new(
+ Transport {
+ stall: true,
+ connect_delay: DRAIN_TIMEOUT * 2,
+ ..Transport::new(SSE)
+ },
+ "anthropic",
+ WireProtocol::Anthropic,
+ );
+ context(
+ journal.clone(),
+ WireProtocol::Anthropic,
+ "anthropic",
+ "model",
+ )
+ .scope(async {
+ let mut stream = client.send_streaming(request()).await.unwrap().into_body();
+ let mut bytes = Vec::new();
+ while let Some(chunk) = stream.next().await {
+ bytes.extend_from_slice(&chunk.unwrap());
+ }
+ assert_eq!(bytes, SSE.as_bytes());
+ })
+ .await;
+ assert_eq!(
+ journal.finals.lock().unwrap()[0].usage,
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(10, 7, 0, 0, 0))
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn dropped_stream_has_a_bounded_drain_and_interrupted_evidence() {
+ let journal = Arc::new(Journal::default());
+ let client = MeteredHttpClient::new(
+ Transport {
+ stall: true,
+ ..Transport::new(SSE)
+ },
+ "anthropic",
+ WireProtocol::Anthropic,
+ );
+ context(
+ journal.clone(),
+ WireProtocol::Anthropic,
+ "anthropic",
+ "model",
+ )
+ .scope(async {
+ drop(client.send_streaming(request()).await.unwrap());
+ })
+ .await;
+ tokio::task::yield_now().await;
+ tokio::time::advance(DRAIN_TIMEOUT + Duration::from_secs(1)).await;
+ for _ in 0..20 {
+ tokio::task::yield_now().await;
+ }
+ assert_eq!(
+ journal.finals.lock().unwrap()[0].usage,
+ UsageEvidence::Missing(UnresolvedReason::Interrupted)
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn cancellation_before_stream_headers_shares_one_drain_budget_with_body() {
+ for connect_delay in [Duration::from_secs(200), DRAIN_TIMEOUT * 2] {
+ let journal = Arc::new(Journal::default());
+ let transport = Transport {
+ connect_delay,
+ stall: true,
+ ..Transport::new(SSE)
+ };
+ let client =
+ MeteredHttpClient::new(transport.clone(), "anthropic", WireProtocol::Anthropic);
+ let scope = context(
+ journal.clone(),
+ WireProtocol::Anthropic,
+ "anthropic",
+ "model",
+ );
+ let caller =
+ tokio::spawn(async move { scope.scope(client.send_streaming(request())).await });
+ while transport.calls.load(Ordering::SeqCst) == 0 {
+ tokio::task::yield_now().await;
+ }
+ caller.abort();
+ let _ = caller.await;
+ tokio::task::yield_now().await;
+ tokio::time::advance(Duration::from_secs(201)).await;
+ for _ in 0..20 {
+ tokio::task::yield_now().await;
+ }
+ assert!(journal.finals.lock().unwrap().is_empty());
+ tokio::time::advance(Duration::from_secs(100)).await;
+ for _ in 0..20 {
+ tokio::task::yield_now().await;
+ }
+ assert_eq!(
+ journal.finals.lock().unwrap()[0].usage,
+ UsageEvidence::Missing(UnresolvedReason::Interrupted)
+ );
+ }
+}
+
+#[tokio::test]
+async fn mixed_session_scopes_preserve_identity_and_new_financial_activation() {
+ use rig_core::test_utils::{MockCompletionModel, MockStreamEvent};
+ let owner = UsageContext::new(
+ AiFeature::Chat,
+ "macro|[email protected]".to_owned().try_into().unwrap(),
+ );
+ let other = UsageContext::new(
+ AiFeature::Chat,
+ "macro|[email protected]".to_owned().try_into().unwrap(),
+ );
+ for stored_mode in [FinancialMode::Activated, FinancialMode::TrackingOnly] {
+ for current_mode in [
+ FinancialMode::Activated,
+ FinancialMode::TrackingOnly,
+ FinancialMode::Legacy,
+ ] {
+ let journal = Arc::new(Journal::default());
+ let stored = MeteringContext::new(
+ stored_mode,
+ FinancialCapability::Available(journal.clone()),
+ owner.clone(),
+ vec![],
+ );
+ let current = MeteringContext::new(
+ current_mode,
+ FinancialCapability::Available(journal),
+ other.clone(),
+ vec![],
+ );
+ let agent = crate::AgentLoop::new(Arc::new(ai_usage::NoOpUsageRecorder));
+ let mut session = stored
+ .scope(agent.test_session(
+ Arc::new(ai_toolset::AsyncToolCollection::<()>::new()),
+ Arc::new(()),
+ "system",
+ owner.clone(),
+ MockCompletionModel::from_stream_turns([vec![
+ MockStreamEvent::text("done"),
+ MockStreamEvent::final_response_with_default_usage(),
+ ]]),
+ ))
+ .await;
+ let result = current
+ .scope(session.send_message(vec![rig_core::message::Message::user("hello")]))
+ .await;
+ if current_mode == FinancialMode::Activated {
+ assert!(result.err().unwrap().to_string().contains("attribution"));
+ } else {
+ let mut stream = result.unwrap();
+ while let Some(item) = stream.next().await {
+ item.unwrap();
+ }
+ }
+ }
+ }
+}
diff --git a/crates/agent/src/model/metering_http/test/tracking.rs b/crates/agent/src/model/metering_http/test/tracking.rs
new file mode 100644
index 0000000000..1359f0af39
--- /dev/null
+++ b/crates/agent/src/model/metering_http/test/tracking.rs
@@ -0,0 +1,342 @@
+use super::*;
+use ai_usage::{TrackedInvocation, UsageTracking};
+
+#[derive(Default)]
+struct Observations {
+ begins: Mutex<Vec<TrackedInvocation>>,
+ finals: Mutex<Vec<FinalizeInvocation>>,
+ fail: bool,
+ lose_ack: bool,
+}
+
+impl UsageTracking for Observations {
+ fn begin(&self, request: TrackedInvocation) -> FinancialFuture<'_, WriteDisposition> {
+ Box::pin(async move {
+ let mut begins = self.begins.lock().unwrap();
+ if !begins
+ .iter()
+ .any(|r| r.invocation_id == request.invocation_id)
+ {
+ begins.push(request);
+ }
+ if self.fail {
+ return Err(FinancialError::CapabilityUnavailable);
+ }
+ Ok(WriteDisposition::Inserted)
+ })
+ }
+
+ fn finalize(&self, evidence: FinalizeInvocation) -> FinancialFuture<'_, WriteDisposition> {
+ Box::pin(async move {
+ let mut finals = self.finals.lock().unwrap();
+ finals.push(evidence);
+ if self.lose_ack && finals.len() == 1 {
+ return Err(FinancialError::CapabilityUnavailable);
+ }
+ Ok(WriteDisposition::Inserted)
+ })
+ }
+}
+
+fn usage(user: &str, feature: AiFeature) -> UsageContext {
+ UsageContext::new(feature, user.to_owned().try_into().unwrap())
+}
+
+#[tokio::test]
+async fn no_funding_or_rates_are_required_and_request_budgets_are_unchanged() {
+ let journal = Arc::new(Observations::default());
+ // No financial capability, funding authorization or provider support profile.
+ let context = MeteringContext::tracking_only(
+ journal.clone(),
+ usage("macro|[email protected]", AiFeature::Chat),
+ );
+ let transport = Transport::new(anthropic_response());
+ let client = MeteredHttpClient::new(transport.clone(), "anthropic", WireProtocol::Anthropic);
+ let body = json!({"model":"model", "max_tokens":50, "tools":[{"type":"web_search"}],
+ "messages":[{"content":[{"type":"image","source":{}}]}]});
+ context
+ .scope(async {
+ for _ in 0..2 {
+ let request = Request::builder()
+ .uri("https://example.test/messages")
+ .body(Bytes::from(serde_json::to_vec(&body).unwrap()))
+ .unwrap();
+ client
+ .send::<_, Bytes>(request)
+ .await
+ .unwrap()
+ .into_body()
+ .await
+ .unwrap();
+ }
+ })
+ .await;
+ assert_eq!(*transport.bodies.lock().unwrap(), vec![body.clone(), body]);
+ let begins = journal.begins.lock().unwrap();
+ assert_eq!(begins.len(), 2);
+ assert_ne!(begins[0].invocation_id, begins[1].invocation_id);
+ assert_eq!(begins[0].run_id, begins[1].run_id);
+ let finals = journal.finals.lock().unwrap();
+ assert_eq!(finals.len(), 2);
+ assert_eq!(
+ finals[0].usage,
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(10, 5, 2, 3, 0))
+ );
+}
+
+#[tokio::test]
+async fn concurrent_users_and_excluded_features_keep_immutable_attribution() {
+ let journal = Arc::new(Observations::default());
+ let client = MeteredHttpClient::new(
+ Transport::new(anthropic_response()),
+ "anthropic",
+ WireProtocol::Anthropic,
+ );
+ let a = MeteringContext::tracking_only(
+ journal.clone(),
+ usage("macro|[email protected]", AiFeature::ChatRename),
+ );
+ let b = MeteringContext::tracking_only(
+ journal.clone(),
+ usage("macro|[email protected]", AiFeature::Import),
+ );
+ let (a, b) = tokio::join!(
+ a.scope(client.send::<_, Bytes>(request())),
+ b.scope(client.send::<_, Bytes>(request())),
+ );
+ a.unwrap();
+ b.unwrap();
+ let begins = journal.begins.lock().unwrap();
+ assert_eq!(begins.len(), 2);
+ assert!(begins.iter().any(|r| r.user.as_ref() == "macro|[email protected]" && r.feature == AiFeature::ChatRename));
+ assert!(
+ begins
+ .iter()
+ .any(|r| r.user.as_ref() == "macro|[email protected]" && r.feature == AiFeature::Import)
+ );
+ assert_ne!(begins[0].run_id, begins[1].run_id);
+}
+
+#[tokio::test]
+async fn recorder_failure_never_becomes_denial_or_stops_later_attempts() {
+ let journal = Arc::new(Observations {
+ fail: true,
+ ..Default::default()
+ });
+ let context = MeteringContext::tracking_only(
+ journal.clone(),
+ usage("macro|[email protected]", AiFeature::Chat),
+ );
+ let transport = Transport::new(anthropic_response());
+ let client = MeteredHttpClient::new(transport.clone(), "anthropic", WireProtocol::Anthropic);
+ context
+ .scope(async {
+ for _ in 0..2 {
+ let response = client.send::<_, Bytes>(request()).await.unwrap();
+ assert_eq!(response.into_body().await.unwrap(), anthropic_response());
+ }
+ })
+ .await;
+ assert_eq!(transport.calls.load(Ordering::SeqCst), 2);
+ assert!(journal.finals.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn lost_ack_retries_identical_evidence_not_the_provider() {
+ let journal = Arc::new(Observations {
+ lose_ack: true,
+ ..Default::default()
+ });
+ let context =
+ MeteringContext::tracking_only(journal.clone(), UsageContext::system(AiFeature::Chat));
+ let transport = Transport::new(anthropic_response());
+ let client = MeteredHttpClient::new(transport.clone(), "anthropic", WireProtocol::Anthropic);
+ context
+ .scope(client.send::<_, Bytes>(request()))
+ .await
+ .unwrap();
+ assert_eq!(transport.calls.load(Ordering::SeqCst), 1);
+ let finals = journal.finals.lock().unwrap();
+ assert_eq!(finals.len(), 2);
+ assert_eq!(finals[0], finals[1]);
+}
+
+#[tokio::test]
+async fn interrupted_stream_is_unresolved_without_adding_a_provider_error() {
+ let journal = Arc::new(Observations::default());
+ let context =
+ MeteringContext::tracking_only(journal.clone(), UsageContext::system(AiFeature::Chat));
+ let client = MeteredHttpClient::new(
+ Transport::new("data: {\"type\":\"message_start\",\"message\":{}}\n\n"),
+ "anthropic",
+ WireProtocol::Anthropic,
+ );
+ context
+ .scope(async {
+ let response = client.send_streaming(request()).await.unwrap();
+ let chunks: Vec<_> = response.into_body().collect().await;
+ assert!(chunks.iter().all(Result::is_ok));
+ })
+ .await;
+ assert_eq!(
+ journal.finals.lock().unwrap()[0].usage,
+ UsageEvidence::Missing(UnresolvedReason::Interrupted)
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn caller_cancellation_does_not_cancel_evidence_delivery() {
+ let journal = Arc::new(Observations::default());
+ let context = MeteringContext::tracking_only(
+ journal.clone(),
+ UsageContext::system(AiFeature::ChannelBot),
+ );
+ let transport = Transport {
+ stall: true,
+ ..Transport::new(anthropic_response())
+ };
+ let client = MeteredHttpClient::new(transport.clone(), "anthropic", WireProtocol::Anthropic);
+ let caller =
+ tokio::spawn(async move { context.scope(client.send::<_, Bytes>(request())).await });
+ while transport.calls.load(Ordering::SeqCst) == 0 {
+ tokio::task::yield_now().await;
+ }
+ caller.abort();
+ let _ = caller.await;
+ tokio::task::yield_now().await;
+ tokio::time::advance(DRAIN_TIMEOUT + Duration::from_secs(1)).await;
+ for _ in 0..20 {
+ tokio::task::yield_now().await;
+ }
+ assert_eq!(
+ journal.finals.lock().unwrap()[0].usage,
+ UsageEvidence::Missing(UnresolvedReason::Interrupted)
+ );
+}
+
+#[tokio::test]
+async fn captured_financial_session_cannot_be_downgraded_by_an_observational_recorder() {
+ use rig_core::test_utils::{MockCompletionModel, MockTurn};
+ let recorder = ai_usage::with_tracking(
+ Arc::new(ai_usage::NoOpUsageRecorder),
+ Arc::new(Observations::default()),
+ );
+ let session_usage = UsageContext::system(AiFeature::Chat);
+ let strict = MeteringContext::new(
+ FinancialMode::Activated,
+ FinancialCapability::Unavailable,
+ session_usage.clone(),
+ vec![],
+ );
+ let agent = crate::AgentLoop::new(recorder);
+ let mut session = strict
+ .scope(agent.test_session(
+ Arc::new(ai_toolset::AsyncToolCollection::<()>::new()),
+ Arc::new(()),
+ "system",
+ session_usage,
+ MockCompletionModel::new([MockTurn::text("must not execute")]),
+ ))
+ .await;
+ let caller_usage = usage("macro|[email protected]", AiFeature::Automation);
+ for caller in [
+ MeteringContext::tracking_only(Arc::new(Observations::default()), caller_usage.clone()),
+ MeteringContext::new(
+ FinancialMode::Legacy,
+ FinancialCapability::Unavailable,
+ caller_usage,
+ vec![],
+ ),
+ ] {
+ let error = caller
+ .scope(session.send_message(vec![rig_core::message::Message::user("hello")]))
+ .await
+ .err()
+ .expect("captured strict scope must fail closed inside a non-financial scope");
+ assert!(error.to_string().contains("capability"));
+ }
+}
+
+#[tokio::test]
+async fn legacy_scope_does_not_disable_injected_observation_and_children_can_inherit_it() {
+ let journal = Arc::new(Observations::default());
+ let recorder = ai_usage::with_tracking(Arc::new(ai_usage::NoOpUsageRecorder), journal.clone());
+ let parent_usage = usage("macro|[email protected]", AiFeature::Chat);
+ let child_usage = usage("macro|[email protected]", AiFeature::ChatRename);
+ let legacy = MeteringContext::new(
+ FinancialMode::Legacy,
+ FinancialCapability::Unavailable,
+ parent_usage.clone(),
+ vec![],
+ );
+ legacy
+ .scope(async {
+ let parent = MeteringContext::for_operation(recorder.as_ref(), &parent_usage).unwrap();
+ parent
+ .scope(async {
+ let child =
+ MeteringContext::for_operation(&ai_usage::NoOpUsageRecorder, &child_usage)
+ .unwrap();
+ child
+ .scope(async {
+ let client = MeteredHttpClient::new(
+ Transport::new(anthropic_response()),
+ "anthropic",
+ WireProtocol::Anthropic,
+ );
+ client.send::<_, Bytes>(request()).await.unwrap();
+ })
+ .await;
+ })
+ .await;
+ })
+ .await;
+ assert_eq!(journal.begins.lock().unwrap()[0].user, child_usage.user);
+ assert_eq!(
+ journal.begins.lock().unwrap()[0].feature,
+ AiFeature::ChatRename
+ );
+}
+
+#[tokio::test]
+async fn scope_bridge_preserves_financial_mode_and_rebinds_observational_children() {
+ let journal = Arc::new(Observations::default());
+ let recorder = ai_usage::with_tracking(Arc::new(ai_usage::NoOpUsageRecorder), journal.clone());
+ let parent_usage = usage("macro|[email protected]", AiFeature::Automation);
+ let child_usage = usage("macro|[email protected]", AiFeature::Import);
+ let parent = MeteringContext::for_operation(recorder.as_ref(), &parent_usage).unwrap();
+ let client = MeteredHttpClient::new(
+ Transport::new(anthropic_response()),
+ "anthropic",
+ WireProtocol::Anthropic,
+ );
+ parent
+ .scope(async {
+ let child = MeteringContext::for_operation(recorder.as_ref(), &child_usage).unwrap();
+ let captured = Some(child);
+ tokio::spawn(MeteringContext::carry(captured, async move {
+ client.send::<_, Bytes>(request()).await
+ }))
+ .await
+ .unwrap()
+ .unwrap();
+ })
+ .await;
+ assert_eq!(journal.begins.lock().unwrap()[0].user, child_usage.user);
+ let strict = MeteringContext::new(
+ FinancialMode::Activated,
+ FinancialCapability::Unavailable,
+ parent_usage,
+ vec![],
+ );
+ strict
+ .scope(async {
+ assert!(
+ MeteringContext::for_operation(recorder.as_ref(), &child_usage)
+ .unwrap()
+ .activated()
+ );
+ assert!(MeteringContext::require_usage(&child_usage).is_err());
+ })
+ .await;
+}
diff --git a/crates/agent/src/model/mod.rs b/crates/agent/src/model/mod.rs
index ce76ee7459..d4fd3a697c 100644
--- a/crates/agent/src/model/mod.rs
+++ b/crates/agent/src/model/mod.rs
@@ -6,5 +6,7 @@ pub(crate) mod types;
pub use predefined_model::*;
mod anthropic;
mod gemini;
+pub mod metering;
+pub mod metering_http;
mod openai;
pub mod router;
diff --git a/crates/agent/src/model/openai.rs b/crates/agent/src/model/openai.rs
index de3b67f94a..dbdf4a449c 100644
--- a/crates/agent/src/model/openai.rs
+++ b/crates/agent/src/model/openai.rs
@@ -1,7 +1,7 @@
use std::sync::Arc;
use crate::model::types::Model;
-use rig_core::{client::CompletionClient, providers::openai};
+use rig_core::{client::CompletionClient, http_client::HttpClientExt, providers::openai};
/// Fireworks' Chat Completions `model` field is the account-scoped path, not
/// the short catalog slug. Routing ids stay `fireworks/<slug>` so the picker,
@@ -23,14 +23,16 @@ fn completion_model_id(model: &Model<'_>) -> String {
/// segment). Fireworks is the one exception on the wire: its API wants the
/// account-scoped path, which [`completion_model_id`] derives from the
/// catalog slug.
-pub struct OpenAiChatCompletionsModel<'a> {
+pub struct OpenAiChatCompletionsModel<'a, H = rig_core::http_client::ReqwestClient> {
model: Model<'a>,
- client: Arc<openai::CompletionsClient>,
+ client: Arc<openai::CompletionsClient<H>>,
}
-impl<'a> OpenAiChatCompletionsModel<'a> {
+impl<'a, H: HttpClientExt + Clone + Default + std::fmt::Debug + 'static>
+ OpenAiChatCompletionsModel<'a, H>
+{
/// Bind `model` to the client that serves it.
- pub fn new(model: Model<'a>, client: Arc<openai::CompletionsClient>) -> Self {
+ pub fn new(model: Model<'a>, client: Arc<openai::CompletionsClient<H>>) -> Self {
Self { model, client }
}
@@ -43,7 +45,7 @@ impl<'a> OpenAiChatCompletionsModel<'a> {
///
/// Unlike the Responses API, the Chat Completions API does not coerce tools
/// into a strict subset, so tools are already sent verbatim.
- pub fn completion(&self) -> openai::completion::CompletionModel {
+ pub fn completion(&self) -> openai::completion::CompletionModel<H> {
self.client
.completion_model(completion_model_id(&self.model))
}
@@ -84,14 +86,16 @@ impl<'a> OpenAiChatCompletionsModel<'a> {
/// This is intentionally separate from OpenAI-compatible Chat Completions:
/// OpenAI GPT reasoning models expect Responses-shaped request fields, while
/// many compatible OSS endpoints only promise `/v1/chat/completions`.
-pub struct OpenAiResponsesModel<'a> {
+pub struct OpenAiResponsesModel<'a, H = rig_core::http_client::ReqwestClient> {
model: Model<'a>,
- client: Arc<openai::Client>,
+ client: Arc<openai::Client<H>>,
}
-impl<'a> OpenAiResponsesModel<'a> {
+impl<'a, H: HttpClientExt + Clone + Default + std::fmt::Debug + 'static>
+ OpenAiResponsesModel<'a, H>
+{
/// Bind `model` to the Responses API client that serves it.
- pub fn new(model: Model<'a>, client: Arc<openai::Client>) -> Self {
+ pub fn new(model: Model<'a>, client: Arc<openai::Client<H>>) -> Self {
Self { model, client }
}
@@ -106,7 +110,7 @@ impl<'a> OpenAiResponsesModel<'a> {
/// `max_output_tokens`, avoiding the Chat Completions `max_tokens` 400s on
/// GPT reasoning models. Tools are sent verbatim (non-strict is rig's
/// default since 0.41) rather than coerced into OpenAI's strict subset.
- pub fn completion(&self) -> openai::responses_api::ResponsesCompletionModel {
+ pub fn completion(&self) -> openai::responses_api::ResponsesCompletionModel<H> {
self.client.completion_model(self.model.name().to_string())
}
diff --git a/crates/agent/src/model/router.rs b/crates/agent/src/model/router.rs
index 665921ecf2..b980d64fae 100644
--- a/crates/agent/src/model/router.rs
+++ b/crates/agent/src/model/router.rs
@@ -7,7 +7,7 @@
//! wire protocol: Anthropic-native, Gemini GenerateContent, OpenAI Responses,
//! and OpenAI-compatible Chat Completions. Compatible providers live in a
//! data registry keyed by name, so adding one is
-//! [`with_openai_provider`](ModelRouter::with_openai_provider).
+//! `with_openai_provider` on the metered router.
//! - [`ProviderAgent`] — a built rig agent, with the same arms. Its
//! [`run_stream`](ProviderAgent::run_stream) matches internally, so callers
//! (e.g. `agent_loop`) hold one type and never fan out.
@@ -28,6 +28,7 @@ use rig_agent::agent::{Agent, AgentBuilder, MultiTurnStreamItem};
use rig_agent::streaming::StreamingPrompt;
use rig_agent::tool::server::ToolServerHandle;
use rig_core::completion::{CompletionModel, GetTokenUsage};
+use rig_core::http_client::{HttpClientExt, ReqwestClient};
use rig_core::message::Message;
use rig_core::providers::{anthropic, gemini, openai};
use rig_core::streaming::StreamedAssistantContent;
@@ -36,6 +37,8 @@ use tracing::Instrument as _;
use super::PredefinedModel;
use super::anthropic::AnthropicModel;
use super::gemini::GeminiModel;
+use super::metering::{MeteringContext, WireProtocol};
+use super::metering_http::MeteredHttpClient;
use super::openai::{OpenAiChatCompletionsModel, OpenAiResponsesModel};
use super::types::Model;
use crate::error::AgentError;
@@ -72,18 +75,18 @@ const FIREWORKS_BASE_URL: &str = "https://api.fireworks.ai/inference/v1";
const GOOGLE_PROVIDER: &str = "google";
/// A routed model id bound to the provider client that serves it.
-pub(crate) enum RoutedModel<'a> {
+pub(crate) enum RoutedModel<'a, H = MeteredHttpClient> {
/// A model on Anthropic's native API.
- Anthropic(AnthropicModel<'a>),
+ Anthropic(AnthropicModel<'a, H>),
/// A model on Gemini's native GenerateContent API.
- Gemini(GeminiModel<'a>),
+ Gemini(GeminiModel<'a, H>),
/// A model on the OpenAI-compatible Chat Completions API.
- OpenAiChatCompletions(OpenAiChatCompletionsModel<'a>),
+ OpenAiChatCompletions(OpenAiChatCompletionsModel<'a, H>),
/// A model on OpenAI's Responses API.
- OpenAiResponses(OpenAiResponsesModel<'a>),
+ OpenAiResponses(OpenAiResponsesModel<'a, H>),
}
-impl<'a> RoutedModel<'a> {
+impl<'a, H: HttpClientExt + Clone + Default + std::fmt::Debug + 'static> RoutedModel<'a, H> {
/// The provider segment of the routed id (`anthropic`, `openai`, …).
pub(crate) fn provider(&self) -> &str {
match self {
@@ -113,7 +116,7 @@ impl<'a> RoutedModel<'a> {
max_turns: usize,
max_tokens: u64,
telemetry: &GenAiContext,
- ) -> ProviderAgent {
+ ) -> ProviderAgent<H> {
match self {
RoutedModel::Anthropic(m) => {
let thinking = m.thinking_params();
@@ -173,22 +176,24 @@ impl<'a> RoutedModel<'a> {
/// that behind one concrete [`ChatCompletionStream`], so callers never match.
///
/// [`run_stream`]: ProviderAgent::run_stream
-pub(crate) enum ProviderAgent {
+pub(crate) enum ProviderAgent<
+ H: HttpClientExt + Clone + Default + std::fmt::Debug + 'static = MeteredHttpClient,
+> {
/// An agent over Anthropic's native completion model.
- Anthropic(Agent<TracedModel<anthropic::completion::CompletionModel>>),
+ Anthropic(Agent<TracedModel<anthropic::completion::CompletionModel<H>>>),
/// An agent over Gemini's native GenerateContent model.
- Gemini(Agent<TracedModel<gemini::completion::CompletionModel>>),
+ Gemini(Agent<TracedModel<gemini::completion::CompletionModel<H>>>),
/// An agent over the OpenAI Chat Completions model.
- OpenAiChatCompletions(Agent<TracedModel<openai::completion::CompletionModel>>),
+ OpenAiChatCompletions(Agent<TracedModel<openai::completion::CompletionModel<H>>>),
/// An agent over the OpenAI Responses model.
- OpenAiResponses(Agent<TracedModel<openai::responses_api::ResponsesCompletionModel>>),
+ OpenAiResponses(Agent<TracedModel<openai::responses_api::ResponsesCompletionModel<H>>>),
/// A test-only agent over an arbitrary completion model (e.g. a scripted
- /// fake), type-erased so the enum itself stays non-generic.
+ /// fake), type-erased so arbitrary model types do not enter this enum.
#[cfg(test)]
Test(Box<dyn DynStreamAgent>),
}
-impl ProviderAgent {
+impl<H: HttpClientExt + Clone + Default + std::fmt::Debug + 'static> ProviderAgent<H> {
/// Run the agentic loop and adapt rig's stream into the provider-agnostic
/// [`StreamPart`] stream consumed by DCS. The provider fan-out is internal.
#[allow(clippy::too_many_arguments)]
@@ -290,19 +295,19 @@ impl ProviderAgent {
/// Holds native Anthropic, Gemini, and OpenAI Responses clients plus a
/// registry of OpenAI-compatible Chat Completions clients keyed by provider
/// name. The built-in [`OPENAI_PROVIDER`] always uses Responses; register
-/// compatible providers with [`with_openai_provider`](Self::with_openai_provider).
+/// compatible providers with `with_openai_provider` on the metered router.
#[derive(Clone)]
-pub struct ModelRouter {
- anthropic: Arc<anthropic::Client>,
- openai: Arc<openai::Client>,
- gemini: Option<Arc<gemini::Client>>,
- openai_compatible: HashMap<String, Arc<openai::CompletionsClient>>,
+pub struct ModelRouter<H = ReqwestClient> {
+ anthropic: Arc<anthropic::Client<H>>,
+ openai: Arc<openai::Client<H>>,
+ gemini: Option<Arc<gemini::Client<H>>>,
+ openai_compatible: HashMap<String, Arc<openai::CompletionsClient<H>>>,
}
-impl ModelRouter {
+impl<H: HttpClientExt + Clone + 'static> ModelRouter<H> {
/// Build a router over native Anthropic and OpenAI Responses clients, with
/// no OpenAI-compatible Chat Completions providers registered yet.
- pub fn new(anthropic: anthropic::Client, openai: openai::Client) -> Self {
+ pub fn new(anthropic: anthropic::Client<H>, openai: openai::Client<H>) -> Self {
Self {
anthropic: Arc::new(anthropic),
openai: Arc::new(openai),
@@ -310,21 +315,39 @@ impl ModelRouter {
openai_compatible: HashMap::new(),
}
}
+}
+impl ModelRouter {
/// Build a router with the built-in providers from the environment.
///
/// Requires `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `CEREBRAS_API_KEY`,
/// `FIREWORK_API_KEY`, and `GOOGLE_GENERATIVE_AI_API_KEY`. Chain
- /// [`with_openai_provider`](Self::with_openai_provider) to add more.
- pub fn try_from_env() -> Result<Self, AgentError> {
+ /// `with_openai_provider` on the returned router to add more.
+ pub fn try_from_env() -> Result<ModelRouter<MeteredHttpClient>, AgentError> {
let env = ApiKeys::new()?;
+ // No executions may hide below the financial HTTP boundary.
+ let http = ReqwestClient::builder()
+ .retry(reqwest::retry::never())
+ .redirect(reqwest::redirect::Policy::none())
+ .build()
+ .map_err(|error| rig_core::http_client::Error::Instance(Box::new(error)))?;
let anthropic = anthropic::Client::builder()
.api_key(env.anthropic_api_key.to_string())
+ .http_client(MeteredHttpClient::new(
+ http.clone(),
+ ANTHROPIC_PROVIDER,
+ WireProtocol::Anthropic,
+ ))
.build()?;
// Default base URL is api.openai.com; OpenAI's GPT models use
// Responses API so reasoning models get max_output_tokens.
let openai = openai::Client::builder()
.api_key(env.openai_api_key.to_string())
+ .http_client(MeteredHttpClient::new(
+ http.clone(),
+ OPENAI_PROVIDER,
+ WireProtocol::Responses,
+ ))
.build()?;
// Cerebras and Fireworks speak the OpenAI Chat Completions API, so they
// ride the compatible-provider registry: a `<provider>/` segment routes
@@ -332,8 +355,13 @@ impl ModelRouter {
// so tool-call thought signatures survive the multi-step tool loop.
let gemini = gemini::Client::builder()
.api_key(env.google_generative_ai_api_key.to_string())
+ .http_client(MeteredHttpClient::new(
+ http.clone(),
+ GOOGLE_PROVIDER,
+ WireProtocol::Gemini,
+ ))
.build()?;
- Self::new(anthropic, openai)
+ ModelRouter::new(anthropic, openai)
.with_gemini_client(gemini)
.with_openai_provider(CEREBRAS_PROVIDER, CEREBRAS_BASE_URL, &env.cerebras_api_key)?
.with_openai_provider(
@@ -349,17 +377,19 @@ impl ModelRouter {
/// the same fully-populated instance, so a model id resolves identically
/// everywhere. Register additional OpenAI-compatible providers here as they
/// are added.
- pub(crate) fn shared() -> Result<&'static ModelRouter, AgentError> {
- static ROUTER: OnceLock<ModelRouter> = OnceLock::new();
+ pub(crate) fn shared() -> Result<&'static ModelRouter<MeteredHttpClient>, AgentError> {
+ static ROUTER: OnceLock<ModelRouter<MeteredHttpClient>> = OnceLock::new();
if let Some(router) = ROUTER.get() {
return Ok(router);
}
let router = Self::try_from_env()?;
Ok(ROUTER.get_or_init(|| router))
}
+}
+impl<H: HttpClientExt + Clone + 'static> ModelRouter<H> {
/// Bind the native Gemini GenerateContent client. Google ids route here.
- pub fn with_gemini_client(mut self, client: gemini::Client) -> Self {
+ pub fn with_gemini_client(mut self, client: gemini::Client<H>) -> Self {
self.gemini = Some(Arc::new(client));
self
}
@@ -369,13 +399,15 @@ impl ModelRouter {
pub fn with_openai_client(
mut self,
provider: impl Into<String>,
- client: openai::CompletionsClient,
+ client: openai::CompletionsClient<H>,
) -> Self {
self.openai_compatible
.insert(provider.into(), Arc::new(client));
self
}
+}
+impl ModelRouter<MeteredHttpClient> {
/// Register an OpenAI-compatible Chat Completions provider from a base URL
/// and key.
///
@@ -383,20 +415,33 @@ impl ModelRouter {
/// then reachable as `provider/<model-id>`. The extension point for the
/// open provider set (Cerebras is wired this way in [`try_from_env`]).
///
- /// [`try_from_env`]: Self::try_from_env
+ /// [`try_from_env`]: ModelRouter::try_from_env
pub fn with_openai_provider(
self,
provider: impl Into<String>,
base_url: &str,
api_key: &str,
) -> Result<Self, AgentError> {
+ let provider = provider.into();
+ let http = ReqwestClient::builder()
+ .retry(reqwest::retry::never())
+ .redirect(reqwest::redirect::Policy::none())
+ .build()
+ .map_err(|error| rig_core::http_client::Error::Instance(Box::new(error)))?;
let client = openai::CompletionsClient::builder()
.api_key(api_key)
.base_url(base_url)
+ .http_client(MeteredHttpClient::new(
+ http,
+ provider.clone(),
+ WireProtocol::ChatCompletions,
+ ))
.build()?;
Ok(self.with_openai_client(provider, client))
}
+}
+impl<H: HttpClientExt + Clone + Default + std::fmt::Debug + 'static> ModelRouter<H> {
/// Route + build the agent in one step, falling back to the default model on
/// an unroutable id. Tells `telemetry` which provider and model the session
/// actually runs on, so its spans report the routed model, not the
@@ -409,7 +454,7 @@ impl ModelRouter {
max_turns: usize,
max_tokens: u64,
telemetry: GenAiContext,
- ) -> ProviderAgent {
+ ) -> ProviderAgent<H> {
let routed = self.route_or_default(model);
telemetry.set_model(routed.provider(), routed.model_name());
routed.into_agent(handle, system_prompt, max_turns, max_tokens, &telemetry)
@@ -419,7 +464,7 @@ impl ModelRouter {
///
/// Returns [`AgentError::UnknownModel`] if no provider claims it (and
/// [`AgentError::MalformedModel`] if the id has no `provider/` segment).
- pub(crate) fn route<'a>(&self, model: &'a str) -> Result<RoutedModel<'a>, AgentError> {
+ pub(crate) fn route<'a>(&self, model: &'a str) -> Result<RoutedModel<'a, H>, AgentError> {
let parsed = Model::try_from(model)?;
if parsed.provider() == ANTHROPIC_PROVIDER {
@@ -453,7 +498,7 @@ impl ModelRouter {
}
/// Route `model`, falling back to the default model on an unroutable id.
- pub(crate) fn route_or_default<'a>(&self, model: &'a str) -> RoutedModel<'a> {
+ pub(crate) fn route_or_default<'a>(&self, model: &'a str) -> RoutedModel<'a, H> {
self.route(model).unwrap_or_else(|_| self.default_model())
}
@@ -462,7 +507,7 @@ impl ModelRouter {
/// Built via `From<PredefinedModel>` so the bound [`Model`] carries the
/// bare api id — `PredefinedModel`'s `Display` is the provider-qualified
/// routing id, which the Anthropic API rejects as a model name.
- fn default_model(&self) -> RoutedModel<'static> {
+ fn default_model(&self) -> RoutedModel<'static, H> {
RoutedModel::Anthropic(AnthropicModel::new(
PredefinedModel::Smart.into(),
self.anthropic.clone(),
@@ -640,8 +685,9 @@ where
concluded: false,
};
let driver_span = agent_span.clone();
+ let financial_context = MeteringContext::current();
let driver = tokio::spawn(
- async move {
+ MeteringContext::carry(financial_context, async move {
let mut liveness = StreamLiveness::new(agent_span.clone());
while let Some(item) = rig_stream.next().await {
@@ -667,7 +713,8 @@ where
&final_resp.output,
&usage,
);
- // Best-effort cost logging; never fails the stream.
+ // Aggregate analytics only. Financial evidence is
+ // persisted per HTTP attempt before SDK parsing.
recorder.record(usage_ctx.clone().into_event(
model.clone(),
usage.input_tokens,
@@ -711,7 +758,7 @@ where
// Dropping `rig_stream` (and with it the hook's sender) plus `driver_tx`
// here closes the channel, ending the consumer stream below.
drop(finish_run);
- }
+ })
// Entered into the agent span: the runtime opens its `chat` and
// `execute_tool` spans from inside this task, and they belong under
// the run, not at the root of a trace of their own.
@@ -740,7 +787,7 @@ where
}
/// Test-only type erasure so [`ProviderAgent`] can hold an arbitrary
-/// [`Agent<M>`] (e.g. a scripted fake model) without the enum becoming generic.
+/// [`Agent<M>`] (e.g. a scripted fake model) without adding a model type parameter.
/// Mirrors the production arms: it just drives [`drive_stream`].
#[cfg(test)]
pub(crate) trait DynStreamAgent: Send + Sync {
diff --git a/crates/agent_inmem/src/rig_engine.rs b/crates/agent_inmem/src/rig_engine.rs
index 9c6b65f39f..0a1393ffe3 100644
--- a/crates/agent_inmem/src/rig_engine.rs
+++ b/crates/agent_inmem/src/rig_engine.rs
@@ -104,12 +104,13 @@ impl TurnEngine for RigTurnEngine {
let (parts, receiver) = mpsc::channel(PART_BUFFER);
let db = self.db.clone();
let tool_context = self.tool_context.clone();
+ let metering = agent::MeteringContext::current();
tokio::spawn(
- async move {
+ agent::MeteringContext::carry(metering, async move {
if let Err(error) = drive_turn(db, tool_context, request, &parts).await {
let _ = parts.send(Err(error)).await;
}
- }
+ })
.in_current_span(),
);
receiver
diff --git a/crates/ai_billing/src/domain.rs b/crates/ai_billing/src/domain.rs
index 59562f9580..47610b00b2 100644
--- a/crates/ai_billing/src/domain.rs
+++ b/crates/ai_billing/src/domain.rs
@@ -1,8 +1,11 @@
//! Domain layer: plans and margin math, the settlement ledger, ports, and the
//! billing service.
+pub mod financial;
pub mod ledger;
pub mod models;
+pub mod period;
+pub mod policy;
pub mod ports;
pub mod service;
@@ -13,7 +16,7 @@ pub use models::{
OVERAGE_CHARGE_THRESHOLD_CENTS, OVERAGE_LIMIT_MAX_CENTS, OVERAGE_LIMIT_MIN_CENTS,
OpenPeriodStart, OverageChargeStatus, PayerScope, PeriodAllowance, PeriodLedger, PlanTier,
Result, SeatAllowance, SeatGeneration, SeatUsage, SubscriptionScope, TARGET_GROSS_MARGIN_BPS,
- UsageSnapshot, list_rate_cents,
+ UsagePolicy, UsageSnapshot, list_rate_cents,
};
pub use ports::{
BillingRepo, BillingService, CreditCheckoutRequest, EntitlementSource, OverageChargeRequest,
diff --git a/crates/ai_billing/src/domain/financial.rs b/crates/ai_billing/src/domain/financial.rs
new file mode 100644
index 0000000000..c8a0ec2211
--- /dev/null
+++ b/crates/ai_billing/src/domain/financial.rs
@@ -0,0 +1,228 @@
+//! Durable credit-first funding. The usage journal calls this owning-domain service;
+//! only its acknowledged authorization permits execution. Repository transactions run
+//! the pure policy transitions under the same payer lock as legacy settlement.
+
+use ai_usage::domain::financial::*;
+use ai_usage::domain::financial_service::validate_final_record;
+use ai_usage::domain::ports::{FinancialFuture, InvocationFunding};
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::models::{BillingPeriod, NON_BILLABLE_AI_FEATURES, UsagePolicy};
+use super::policy::{FundingAvailability, PolicyError, UsageAllocation};
+use super::ports::FundingRepo;
+
+#[cfg(test)]
+mod test;
+
+/// Verified subscription identity, not a product label, role or purchasable tier.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct FundingSubscription(String);
+
+impl FundingSubscription {
+ /// Validate a durable identity received from the subscription owner.
+ pub fn new(value: String) -> FinancialResult<Self> {
+ if value.is_empty() || value.chars().any(|c| c.is_whitespace() || c.is_control()) {
+ return Err(FinancialError::InvalidIdentifier);
+ }
+ Ok(Self(value))
+ }
+
+ /// Persistence representation.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+/// Immutable seat/payer/period policy binding. The period synchronization use case
+/// must verify eligibility and prospective effective dates before publishing it.
+/// No default, current role, or inferred calendar period can authorize V1 traffic.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct FundingPeriod {
+ /// Seat owns its allowance even after leaving/rejoining a team.
+ pub seat: MacroUserIdStr<'static>,
+ /// Payer owns shared credits and caps.
+ pub payer: MacroUserIdStr<'static>,
+ /// Verified subscription identity, retained historically.
+ pub subscription: FundingSubscription,
+ /// Verified half-open interval, never an extrapolated anchor.
+ pub period: BillingPeriod,
+ /// Policy selected prospectively for this particular seat.
+ pub policy: UsagePolicy,
+}
+
+impl FundingPeriod {
+ /// Reject ambiguous timestamp precision and invalid intervals.
+ pub fn validate(&self) -> FinancialResult<()> {
+ if self.period.start >= self.period.end
+ || !self
+ .period
+ .start
+ .timestamp_subsec_nanos()
+ .is_multiple_of(1000)
+ || !self
+ .period
+ .end
+ .timestamp_subsec_nanos()
+ .is_multiple_of(1000)
+ {
+ return Err(FinancialError::FundingDenied);
+ }
+ Ok(())
+ }
+}
+
+/// Exact reserved/spent credits outside the existing whole-cent ledger.
+#[derive(Debug, Clone, Copy)]
+pub struct CreditCommitments {
+ /// Fraction of consumption not yet debited as a whole cent.
+ pub remainder: CustomerMoney,
+ /// Outstanding exclusive prepaid holds.
+ pub held: CustomerMoney,
+ /// Earlier releases still reserved for eligible pending attempts.
+ pub release_pool: CustomerMoney,
+}
+
+impl CreditCommitments {
+ /// Exact credits available to new admissions; no rounded fraction is restored.
+ pub fn available(self, ledger_cents: i64) -> FinancialResult<CustomerMoney> {
+ let balance = CustomerMoney::from_cents(ledger_cents.max(0) as u64)?;
+ let committed = self
+ .remainder
+ .checked_add(self.held)?
+ .checked_add(self.release_pool)?;
+ Ok(CustomerMoney::from_units(
+ balance.units().saturating_sub(committed.units()),
+ ))
+ }
+
+ /// Whole cents legacy settlement may spend without touching fractional money,
+ /// pending holds, or releases owed to earlier admissions.
+ pub fn legacy_available_cents(self, ledger_cents: i64) -> FinancialResult<i64> {
+ i64::try_from(self.available(ledger_cents)?.split_cents().whole_cents)
+ .map_err(|_| FinancialError::ArithmeticOverflow)
+ }
+}
+
+/// Consume once, debiting only new whole cents and retaining the exact remainder.
+/// The debit, allocation, released holds and watermark must commit atomically.
+pub fn prepaid_debit(
+ remainder: CustomerMoney,
+ consumed: CustomerMoney,
+) -> FinancialResult<(i64, CustomerMoney)> {
+ let parts = remainder.checked_add(consumed)?.split_cents();
+ Ok((
+ i64::try_from(parts.whole_cents).map_err(|_| FinancialError::ArithmeticOverflow)?,
+ CustomerMoney::from_units(parts.subcent_units),
+ ))
+}
+
+/// Preserve shared cap semantics with legacy seats on the same payer/period.
+/// Round commitments up only for legacy's whole-cent admission, not customer billing.
+pub fn legacy_cap_remaining(limit_cents: i64, committed: CustomerMoney) -> i64 {
+ let parts = committed.split_cents();
+ let unavailable = parts.whole_cents + u64::from(parts.subcent_units != 0);
+ limit_cents
+ .saturating_sub(i64::try_from(unavailable).unwrap_or(i64::MAX))
+ .max(0)
+}
+
+/// Convert policy errors without granting any execution on failure.
+pub fn funding_error(error: PolicyError) -> FinancialError {
+ match error {
+ PolicyError::Arithmetic(error) => error,
+ _ => FinancialError::FundingDenied,
+ }
+}
+
+/// Owning-domain facade injected into `ai_usage::FinancialUsageService`.
+/// The journal pins intent before calling authorize and retries its durable handoff
+/// after finalize. Funding writes are idempotent on invocation ID, including a lost
+/// acknowledgement; no adapter imports another domain's outbound implementation.
+pub struct FundingService<R> {
+ repo: R,
+}
+
+impl<R: FundingRepo> FundingService<R> {
+ /// Composition roots construct the repository and inject it here.
+ pub fn new(repo: R) -> Self {
+ Self { repo }
+ }
+
+ /// Recorded policy at occurrence time; absence preserves the legacy path.
+ pub async fn period(
+ &self,
+ seat: MacroUserIdStr<'static>,
+ at: DateTime<Utc>,
+ ) -> FinancialResult<Option<FundingPeriod>> {
+ self.repo.period(seat, at).await
+ }
+
+ /// Publish only verified prospective facts from the period synchronization use case.
+ pub async fn record_period(&self, period: FundingPeriod) -> FinancialResult<()> {
+ period.validate()?;
+ self.repo.record_period(period).await
+ }
+
+ /// Exact immutable source allocation, or None while evidence/order is unresolved.
+ pub async fn allocation(&self, id: InvocationId) -> FinancialResult<Option<UsageAllocation>> {
+ self.repo.allocation(id).await
+ }
+
+ /// Restart-safe discovery of outstanding authorizations and blocked allocation work.
+ pub async fn pending(&self, query: PendingInvocations) -> FinancialResult<Vec<InvocationId>> {
+ self.repo.pending(query).await
+ }
+
+ /// Continue bounded reconciliation after a crash or a large completion backlog.
+ pub async fn reconcile(&self, payer: MacroUserIdStr<'static>) -> FinancialResult<()> {
+ self.repo.reconcile(payer).await
+ }
+}
+
+impl<R: FundingRepo> InvocationFunding for FundingService<R> {
+ fn authorize(
+ &self,
+ request: BeginInvocation,
+ rate: RateSnapshot,
+ ) -> FinancialFuture<'_, FundingAuthorization> {
+ Box::pin(async move {
+ rate.require_model(&request.model)?;
+ if NON_BILLABLE_AI_FEATURES.contains(&request.feature) {
+ return Err(FinancialError::FundingDenied);
+ }
+ rate.tokens.price(request.token_budget)?;
+ self.repo.authorize(request, rate).await
+ })
+ }
+
+ fn finalize(&self, record: InvocationRecord) -> FinancialFuture<'_, ()> {
+ Box::pin(async move {
+ validate_final_record(&record)?;
+ // This facade only admits V1 billable traffic. A later exclusion cannot
+ // release incurred charges or turn missing provider evidence into zero.
+ if matches!(record.state, InvocationState::Excluded { .. }) {
+ return Err(FinancialError::FundingDenied);
+ }
+ self.repo.finalize(record).await
+ })
+ }
+}
+
+/// Derive admission capacity from exact repository facts under the payer lock.
+/// The legacy charged amount already includes collectible/pending legacy invoices.
+pub fn funding_availability(
+ mut available: FundingAvailability,
+ ledger_cents: i64,
+ credits: CreditCommitments,
+ legacy_charged_cents: i64,
+) -> FinancialResult<FundingAvailability> {
+ available.prepaid_available = credits.available(ledger_cents)?;
+ available.postpaid_incurred =
+ available
+ .postpaid_incurred
+ .checked_add(CustomerMoney::from_cents(
+ legacy_charged_cents.max(0) as u64
+ )?)?;
+ Ok(available)
+}
diff --git a/crates/ai_billing/src/domain/financial/test.rs b/crates/ai_billing/src/domain/financial/test.rs
new file mode 100644
index 0000000000..6f116b9bcb
--- /dev/null
+++ b/crates/ai_billing/src/domain/financial/test.rs
@@ -0,0 +1,64 @@
+use super::*;
+
+fn money(units: u64) -> CustomerMoney {
+ CustomerMoney::from_units(units)
+}
+
+#[test]
+fn fractional_spend_and_holds_are_not_spendable_by_either_ledger() {
+ let cent = CustomerMoney::UNITS_PER_CENT;
+ let credits = CreditCommitments {
+ remainder: money(cent / 4),
+ held: money(cent),
+ release_pool: money(cent / 2),
+ };
+ assert_eq!(credits.available(2).unwrap(), money(cent / 4));
+ assert_eq!(credits.legacy_available_cents(2).unwrap(), 0);
+ assert_eq!(credits.available(1).unwrap(), money(0));
+}
+
+#[test]
+fn prepaid_debits_partition_without_rounding_or_double_debits() {
+ let cent = CustomerMoney::UNITS_PER_CENT;
+ let mut remainder = money(0);
+ let mut debited = 0;
+ for _ in 0..7 {
+ let (debit, next) = prepaid_debit(remainder, money(cent / 4)).unwrap();
+ debited += debit;
+ remainder = next;
+ }
+ assert_eq!(debited, 1);
+ assert_eq!(remainder, money(cent * 3 / 4));
+ assert_eq!(
+ prepaid_debit(money(0), money(cent * 7 / 4)).unwrap(),
+ (debited, remainder)
+ );
+}
+
+#[test]
+fn legacy_cap_reserves_any_fraction_without_rounding_customer_liability() {
+ let cent = CustomerMoney::UNITS_PER_CENT;
+ assert_eq!(legacy_cap_remaining(100, money(cent + 1)), 98);
+ assert_eq!(legacy_cap_remaining(1, money(cent + 1)), 0);
+}
+
+#[test]
+fn credit_overflow_fails_closed() {
+ assert!(prepaid_debit(money(1), money(u64::MAX)).is_err());
+ assert!(
+ CreditCommitments {
+ remainder: money(0),
+ held: money(0),
+ release_pool: money(0)
+ }
+ .available(i64::MAX)
+ .is_err()
+ );
+}
+
+#[test]
+fn subscription_identity_is_not_an_empty_or_whitespace_label() {
+ assert!(FundingSubscription::new(String::new()).is_err());
+ assert!(FundingSubscription::new("sub invalid".into()).is_err());
+ assert!(FundingSubscription::new("sub_verified".into()).is_ok());
+}
diff --git a/crates/ai_billing/src/domain/models.rs b/crates/ai_billing/src/domain/models.rs
index a9b76f8919..50becdd86a 100644
--- a/crates/ai_billing/src/domain/models.rs
+++ b/crates/ai_billing/src/domain/models.rs
@@ -10,7 +10,18 @@ use std::collections::HashSet;
use thiserror::Error;
use utoipa::ToSchema;
-/// Target gross margin on AI, in basis points. The list rate is provider cost
+/// Persisted usage-policy identity, independent of purchase availability or today's roles.
+/// A verified period activation selects this value; legacy records are never repriced.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum UsagePolicy {
+ /// Original 2.5x list-rate arithmetic and plan allowances.
+ Legacy,
+ /// Existing $40 offer: $20 public usage per seat, then public usage times 1.05.
+ PublicAllowanceV1,
+}
+
+/// Legacy target gross margin on AI, in basis points. The list rate is provider cost
/// divided by `(1 - margin)`; at 60% that is a 2.5x markup.
pub const TARGET_GROSS_MARGIN_BPS: i64 = 6_000;
@@ -25,7 +36,7 @@ pub const NON_BILLABLE_AI_FEATURES: [AiFeature; 4] = [
AiFeature::Dictation,
];
-/// Convert a provider cost in USD to Macro's list rate in whole cents,
+/// Legacy only: convert a provider cost in USD to Macro's list rate in whole cents,
/// rounding up so fractional cents never accrue in the customer's favour.
pub fn list_rate_cents(provider_cost_usd: f64) -> i64 {
if !provider_cost_usd.is_finite() || provider_cost_usd <= 0.0 {
@@ -87,7 +98,7 @@ impl PlanTier {
}
}
- /// AI usage included per seat per period, in list-rate cents. Equal to the
+ /// Legacy AI usage included per seat per period, in list-rate cents. Equal to the
/// plan price by construction: spending it all costs Macro
/// `price x (1 - margin)`, which is exactly the target margin.
pub const fn included_ai_cents_per_seat(self) -> i64 {
@@ -122,7 +133,7 @@ impl From<teams::domain::model::SeatPlan> for PlanTier {
}
/// A half-open `[start, end)` window that usage is metered against.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct BillingPeriod {
/// Inclusive start.
pub start: DateTime<Utc>,
diff --git a/crates/ai_billing/src/domain/period.rs b/crates/ai_billing/src/domain/period.rs
new file mode 100644
index 0000000000..6f7c3e4c0c
--- /dev/null
+++ b/crates/ai_billing/src/domain/period.rs
@@ -0,0 +1,423 @@
+//! Prospective usage-policy activation. Stripe transport and base subscription
+//! operations stay outside this use case; neither roles nor calendar anchors can
+//! authorize an allowance reset.
+
+use ai_usage::domain::financial::{FinancialError, FinancialResult};
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use serde::{Deserialize, Serialize};
+
+use super::models::{BillingPeriod, Result, UsagePolicy};
+
+#[cfg(test)]
+mod test;
+
+/// Validated provider billing identity. Domain code does not depend on a Stripe
+/// SDK version, and malformed identities cannot become durable activation facts.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(try_from = "String")]
+pub struct BillingIdentity(String);
+
+impl BillingIdentity {
+ /// Stable provider representation for persistence and owning-domain ports.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl TryFrom<String> for BillingIdentity {
+ type Error = FinancialError;
+
+ fn try_from(value: String) -> FinancialResult<Self> {
+ let Some((prefix, suffix)) = value.split_once('_') else {
+ return Err(FinancialError::InvalidIdentifier);
+ };
+ if !matches!(prefix, "evt" | "sub" | "cus" | "si" | "price" | "prod")
+ || suffix.is_empty()
+ || !suffix
+ .bytes()
+ .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
+ {
+ return Err(FinancialError::InvalidIdentifier);
+ }
+ Ok(Self(value))
+ }
+}
+
+impl std::str::FromStr for BillingIdentity {
+ type Err = FinancialError;
+ fn from_str(value: &str) -> FinancialResult<Self> {
+ value.to_owned().try_into()
+ }
+}
+
+impl std::fmt::Display for BillingIdentity {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ self.0.fmt(formatter)
+ }
+}
+
+/// Immutable rollout configuration, supplied only after producer/rollout gates pass.
+/// It is persisted with every observation so a restart cannot move the effective date.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct UsageRollout {
+ /// Prospective rollout instant. Never derive this from process startup time.
+ pub effective_at: DateTime<Utc>,
+ /// Explicit verified $40 price; not the purchasable catalog or a role mapping.
+ pub price_id: BillingIdentity,
+ /// Product owning that price.
+ pub product_id: BillingIdentity,
+}
+
+impl UsageRollout {
+ /// Reject malformed configuration before constructing the activation service.
+ pub fn validate(&self) -> FinancialResult<()> {
+ if !self.price_id.as_str().starts_with("price_")
+ || !self.product_id.as_str().starts_with("prod_")
+ || !self
+ .effective_at
+ .timestamp_subsec_nanos()
+ .is_multiple_of(1000)
+ {
+ return Err(FinancialError::InvalidIdentifier);
+ }
+ Ok(())
+ }
+}
+
+/// Why a verified Stripe period was observed.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub enum PeriodEvidence {
+ /// Explicit rollout inventory, freshly retrieved from the provider. This
+ /// capability is never inferred from an old webhook's delivery time.
+ RolloutBaseline,
+ /// Current subscription snapshot or ordinary update; may establish a baseline only.
+ Snapshot,
+ /// First paid period of a newly created subscription.
+ Initial,
+ /// Paid subscription-cycle invoice whose line matches this item and exact interval.
+ Renewal,
+}
+
+/// Verified subscription status relevant to prospective policy activation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub enum SubscriptionActivity {
+ /// Eligible to activate on a matching paid period.
+ Active,
+ /// May establish the rollout baseline, but never authorizes paid usage policy.
+ Trialing,
+ /// Canceled, paused, unpaid, unknown, or otherwise inactive.
+ Inactive,
+}
+
+/// Facts about one subscription item, verified by the payment-provider adapter.
+/// Discounts are deliberately absent: qualification uses the undiscounted price,
+/// never the amount paid on an invoice.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SubscriptionPeriod {
+ /// Signed event or explicit rollout-inventory identity, retained for replay/audit.
+ pub event_id: BillingIdentity,
+ /// Event occurrence time (or fresh inventory observation time), never the
+ /// delivery time of a historical webhook.
+ pub event_at: DateTime<Utc>,
+ /// Durable subscription identity.
+ pub subscription_id: BillingIdentity,
+ /// Subscription creation time distinguishes existing from new subscribers.
+ pub subscription_created_at: DateTime<Utc>,
+ /// Customer identity checked against the owning domain's stored binding.
+ pub customer_id: BillingIdentity,
+ /// Team metadata, checked against the owning team's subscription binding.
+ pub team_id: Option<macro_uuid::Uuid>,
+ /// Number of seats on this item.
+ pub quantity: u64,
+ /// Number of items in the complete subscription (personal subscriptions need one).
+ pub item_count: usize,
+ /// Subscription item identity, not its position in the payload.
+ pub item_id: BillingIdentity,
+ /// Immutable price identity.
+ pub price_id: BillingIdentity,
+ /// Product owning the price.
+ pub product_id: BillingIdentity,
+ /// Undiscounted price in cents.
+ pub unit_amount: Option<i64>,
+ /// Price currency.
+ pub currency: String,
+ /// True only for a recurring price with interval=month, interval_count=1.
+ pub monthly: bool,
+ /// Trials may establish a baseline; only active paid periods can activate.
+ pub activity: SubscriptionActivity,
+ /// Explicit provider interval, never a calendar fallback or extrapolated anchor.
+ pub period: BillingPeriod,
+ /// Verified cause of this observation.
+ pub evidence: PeriodEvidence,
+}
+
+/// A seat/customer binding resolved through the owning identity/subscription port.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SeatPeriodObservation {
+ /// Seat owns its allowance even after departure or rejoin.
+ pub seat: MacroUserIdStr<'static>,
+ /// Frozen payer, never recomputed when historical usage completes.
+ pub payer: MacroUserIdStr<'static>,
+ /// Verified subscription and item facts.
+ pub subscription: SubscriptionPeriod,
+}
+
+/// Durable transition state for a payer/subscription/item. Seats joining an
+/// already verified period share its renewal proof, but never share allowance.
+/// Financial allocations
+/// remain in their original periods and are never changed by these transitions.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct EligibilityState {
+ /// End of the explicitly observed period spanning rollout for existing users.
+ pub baseline_end: Option<DateTime<Utc>>,
+ /// Highest accepted start, rejecting out-of-order regressions.
+ pub latest_start: Option<DateTime<Utc>>,
+ /// End paired with the latest start; a same-period seat join must match both.
+ pub latest_end: Option<DateTime<Utc>>,
+ /// First effective V1 period, immutable once selected.
+ pub effective_start: Option<DateTime<Utc>>,
+}
+
+/// Activation exceptions are durable and inspectable, not guessed monthly periods.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub enum ActivationException {
+ /// Missing or unsupported price/product/recurrence/status facts.
+ Ineligible,
+ /// Event predates rollout or does not prove the supplied interval has begun.
+ Delayed,
+ /// Period regresses or overlaps a previously accepted period.
+ Stale,
+ /// Existing subscriber lacks an observed rollout baseline.
+ MissingBaseline,
+ /// An ordinary update cannot authorize a new-policy period.
+ UnverifiedRenewal,
+ /// Historical seat or payer attribution conflicts with this observation.
+ AmbiguousBinding,
+ /// Legacy admission/financial activity already exists in the target period.
+ LegacyPeriodInUse,
+}
+
+/// Pure transition result persisted atomically with any immutable usage period.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub enum PeriodDecision {
+ /// Preserve legacy accounting for the current rollout period.
+ Legacy,
+ /// Publish exactly one new immutable usage period.
+ Activate,
+ /// No policy change; retain the reason for operational review.
+ Exception(ActivationException),
+}
+
+impl PeriodDecision {
+ /// A delayed renewal must not convert an already-open legacy period. The
+ /// repository supplies this fact under the shared payer serialization lock.
+ pub fn preserve_legacy(self, legacy_in_use: bool) -> Self {
+ if self == Self::Activate && legacy_in_use {
+ Self::Exception(ActivationException::LegacyPeriodInUse)
+ } else {
+ self
+ }
+ }
+
+ /// Policy to publish; exceptions never authorize traffic.
+ pub fn policy(&self) -> Option<UsagePolicy> {
+ match self {
+ Self::Legacy => Some(UsagePolicy::Legacy),
+ Self::Activate => Some(UsagePolicy::PublicAllowanceV1),
+ Self::Exception(_) => None,
+ }
+ }
+}
+
+/// Decide from immutable provider facts under the repository's seat/payer locks.
+/// No current credit balance, opt-in, cap, role, or invoice total participates.
+pub fn transition(
+ rollout: &UsageRollout,
+ facts: &SubscriptionPeriod,
+ state: &mut EligibilityState,
+) -> PeriodDecision {
+ use ActivationException as Exception;
+ let period = facts.period;
+ if facts.price_id != rollout.price_id
+ || facts.product_id != rollout.product_id
+ || facts.unit_amount != Some(4_000)
+ || facts.currency != "usd"
+ || !facts.monthly
+ || facts.activity == SubscriptionActivity::Inactive
+ || facts.quantity == 0
+ || facts.item_count == 0
+ || facts.subscription_created_at > period.start
+ || period.start >= period.end
+ || [
+ (facts.event_id.as_str(), "evt_"),
+ (facts.subscription_id.as_str(), "sub_"),
+ (facts.customer_id.as_str(), "cus_"),
+ (facts.item_id.as_str(), "si_"),
+ (rollout.price_id.as_str(), "price_"),
+ (rollout.product_id.as_str(), "prod_"),
+ ]
+ .iter()
+ .any(|(id, prefix)| !id.starts_with(prefix))
+ {
+ return PeriodDecision::Exception(Exception::Ineligible);
+ }
+ let inventory = facts.evidence == PeriodEvidence::RolloutBaseline
+ && period.start <= facts.event_at
+ && facts.event_at < period.end
+ && facts.event_at <= rollout.effective_at;
+ if (facts.event_at < rollout.effective_at && !inventory)
+ || facts.event_at < period.start
+ || facts.event_at >= period.end
+ {
+ return PeriodDecision::Exception(Exception::Delayed);
+ }
+ if state.latest_start.is_some_and(|start| period.start < start) {
+ return PeriodDecision::Exception(Exception::Stale);
+ }
+ if period.start < rollout.effective_at && rollout.effective_at <= period.end {
+ if state.baseline_end.is_some_and(|end| end != period.end) {
+ return PeriodDecision::Exception(Exception::Stale);
+ }
+ state.baseline_end = Some(period.end);
+ state.latest_start = Some(period.start);
+ state.latest_end = Some(period.end);
+ return PeriodDecision::Legacy;
+ }
+ if facts.activity != SubscriptionActivity::Active {
+ return PeriodDecision::Exception(Exception::Ineligible);
+ }
+ // A new/rejoining seat can use a renewal already verified for this item.
+ // This is not permission to roll the item forward on an ordinary update.
+ if state.effective_start.is_some()
+ && state.latest_start == Some(period.start)
+ && state.latest_end == Some(period.end)
+ {
+ return PeriodDecision::Activate;
+ }
+ if facts.subscription_created_at < rollout.effective_at {
+ let Some(end) = state.baseline_end else {
+ return PeriodDecision::Exception(Exception::MissingBaseline);
+ };
+ if period.start < end {
+ return PeriodDecision::Exception(Exception::Stale);
+ }
+ if facts.evidence != PeriodEvidence::Renewal {
+ return PeriodDecision::Exception(Exception::UnverifiedRenewal);
+ }
+ } else if period.start < rollout.effective_at
+ || !matches!(
+ facts.evidence,
+ PeriodEvidence::Initial | PeriodEvidence::Renewal
+ )
+ {
+ return PeriodDecision::Exception(Exception::UnverifiedRenewal);
+ }
+ state.latest_start = Some(period.start);
+ state.latest_end = Some(period.end);
+ state.effective_start.get_or_insert(period.start);
+ PeriodDecision::Activate
+}
+
+/// Owning-domain identity resolution. None means quarantine, never email inference.
+pub trait PeriodBindingSource: Send + Sync + 'static {
+ /// Verify customer/subscription/team identity and resolve stored $40-seat
+ /// candidates. The domain transition must still verify the item's exact
+ /// price/product/recurrence; these candidates alone never prove eligibility.
+ fn seats(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ observation: &SubscriptionPeriod,
+ ) -> impl Future<Output = Result<Option<Vec<MacroUserIdStr<'static>>>>> + Send;
+}
+
+/// Atomic persistence of eligibility, exceptions, and immutable period publication.
+pub trait PeriodRepo: Send + Sync + 'static {
+ /// Apply the domain transition under seat/payer serialization. An unverified
+ /// binding is retained as an exception and must not create a usage period.
+ fn observe(
+ &self,
+ rollout: &UsageRollout,
+ observation: SeatPeriodObservation,
+ verified_binding: bool,
+ ) -> impl Future<Output = Result<PeriodDecision>> + Send;
+}
+
+/// Renewal use case over owning-domain identity and persistence ports. It has no
+/// payment gateway and therefore cannot write a Stripe price or subscription.
+pub struct PeriodService<E, R> {
+ bindings: E,
+ repo: R,
+ rollout: UsageRollout,
+}
+
+impl<E, R> PeriodService<E, R> {
+ /// Construct at the composition root; invalid configuration fails startup.
+ pub fn new(bindings: E, repo: R, rollout: UsageRollout) -> FinancialResult<Self> {
+ rollout.validate()?;
+ Ok(Self {
+ bindings,
+ repo,
+ rollout,
+ })
+ }
+}
+
+impl<E: PeriodBindingSource, R: PeriodRepo> PeriodService<E, R> {
+ /// Seed existing subscribers before rollout from freshly retrieved provider
+ /// facts, not historical/delayed webhooks. Missing inventory at renewal remains
+ /// a durable exception; it is never repaired by extrapolating an older anchor.
+ pub async fn record_rollout_baseline(
+ &self,
+ payer: MacroUserIdStr<'static>,
+ mut observation: SubscriptionPeriod,
+ ) -> Result<()> {
+ observation.evidence = PeriodEvidence::RolloutBaseline;
+ self.sync(payer, observation).await
+ }
+}
+
+impl<E: PeriodBindingSource, R: PeriodRepo> PeriodSync for PeriodService<E, R> {
+ fn sync<'a>(
+ &'a self,
+ payer: MacroUserIdStr<'static>,
+ observation: SubscriptionPeriod,
+ ) -> std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
+ Box::pin(async move {
+ let seats = self.bindings.seats(&payer, &observation).await?;
+ let verified = seats.as_ref().is_some_and(|seats| !seats.is_empty());
+ let seats = seats
+ .filter(|seats| !seats.is_empty())
+ .unwrap_or_else(|| vec![payer.clone()]);
+ for seat in seats {
+ let decision = self
+ .repo
+ .observe(
+ &self.rollout,
+ SeatPeriodObservation {
+ seat,
+ payer: payer.clone(),
+ subscription: observation.clone(),
+ },
+ verified,
+ )
+ .await?;
+ if let PeriodDecision::Exception(reason) = decision {
+ tracing::warn!(?reason, subscription_id = %observation.subscription_id, "usage policy activation quarantined");
+ }
+ }
+ Ok(())
+ })
+ }
+}
+
+/// Inbound capability installed by the composition root only after rollout gates.
+/// Implementations resolve identities before publishing verified seat observations.
+pub trait PeriodSync: Send + Sync + 'static {
+ /// Synchronize a verified subscription item without any base billing writes.
+ fn sync<'a>(
+ &'a self,
+ payer: MacroUserIdStr<'static>,
+ observation: SubscriptionPeriod,
+ ) -> std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
+}
diff --git a/crates/ai_billing/src/domain/period/test.rs b/crates/ai_billing/src/domain/period/test.rs
new file mode 100644
index 0000000000..9edcf4031a
--- /dev/null
+++ b/crates/ai_billing/src/domain/period/test.rs
@@ -0,0 +1,275 @@
+use super::*;
+use chrono::Duration;
+
+#[test]
+fn billing_identities_and_rollout_configuration_are_validated() {
+ for id in [
+ "",
+ "price_",
+ "price_with space",
+ "unexpected_id",
+ "sub_bad\n",
+ ] {
+ assert!(id.parse::<BillingIdentity>().is_err());
+ assert!(serde_json::from_value::<BillingIdentity>(serde_json::json!(id)).is_err());
+ }
+ let mut invalid = rollout();
+ invalid.price_id = "prod_not_a_price".parse().unwrap();
+ assert!(invalid.validate().is_err());
+}
+
+struct Bindings(Option<Vec<MacroUserIdStr<'static>>>);
+
+impl PeriodBindingSource for Bindings {
+ async fn seats(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ _: &SubscriptionPeriod,
+ ) -> Result<Option<Vec<MacroUserIdStr<'static>>>> {
+ Ok(self.0.clone())
+ }
+}
+
+#[derive(Clone, Default)]
+struct Observations(std::sync::Arc<std::sync::Mutex<Vec<(SeatPeriodObservation, bool)>>>);
+
+impl PeriodRepo for Observations {
+ async fn observe(
+ &self,
+ _: &UsageRollout,
+ observation: SeatPeriodObservation,
+ verified: bool,
+ ) -> Result<PeriodDecision> {
+ self.0.lock().unwrap().push((observation, verified));
+ Ok(PeriodDecision::Exception(
+ ActivationException::AmbiguousBinding,
+ ))
+ }
+}
+
+#[tokio::test]
+async fn unresolved_bindings_are_quarantined_without_inventing_seats() {
+ let payer = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();
+ for bindings in [None, Some(vec![])] {
+ let repo = Observations::default();
+ let service = PeriodService::new(Bindings(bindings), repo.clone(), rollout()).unwrap();
+ service.sync(payer.clone(), baseline()).await.unwrap();
+ let observations = repo.0.lock().unwrap();
+ assert_eq!(observations.len(), 1);
+ assert!(!observations[0].1);
+ assert_eq!(observations[0].0.payer, payer);
+ }
+ let seat = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();
+ let repo = Observations::default();
+ let service =
+ PeriodService::new(Bindings(Some(vec![seat.clone()])), repo.clone(), rollout()).unwrap();
+ service.sync(payer.clone(), baseline()).await.unwrap();
+ let observations = repo.0.lock().unwrap();
+ assert!(observations[0].1);
+ assert_eq!(observations[0].0.seat, seat);
+ assert_eq!(observations[0].0.payer, payer);
+}
+
+fn rollout() -> UsageRollout {
+ UsageRollout {
+ effective_at: DateTime::from_timestamp(1_800_000_000, 0).unwrap(),
+ price_id: "price_40".parse().unwrap(),
+ product_id: "prod_40".parse().unwrap(),
+ }
+}
+
+fn baseline() -> SubscriptionPeriod {
+ let at = rollout().effective_at;
+ SubscriptionPeriod {
+ event_id: "evt_baseline".parse().unwrap(),
+ event_at: at,
+ subscription_id: "sub_existing".parse().unwrap(),
+ subscription_created_at: at - Duration::days(90),
+ customer_id: "cus_payer".parse().unwrap(),
+ team_id: None,
+ quantity: 1,
+ item_count: 1,
+ item_id: "si_seat".parse().unwrap(),
+ price_id: rollout().price_id,
+ product_id: rollout().product_id,
+ unit_amount: Some(4_000),
+ currency: "usd".into(),
+ monthly: true,
+ activity: SubscriptionActivity::Active,
+ period: BillingPeriod {
+ start: at - Duration::days(10),
+ end: at + Duration::days(20),
+ },
+ evidence: PeriodEvidence::Snapshot,
+ }
+}
+
+fn renewal() -> SubscriptionPeriod {
+ let mut facts = baseline();
+ facts.event_id = "evt_renewal".parse().unwrap();
+ facts.period.start = facts.period.end;
+ facts.period.end += Duration::days(31);
+ facts.event_at = facts.period.start;
+ facts.evidence = PeriodEvidence::Renewal;
+ facts
+}
+
+#[test]
+fn existing_subscription_waits_for_verified_renewal() {
+ let mut state = EligibilityState::default();
+ assert_eq!(
+ transition(&rollout(), &baseline(), &mut state),
+ PeriodDecision::Legacy
+ );
+ let saved = state.clone();
+ let mut ordinary = renewal();
+ ordinary.evidence = PeriodEvidence::Snapshot;
+ assert_eq!(
+ transition(&rollout(), &ordinary, &mut state),
+ PeriodDecision::Exception(ActivationException::UnverifiedRenewal)
+ );
+ assert_eq!(state, saved);
+ assert_eq!(
+ transition(&rollout(), &renewal(), &mut state),
+ PeriodDecision::Activate
+ );
+ let activated = state.clone();
+ assert_eq!(
+ transition(&rollout(), &renewal(), &mut state),
+ PeriodDecision::Activate
+ );
+ assert_eq!(state, activated);
+ assert_eq!(
+ transition(&rollout(), &baseline(), &mut state),
+ PeriodDecision::Exception(ActivationException::Stale)
+ );
+ assert_eq!(state, activated);
+}
+
+#[test]
+fn delayed_pre_rollout_events_cannot_establish_a_baseline() {
+ let mut facts = baseline();
+ facts.event_at -= Duration::seconds(1);
+ let mut state = EligibilityState::default();
+ assert_eq!(
+ transition(&rollout(), &facts, &mut state),
+ PeriodDecision::Exception(ActivationException::Delayed)
+ );
+ assert_eq!(state, EligibilityState::default());
+ assert_eq!(
+ transition(&rollout(), &renewal(), &mut state),
+ PeriodDecision::Exception(ActivationException::MissingBaseline)
+ );
+}
+
+#[test]
+fn new_subscriptions_use_first_verified_period_not_an_update() {
+ let mut facts = renewal();
+ facts.subscription_created_at = facts.period.start;
+ facts.evidence = PeriodEvidence::Initial;
+ let mut state = EligibilityState::default();
+ assert_eq!(
+ transition(&rollout(), &facts, &mut state),
+ PeriodDecision::Activate
+ );
+ assert_eq!(state.effective_start, Some(facts.period.start));
+}
+
+#[test]
+fn role_only_unknown_custom_and_canceled_subscriptions_are_ineligible() {
+ let mut cases = vec![baseline(); 7];
+ cases[0].price_id = "price_custom".parse().unwrap();
+ cases[1].product_id = "prod_other".parse().unwrap();
+ cases[2].monthly = false;
+ cases[3].unit_amount = None;
+ cases[4].activity = SubscriptionActivity::Inactive;
+ cases[5].unit_amount = Some(20_000);
+ cases[6].currency = "eur".into();
+ for facts in cases {
+ let mut state = EligibilityState::default();
+ assert_eq!(
+ transition(&rollout(), &facts, &mut state),
+ PeriodDecision::Exception(ActivationException::Ineligible)
+ );
+ assert_eq!(state, EligibilityState::default());
+ }
+}
+
+#[test]
+fn explicit_rollout_inventory_can_seed_the_next_renewal_before_launch() {
+ let mut facts = baseline();
+ facts.event_at -= Duration::days(1);
+ facts.evidence = PeriodEvidence::RolloutBaseline;
+ let mut state = EligibilityState::default();
+ assert_eq!(
+ transition(&rollout(), &facts, &mut state),
+ PeriodDecision::Legacy
+ );
+ assert_eq!(
+ transition(&rollout(), &renewal(), &mut state),
+ PeriodDecision::Activate
+ );
+}
+
+#[test]
+fn trial_promotions_preserve_the_baseline_until_the_first_paid_renewal() {
+ let mut facts = baseline();
+ facts.activity = SubscriptionActivity::Trialing;
+ let mut state = EligibilityState::default();
+ assert_eq!(
+ transition(&rollout(), &facts, &mut state),
+ PeriodDecision::Legacy
+ );
+ let mut trial = renewal();
+ trial.activity = SubscriptionActivity::Trialing;
+ assert_eq!(
+ transition(&rollout(), &trial, &mut state),
+ PeriodDecision::Exception(ActivationException::Ineligible)
+ );
+ assert_eq!(
+ transition(&rollout(), &renewal(), &mut state),
+ PeriodDecision::Activate
+ );
+}
+
+#[test]
+fn legacy_use_prevents_retroactive_period_conversion() {
+ assert_eq!(
+ PeriodDecision::Activate.preserve_legacy(true),
+ PeriodDecision::Exception(ActivationException::LegacyPeriodInUse)
+ );
+ assert_eq!(
+ PeriodDecision::Legacy.preserve_legacy(true),
+ PeriodDecision::Legacy
+ );
+ assert_eq!(
+ PeriodDecision::Activate.preserve_legacy(false),
+ PeriodDecision::Activate
+ );
+}
+
+#[test]
+fn event_outside_its_claimed_period_cannot_activate() {
+ let mut facts = renewal();
+ facts.subscription_created_at = facts.period.start;
+ facts.event_at = facts.period.end;
+ assert_eq!(
+ transition(&rollout(), &facts, &mut EligibilityState::default()),
+ PeriodDecision::Exception(ActivationException::Delayed)
+ );
+}
+
+#[test]
+fn cancellation_preserves_effective_policy_and_baseline() {
+ let mut state = EligibilityState::default();
+ transition(&rollout(), &baseline(), &mut state);
+ transition(&rollout(), &renewal(), &mut state);
+ let saved = state.clone();
+ let mut canceled = renewal();
+ canceled.activity = SubscriptionActivity::Inactive;
+ assert_eq!(
+ transition(&rollout(), &canceled, &mut state),
+ PeriodDecision::Exception(ActivationException::Ineligible)
+ );
+ assert_eq!(saved, state);
+}
diff --git a/crates/ai_billing/src/domain/policy.rs b/crates/ai_billing/src/domain/policy.rs
new file mode 100644
index 0000000000..cc322e3f4d
--- /dev/null
+++ b/crates/ai_billing/src/domain/policy.rs
@@ -0,0 +1,719 @@
+//! Prospective public-rate policy; legacy arithmetic stays in `models` and `ledger`.
+//!
+//! All amounts remain exact through allocation. Included usage is per seat, not pooled;
+//! credits and postpaid caps are payer-wide. Repositories must serialize admission and
+//! allocation with legacy settlement and credit purchases under the same payer lock.
+//! Reconcile released credits with eligible pending reservations in sequence before
+//! making any remainder available to new admissions; a newer hold must not steal a
+//! predecessor's eligible release pool. Keep release provenance until reconciliation.
+//! Allocate in admission sequence, never completion order. Unresolved evidence blocks
+//! the watermark; only proved non-execution or measured usage can release a hold.
+//!
+//! Holds constrain admission, not final pricing. Final pricing uses only actual earlier
+//! seat usage. Earlier released credits can replace provisional postpaid holds, but
+//! only within the credits and total funding budget captured at admission. Later
+//! purchases or opt-in changes cannot re-fund history. Unavoidable unfunded excess is
+//! Macro-absorbed, not debt. This module does not activate policy or change subscriptions.
+
+use ai_usage::AiFeature;
+use ai_usage::domain::financial::{
+ CentParts, CustomerMoney, FinancialError, FundingAuthorizationId, InvocationId, PublicUsage,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use thiserror::Error;
+
+use super::models::{
+ BillingPeriod, BillingSettings, Entitlement, MIN_STRIPE_CHARGE_CENTS, NON_BILLABLE_AI_FEATURES,
+ OVERAGE_CHARGE_THRESHOLD_CENTS, PlanTier, UsagePolicy,
+};
+
+#[cfg(test)]
+mod test;
+
+const ZERO_PUBLIC: PublicUsage = PublicUsage::from_units(0);
+const ZERO_MONEY: CustomerMoney = CustomerMoney::from_units(0);
+const PUBLIC_UNITS_PER_CENT: u64 = CustomerMoney::UNITS_PER_CENT / 100;
+const EXTRA_RATE_NUMERATOR: u64 = 105;
+const EXTRA_RATE_DENOMINATOR: u64 = 100;
+
+/// Non-rolling $20 public-provider-price allowance for each activated seat and period.
+pub const INCLUDED_PUBLIC_USAGE: PublicUsage =
+ PublicUsage::from_units(2_000 * PUBLIC_UNITS_PER_CENT);
+
+/// Accounting path after a trusted caller resolves the recorded policy and entitlement.
+/// This is not eligibility detection: a Premium role alone must never activate V1.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AccountingRoute {
+ /// Preserve legacy arithmetic and settlement exclusively.
+ Legacy,
+ /// Use this module, never also legacy settlement.
+ PublicAllowanceV1,
+ /// Preserve the existing feature exemption, while retaining provider analytics.
+ ExemptFeature,
+ /// Free/enterprise behavior stays outside this policy's customer ledger.
+ Unmetered,
+}
+
+/// Preserve existing exclusions without inferring policy eligibility from a plan catalog.
+pub fn accounting_route(
+ policy: UsagePolicy,
+ feature: AiFeature,
+ entitlement: &Entitlement,
+) -> AccountingRoute {
+ if NON_BILLABLE_AI_FEATURES.contains(&feature) {
+ return AccountingRoute::ExemptFeature;
+ }
+ if entitlement.unlimited || entitlement.tier == PlanTier::Free {
+ return AccountingRoute::Unmetered;
+ }
+ match policy {
+ UsagePolicy::Legacy => AccountingRoute::Legacy,
+ UsagePolicy::PublicAllowanceV1 => AccountingRoute::PublicAllowanceV1,
+ }
+}
+
+/// Pricing is independent of which source funds the usage.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PricingCategory {
+ /// First $20 public usage: zero additional customer money, no markup.
+ Included,
+ /// Beyond $20: public usage multiplied by exactly 1.05 (not divided by 0.95).
+ Extra,
+}
+
+/// Actual consumption source, never inferred just from an enabled toggle.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum FundingSource {
+ /// Per-seat public-rate allowance.
+ Included,
+ /// Previously purchased customer money, dollar for dollar after markup.
+ Prepaid,
+ /// Explicitly authorized customer liability, regardless of invoice state.
+ Postpaid,
+ /// Unfunded in-flight excess; never collectible from the customer.
+ MacroAbsorbed,
+}
+
+/// An exact money split. A source boundary can fall inside one public picodollar,
+/// so public usage is retained by pricing category, not divided/rounded by source.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct FundingPortion {
+ /// Who funded this portion.
+ pub source: FundingSource,
+ /// Extra-price customer money; included portions always have zero money.
+ /// For Macro-absorbed portions this is a valuation, not customer liability.
+ pub amount: CustomerMoney,
+}
+
+impl FundingPortion {
+ /// Pricing category is not affected by postpaid opt-in or collection status.
+ pub fn category(self) -> PricingCategory {
+ match self.source {
+ FundingSource::Included => PricingCategory::Included,
+ FundingSource::Prepaid | FundingSource::Postpaid | FundingSource::MacroAbsorbed => {
+ PricingCategory::Extra
+ }
+ }
+ }
+}
+
+/// Monotonic revision of the payer's funding settings, captured at admission.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct AuthorizationRevision(u64);
+
+impl AuthorizationRevision {
+ /// Rehydrate a persisted settings revision (zero may represent initial defaults).
+ pub const fn from_raw(value: u64) -> Self {
+ Self(value)
+ }
+
+ /// Persistence representation.
+ pub const fn raw(self) -> u64 {
+ self.0
+ }
+}
+
+/// Opt-in state is separate from consumption and collection.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PostpaidAuthorization {
+ /// No authorization to create postpaid liability.
+ Disabled,
+ /// A failed collection prevents new postpaid authorization, not prepaid usage.
+ Suspended,
+ /// Explicit opt-in with a shared per-period postpaid-only cap.
+ Enabled {
+ /// Customer-money cap; prepaid consumption does not count toward it.
+ limit: CustomerMoney,
+ },
+}
+
+impl PostpaidAuthorization {
+ /// Capture existing enable/cap/suspension semantics without changing settings.
+ pub fn from_settings(settings: &BillingSettings) -> Result<Self, PolicyError> {
+ if !settings.overage_enabled {
+ return Ok(Self::Disabled);
+ }
+ if settings.overage_suspended_at.is_some() {
+ return Ok(Self::Suspended);
+ }
+ if settings.overage_limit_cents <= 0 {
+ return Ok(Self::Disabled);
+ }
+ Ok(Self::Enabled {
+ limit: CustomerMoney::from_cents(settings.overage_limit_cents as u64)?,
+ })
+ }
+}
+
+/// Immutable admission facts. Only trusted services may construct/persist these;
+/// adapters must bind policy, payer and seat to the verified period before admission.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct AuthorizationSnapshot {
+ /// Stable authorization identity for journal handoff and replay.
+ pub id: FundingAuthorizationId,
+ /// Exactly one actual provider attempt, not a logical multi-attempt run.
+ pub invocation_id: InvocationId,
+ /// Account owning shared credits and postpaid cap.
+ pub payer: MacroUserIdStr<'static>,
+ /// Seat whose own included allowance is consumed.
+ pub seat: MacroUserIdStr<'static>,
+ /// Frozen verified period; do not derive from current time at finalization.
+ pub period: BillingPeriod,
+ /// Policy selected prospectively for this seat/period.
+ pub policy: UsagePolicy,
+ /// Settings version at admission, not settlement.
+ pub settings_revision: AuthorizationRevision,
+ /// Frozen opt-in, suspension and cap decision.
+ pub postpaid: PostpaidAuthorization,
+}
+
+/// Payer-wide admission order. Persist the next sequence under the payer lock and
+/// advance the allocation watermark only over allocated/proved-unexecuted attempts.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub struct AllocationSequence(u64);
+
+impl AllocationSequence {
+ /// Rehydrate a persisted sequence; zero is the first admission.
+ pub const fn from_raw(value: u64) -> Self {
+ Self(value)
+ }
+
+ /// Persistence representation.
+ pub const fn raw(self) -> u64 {
+ self.0
+ }
+
+ /// Checked successor for admission and allocation watermarks.
+ pub fn next(self) -> Result<Self, PolicyError> {
+ self.0
+ .checked_add(1)
+ .map(Self)
+ .ok_or(PolicyError::SequenceOverflow)
+ }
+}
+
+/// Exact capacity observed under the payer lock before creating another reservation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct FundingAvailability {
+ /// Actual allocated public usage for this seat/period, never other seats' usage.
+ pub seat_public_used: PublicUsage,
+ /// Outstanding included holds for this seat/period only.
+ pub seat_public_held: PublicUsage,
+ /// Shared credits net of exact consumption, all outstanding holds and release
+ /// pools still owed to earlier pending reservations. Do not restore fractional
+ /// spent money from a rounded whole-cent ledger balance.
+ pub prepaid_available: CustomerMoney,
+ /// Prepaid held by earlier admissions. If released, these already-purchased
+ /// credits can replace this attempt's provisional postpaid funding at allocation.
+ pub prepaid_held: CustomerMoney,
+ /// All incurred postpaid in this payer/period, including uncollected and paid.
+ pub postpaid_incurred: CustomerMoney,
+ /// All outstanding postpaid holds sharing this payer/period cap.
+ pub postpaid_held: CustomerMoney,
+}
+
+/// Provisional budgets, not pricing or final funding classifications.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct FundingHolds {
+ /// Public allowance provisionally held for this attempt.
+ pub included_public: PublicUsage,
+ /// Exact prepaid money held exclusively for this attempt.
+ pub prepaid: CustomerMoney,
+ /// Exact, explicitly authorized postpaid budget held against the cap.
+ pub postpaid: CustomerMoney,
+}
+
+/// Reservation lifecycle, separate from usage pricing and collection.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ReservationState {
+ /// Awaiting reliable evidence and its deterministic allocation turn.
+ Held,
+ /// Actual usage consumed the needed funds; unused holds were released.
+ Consumed,
+ /// Proved not executed; entire hold released without inventing provider evidence.
+ Released,
+}
+
+/// Allocation lifecycle. Evidence state remains owned by the invocation journal.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum AllocationState {
+ /// Evidence is pending/unresolved or a preceding admission still blocks allocation.
+ Unallocated,
+ /// Immutable pricing and funding facts, independent of current billing settings.
+ Allocated(UsageAllocation),
+ /// Proved non-execution, distinct from measured zero provider usage.
+ NotExecuted,
+}
+
+/// Bounded admission for one provider attempt. Persist before acknowledging execution.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Reservation {
+ authorization: AuthorizationSnapshot,
+ sequence: AllocationSequence,
+ maximum_public_usage: PublicUsage,
+ holds: FundingHolds,
+ prepaid_reclaim_limit: CustomerMoney,
+ allocation: AllocationState,
+}
+
+/// Actual prior usage read at the allocation watermark, not admission's projected usage.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct AllocationPosition {
+ /// Next unresolved sequence for this payer. Later completions must wait.
+ pub next_sequence: AllocationSequence,
+ /// Actual prior allocated usage for this reservation's frozen seat and period.
+ pub seat_public_used: PublicUsage,
+ /// Still-unspent credits released by earlier admissions that held them when this
+ /// attempt was admitted. Exclude later purchases and releases from later attempts.
+ /// The repository must retain release provenance and debit this pool atomically;
+ /// neither the current cent balance nor the current toggle proves eligibility.
+ pub prepaid_released_before: CustomerMoney,
+}
+
+/// Final exact split for one invocation. Preserve these facts through credit purchases,
+/// toggle changes and collection retries; never rerun funding against today's balances.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct UsageAllocation {
+ /// Public usage classified as included, without markup or liability.
+ pub included_public: PublicUsage,
+ /// Public usage classified as extra (including unavoidable unfunded excess).
+ pub extra_public: PublicUsage,
+ /// Previously paid credit consumed; not a new invoice or liability.
+ pub prepaid: CustomerMoney,
+ /// Subset of `prepaid` drawn from eligible earlier releases instead of this
+ /// attempt's original hold. Debit that release pool once, not the original hold.
+ pub reclaimed_prepaid: CustomerMoney,
+ /// Authorized incurred liability, irrespective of whether it has been collected.
+ pub postpaid: CustomerMoney,
+ /// Extra-price valuation of unfunded overshoot, not provider expense or customer debt.
+ pub macro_absorbed: CustomerMoney,
+}
+
+impl UsageAllocation {
+ /// Exact extra valuation, including Macro-absorbed usage.
+ pub fn extra_money(&self) -> Result<CustomerMoney, PolicyError> {
+ Ok(self
+ .prepaid
+ .checked_add(self.postpaid)?
+ .checked_add(self.macro_absorbed)?)
+ }
+
+ /// Only postpaid creates new customer liability; credit purchases were paid separately.
+ pub fn customer_liability(&self) -> CustomerMoney {
+ self.postpaid
+ }
+
+ /// Stable funding-source order; zero portions may be omitted by presentation adapters.
+ pub fn funding_portions(&self) -> [FundingPortion; 4] {
+ [
+ FundingPortion {
+ source: FundingSource::Included,
+ amount: ZERO_MONEY,
+ },
+ FundingPortion {
+ source: FundingSource::Prepaid,
+ amount: self.prepaid,
+ },
+ FundingPortion {
+ source: FundingSource::Postpaid,
+ amount: self.postpaid,
+ },
+ FundingPortion {
+ source: FundingSource::MacroAbsorbed,
+ amount: self.macro_absorbed,
+ },
+ ]
+ }
+}
+
+fn remaining_included(used: PublicUsage) -> PublicUsage {
+ PublicUsage::from_units(INCLUDED_PUBLIC_USAGE.units().saturating_sub(used.units()))
+}
+
+fn extra_price(usage: PublicUsage) -> Result<CustomerMoney, PolicyError> {
+ Ok(CustomerMoney::from_public_ratio(
+ usage,
+ EXTRA_RATE_NUMERATOR,
+ EXTRA_RATE_DENOMINATOR,
+ )?)
+}
+
+fn available_holds(
+ authorization: &AuthorizationSnapshot,
+ available: FundingAvailability,
+) -> Result<FundingHolds, PolicyError> {
+ if authorization.policy != UsagePolicy::PublicAllowanceV1 {
+ return Err(PolicyError::WrongPolicy);
+ }
+ let postpaid = match authorization.postpaid {
+ PostpaidAuthorization::Disabled | PostpaidAuthorization::Suspended => ZERO_MONEY,
+ PostpaidAuthorization::Enabled { limit } => {
+ let committed = available
+ .postpaid_incurred
+ .checked_add(available.postpaid_held)?;
+ CustomerMoney::from_units(limit.units().saturating_sub(committed.units()))
+ }
+ };
+ Ok(FundingHolds {
+ included_public: remaining_included(
+ available
+ .seat_public_used
+ .checked_add(available.seat_public_held)?,
+ ),
+ prepaid: available.prepaid_available,
+ postpaid,
+ })
+}
+
+/// Maximum fully funded public usage up to a trusted execution ceiling. Floor only this
+/// admission bound, never actual usage/money. Hosts must lower their execution ceiling
+/// before retrying a rejected admission; an oversized token budget is not authorized.
+pub fn funded_capacity(
+ authorization: &AuthorizationSnapshot,
+ maximum_public_usage: PublicUsage,
+ available: FundingAvailability,
+) -> Result<PublicUsage, PolicyError> {
+ let holds = available_holds(authorization, available)?;
+ let money = u128::from(holds.prepaid.units()) + u128::from(holds.postpaid.units());
+ let money_per_public_unit = extra_price(PublicUsage::from_units(1))?.units();
+ let public =
+ u128::from(holds.included_public.units()) + money / u128::from(money_per_public_unit);
+ Ok(PublicUsage::from_units(
+ public.min(u128::from(maximum_public_usage.units())) as u64,
+ ))
+}
+
+/// Reserve the complete trusted per-attempt ceiling, credit-first. No partially funded
+/// execution is admitted. A rejection carries the maximum affordable smaller ceiling.
+pub fn reserve(
+ authorization: AuthorizationSnapshot,
+ sequence: AllocationSequence,
+ maximum_public_usage: PublicUsage,
+ available: FundingAvailability,
+) -> Result<Reservation, PolicyError> {
+ if maximum_public_usage == ZERO_PUBLIC {
+ return Err(PolicyError::EmptyBudget);
+ }
+ let capacity = funded_capacity(&authorization, maximum_public_usage, available)?;
+ if maximum_public_usage > capacity {
+ return Err(PolicyError::InsufficientFunding {
+ maximum_public_usage: capacity,
+ });
+ }
+ let prior_prepaid_held = available.prepaid_held;
+ let available = available_holds(&authorization, available)?;
+ let included_public = maximum_public_usage.min(available.included_public);
+ let extra = extra_price(maximum_public_usage.checked_sub(included_public)?)?;
+ let prepaid = extra.min(available.prepaid);
+ let postpaid = extra.checked_sub(prepaid)?;
+ Ok(Reservation {
+ authorization,
+ sequence,
+ maximum_public_usage,
+ holds: FundingHolds {
+ included_public,
+ prepaid,
+ postpaid,
+ },
+ prepaid_reclaim_limit: prior_prepaid_held.min(postpaid),
+ allocation: AllocationState::Unallocated,
+ })
+}
+
+impl Reservation {
+ /// Captured facts, never a live settings lookup.
+ pub fn authorization(&self) -> &AuthorizationSnapshot {
+ &self.authorization
+ }
+
+ /// Payer-wide deterministic allocation order.
+ pub fn sequence(&self) -> AllocationSequence {
+ self.sequence
+ }
+
+ /// Public-price execution ceiling acknowledged to the producer.
+ pub fn maximum_public_usage(&self) -> PublicUsage {
+ self.maximum_public_usage
+ }
+
+ /// Original exact holds; release unused amounts only when resolved.
+ pub fn holds(&self) -> FundingHolds {
+ self.holds
+ }
+
+ /// Captured ceiling on earlier held credits that may replace provisional postpaid.
+ pub fn prepaid_reclaim_limit(&self) -> CustomerMoney {
+ self.prepaid_reclaim_limit
+ }
+
+ /// Reservation lifecycle derived from allocation, avoiding inconsistent flags.
+ pub fn state(&self) -> ReservationState {
+ match self.allocation {
+ AllocationState::Unallocated => ReservationState::Held,
+ AllocationState::Allocated(_) => ReservationState::Consumed,
+ AllocationState::NotExecuted => ReservationState::Released,
+ }
+ }
+
+ /// Immutable source allocation when resolved, never an invoice status.
+ pub fn allocation_state(&self) -> &AllocationState {
+ &self.allocation
+ }
+
+ fn require_held(&self) -> Result<(), PolicyError> {
+ if self.state() != ReservationState::Held {
+ return Err(PolicyError::ReservationResolved);
+ }
+ Ok(())
+ }
+
+ /// Reconcile complete evidence at the payer's allocation watermark. Only actual
+ /// earlier usage consumes allowance. No current toggle/credit input is accepted.
+ /// Persist this transition, source debits, releases and watermark atomically;
+ /// repositories handle identical replay by returning the already persisted result.
+ pub fn allocate(
+ &mut self,
+ position: AllocationPosition,
+ actual: PublicUsage,
+ ) -> Result<UsageAllocation, PolicyError> {
+ self.require_held()?;
+ if position.next_sequence != self.sequence {
+ return Err(PolicyError::OutOfOrder);
+ }
+ // Check the total the repository will persist before changing any state.
+ position.seat_public_used.checked_add(actual)?;
+ let included_public = actual.min(remaining_included(position.seat_public_used));
+ let extra_public = actual.checked_sub(included_public)?;
+ let extra = extra_price(extra_public)?;
+ let prepaid = extra.min(self.holds.prepaid);
+ let remainder = extra.checked_sub(prepaid)?;
+ let postpaid_budget = remainder.min(self.holds.postpaid);
+ let reclaimed_prepaid = postpaid_budget
+ .min(self.prepaid_reclaim_limit)
+ .min(position.prepaid_released_before);
+ let allocation = UsageAllocation {
+ included_public,
+ extra_public,
+ prepaid: prepaid.checked_add(reclaimed_prepaid)?,
+ reclaimed_prepaid,
+ postpaid: postpaid_budget.checked_sub(reclaimed_prepaid)?,
+ macro_absorbed: remainder.checked_sub(postpaid_budget)?,
+ };
+ self.allocation = AllocationState::Allocated(allocation.clone());
+ Ok(allocation)
+ }
+
+ /// Only call with proof the provider did not execute. Timeouts/cancellation or
+ /// absent counters are not proof; retain those holds for evidence reconciliation.
+ pub fn release_without_execution(&mut self) -> Result<FundingHolds, PolicyError> {
+ self.require_held()?;
+ self.allocation = AllocationState::NotExecuted;
+ Ok(self.holds)
+ }
+
+ /// Unused original budgets after final allocation or proved non-execution.
+ pub fn released_holds(&self) -> Result<FundingHolds, PolicyError> {
+ match &self.allocation {
+ AllocationState::Unallocated => Err(PolicyError::UnresolvedReservation),
+ AllocationState::NotExecuted => Ok(self.holds),
+ AllocationState::Allocated(allocation) => Ok(FundingHolds {
+ included_public: self
+ .holds
+ .included_public
+ .checked_sub(allocation.included_public.min(self.holds.included_public))?,
+ prepaid: self.holds.prepaid.checked_sub(
+ allocation
+ .prepaid
+ .checked_sub(allocation.reclaimed_prepaid)?,
+ )?,
+ postpaid: self.holds.postpaid.checked_sub(allocation.postpaid)?,
+ }),
+ }
+ }
+}
+
+/// Collection state is orthogonal to authorization and immutable source allocation.
+/// Failed collection never releases prepaid or authorizes repricing/reclassification.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CollectionState {
+ /// Incurred liability below the existing collection threshold.
+ Accruing,
+ /// Reserved for an idempotent collection attempt, including an existing invoice.
+ Pending,
+ /// Collected; terminal even if a delayed failure notification arrives.
+ Paid,
+ /// Retry the same collectible charge, not a new funding allocation.
+ Failed,
+ /// Period-end amount below the payment minimum, explicitly forgiven.
+ Forgiven,
+}
+
+/// Retain exact cumulative postpaid liability per payer/period and a whole-cent
+/// booking watermark. Rounding deltas per request or settlement would overcharge.
+/// The exact total is never replaced by a rounded value; after rounding up the next
+/// accrual must first cover that advance before another cent can be booked.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct CumulativeCollection {
+ exact_total: CustomerMoney,
+ booked_cents: u64,
+}
+
+impl Default for CumulativeCollection {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl CumulativeCollection {
+ /// Empty collection accumulator for a new payer/period (not each settlement).
+ pub const fn new() -> Self {
+ Self {
+ exact_total: ZERO_MONEY,
+ booked_cents: 0,
+ }
+ }
+
+ /// Restore durable progress without permitting bookings above rounded liability.
+ pub fn restore(exact_total: CustomerMoney, booked_cents: u64) -> Result<Self, PolicyError> {
+ if booked_cents > round_half_up(exact_total) {
+ return Err(PolicyError::InvalidCollection);
+ }
+ Ok(Self {
+ exact_total,
+ booked_cents,
+ })
+ }
+
+ /// Add only newly allocated postpaid money, once per durable allocation identity.
+ pub fn accrue(&mut self, amount: CustomerMoney) -> Result<(), PolicyError> {
+ self.exact_total = self.exact_total.checked_add(amount)?;
+ Ok(())
+ }
+
+ /// Exact total including any subcent remainder and already booked liability.
+ pub fn exact_total(self) -> CustomerMoney {
+ self.exact_total
+ }
+
+ /// Pending, paid, failed-but-collectible and explicitly forgiven cents, counted once.
+ pub fn booked_cents(self) -> u64 {
+ self.booked_cents
+ }
+
+ /// Lossless unrounded cents/remainder. Persist the total and booking watermark
+ /// together; persisting only a positive remainder loses a prior rounding advance.
+ pub fn remainder(self) -> CentParts {
+ self.exact_total.split_cents()
+ }
+
+ /// Difference of rounded cumulative totals, never a rounded incremental amount.
+ pub fn unbooked_cents(self) -> Result<u64, PolicyError> {
+ round_half_up(self.exact_total)
+ .checked_sub(self.booked_cents)
+ .ok_or(PolicyError::InvalidCollection)
+ }
+
+ /// Advance exactly once when reserving collection or explicitly forgiving money.
+ /// Retrying/finishing a reserved charge must not advance this watermark again.
+ pub fn book(&mut self, cents: u64) -> Result<(), PolicyError> {
+ if cents > self.unbooked_cents()? {
+ return Err(PolicyError::InvalidCollection);
+ }
+ self.booked_cents += cents;
+ Ok(())
+ }
+
+ /// Preserve existing $10 collection cadence and $0.50 period-end payment minimum.
+ /// Flush/forgive only after the period has ended AND all its evidence is allocated.
+ pub fn plan(self, period_closed_and_allocated: bool) -> Result<CollectionPlan, PolicyError> {
+ let cents = self.unbooked_cents()?;
+ if cents >= OVERAGE_CHARGE_THRESHOLD_CENTS as u64
+ || (period_closed_and_allocated && cents >= MIN_STRIPE_CHARGE_CENTS as u64)
+ {
+ return Ok(CollectionPlan::Collect { cents });
+ }
+ if period_closed_and_allocated && cents > 0 {
+ return Ok(CollectionPlan::Forgive { cents });
+ }
+ Ok(CollectionPlan::Wait)
+ }
+}
+
+/// Collection action; funding has already been decided and must not be rerun.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CollectionPlan {
+ /// No collectible chunk yet.
+ Wait,
+ /// Reserve these newly collectible cents using a stable charge identity.
+ Collect {
+ /// Whole-cent difference from the cumulative booking watermark.
+ cents: u64,
+ },
+ /// Book the below-minimum period-end remainder without a payment attempt.
+ Forgive {
+ /// Rounded cents to forgive exactly once.
+ cents: u64,
+ },
+}
+
+/// Round a nonnegative cumulative customer-money total to cents: exact half cents
+/// round up. Use differences of these cumulative values, never sum rounded chunks.
+pub fn round_half_up(total: CustomerMoney) -> u64 {
+ let parts = total.split_cents();
+ parts.whole_cents + u64::from(parts.subcent_units >= CustomerMoney::UNITS_PER_CENT / 2)
+}
+
+/// Pure-policy errors; no error permits provider execution or creates customer debt.
+#[derive(Debug, Error)]
+pub enum PolicyError {
+ /// The recorded policy belongs on another accounting path.
+ #[error("public allowance allocation requires the recorded V1 policy")]
+ WrongPolicy,
+ /// Require a meaningful bounded provider attempt at admission.
+ #[error("attempt budget must be positive")]
+ EmptyBudget,
+ /// Caller must constrain execution and request fresh authorization, not execute partially funded.
+ #[error("attempt exceeds funded capacity")]
+ InsufficientFunding {
+ /// Maximum affordable public usage within the requested ceiling.
+ maximum_public_usage: PublicUsage,
+ },
+ /// A preceding admission still requires reconciliation.
+ #[error("allocation must follow payer admission order")]
+ OutOfOrder,
+ /// No second allocation or release of a terminal reservation.
+ #[error("reservation already resolved")]
+ ReservationResolved,
+ /// Pending/unresolved evidence is not zero usage.
+ #[error("reservation still awaits evidence or allocation")]
+ UnresolvedReservation,
+ /// Whole-cent progress cannot exceed rounded cumulative liability.
+ #[error("invalid cumulative collection progress")]
+ InvalidCollection,
+ /// Allocation order never wraps.
+ #[error("allocation sequence overflow")]
+ SequenceOverflow,
+ /// Reuse the financial domain's checked fixed-point arithmetic errors.
+ #[error(transparent)]
+ Arithmetic(#[from] FinancialError),
+}
diff --git a/crates/ai_billing/src/domain/policy/test.rs b/crates/ai_billing/src/domain/policy/test.rs
new file mode 100644
index 0000000000..b117e60e61
--- /dev/null
+++ b/crates/ai_billing/src/domain/policy/test.rs
@@ -0,0 +1,572 @@
+use super::*;
+use chrono::{TimeZone, Utc};
+
+fn public_cents(cents: u64) -> PublicUsage {
+ PublicUsage::from_units(cents * PUBLIC_UNITS_PER_CENT)
+}
+
+fn money(cents: u64) -> CustomerMoney {
+ CustomerMoney::from_cents(cents).unwrap()
+}
+
+fn authorization(enabled: bool) -> AuthorizationSnapshot {
+ AuthorizationSnapshot {
+ id: FundingAuthorizationId::new(),
+ invocation_id: InvocationId::new(),
+ payer: MacroUserIdStr::try_from("macro|[email protected]").unwrap(),
+ seat: MacroUserIdStr::try_from("macro|[email protected]").unwrap(),
+ period: BillingPeriod {
+ start: Utc.with_ymd_and_hms(2026, 9, 1, 0, 0, 0).unwrap(),
+ end: Utc.with_ymd_and_hms(2026, 10, 1, 0, 0, 0).unwrap(),
+ },
+ policy: UsagePolicy::PublicAllowanceV1,
+ settings_revision: AuthorizationRevision::from_raw(1),
+ postpaid: if enabled {
+ PostpaidAuthorization::Enabled {
+ limit: money(5_000),
+ }
+ } else {
+ PostpaidAuthorization::Disabled
+ },
+ }
+}
+
+fn availability(used: PublicUsage, credits: CustomerMoney) -> FundingAvailability {
+ FundingAvailability {
+ seat_public_used: used,
+ seat_public_held: ZERO_PUBLIC,
+ prepaid_available: credits,
+ prepaid_held: ZERO_MONEY,
+ postpaid_incurred: ZERO_MONEY,
+ postpaid_held: ZERO_MONEY,
+ }
+}
+
+fn position(sequence: u64, used: PublicUsage) -> AllocationPosition {
+ AllocationPosition {
+ next_sequence: AllocationSequence::from_raw(sequence),
+ seat_public_used: used,
+ prepaid_released_before: ZERO_MONEY,
+ }
+}
+
+fn allocate_call(
+ used: PublicUsage,
+ actual: PublicUsage,
+ credits: CustomerMoney,
+ enabled: bool,
+) -> UsageAllocation {
+ let mut reservation = reserve(
+ authorization(enabled),
+ AllocationSequence::from_raw(0),
+ actual,
+ availability(used, credits),
+ )
+ .unwrap();
+ reservation.allocate(position(0, used), actual).unwrap()
+}
+
+#[test]
+fn pricing_table_and_enabled_does_not_mean_consumed() {
+ for enabled in [false, true] {
+ for cents in [1_900, 2_000] {
+ let allocation = allocate_call(ZERO_PUBLIC, public_cents(cents), ZERO_MONEY, enabled);
+ assert_eq!(allocation.included_public, public_cents(cents));
+ assert_eq!(allocation.extra_public, ZERO_PUBLIC);
+ assert_eq!(allocation.extra_money().unwrap(), ZERO_MONEY);
+ assert_eq!(allocation.postpaid, ZERO_MONEY);
+ }
+ }
+ for (credits, enabled, prepaid, postpaid) in [
+ (0, true, 0, 1_050),
+ (1_050, false, 1_050, 0),
+ (1_000, true, 1_000, 50),
+ ] {
+ let allocation = allocate_call(ZERO_PUBLIC, public_cents(3_000), money(credits), enabled);
+ assert_eq!(allocation.included_public, public_cents(2_000));
+ assert_eq!(allocation.extra_public, public_cents(1_000));
+ assert_eq!(allocation.prepaid, money(prepaid));
+ assert_eq!(allocation.postpaid, money(postpaid));
+ assert_eq!(allocation.macro_absorbed, ZERO_MONEY);
+ }
+}
+
+#[test]
+fn opt_out_stops_at_exact_funded_capacity() {
+ let available = availability(ZERO_PUBLIC, money(1_000));
+ let capacity = funded_capacity(&authorization(false), public_cents(3_000), available).unwrap();
+ assert_eq!(capacity.units(), 29_523_809_523_809);
+ assert!(matches!(
+ reserve(authorization(false), AllocationSequence::from_raw(0), public_cents(3_000), available),
+ Err(PolicyError::InsufficientFunding { maximum_public_usage }) if maximum_public_usage == capacity
+ ));
+ let allocation = allocate_call(ZERO_PUBLIC, capacity, money(1_000), false);
+ assert!(allocation.prepaid <= money(1_000));
+ assert_eq!(allocation.postpaid, ZERO_MONEY);
+ assert!(matches!(
+ reserve(authorization(false), AllocationSequence::from_raw(0), PublicUsage::from_units(1), availability(public_cents(2_000), ZERO_MONEY)),
+ Err(PolicyError::InsufficientFunding { maximum_public_usage }) if maximum_public_usage == ZERO_PUBLIC
+ ));
+}
+
+#[test]
+fn threshold_crossing_and_fractional_credit_boundary_are_lossless() {
+ let allocation = allocate_call(
+ public_cents(1_999),
+ public_cents(2),
+ CustomerMoney::from_units(1),
+ true,
+ );
+ assert_eq!(allocation.included_public, public_cents(1));
+ assert_eq!(allocation.extra_public, public_cents(1));
+ assert_eq!(allocation.prepaid.units(), 1);
+ assert_eq!(allocation.postpaid.units(), 1_050_000_000_000 - 1);
+ let tiny = allocate_call(
+ PublicUsage::from_units(INCLUDED_PUBLIC_USAGE.units() - 1),
+ PublicUsage::from_units(2),
+ ZERO_MONEY,
+ true,
+ );
+ assert_eq!(tiny.included_public.units(), 1);
+ assert_eq!(tiny.extra_public.units(), 1);
+ assert_eq!(tiny.postpaid.units(), 105);
+ assert_eq!(
+ tiny.funding_portions()[0].category(),
+ PricingCategory::Included
+ );
+ assert_eq!(tiny.funding_portions()[2].source, FundingSource::Postpaid);
+}
+
+#[test]
+fn unused_holds_never_turn_included_usage_into_extra() {
+ for credits in [ZERO_MONEY, money(1_050)] {
+ let mut available = availability(ZERO_PUBLIC, credits);
+ available.seat_public_held = INCLUDED_PUBLIC_USAGE;
+ let mut later = reserve(
+ authorization(true),
+ AllocationSequence::from_raw(1),
+ public_cents(1_000),
+ available,
+ )
+ .unwrap();
+ assert_eq!(later.holds().prepaid, credits);
+ assert_eq!(
+ later.holds().postpaid,
+ money(1_050).checked_sub(credits).unwrap()
+ );
+ assert!(matches!(
+ later.allocate(position(0, ZERO_PUBLIC), public_cents(1_000)),
+ Err(PolicyError::OutOfOrder)
+ ));
+ // Earlier attempt released its hold without execution, or finalized measured zero.
+ let allocation = later
+ .allocate(position(1, ZERO_PUBLIC), public_cents(1_000))
+ .unwrap();
+ assert_eq!(allocation.included_public, public_cents(1_000));
+ assert_eq!(allocation.extra_money().unwrap(), ZERO_MONEY);
+ assert_eq!(allocation.customer_liability(), ZERO_MONEY);
+ assert_eq!(later.released_holds().unwrap(), later.holds());
+ }
+}
+
+#[test]
+fn release_is_terminal_and_unresolved_attempts_must_keep_their_holds() {
+ let mut reservation = reserve(
+ authorization(false),
+ AllocationSequence::from_raw(0),
+ public_cents(100),
+ availability(ZERO_PUBLIC, ZERO_MONEY),
+ )
+ .unwrap();
+ assert_eq!(reservation.state(), ReservationState::Held);
+ assert!(matches!(
+ reservation.released_holds(),
+ Err(PolicyError::UnresolvedReservation)
+ ));
+ let holds = reservation.release_without_execution().unwrap();
+ assert_eq!(holds.included_public, public_cents(100));
+ assert_eq!(reservation.state(), ReservationState::Released);
+ assert!(matches!(
+ reservation.release_without_execution(),
+ Err(PolicyError::ReservationResolved)
+ ));
+ assert!(matches!(
+ reservation.allocate(position(0, ZERO_PUBLIC), public_cents(1)),
+ Err(PolicyError::ReservationResolved)
+ ));
+}
+
+#[test]
+fn overshoot_is_macro_absorbed_not_unauthorized_debt() {
+ let mut reservation = reserve(
+ authorization(false),
+ AllocationSequence::from_raw(0),
+ public_cents(2_000),
+ availability(ZERO_PUBLIC, ZERO_MONEY),
+ )
+ .unwrap();
+ let allocation = reservation
+ .allocate(position(0, ZERO_PUBLIC), public_cents(3_000))
+ .unwrap();
+ assert_eq!(allocation.macro_absorbed, money(1_050));
+ assert_eq!(allocation.customer_liability(), ZERO_MONEY);
+ assert_eq!(allocation.extra_money().unwrap(), money(1_050));
+}
+
+#[test]
+fn holds_and_incurred_liability_reduce_only_postpaid_cap_not_prepaid() {
+ let mut auth = authorization(true);
+ auth.postpaid = PostpaidAuthorization::Enabled { limit: money(500) };
+ let mut available = availability(INCLUDED_PUBLIC_USAGE, money(105));
+ available.postpaid_incurred = money(300);
+ available.postpaid_held = money(200);
+ let mut reservation = reserve(
+ auth,
+ AllocationSequence::from_raw(0),
+ public_cents(100),
+ available,
+ )
+ .unwrap();
+ assert_eq!(reservation.holds().prepaid, money(105));
+ assert_eq!(reservation.holds().postpaid, ZERO_MONEY);
+ let allocation = reservation
+ .allocate(position(0, INCLUDED_PUBLIC_USAGE), public_cents(200))
+ .unwrap();
+ assert_eq!(allocation.prepaid, money(105));
+ assert_eq!(allocation.postpaid, ZERO_MONEY);
+ assert_eq!(allocation.macro_absorbed, money(105));
+}
+
+#[test]
+fn captured_authorization_survives_toggle_changes_without_retroactive_funding() {
+ let mut auth = authorization(true);
+ let mut reservation = reserve(
+ auth.clone(),
+ AllocationSequence::from_raw(0),
+ public_cents(100),
+ availability(INCLUDED_PUBLIC_USAGE, ZERO_MONEY),
+ )
+ .unwrap();
+ auth.postpaid = PostpaidAuthorization::Disabled;
+ let allocation = reservation
+ .allocate(position(0, INCLUDED_PUBLIC_USAGE), public_cents(100))
+ .unwrap();
+ assert_eq!(allocation.postpaid, money(105));
+ assert!(matches!(
+ reserve(
+ auth,
+ AllocationSequence::from_raw(1),
+ public_cents(100),
+ availability(INCLUDED_PUBLIC_USAGE, ZERO_MONEY)
+ ),
+ Err(PolicyError::InsufficientFunding { .. })
+ ));
+ assert_eq!(
+ reservation.authorization().postpaid,
+ authorization(true).postpaid
+ );
+}
+
+#[test]
+fn released_earlier_credits_replace_provisional_postpaid_not_finalized_liability() {
+ let mut available = availability(INCLUDED_PUBLIC_USAGE, ZERO_MONEY);
+ available.prepaid_held = money(105);
+ let mut later = reserve(
+ authorization(true),
+ AllocationSequence::from_raw(1),
+ public_cents(100),
+ available,
+ )
+ .unwrap();
+ assert_eq!(later.holds().postpaid, money(105));
+ assert_eq!(later.prepaid_reclaim_limit(), money(105));
+ let mut at_turn = position(1, INCLUDED_PUBLIC_USAGE);
+ at_turn.prepaid_released_before = money(105);
+ let allocation = later.allocate(at_turn, public_cents(200)).unwrap();
+ assert_eq!(allocation.prepaid, money(105));
+ assert_eq!(allocation.reclaimed_prepaid, money(105));
+ assert_eq!(allocation.postpaid, ZERO_MONEY);
+ // Reclaimed credits substitute the captured budget, never expand it for overshoot.
+ assert_eq!(allocation.macro_absorbed, money(105));
+ assert_eq!(later.released_holds().unwrap().postpaid, money(105));
+ assert_eq!(later.released_holds().unwrap().prepaid, ZERO_MONEY);
+ assert_eq!(later.state(), ReservationState::Consumed);
+ assert_eq!(
+ later.allocation_state(),
+ &AllocationState::Allocated(allocation)
+ );
+ assert!(matches!(
+ later.allocate(at_turn, public_cents(200)),
+ Err(PolicyError::ReservationResolved)
+ ));
+}
+
+#[test]
+fn new_credits_cannot_reclassify_captured_or_settled_sources() {
+ let mut reservation = reserve(
+ authorization(true),
+ AllocationSequence::from_raw(0),
+ public_cents(100),
+ availability(INCLUDED_PUBLIC_USAGE, ZERO_MONEY),
+ )
+ .unwrap();
+ // No earlier credits existed at admission, so even an erroneous release input
+ // cannot use a subsequent purchase to displace the captured postpaid funding.
+ let mut at_turn = position(0, INCLUDED_PUBLIC_USAGE);
+ at_turn.prepaid_released_before = money(105);
+ let allocation = reservation.allocate(at_turn, public_cents(100)).unwrap();
+ assert_eq!(allocation.prepaid, ZERO_MONEY);
+ assert_eq!(allocation.postpaid, money(105));
+ assert!(matches!(
+ reservation.release_without_execution(),
+ Err(PolicyError::ReservationResolved)
+ ));
+}
+
+#[test]
+fn captured_suspension_and_zero_cap_deny_only_new_postpaid() {
+ let mut settings = BillingSettings {
+ overage_enabled: true,
+ overage_limit_cents: 500,
+ ..Default::default()
+ };
+ assert_eq!(
+ PostpaidAuthorization::from_settings(&settings).unwrap(),
+ PostpaidAuthorization::Enabled { limit: money(500) }
+ );
+ settings.overage_suspended_at = Some(Utc::now());
+ let mut auth = authorization(true);
+ auth.postpaid = PostpaidAuthorization::from_settings(&settings).unwrap();
+ assert_eq!(auth.postpaid, PostpaidAuthorization::Suspended);
+ assert!(matches!(
+ reserve(
+ auth.clone(),
+ AllocationSequence::from_raw(0),
+ public_cents(100),
+ availability(INCLUDED_PUBLIC_USAGE, ZERO_MONEY)
+ ),
+ Err(PolicyError::InsufficientFunding { .. })
+ ));
+ let prepaid = reserve(
+ auth,
+ AllocationSequence::from_raw(0),
+ public_cents(100),
+ availability(INCLUDED_PUBLIC_USAGE, money(105)),
+ )
+ .unwrap();
+ assert_eq!(prepaid.holds().prepaid, money(105));
+ settings.overage_suspended_at = None;
+ for cap in [0, -1] {
+ settings.overage_limit_cents = cap;
+ assert_eq!(
+ PostpaidAuthorization::from_settings(&settings).unwrap(),
+ PostpaidAuthorization::Disabled
+ );
+ }
+ settings.overage_limit_cents = 500;
+ settings.overage_enabled = false;
+ assert_eq!(
+ PostpaidAuthorization::from_settings(&settings).unwrap(),
+ PostpaidAuthorization::Disabled
+ );
+}
+
+#[test]
+fn collection_cadence_remainders_and_restore_preserve_existing_thresholds() {
+ for (cents, open, ended) in [
+ (0, CollectionPlan::Wait, CollectionPlan::Wait),
+ (
+ 49,
+ CollectionPlan::Wait,
+ CollectionPlan::Forgive { cents: 49 },
+ ),
+ (
+ 50,
+ CollectionPlan::Wait,
+ CollectionPlan::Collect { cents: 50 },
+ ),
+ (
+ 999,
+ CollectionPlan::Wait,
+ CollectionPlan::Collect { cents: 999 },
+ ),
+ (
+ 1_000,
+ CollectionPlan::Collect { cents: 1_000 },
+ CollectionPlan::Collect { cents: 1_000 },
+ ),
+ ] {
+ let mut collection = CumulativeCollection::restore(money(cents), 0).unwrap();
+ assert_eq!(collection.plan(false).unwrap(), open);
+ assert_eq!(collection.plan(true).unwrap(), ended);
+ collection.book(cents).unwrap();
+ assert_eq!(collection.plan(true).unwrap(), CollectionPlan::Wait);
+ assert_eq!(
+ CumulativeCollection::restore(collection.exact_total(), collection.booked_cents())
+ .unwrap(),
+ collection
+ );
+ }
+ assert!(CumulativeCollection::restore(ZERO_MONEY, 1).is_err());
+}
+
+#[test]
+fn checked_arithmetic_fails_without_partial_allocation_or_collection() {
+ assert!(matches!(
+ AllocationSequence::from_raw(u64::MAX).next(),
+ Err(PolicyError::SequenceOverflow)
+ ));
+ assert!(matches!(
+ reserve(
+ authorization(true),
+ AllocationSequence::from_raw(0),
+ ZERO_PUBLIC,
+ availability(ZERO_PUBLIC, ZERO_MONEY)
+ ),
+ Err(PolicyError::EmptyBudget)
+ ));
+ let mut reservation = reserve(
+ authorization(true),
+ AllocationSequence::from_raw(0),
+ public_cents(1),
+ availability(INCLUDED_PUBLIC_USAGE, ZERO_MONEY),
+ )
+ .unwrap();
+ assert!(matches!(
+ reservation.allocate(
+ position(0, INCLUDED_PUBLIC_USAGE),
+ PublicUsage::from_units(u64::MAX)
+ ),
+ Err(PolicyError::Arithmetic(_))
+ ));
+ assert_eq!(reservation.state(), ReservationState::Held);
+ assert!(matches!(
+ extra_price(PublicUsage::from_units(u64::MAX)),
+ Err(PolicyError::Arithmetic(_))
+ ));
+ let mut collection =
+ CumulativeCollection::restore(CustomerMoney::from_units(u64::MAX), 0).unwrap();
+ assert!(collection.accrue(CustomerMoney::from_units(1)).is_err());
+ assert_eq!(collection.exact_total().units(), u64::MAX);
+ // Measured zero is allocated, not silently treated as non-execution.
+ let zero = reservation
+ .allocate(position(0, INCLUDED_PUBLIC_USAGE), ZERO_PUBLIC)
+ .unwrap();
+ assert_eq!(zero.extra_money().unwrap(), ZERO_MONEY);
+ assert_eq!(reservation.state(), ReservationState::Consumed);
+ assert_eq!(reservation.released_holds().unwrap(), reservation.holds());
+}
+
+#[test]
+fn unequal_seats_do_not_pool_allowance() {
+ let heavy = allocate_call(ZERO_PUBLIC, public_cents(3_000), ZERO_MONEY, true);
+ let light = allocate_call(ZERO_PUBLIC, public_cents(1_000), ZERO_MONEY, true);
+ assert_eq!(heavy.postpaid, money(1_050));
+ assert_eq!(light.postpaid, ZERO_MONEY);
+ assert_eq!(light.included_public, public_cents(1_000));
+}
+
+#[test]
+fn request_and_collection_partitioning_cannot_increase_charges() {
+ let total = public_cents(3_003);
+ let credits = CustomerMoney::from_units(money(1_000).units() + 17);
+ let unsplit = allocate_call(ZERO_PUBLIC, total, credits, true);
+ for partitions in [1, 2, 3, 7, 101, 1_003] {
+ let mut used = ZERO_PUBLIC;
+ let mut remaining_credit = credits;
+ let mut collection = CumulativeCollection::new();
+ let mut prepaid = ZERO_MONEY;
+ let mut charged = 0;
+ for index in 0..partitions {
+ let units = total.units() / partitions + u64::from(index < total.units() % partitions);
+ let usage = PublicUsage::from_units(units);
+ let allocation = allocate_call(used, usage, remaining_credit, true);
+ used = used.checked_add(usage).unwrap();
+ remaining_credit = remaining_credit.checked_sub(allocation.prepaid).unwrap();
+ prepaid = prepaid.checked_add(allocation.prepaid).unwrap();
+ collection.accrue(allocation.postpaid).unwrap();
+ let delta = collection.unbooked_cents().unwrap();
+ collection.book(delta).unwrap();
+ charged += delta;
+ }
+ assert_eq!(prepaid, unsplit.prepaid);
+ assert_eq!(collection.exact_total(), unsplit.postpaid);
+ assert_eq!(charged, round_half_up(unsplit.postpaid));
+ assert_eq!(collection.unbooked_cents().unwrap(), 0);
+ assert_eq!(collection.remainder(), unsplit.postpaid.split_cents());
+ }
+}
+
+#[test]
+fn rounding_is_cumulative_half_up_with_signed_carry_preserved() {
+ let half = CustomerMoney::UNITS_PER_CENT / 2;
+ assert_eq!(round_half_up(CustomerMoney::from_units(half - 1)), 0);
+ assert_eq!(round_half_up(CustomerMoney::from_units(half)), 1);
+ assert_eq!(round_half_up(CustomerMoney::from_units(half + 1)), 1);
+ let mut collection = CumulativeCollection::new();
+ for index in 1..=10 {
+ collection.accrue(CustomerMoney::from_units(half)).unwrap();
+ let delta = collection.unbooked_cents().unwrap();
+ assert_eq!(delta, index % 2);
+ collection.book(delta).unwrap();
+ }
+ assert_eq!(collection.booked_cents(), 5);
+ assert!(collection.book(1).is_err());
+}
+
+#[test]
+fn legacy_free_enterprise_and_exempt_features_keep_their_paths() {
+ let user = MacroUserIdStr::try_from("macro|[email protected]").unwrap();
+ let mut entitlement = Entitlement::personal(user, PlanTier::Premium);
+ assert_eq!(
+ accounting_route(UsagePolicy::Legacy, AiFeature::Chat, &entitlement),
+ AccountingRoute::Legacy
+ );
+ assert_eq!(
+ accounting_route(
+ UsagePolicy::PublicAllowanceV1,
+ AiFeature::Chat,
+ &entitlement
+ ),
+ AccountingRoute::PublicAllowanceV1
+ );
+ for feature in NON_BILLABLE_AI_FEATURES {
+ assert_eq!(
+ accounting_route(UsagePolicy::PublicAllowanceV1, feature, &entitlement),
+ AccountingRoute::ExemptFeature
+ );
+ }
+ entitlement.tier = PlanTier::Free;
+ assert_eq!(
+ accounting_route(
+ UsagePolicy::PublicAllowanceV1,
+ AiFeature::Chat,
+ &entitlement
+ ),
+ AccountingRoute::Unmetered
+ );
+ entitlement.tier = PlanTier::Max;
+ entitlement.unlimited = true;
+ assert_eq!(
+ accounting_route(
+ UsagePolicy::PublicAllowanceV1,
+ AiFeature::Chat,
+ &entitlement
+ ),
+ AccountingRoute::Unmetered
+ );
+ assert_eq!(PlanTier::Premium.monthly_price_cents(), 4_000);
+ assert_eq!(PlanTier::Max.included_ai_cents_per_seat(), 20_000);
+ assert_eq!(super::super::models::list_rate_cents(1.0), 250);
+ let mut auth = authorization(true);
+ auth.policy = UsagePolicy::Legacy;
+ assert!(matches!(
+ reserve(
+ auth,
+ AllocationSequence::from_raw(0),
+ public_cents(100),
+ availability(ZERO_PUBLIC, ZERO_MONEY)
+ ),
+ Err(PolicyError::WrongPolicy)
+ ));
+}
diff --git a/crates/ai_billing/src/domain/ports.rs b/crates/ai_billing/src/domain/ports.rs
index 2a94421f90..4785becea3 100644
--- a/crates/ai_billing/src/domain/ports.rs
+++ b/crates/ai_billing/src/domain/ports.rs
@@ -1,16 +1,53 @@
//! Ports: what the billing service needs from the outside world, and what it
//! offers inbound adapters.
+use super::financial::FundingPeriod;
use super::ledger::SettlementPolicy;
use super::models::{
AllowanceDecision, AllowanceStore, BillingPeriod, BillingSettings, Entitlement,
OpenPeriodStart, OverageChargeStatus, PeriodAllowance, PeriodLedger, Result, SeatAllowance,
SeatGeneration, SeatUsage, SubscriptionScope, UsageSnapshot,
};
+use super::policy::UsageAllocation;
+use ai_usage::domain::financial::{
+ BeginInvocation, FundingAuthorization, InvocationId, InvocationRecord, PendingInvocations,
+ RateSnapshot,
+};
+use ai_usage::domain::ports::FinancialFuture;
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
+/// Durable V1 funding transactions. All mutations serialize on the existing payer
+/// account row, including legacy settlement, settings and credit purchases. Replays
+/// compare immutable request/rate/authorization/evidence facts before returning success.
+pub trait FundingRepo: Send + Sync + 'static {
+ /// Resolve the recorded seat policy at occurrence time, never today's role/catalog.
+ fn period(
+ &self,
+ seat: MacroUserIdStr<'static>,
+ at: DateTime<Utc>,
+ ) -> FinancialFuture<'_, Option<FundingPeriod>>;
+ /// Insert immutable verified facts. Reject overlapping or contradictory bindings.
+ fn record_period(&self, period: FundingPeriod) -> FinancialFuture<'_, ()>;
+ /// Reserve the entire execution ceiling before acknowledging authorization.
+ /// Funding denials are durable for this identity: later purchases/settings require
+ /// a new attempt ID, never retroactive authorization of blocked history.
+ fn authorize(
+ &self,
+ request: BeginInvocation,
+ rate: RateSnapshot,
+ ) -> FinancialFuture<'_, FundingAuthorization>;
+ /// Persist handoff once, then allocate in payer sequence, not completion order.
+ fn finalize(&self, record: InvocationRecord) -> FinancialFuture<'_, ()>;
+ /// Read recorded source consumption, never recalculate from current settings.
+ fn allocation(&self, id: InvocationId) -> FinancialFuture<'_, Option<UsageAllocation>>;
+ /// Discover unresolved and ready-but-unallocated work, including old periods.
+ fn pending(&self, query: PendingInvocations) -> FinancialFuture<'_, Vec<InvocationId>>;
+ /// Process a bounded prefix at the allocation watermark; unresolved work retains holds.
+ fn reconcile(&self, payer: MacroUserIdStr<'static>) -> FinancialFuture<'_, ()>;
+}
+
/// Resolves who a user is billed as.
pub trait EntitlementSource: Send + Sync + 'static {
/// The user's plan, payer, and billed seats.
@@ -71,6 +108,15 @@ pub struct SettlementOutcome {
/// The billing tables.
pub trait BillingRepo: Send + Sync + 'static {
+ /// Exclude recorded V1 seats from legacy analytics/settlement for this period.
+ /// A mixed-policy payer must retain only its legacy seats on this path.
+ fn legacy_seats(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ period: BillingPeriod,
+ seats: Vec<SeatAllowance>,
+ ) -> impl Future<Output = Result<Vec<SeatAllowance>>> + Send;
+
/// The payer's settings (defaults when no row exists).
fn settings(
&self,
@@ -85,7 +131,9 @@ pub trait BillingRepo: Send + Sync + 'static {
limit_cents: i64,
) -> impl Future<Output = Result<()>> + Send;
- /// Record the subscription period synced from Stripe.
+ /// Record the legacy subscription anchor synced from Stripe. A correction
+ /// to the current start's end is allowed; older/overlapping starts cannot
+ /// replace it. This does not rewrite allowance or financial period history.
fn set_period(
&self,
payer: &MacroUserIdStr<'_>,
@@ -303,7 +351,12 @@ impl SettlementTrigger for NoOpSettlementTrigger {
fn request_settlement(&self, _payer: MacroUserIdStr<'static>) {}
}
-/// The use cases offered to inbound adapters and other services.
+/// Existing billing use cases offered to inbound adapters and other services.
+///
+/// Admission and aggregate settlement here retain legacy semantics. Activated
+/// public-allowance traffic must instead use the awaited financial funding port
+/// (`ai_usage::domain::ports::InvocationFunding`) backed by the reservation and
+/// allocation rules in [`super::policy`]. It must never also enter legacy settlement.
pub trait BillingService: Send + Sync + 'static {
/// May `user` start another AI request?
///
@@ -359,12 +412,14 @@ pub trait BillingService: Send + Sync + 'static {
stripe_reference: &str,
) -> impl Future<Output = Result<()>> + Send;
- /// Record the payer's subscription period (webhook).
+ /// Record the payer's explicit subscription interval. Optional verified item
+ /// facts feed the gated renewal use case; bare anchors remain legacy-only.
fn sync_period(
&self,
payer: &MacroUserIdStr<'_>,
start: DateTime<Utc>,
end: DateTime<Utc>,
+ verified: Option<super::period::SubscriptionPeriod>,
) -> impl Future<Output = Result<()>> + Send;
/// Record the outcome of an overage invoice (webhook). Unknown invoices
diff --git a/crates/ai_billing/src/domain/service.rs b/crates/ai_billing/src/domain/service.rs
index 8c40607fe6..8fd5ec5823 100644
--- a/crates/ai_billing/src/domain/service.rs
+++ b/crates/ai_billing/src/domain/service.rs
@@ -11,14 +11,16 @@ use super::models::{
OVERAGE_LIMIT_MIN_CENTS, OverageChargeStatus, PayerScope, PeriodAllowance, PlanTier, Result,
SeatAllowance, SeatUsage, SubscriptionScope, UsageSnapshot,
};
+use super::period::{PeriodSync, SubscriptionPeriod};
use super::ports::{
BillingRepo, BillingService, CreditCheckoutRequest, EntitlementSource, OverageChargeRequest,
PaymentGateway, PendingCharge, UsageReader,
};
use chrono::{DateTime, Utc};
use macro_env::Environment;
-use macro_user_id::user_id::MacroUserIdStr;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use macro_uuid::Uuid;
+use std::sync::Arc;
use teams::domain::open_seat_release::OpenSeatRelease;
/// The billing service over its four ports.
@@ -29,6 +31,7 @@ pub struct BillingServiceImpl<E, U, R, P> {
repo: R,
payments: P,
environment: Environment,
+ period_sync: Option<Arc<dyn PeriodSync>>,
}
impl<E, U, R, P> BillingServiceImpl<E, U, R, P> {
@@ -40,8 +43,16 @@ impl<E, U, R, P> BillingServiceImpl<E, U, R, P> {
repo,
payments,
environment,
+ period_sync: None,
}
}
+
+ /// Install verified renewal activation at the composition root only after the
+ /// producer and rollout gates pass. Absence never authorizes the new policy.
+ pub fn with_period_sync(mut self, period_sync: Arc<dyn PeriodSync>) -> Self {
+ self.period_sync = Some(period_sync);
+ self
+ }
}
/// Everything resolved for one user at one instant.
@@ -184,7 +195,15 @@ where
.usage
.list_rate_usage_cents_by_user(&users, *period)
.await?;
- let used = usage_for(user, &usage);
+ let seats = self
+ .repo
+ .legacy_seats(&entitlement.payer, *period, seats)
+ .await?;
+ let used = if seats.iter().any(|seat| seat.user.as_ref() == user.as_ref()) {
+ usage_for(user, &usage)
+ } else {
+ 0
+ };
let chargeable = chargeable_usage_cents(&seats, &usage);
let ledger = self
.repo
@@ -252,6 +271,13 @@ where
.usage
.list_rate_usage_cents_by_user(&users, period)
.await?;
+ // Read policy AFTER analytics. V1 execution requires a committed binding,
+ // so any V1 analytics just observed must now be excluded. Filtering before
+ // the usage read would race renewal activation and could double bill.
+ let seats = self
+ .repo
+ .legacy_seats(&entitlement.payer, period, seats)
+ .await?;
let chargeable_cents = chargeable_usage_cents(&seats, &usage);
if chargeable_cents == 0 {
return Ok(());
@@ -576,11 +602,23 @@ where
payer: &MacroUserIdStr<'_>,
start: DateTime<Utc>,
end: DateTime<Utc>,
+ verified: Option<SubscriptionPeriod>,
) -> Result<()> {
if start >= end {
tracing::warn!("ignoring inverted subscription period");
return Ok(());
}
+ if let Some(facts) = verified {
+ if facts.period != (BillingPeriod { start, end }) {
+ tracing::warn!("ignoring mismatched verified subscription period");
+ return Ok(());
+ }
+ if let Some(sync) = &self.period_sync {
+ sync.sync(payer.clone().into_owned(), facts).await?;
+ }
+ // Item-level policy periods do not change the legacy payer anchor.
+ return Ok(());
+ }
self.repo.set_period(payer, start, end).await
}
diff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rs
index 65c86648c8..7f56af64db 100644
--- a/crates/ai_billing/src/domain/service/test.rs
+++ b/crates/ai_billing/src/domain/service/test.rs
@@ -156,6 +156,7 @@ struct RepoState {
suspended: bool,
allowances: HashMap<DateTime<Utc>, PeriodAllowance>,
releases: Vec<(String, DateTime<Utc>, String)>,
+ activated_seats: Vec<String>,
}
impl RepoState {
@@ -206,6 +207,22 @@ impl FakeRepo {
}
impl BillingRepo for FakeRepo {
+ async fn legacy_seats(
+ &self,
+ _payer: &MacroUserIdStr<'_>,
+ _period: BillingPeriod,
+ mut seats: Vec<SeatAllowance>,
+ ) -> Result<Vec<SeatAllowance>> {
+ let state = self.state.lock().unwrap();
+ seats.retain(|seat| {
+ !state
+ .activated_seats
+ .iter()
+ .any(|user| user == seat.user.as_ref())
+ });
+ Ok(seats)
+ }
+
async fn settings(&self, _payer: &MacroUserIdStr<'_>) -> Result<BillingSettings> {
let s = self.state.lock().unwrap();
let mut settings = s.settings.clone();
@@ -488,6 +505,68 @@ impl PaymentGateway for FakePayments {
}
}
+#[derive(Default)]
+struct FakePeriodSync(Mutex<Vec<SubscriptionPeriod>>);
+
+impl PeriodSync for FakePeriodSync {
+ fn sync<'a>(
+ &'a self,
+ _payer: MacroUserIdStr<'static>,
+ observation: SubscriptionPeriod,
+ ) -> std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
+ Box::pin(async move {
+ self.0.lock().unwrap().push(observation);
+ Ok(())
+ })
+ }
+}
+
+#[tokio::test]
+async fn period_sync_is_gated_and_never_calls_payments_or_changes_item_anchors() {
+ let (svc, repo, payments, _) = premium_service(0);
+ let payer = user("[email protected]");
+ let start = Utc::now();
+ let end = start + chrono::Duration::days(31);
+ let facts = SubscriptionPeriod {
+ event_id: "evt_period".parse().unwrap(),
+ event_at: start,
+ subscription_id: "sub_verified".parse().unwrap(),
+ subscription_created_at: start,
+ customer_id: "cus_123".parse().unwrap(),
+ team_id: None,
+ quantity: 1,
+ item_count: 1,
+ item_id: "si_verified".parse().unwrap(),
+ price_id: "price_verified".parse().unwrap(),
+ product_id: "prod_verified".parse().unwrap(),
+ unit_amount: Some(4000),
+ currency: "usd".into(),
+ monthly: true,
+ activity: super::super::period::SubscriptionActivity::Active,
+ period: BillingPeriod { start, end },
+ evidence: super::super::period::PeriodEvidence::Initial,
+ };
+ svc.sync_period(&payer, start, end, Some(facts.clone()))
+ .await
+ .unwrap();
+ assert!(repo.settings(&payer).await.unwrap().period_anchor.is_none());
+ let sync = Arc::new(FakePeriodSync::default());
+ let svc = svc.with_period_sync(sync.clone());
+ svc.sync_period(&payer, start, end, None).await.unwrap();
+ assert!(sync.0.lock().unwrap().is_empty());
+ svc.sync_period(&payer, start, end, Some(facts.clone()))
+ .await
+ .unwrap();
+ assert_eq!(*sync.0.lock().unwrap(), vec![facts.clone()]);
+ svc.sync_period(&payer, start, end + chrono::Duration::days(1), Some(facts))
+ .await
+ .unwrap();
+ assert_eq!(sync.0.lock().unwrap().len(), 1);
+ assert!(payments.opened().is_empty());
+ assert!(payments.payments().is_empty());
+ assert!(payments.checkouts.lock().unwrap().is_empty());
+}
+
type Service = BillingServiceImpl<FakeEntitlements, FakeUsage, FakeRepo, FakePayments>;
fn premium_service(used_cents: i64) -> (Service, FakeRepo, FakePayments, FakeUsage) {
@@ -522,6 +601,59 @@ fn premium_service_in(
)
}
+#[tokio::test]
+async fn recorded_new_policy_never_enters_legacy_analytics_settlement() {
+ let (svc, repo, payments, _) = premium_service(100_000);
+ let payer = user("[email protected]");
+ {
+ let mut state = repo.state.lock().unwrap();
+ state.activated_seats.push(payer.as_ref().to_owned());
+ state.balance = 10_000;
+ state.settings.overage_enabled = true;
+ state.settings.overage_limit_cents = 10_000;
+ }
+ svc.settle(&payer).await.unwrap();
+ assert!(repo.state.lock().unwrap().consumed.is_empty());
+ assert!(repo.charges().is_empty());
+ assert!(payments.opened().is_empty());
+ assert_eq!(repo.state.lock().unwrap().balance, 10_000);
+}
+
+#[tokio::test]
+async fn policy_activation_during_analytics_read_cannot_double_bill() {
+ struct ActivatingUsage(FakeRepo);
+ impl UsageReader for ActivatingUsage {
+ async fn list_rate_usage_cents_by_user(
+ &self,
+ users: &[MacroUserIdStr<'static>],
+ _period: BillingPeriod,
+ ) -> Result<Vec<SeatUsage>> {
+ self.0.state.lock().unwrap().activated_seats =
+ users.iter().map(ToString::to_string).collect();
+ Ok(users
+ .iter()
+ .map(|user| SeatUsage {
+ user: user.clone(),
+ used_cents: 100_000,
+ })
+ .collect())
+ }
+ }
+ let (svc, repo, payments, _) = premium_service(0);
+ repo.state.lock().unwrap().balance = 10_000;
+ let svc = BillingServiceImpl::new(
+ svc.entitlements,
+ ActivatingUsage(repo.clone()),
+ repo.clone(),
+ payments.clone(),
+ Environment::Develop,
+ );
+ svc.settle(&user("[email protected]")).await.unwrap();
+ assert!(repo.state.lock().unwrap().consumed.is_empty());
+ assert!(repo.charges().is_empty());
+ assert!(payments.opened().is_empty());
+}
+
#[tokio::test]
async fn allows_within_allowance_and_denies_past_it() {
let (svc, _, _, usage) = premium_service(3_000);
@@ -574,7 +706,7 @@ async fn outside_dev_preserves_credits_and_never_reserves_or_collects_overage()
let (mut svc, repo, payments, usage, _, payer, previous, current) =
anchored_premium(1_000_000);
svc.environment = environment;
- svc.sync_period(&payer, current.start, current.end)
+ svc.sync_period(&payer, current.start, current.end, None)
.await
.unwrap();
usage.add(
@@ -1057,12 +1189,25 @@ async fn synced_period_anchors_the_snapshot() {
let payer = user("[email protected]");
let start = Utc::now() - chrono::Duration::days(3);
let end = start + chrono::Duration::days(30);
- svc.sync_period(&payer, start, end).await.unwrap();
+ svc.sync_period(&payer, start, end, None).await.unwrap();
let snap = svc.snapshot(&payer).await.unwrap();
assert_eq!(snap.period_start, start);
assert_eq!(snap.period_end, end);
+ for corrected in [
+ end + chrono::Duration::days(2),
+ end - chrono::Duration::days(2),
+ ] {
+ svc.sync_period(&payer, start, corrected, None)
+ .await
+ .unwrap();
+ let snapshot = svc.snapshot(&payer).await.unwrap();
+ assert_eq!(
+ (snapshot.period_start, snapshot.period_end),
+ (start, corrected)
+ );
+ }
// Inverted periods are ignored.
- svc.sync_period(&payer, end, start).await.unwrap();
+ svc.sync_period(&payer, end, start, None).await.unwrap();
assert_eq!(svc.snapshot(&payer).await.unwrap().period_start, start);
}
@@ -1108,7 +1253,7 @@ fn anchored_premium(
#[tokio::test]
async fn snapshot_freezes_the_open_period_allowance_and_refreshes_it() {
let (svc, repo, _, _, ents, payer, _, current) = anchored_premium(0);
- svc.sync_period(&payer, current.start, current.end)
+ svc.sync_period(&payer, current.start, current.end, None)
.await
.unwrap();
svc.snapshot(&payer).await.unwrap();
@@ -1132,7 +1277,7 @@ async fn snapshot_freezes_the_open_period_allowance_and_refreshes_it() {
#[tokio::test]
async fn previous_period_overage_survives_an_upgrade() {
let (svc, repo, payments, usage, ents, payer, previous, current) = anchored_premium(0);
- svc.sync_period(&payer, current.start, current.end)
+ svc.sync_period(&payer, current.start, current.end, None)
.await
.unwrap();
repo.freeze(
@@ -1169,7 +1314,7 @@ async fn previous_period_overage_survives_an_upgrade() {
#[tokio::test]
async fn previous_period_does_not_charge_included_usage_after_a_downgrade() {
let (svc, repo, payments, usage, ents, payer, previous, current) = anchored_premium(0);
- svc.sync_period(&payer, current.start, current.end)
+ svc.sync_period(&payer, current.start, current.end, None)
.await
.unwrap();
repo.freeze(
@@ -1229,7 +1374,7 @@ async fn previous_period_usage_uses_the_frozen_billed_users() {
end: current_end,
};
let previous = current.previous();
- svc.sync_period(&owner, current.start, current.end)
+ svc.sync_period(&owner, current.start, current.end, None)
.await
.unwrap();
repo.freeze(
@@ -1269,7 +1414,7 @@ async fn previous_period_usage_uses_the_frozen_billed_users() {
#[tokio::test]
async fn current_period_uses_the_live_allowance_after_an_upgrade() {
let (svc, repo, payments, usage, ents, payer, previous, current) = anchored_premium(0);
- svc.sync_period(&payer, current.start, current.end)
+ svc.sync_period(&payer, current.start, current.end, None)
.await
.unwrap();
repo.freeze(
diff --git a/crates/ai_billing/src/outbound.rs b/crates/ai_billing/src/outbound.rs
index 520be79436..3fcea3d6c7 100644
--- a/crates/ai_billing/src/outbound.rs
+++ b/crates/ai_billing/src/outbound.rs
@@ -4,6 +4,7 @@
pub mod entitlement;
pub mod http_settlement_trigger;
pub mod pg_billing_repo;
+pub mod pg_funding_repo;
pub mod pg_usage_reader;
pub mod settling_recorder;
pub mod stripe_gateway;
@@ -11,6 +12,7 @@ pub mod stripe_gateway;
pub use entitlement::RolesTeamsEntitlementSource;
pub use http_settlement_trigger::HttpSettlementTrigger;
pub use pg_billing_repo::PgBillingRepo;
+pub use pg_funding_repo::PgFundingRepo;
pub use pg_usage_reader::PgUsageReader;
pub use settling_recorder::SettlingUsageRecorder;
pub use stripe_gateway::{NoOpPaymentGateway, StripePaymentGateway};
diff --git a/crates/ai_billing/src/outbound/entitlement.rs b/crates/ai_billing/src/outbound/entitlement.rs
index b0d704f2e1..3d65a3e831 100644
--- a/crates/ai_billing/src/outbound/entitlement.rs
+++ b/crates/ai_billing/src/outbound/entitlement.rs
@@ -1,5 +1,6 @@
//! Resolves a user's plan and payer from their roles and team membership.
+use crate::domain::period::{PeriodBindingSource, SubscriptionPeriod};
use crate::domain::{BillingError, Entitlement, EntitlementSource, PayerScope, PlanTier, Result};
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
@@ -48,6 +49,88 @@ where
}
}
+impl<P, T> PeriodBindingSource for RolesTeamsEntitlementSource<P, T>
+where
+ P: UserRolesAndPermissionsService,
+ T: TeamRepository,
+{
+ async fn seats(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ observation: &SubscriptionPeriod,
+ ) -> Result<Option<Vec<MacroUserIdStr<'static>>>> {
+ // The user/customer mapping is unique in the owning domain. Email is only
+ // an existing webhook candidate, never sufficient evidence of ownership.
+ let customer = self
+ .teams
+ .get_stripe_customer_id(payer)
+ .await
+ .map_err(entitlement_err)?;
+ if customer.as_ref().map(|id| id.as_str()) != Some(observation.customer_id.as_str()) {
+ return Ok(None);
+ }
+ let Some(team_id) = observation.team_id else {
+ if observation.quantity != 1 || observation.item_count != 1 {
+ return Ok(None);
+ }
+ // Do not bind a personal subscription to a seat currently billed by
+ // another subscription. This uses team facts, not role fallback.
+ for team in self
+ .teams
+ .get_user_teams(payer)
+ .await
+ .map_err(entitlement_err)?
+ {
+ if team.enterprise()
+ || self
+ .teams
+ .get_team_subscription_id(team.id())
+ .await
+ .map_err(entitlement_err)?
+ .is_some()
+ {
+ return Ok(None);
+ }
+ }
+ return Ok(Some(vec![payer.clone().into_owned()]));
+ };
+ let owner = match self.teams.get_team_owner(&team_id).await {
+ Ok(owner) => owner,
+ Err(TeamError::TeamDoesNotExist) => return Ok(None),
+ Err(error) => return Err(entitlement_err(error)),
+ };
+ let subscription = self
+ .teams
+ .get_team_subscription_id(&team_id)
+ .await
+ .map_err(entitlement_err)?;
+ if owner.as_ref() != payer.as_ref()
+ || subscription.as_ref().map(|id| id.as_str())
+ != Some(observation.subscription_id.as_str())
+ || self
+ .teams
+ .get_team_enterprise_status(&team_id)
+ .await
+ .map_err(entitlement_err)?
+ {
+ return Ok(None);
+ }
+ let seats: Vec<_> = self
+ .teams
+ .get_team_members(&team_id)
+ .await
+ .map_err(entitlement_err)?
+ .into_iter()
+ .filter(|member| member.plan == teams::domain::model::SeatPlan::Premium)
+ .map(|member| member.user_id.into_owned())
+ .collect();
+ if seats.is_empty() || seats.len() as u64 > observation.quantity {
+ return Ok(None);
+ }
+ Ok(Some(seats))
+ }
+}
+
impl<P, T> EntitlementSource for RolesTeamsEntitlementSource<P, T>
where
P: UserRolesAndPermissionsService,
diff --git a/crates/ai_billing/src/outbound/pg_billing_repo.rs b/crates/ai_billing/src/outbound/pg_billing_repo.rs
index 09f24301e7..57556c708e 100644
--- a/crates/ai_billing/src/outbound/pg_billing_repo.rs
+++ b/crates/ai_billing/src/outbound/pg_billing_repo.rs
@@ -4,6 +4,8 @@
#[cfg(test)]
mod test;
+use super::pg_funding_repo::{credit_commitments, lock_payer, postpaid_commitments};
+use crate::domain::financial::legacy_cap_remaining;
use crate::domain::{
AllowanceStore, BillingError, BillingRepo, BillingSettings, OpenPeriodStart,
OverageChargeStatus, PendingCharge, PeriodAllowance, PeriodLedger, Result, SeatAllowance,
@@ -32,7 +34,37 @@ fn storage(e: sqlx::Error) -> BillingError {
BillingError::Storage(e.into())
}
+fn funding_storage(e: ai_usage::domain::financial::FinancialError) -> BillingError {
+ BillingError::Storage(anyhow::anyhow!(e))
+}
+
impl BillingRepo for PgBillingRepo {
+ async fn legacy_seats(
+ &self,
+ _payer: &MacroUserIdStr<'_>,
+ period: crate::domain::BillingPeriod,
+ mut seats: Vec<SeatAllowance>,
+ ) -> Result<Vec<SeatAllowance>> {
+ let users: Vec<_> = seats
+ .iter()
+ .map(|seat| seat.user.as_ref().to_owned())
+ .collect();
+ // Exclude even a historical binding to another payer: changing membership
+ // must never route V1 analytics into a new owner's legacy settlement.
+ let activated = sqlx::query_scalar!(
+ "SELECT user_id FROM ai_billing_usage_period WHERE user_id = ANY($1)
+ AND policy = 'public_allowance_v1' AND period_start < $3 AND period_end > $2",
+ &users,
+ period.start,
+ period.end,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(storage)?;
+ seats.retain(|seat| !activated.iter().any(|user| user == seat.user.as_ref()));
+ Ok(seats)
+ }
+
async fn settings(&self, payer: &MacroUserIdStr<'_>) -> Result<BillingSettings> {
let row = sqlx::query!(
r#"
@@ -98,6 +130,11 @@ impl BillingRepo for PgBillingRepo {
SET period_start = EXCLUDED.period_start,
period_end = EXCLUDED.period_end,
updated_at = NOW()
+ WHERE ai_billing_account.period_start IS NULL
+ OR (EXCLUDED.period_start > ai_billing_account.period_start
+ AND EXCLUDED.period_start >= ai_billing_account.period_end)
+ OR (EXCLUDED.period_start = ai_billing_account.period_start
+ AND EXCLUDED.period_end > EXCLUDED.period_start)
"#,
payer.as_ref(),
start,
@@ -333,6 +370,10 @@ impl BillingRepo for PgBillingRepo {
stripe_reference: &str,
) -> Result<bool> {
let id = macro_uuid::generate_uuid_v7();
+ let mut tx = self.pool.begin().await.map_err(storage)?;
+ lock_payer(&mut tx, payer.as_ref())
+ .await
+ .map_err(funding_storage)?;
let result = sqlx::query!(
r#"
INSERT INTO ai_credit_ledger (id, user_id, kind, delta_cents, stripe_reference, note)
@@ -344,9 +385,10 @@ impl BillingRepo for PgBillingRepo {
amount_cents,
stripe_reference,
)
- .execute(&self.pool)
+ .execute(&mut *tx)
.await
.map_err(storage)?;
+ tx.commit().await.map_err(storage)?;
Ok(result.rows_affected() == 1)
}
@@ -395,6 +437,16 @@ impl BillingRepo for PgBillingRepo {
.fetch_one(&mut *tx)
.await
.map_err(storage)?;
+ let commitments = credit_commitments(&mut tx, payer)
+ .await
+ .map_err(funding_storage)?;
+ let balance = commitments
+ .legacy_available_cents(balance)
+ .map_err(funding_storage)?;
+ let committed_postpaid = postpaid_commitments(&mut tx, payer, period_start)
+ .await
+ .map_err(funding_storage)?;
+ let legacy_limit = legacy_cap_remaining(account.overage_limit_cents, committed_postpaid);
let ledger = read_period_ledger(&mut tx, payer, period_start).await?;
let overage_active = account.overage_enabled
&& account.overage_suspended_at.is_none()
@@ -409,7 +461,7 @@ impl BillingRepo for PgBillingRepo {
},
SettlementPolicy {
overage_active,
- overage_limit_cents: account.overage_limit_cents,
+ overage_limit_cents: legacy_limit,
charge_threshold_cents: policy.charge_threshold_cents,
period_ended: policy.period_ended,
},
@@ -444,6 +496,7 @@ impl BillingRepo for PgBillingRepo {
FROM ai_overage_charge
WHERE user_id = $1
AND period_start = $2
+ AND accounting_policy = 'legacy'
AND (
status = 'failed'
OR (
@@ -618,6 +671,7 @@ async fn read_period_ledger(
SELECT COALESCE(-SUM(delta_cents), 0)::bigint AS "consumed!"
FROM ai_credit_ledger
WHERE user_id = $1 AND kind = 'consumption' AND period_start = $2
+ AND funding_invocation_id IS NULL
"#,
payer,
period_start,
@@ -631,6 +685,7 @@ async fn read_period_ledger(
FROM ai_overage_charge
WHERE user_id = $1
AND period_start = $2
+ AND accounting_policy = 'legacy'
AND (status <> 'failed' OR stripe_invoice_id IS NOT NULL)
"#,
payer,
diff --git a/crates/ai_billing/src/outbound/pg_billing_repo/test.rs b/crates/ai_billing/src/outbound/pg_billing_repo/test.rs
index 68934a21e9..ba735dcc26 100644
--- a/crates/ai_billing/src/outbound/pg_billing_repo/test.rs
+++ b/crates/ai_billing/src/outbound/pg_billing_repo/test.rs
@@ -7,6 +7,47 @@ fn payer() -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn legacy_anchor_accepts_end_corrections_but_not_stale_or_overlapping_starts(pool: PgPool) {
+ let repo = PgBillingRepo::new(pool);
+ let start = DateTime::from_timestamp(1_800_000_000, 0).unwrap();
+ let end = start + chrono::Duration::days(30);
+ repo.set_period(&payer(), start, end).await.unwrap();
+ for corrected in [
+ end + chrono::Duration::days(2),
+ end - chrono::Duration::days(2),
+ ] {
+ repo.set_period(&payer(), start, corrected).await.unwrap();
+ assert_eq!(
+ repo.settings(&payer()).await.unwrap().period_anchor,
+ Some((start, corrected))
+ );
+ for stale_start in [
+ start - chrono::Duration::days(30),
+ start + chrono::Duration::days(1),
+ ] {
+ repo.set_period(&payer(), stale_start, end).await.unwrap();
+ assert_eq!(
+ repo.settings(&payer()).await.unwrap().period_anchor,
+ Some((start, corrected))
+ );
+ }
+ }
+ let next_start = end;
+ let next_end = end + chrono::Duration::days(30);
+ repo.set_period(&payer(), next_start, next_end)
+ .await
+ .unwrap();
+ // A delayed correction for the old period must not rewind the new anchor.
+ repo.set_period(&payer(), start, end + chrono::Duration::days(1))
+ .await
+ .unwrap();
+ assert_eq!(
+ repo.settings(&payer()).await.unwrap().period_anchor,
+ Some((next_start, next_end))
+ );
+}
+
fn policy(period_ended: bool) -> SettlementPolicy {
SettlementPolicy {
overage_active: true,
diff --git a/crates/ai_billing/src/outbound/pg_funding_repo.rs b/crates/ai_billing/src/outbound/pg_funding_repo.rs
new file mode 100644
index 0000000000..966738bba0
--- /dev/null
+++ b/crates/ai_billing/src/outbound/pg_funding_repo.rs
@@ -0,0 +1,817 @@
+//! Durable funding adapter. Policy transitions live in the domain; this adapter
+//! owns locking, immutable replay checks and atomic persistence of their results.
+
+use ai_usage::domain::financial::*;
+use ai_usage::domain::financial_service::validate_final_record;
+use ai_usage::domain::ports::FinancialFuture;
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+use sqlx::{PgConnection, PgPool, types::Json};
+
+use crate::domain::financial::*;
+use crate::domain::models::{BillingPeriod, UsagePolicy};
+use crate::domain::period::{
+ self, ActivationException, EligibilityState, PeriodDecision, PeriodRepo, SeatPeriodObservation,
+ UsageRollout,
+};
+use crate::domain::policy::*;
+use crate::domain::ports::FundingRepo;
+
+#[cfg(test)]
+mod test;
+
+/// Postgres funding persistence, constructed only at composition roots.
+#[derive(Clone)]
+pub struct PgFundingRepo {
+ pool: PgPool,
+}
+
+impl PgFundingRepo {
+ /// Share the same database/payer account lock as `PgBillingRepo`.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+/// Serialize purchases, settings, legacy settlement and funding on the account row.
+/// Account upserts/updates inherently acquire this same row lock.
+pub(super) async fn lock_payer(conn: &mut PgConnection, payer: &str) -> FinancialResult<()> {
+ sqlx::query!(
+ "INSERT INTO ai_billing_account (user_id) VALUES ($1) ON CONFLICT DO NOTHING",
+ payer,
+ )
+ .execute(&mut *conn)
+ .await?;
+ sqlx::query!(
+ "SELECT user_id FROM ai_billing_account WHERE user_id = $1 FOR UPDATE",
+ payer
+ )
+ .fetch_one(conn)
+ .await?;
+ Ok(())
+}
+
+fn units(value: i64) -> FinancialResult<u64> {
+ u64::try_from(value).map_err(|_| FinancialError::ArithmeticOverflow)
+}
+
+fn db_units(value: u64) -> FinancialResult<i64> {
+ i64::try_from(value).map_err(|_| FinancialError::ArithmeticOverflow)
+}
+
+fn conflict(id: InvocationId, phase: ReplayPhase) -> FinancialError {
+ FinancialError::ReplayConflict {
+ invocation_id: id,
+ phase,
+ }
+}
+
+/// Read exact money unavailable to legacy settlement as well as new admission.
+pub(super) async fn credit_commitments(
+ conn: &mut PgConnection,
+ payer: &str,
+) -> FinancialResult<CreditCommitments> {
+ let row = sqlx::query!(
+ r#"SELECT
+ COALESCE((SELECT prepaid_remainder FROM ai_funding_state WHERE user_id = $1), 0) AS "remainder!",
+ COALESCE((SELECT SUM(prepaid_hold)::bigint FROM ai_funding_reservation WHERE payer_id = $1 AND NOT allocated), 0) AS "held!",
+ COALESCE((SELECT SUM(units)::bigint FROM ai_funding_prepaid_release WHERE payer_id = $1), 0) AS "released!""#,
+ payer,
+ ).fetch_one(conn).await?;
+ Ok(CreditCommitments {
+ remainder: CustomerMoney::from_units(units(row.remainder)?),
+ held: CustomerMoney::from_units(units(row.held)?),
+ release_pool: CustomerMoney::from_units(units(row.released)?),
+ })
+}
+
+/// New-policy cap commitments are protected from legacy settlement, including holds.
+pub(super) async fn postpaid_commitments(
+ conn: &mut PgConnection,
+ payer: &str,
+ start: DateTime<Utc>,
+) -> FinancialResult<CustomerMoney> {
+ let amount = sqlx::query_scalar!(
+ r#"SELECT COALESCE(SUM(CASE WHEN allocated THEN postpaid ELSE postpaid_hold END), 0)::bigint AS "amount!"
+ FROM ai_funding_reservation WHERE payer_id = $1 AND period_start = $2"#,
+ payer, start,
+ ).fetch_one(conn).await?;
+ Ok(CustomerMoney::from_units(units(amount)?))
+}
+
+async fn read_period(
+ conn: &mut PgConnection,
+ seat: &str,
+ at: DateTime<Utc>,
+) -> FinancialResult<Option<FundingPeriod>> {
+ let row = sqlx::query!(
+ "SELECT user_id, payer_id, subscription_id, period_start, period_end, policy FROM ai_billing_usage_period
+ WHERE user_id = $1 AND period_start <= $2 AND period_end > $2",
+ seat, at,
+ ).fetch_optional(conn).await?;
+ row.map(|r| {
+ Ok(FundingPeriod {
+ seat: MacroUserIdStr::try_from(r.user_id)
+ .map_err(|_| FinancialError::InvalidIdentifier)?,
+ payer: MacroUserIdStr::try_from(r.payer_id)
+ .map_err(|_| FinancialError::InvalidIdentifier)?,
+ subscription: FundingSubscription::new(r.subscription_id)?,
+ period: BillingPeriod {
+ start: r.period_start,
+ end: r.period_end,
+ },
+ policy: match r.policy.as_str() {
+ "legacy" => UsagePolicy::Legacy,
+ "public_allowance_v1" => UsagePolicy::PublicAllowanceV1,
+ _ => return Err(FinancialError::FundingDenied),
+ },
+ })
+ })
+ .transpose()
+}
+
+impl PeriodRepo for PgFundingRepo {
+ async fn observe(
+ &self,
+ rollout: &UsageRollout,
+ observation: SeatPeriodObservation,
+ verified_binding: bool,
+ ) -> crate::domain::Result<PeriodDecision> {
+ self.observe_period(rollout, observation, verified_binding)
+ .await
+ .map_err(|error| crate::domain::BillingError::Storage(error.into()))
+ }
+}
+
+impl PgFundingRepo {
+ async fn observe_period(
+ &self,
+ rollout: &UsageRollout,
+ observation: SeatPeriodObservation,
+ verified_binding: bool,
+ ) -> FinancialResult<PeriodDecision> {
+ rollout.validate()?;
+ let facts = &observation.subscription;
+ let seat = observation.seat.as_ref();
+ let mut tx = self.pool.begin().await?;
+ sqlx::query!("INSERT INTO ai_billing_usage_rollout (policy, configuration) VALUES ('public_allowance_v1', $1) ON CONFLICT DO NOTHING", Json(rollout) as _)
+ .execute(&mut *tx).await?;
+ let configured = sqlx::query_scalar!(r#"SELECT configuration AS "configuration: Json<UsageRollout>" FROM ai_billing_usage_rollout WHERE policy = 'public_allowance_v1'"#)
+ .fetch_one(&mut *tx).await?;
+ if configured.0 != *rollout {
+ return Err(FinancialError::FundingDenied);
+ }
+ sqlx::query!(
+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 7404))",
+ seat
+ )
+ .execute(&mut *tx)
+ .await?;
+ let previous = sqlx::query!(r#"SELECT facts AS "facts: Json<SeatPeriodObservation>", decision AS "decision: Json<PeriodDecision>"
+ FROM ai_billing_usage_observation WHERE event_id = $1 AND user_id = $2 AND subscription_id = $3 AND item_id = $4"#,
+ facts.event_id.as_str(), seat, facts.subscription_id.as_str(), facts.item_id.as_str()).fetch_optional(&mut *tx).await?;
+ if let Some(previous) = previous {
+ if previous.facts.0 != observation {
+ return Err(FinancialError::FundingDenied);
+ }
+ return Ok(previous.decision.0);
+ }
+ // The item renewal proof is shared by its seats; acquire the payer lock
+ // before reading it so concurrent seat events cannot regress that proof.
+ if verified_binding {
+ lock_payer(&mut tx, observation.payer.as_ref()).await?;
+ }
+ let identity = json!({"payer": observation.payer.as_ref(), "customer": facts.customer_id,
+ "created": facts.subscription_created_at, "price": facts.price_id, "product": facts.product_id});
+ let stored = sqlx::query!(r#"SELECT identity, state AS "state: Json<EligibilityState>" FROM ai_billing_usage_eligibility
+ WHERE user_id = $1 AND subscription_id = $2 AND item_id = $3"#,
+ observation.payer.as_ref(), facts.subscription_id.as_str(), facts.item_id.as_str()).fetch_optional(&mut *tx).await?;
+ let identity_matches = stored.as_ref().is_none_or(|row| row.identity == identity);
+ let mut state = stored.map(|row| row.state.0).unwrap_or_default();
+ let mut decision = if verified_binding && identity_matches {
+ period::transition(rollout, facts, &mut state)
+ } else {
+ PeriodDecision::Exception(ActivationException::AmbiguousBinding)
+ };
+ if let Some(policy) = decision.policy() {
+ let period = FundingPeriod {
+ seat: observation.seat.clone(),
+ payer: observation.payer.clone(),
+ subscription: FundingSubscription::new(facts.subscription_id.as_str().to_owned())?,
+ period: facts.period,
+ policy,
+ };
+ period.validate()?;
+ let overlaps = sqlx::query_scalar!(r#"SELECT EXISTS(SELECT 1 FROM ai_billing_usage_period
+ WHERE user_id = $1 AND (period_start > $2 OR (period_start < $3 AND period_end > $2))) AS "exists!""#,
+ seat, facts.period.start, facts.period.end).fetch_one(&mut *tx).await?;
+ let existing = read_period(&mut tx, seat, facts.period.start).await?;
+ let legacy_in_use = sqlx::query_scalar!(r#"SELECT (
+ EXISTS(SELECT 1 FROM ai_billing_period_allowance WHERE user_id = $1 AND period_start = $2 AND $3 = ANY(billed_users))
+ OR EXISTS(SELECT 1 FROM ai_overage_charge WHERE user_id = $1 AND period_start = $2 AND accounting_policy = 'legacy')
+ OR EXISTS(SELECT 1 FROM ai_credit_ledger WHERE user_id = $1 AND period_start = $2 AND kind = 'consumption' AND funding_invocation_id IS NULL)
+ ) AS "used!""#, observation.payer.as_ref(), facts.period.start, seat)
+ .fetch_one(&mut *tx).await?;
+ decision = decision.preserve_legacy(existing.is_none() && legacy_in_use);
+ if overlaps && existing.as_ref() != Some(&period) {
+ decision = PeriodDecision::Exception(ActivationException::AmbiguousBinding);
+ } else if decision.policy().is_some() {
+ let policy = match policy {
+ UsagePolicy::Legacy => "legacy",
+ UsagePolicy::PublicAllowanceV1 => "public_allowance_v1",
+ };
+ sqlx::query!("INSERT INTO ai_billing_usage_period (user_id, payer_id, subscription_id, period_start, period_end, policy)
+ VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT DO NOTHING", seat, observation.payer.as_ref(), facts.subscription_id.as_str(),
+ facts.period.start, facts.period.end, policy).execute(&mut *tx).await?;
+ sqlx::query!("INSERT INTO ai_billing_usage_eligibility (user_id, subscription_id, item_id, identity, state)
+ VALUES ($1,$2,$3,$4,$5) ON CONFLICT (user_id, subscription_id, item_id) DO UPDATE SET state = EXCLUDED.state",
+ observation.payer.as_ref(), facts.subscription_id.as_str(), facts.item_id.as_str(), identity, Json(state) as _).execute(&mut *tx).await?;
+ }
+ }
+ sqlx::query!("INSERT INTO ai_billing_usage_observation (event_id, user_id, subscription_id, item_id, facts, decision)
+ VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT DO NOTHING", facts.event_id.as_str(), seat, facts.subscription_id.as_str(),
+ facts.item_id.as_str(), Json(&observation) as _, Json(&decision) as _).execute(&mut *tx).await?;
+ tx.commit().await?;
+ Ok(decision)
+ }
+}
+
+impl FundingRepo for PgFundingRepo {
+ fn period(
+ &self,
+ seat: MacroUserIdStr<'static>,
+ at: DateTime<Utc>,
+ ) -> FinancialFuture<'_, Option<FundingPeriod>> {
+ Box::pin(
+ async move { read_period(&mut *self.pool.acquire().await?, seat.as_ref(), at).await },
+ )
+ }
+
+ fn record_period(&self, period: FundingPeriod) -> FinancialFuture<'_, ()> {
+ Box::pin(async move {
+ period.validate()?;
+ let mut tx = self.pool.begin().await?;
+ // Serialize seat bindings across payer changes, then acquire the payer lock.
+ // This lock is not used by admission, which never mutates period bindings.
+ sqlx::query!(
+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 7404))",
+ period.seat.as_ref()
+ )
+ .execute(&mut *tx)
+ .await?;
+ lock_payer(&mut tx, period.payer.as_ref()).await?;
+ let overlap = sqlx::query_scalar!(
+ r#"SELECT EXISTS(SELECT 1 FROM ai_billing_usage_period
+ WHERE user_id = $1 AND period_start < $3 AND period_end > $2) AS "exists!""#,
+ period.seat.as_ref(),
+ period.period.start,
+ period.period.end,
+ )
+ .fetch_one(&mut *tx)
+ .await?;
+ if overlap {
+ if read_period(&mut tx, period.seat.as_ref(), period.period.start)
+ .await?
+ .as_ref()
+ != Some(&period)
+ {
+ return Err(FinancialError::FundingDenied);
+ }
+ return Ok(());
+ }
+ let policy = match period.policy {
+ UsagePolicy::Legacy => "legacy",
+ UsagePolicy::PublicAllowanceV1 => "public_allowance_v1",
+ };
+ sqlx::query!(
+ "INSERT INTO ai_billing_usage_period (user_id, payer_id, subscription_id, period_start, period_end, policy)
+ VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT DO NOTHING",
+ period.seat.as_ref(), period.payer.as_ref(), period.subscription.as_str(),
+ period.period.start, period.period.end, policy,
+ ).execute(&mut *tx).await?;
+ tx.commit().await?;
+ Ok(())
+ })
+ }
+
+ fn authorize(
+ &self,
+ request: BeginInvocation,
+ rate: RateSnapshot,
+ ) -> FinancialFuture<'_, FundingAuthorization> {
+ Box::pin(async move {
+ rate.require_model(&request.model)?;
+ let identity = admission_identity(&request, &rate);
+ let mut tx = self.pool.begin().await?;
+ // Lock a global invocation identity before resolving/locking its payer.
+ // This also serializes conflicting identities attributed to different payers.
+ sqlx::query!(
+ "INSERT INTO ai_funding_intent (invocation_id, identity) VALUES ($1, $2) ON CONFLICT DO NOTHING",
+ request.invocation_id.as_uuid(), identity,
+ ).execute(&mut *tx).await?;
+ let intent = sqlx::query!(
+ "SELECT identity, denied FROM ai_funding_intent WHERE invocation_id = $1 FOR UPDATE",
+ request.invocation_id.as_uuid(),
+ ).fetch_one(&mut *tx).await?;
+ if intent.identity != identity {
+ return Err(conflict(request.invocation_id, ReplayPhase::Begin));
+ }
+ if intent.denied {
+ return Err(FinancialError::FundingDenied);
+ }
+ let period = read_period(&mut tx, request.user.as_ref(), request.occurred_at).await?;
+ let Some(period) =
+ period.filter(|period| period.policy == UsagePolicy::PublicAllowanceV1)
+ else {
+ return reject(tx, request.invocation_id, FinancialError::FundingDenied).await;
+ };
+ lock_payer(&mut tx, period.payer.as_ref()).await?;
+ if let Some(row) = sqlx::query!(
+ r#"SELECT admission AS "admission: Json<AdmissionData>" FROM ai_funding_reservation WHERE invocation_id = $1"#,
+ request.invocation_id.as_uuid(),
+ ).fetch_optional(&mut *tx).await? {
+ if row.admission.identity != identity {
+ return Err(conflict(request.invocation_id, ReplayPhase::Begin));
+ }
+ return row.admission.authorization();
+ }
+ sqlx::query!(
+ "INSERT INTO ai_funding_state (user_id) VALUES ($1) ON CONFLICT DO NOTHING",
+ period.payer.as_ref()
+ )
+ .execute(&mut *tx)
+ .await?;
+ let account = sqlx::query!(
+ "SELECT a.overage_enabled, a.overage_limit_cents, a.overage_suspended_at, a.authorization_revision,
+ f.next_sequence FROM ai_billing_account a JOIN ai_funding_state f USING (user_id) WHERE a.user_id = $1",
+ period.payer.as_ref(),
+ ).fetch_one(&mut *tx).await?;
+ let settings = crate::domain::BillingSettings {
+ overage_enabled: account.overage_enabled,
+ overage_limit_cents: account.overage_limit_cents,
+ overage_suspended_at: account.overage_suspended_at,
+ ..Default::default()
+ };
+ let snapshot = AuthorizationSnapshot {
+ id: FundingAuthorizationId::new(),
+ invocation_id: request.invocation_id,
+ payer: period.payer.clone(),
+ seat: period.seat.clone(),
+ period: period.period,
+ policy: period.policy,
+ settings_revision: AuthorizationRevision::from_raw(units(
+ account.authorization_revision,
+ )?),
+ postpaid: PostpaidAuthorization::from_settings(&settings).map_err(funding_error)?,
+ };
+ let available = availability(&mut tx, &period).await?;
+ let maximum = rate.tokens.price(request.token_budget)?;
+ let reservation = match reserve(
+ snapshot,
+ AllocationSequence::from_raw(units(account.next_sequence)?),
+ maximum,
+ available,
+ ) {
+ Ok(reservation) => reservation,
+ Err(error) => return reject(tx, request.invocation_id, funding_error(error)).await,
+ };
+ let data = AdmissionData::new(identity, &reservation, available, &settings);
+ let funding = data.authorization()?;
+ let holds = reservation.holds();
+ // Validate the persistence range before acknowledging any execution.
+ db_units(maximum.units())?;
+ sqlx::query!(
+ "INSERT INTO ai_funding_reservation (invocation_id, authorization_id, payer_id, sequence, user_id, period_start,
+ admission, included_hold, prepaid_hold, postpaid_hold) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) ON CONFLICT DO NOTHING",
+ funding.invocation_id.as_uuid(), funding.id.as_uuid(), period.payer.as_ref(), account.next_sequence,
+ period.seat.as_ref(), period.period.start, Json(data) as _,
+ db_units(holds.included_public.units())?, db_units(holds.prepaid.units())?, db_units(holds.postpaid.units())?,
+ ).execute(&mut *tx).await?;
+ // A conflicting ID under another payer must not receive a new authorization.
+ let stored = sqlx::query!(
+ r#"SELECT admission AS "admission: Json<AdmissionData>" FROM ai_funding_reservation WHERE invocation_id = $1"#,
+ request.invocation_id.as_uuid(),
+ ).fetch_one(&mut *tx).await?;
+ if stored.admission.authorization()? != funding {
+ return Err(conflict(request.invocation_id, ReplayPhase::Begin));
+ }
+ sqlx::query!(
+ "UPDATE ai_funding_state SET next_sequence = next_sequence + 1 WHERE user_id = $1",
+ period.payer.as_ref()
+ )
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(funding)
+ })
+ }
+
+ fn finalize(&self, record: InvocationRecord) -> FinancialFuture<'_, ()> {
+ Box::pin(async move {
+ validate_final_record(&record)?;
+ let id = record.admission.request.invocation_id;
+ let identity = admission_identity(&record.admission.request, &record.admission.rate);
+ let completion = completion_identity(&record.state)?;
+ let actual = match record.state {
+ InvocationState::Priced { public_usage, .. } => {
+ Some(db_units(public_usage.units())?)
+ }
+ InvocationState::Unpriced { .. } | InvocationState::Unresolved { .. } => None,
+ _ => return Err(FinancialError::FundingDenied),
+ };
+ let mut tx = self.pool.begin().await?;
+ let row = sqlx::query!(
+ r#"SELECT payer_id, admission AS "admission: Json<AdmissionData>" FROM ai_funding_reservation WHERE invocation_id = $1"#,
+ id.as_uuid(),
+ ).fetch_optional(&mut *tx).await?.ok_or(FinancialError::InvocationNotFound)?;
+ if row.admission.identity != identity
+ || row.admission.authorization()? != record.admission.funding
+ {
+ return Err(conflict(id, ReplayPhase::Finalize));
+ }
+ lock_payer(&mut tx, &row.payer_id).await?;
+ let previous = sqlx::query!(
+ "SELECT completion FROM ai_funding_reservation WHERE invocation_id = $1",
+ id.as_uuid()
+ )
+ .fetch_one(&mut *tx)
+ .await?
+ .completion;
+ if let Some(previous) = previous {
+ if previous != completion {
+ return Err(conflict(id, ReplayPhase::Finalize));
+ }
+ } else {
+ sqlx::query!("UPDATE ai_funding_reservation SET completion = $2, actual_public = $3 WHERE invocation_id = $1",
+ id.as_uuid(), completion, actual).execute(&mut *tx).await?;
+ }
+ reconcile_locked(&mut tx, &row.payer_id).await?;
+ tx.commit().await?;
+ Ok(())
+ })
+ }
+
+ fn allocation(&self, id: InvocationId) -> FinancialFuture<'_, Option<UsageAllocation>> {
+ Box::pin(async move {
+ let row = sqlx::query!(
+ "SELECT included_public, extra_public, prepaid, reclaimed_prepaid, postpaid, macro_absorbed
+ FROM ai_funding_reservation WHERE invocation_id = $1 AND allocated", id.as_uuid(),
+ ).fetch_optional(&self.pool).await?;
+ row.map(|r| {
+ Ok(UsageAllocation {
+ included_public: PublicUsage::from_units(units(r.included_public)?),
+ extra_public: PublicUsage::from_units(units(r.extra_public)?),
+ prepaid: CustomerMoney::from_units(units(r.prepaid)?),
+ reclaimed_prepaid: CustomerMoney::from_units(units(r.reclaimed_prepaid)?),
+ postpaid: CustomerMoney::from_units(units(r.postpaid)?),
+ macro_absorbed: CustomerMoney::from_units(units(r.macro_absorbed)?),
+ })
+ })
+ .transpose()
+ })
+ }
+
+ fn pending(&self, query: PendingInvocations) -> FinancialFuture<'_, Vec<InvocationId>> {
+ Box::pin(async move {
+ let rows = sqlx::query!(
+ "SELECT invocation_id FROM ai_funding_reservation WHERE NOT allocated AND created_at < $1
+ AND ($2::uuid IS NULL OR invocation_id > $2) ORDER BY invocation_id LIMIT $3",
+ query.before, query.after.map(InvocationId::as_uuid), i64::from(query.limit.get()),
+ ).fetch_all(&self.pool).await?;
+ rows.into_iter()
+ .map(|r| r.invocation_id.try_into())
+ .collect()
+ })
+ }
+
+ fn reconcile(&self, payer: MacroUserIdStr<'static>) -> FinancialFuture<'_, ()> {
+ Box::pin(async move {
+ let mut tx = self.pool.begin().await?;
+ lock_payer(&mut tx, payer.as_ref()).await?;
+ reconcile_locked(&mut tx, payer.as_ref()).await?;
+ tx.commit().await?;
+ Ok(())
+ })
+ }
+}
+
+async fn reject(
+ mut tx: sqlx::Transaction<'_, sqlx::Postgres>,
+ id: InvocationId,
+ error: FinancialError,
+) -> FinancialResult<FundingAuthorization> {
+ sqlx::query!(
+ "UPDATE ai_funding_intent SET denied = TRUE WHERE invocation_id = $1",
+ id.as_uuid()
+ )
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Err(error)
+}
+
+async fn availability(
+ conn: &mut PgConnection,
+ period: &FundingPeriod,
+) -> FinancialResult<FundingAvailability> {
+ let payer = period.payer.as_ref();
+ let row = sqlx::query!(
+ r#"SELECT
+ COALESCE(SUM(actual_public) FILTER (WHERE allocated AND user_id = $2), 0)::bigint AS "used!",
+ COALESCE(SUM(included_hold) FILTER (WHERE NOT allocated AND user_id = $2), 0)::bigint AS "included_held!",
+ COALESCE(SUM(postpaid) FILTER (WHERE allocated), 0)::bigint AS "postpaid!",
+ COALESCE(SUM(postpaid_hold) FILTER (WHERE NOT allocated), 0)::bigint AS "postpaid_held!"
+ FROM ai_funding_reservation WHERE payer_id = $1 AND period_start = $3"#,
+ payer, period.seat.as_ref(), period.period.start,
+ ).fetch_one(&mut *conn).await?;
+ let ledger = sqlx::query!(
+ r#"SELECT
+ COALESCE((SELECT SUM(delta_cents)::bigint FROM ai_credit_ledger WHERE user_id = $1), 0) AS "balance!",
+ COALESCE((SELECT SUM(amount_cents)::bigint FROM ai_overage_charge WHERE user_id = $1 AND period_start = $2
+ AND accounting_policy = 'legacy' AND (status <> 'failed' OR stripe_invoice_id IS NOT NULL)), 0) AS "charged!""#,
+ payer, period.period.start,
+ ).fetch_one(&mut *conn).await?;
+ let credits = credit_commitments(conn, payer).await?;
+ funding_availability(
+ FundingAvailability {
+ seat_public_used: PublicUsage::from_units(units(row.used)?),
+ seat_public_held: PublicUsage::from_units(units(row.included_held)?),
+ prepaid_available: CustomerMoney::from_units(0),
+ prepaid_held: credits.held,
+ postpaid_incurred: CustomerMoney::from_units(units(row.postpaid)?),
+ postpaid_held: CustomerMoney::from_units(units(row.postpaid_held)?),
+ },
+ ledger.balance,
+ credits,
+ ledger.charged,
+ )
+}
+
+/// Bounded work makes a large ready backlog restart-safe without unbounded transactions.
+/// Unresolved evidence stops the watermark and retains every later hold.
+async fn reconcile_locked(conn: &mut PgConnection, payer: &str) -> FinancialResult<()> {
+ for _ in 0..100 {
+ let row = sqlx::query!(
+ r#"SELECT r.invocation_id, r.sequence, r.user_id, r.period_start, r.actual_public,
+ r.admission AS "admission: Json<AdmissionData>", f.next_sequence, f.prepaid_remainder
+ FROM ai_funding_state f JOIN ai_funding_reservation r ON r.payer_id = f.user_id AND r.sequence = f.watermark
+ WHERE f.user_id = $1 AND NOT r.allocated"#, payer,
+ ).fetch_optional(&mut *conn).await?;
+ let Some(row) = row else { break };
+ let Some(actual) = row.actual_public else {
+ break;
+ };
+ let used = sqlx::query_scalar!(
+ r#"SELECT COALESCE(SUM(actual_public), 0)::bigint AS "used!" FROM ai_funding_reservation
+ WHERE payer_id = $1 AND user_id = $2 AND period_start = $3 AND allocated"#,
+ payer,
+ row.user_id,
+ row.period_start,
+ )
+ .fetch_one(&mut *conn)
+ .await?;
+ let releases = sqlx::query!(
+ "SELECT sequence, units FROM ai_funding_prepaid_release WHERE payer_id = $1 AND through_sequence >= $2 ORDER BY sequence",
+ payer, row.sequence,
+ ).fetch_all(&mut *conn).await?;
+ let released = releases
+ .iter()
+ .try_fold(CustomerMoney::from_units(0), |total, r| {
+ total.checked_add(CustomerMoney::from_units(units(r.units)?))
+ })?;
+ let mut reservation = row.admission.reservation()?;
+ let allocation = reservation
+ .allocate(
+ AllocationPosition {
+ next_sequence: AllocationSequence::from_raw(units(row.sequence)?),
+ seat_public_used: PublicUsage::from_units(units(used)?),
+ prepaid_released_before: released,
+ },
+ PublicUsage::from_units(units(actual)?),
+ )
+ .map_err(funding_error)?;
+ let (debit, remainder) = prepaid_debit(
+ CustomerMoney::from_units(units(row.prepaid_remainder)?),
+ allocation.prepaid,
+ )?;
+ if debit > 0 {
+ sqlx::query!(
+ "INSERT INTO ai_credit_ledger (id, user_id, kind, delta_cents, period_start, funding_invocation_id, note)
+ VALUES ($1, $2, 'consumption', $3, $4, $5, 'Authorized public-rate AI usage') ON CONFLICT (funding_invocation_id) DO NOTHING",
+ macro_uuid::generate_uuid_v7(), payer, -debit, row.period_start, row.invocation_id,
+ ).execute(&mut *conn).await?;
+ }
+ let mut reclaim = db_units(allocation.reclaimed_prepaid.units())?;
+ for release in releases {
+ let take = reclaim.min(release.units);
+ if take == release.units {
+ sqlx::query!(
+ "DELETE FROM ai_funding_prepaid_release WHERE payer_id = $1 AND sequence = $2",
+ payer,
+ release.sequence
+ )
+ .execute(&mut *conn)
+ .await?;
+ } else if take > 0 {
+ sqlx::query!("UPDATE ai_funding_prepaid_release SET units = units - $3 WHERE payer_id = $1 AND sequence = $2", payer, release.sequence, take)
+ .execute(&mut *conn).await?;
+ }
+ reclaim -= take;
+ }
+ let released = reservation.released_holds().map_err(funding_error)?.prepaid;
+ if released.units() > 0 && row.next_sequence > row.sequence + 1 {
+ sqlx::query!(
+ "INSERT INTO ai_funding_prepaid_release (payer_id, sequence, through_sequence, units) VALUES ($1,$2,$3,$4) ON CONFLICT DO NOTHING",
+ payer, row.sequence, row.next_sequence - 1, db_units(released.units())?,
+ ).execute(&mut *conn).await?;
+ }
+ sqlx::query!(
+ "UPDATE ai_funding_reservation SET allocated = TRUE, included_public = $2, extra_public = $3,
+ prepaid = $4, reclaimed_prepaid = $5, postpaid = $6, macro_absorbed = $7 WHERE invocation_id = $1",
+ row.invocation_id, db_units(allocation.included_public.units())?, db_units(allocation.extra_public.units())?,
+ db_units(allocation.prepaid.units())?, db_units(allocation.reclaimed_prepaid.units())?,
+ db_units(allocation.postpaid.units())?, db_units(allocation.macro_absorbed.units())?,
+ ).execute(&mut *conn).await?;
+ sqlx::query!("UPDATE ai_funding_state SET watermark = watermark + 1, prepaid_remainder = $2 WHERE user_id = $1", payer, db_units(remainder.units())?)
+ .execute(&mut *conn).await?;
+ sqlx::query!(
+ "DELETE FROM ai_funding_prepaid_release WHERE payer_id = $1 AND through_sequence <= $2",
+ payer,
+ row.sequence
+ )
+ .execute(&mut *conn)
+ .await?;
+ }
+ Ok(())
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct AdmissionData {
+ identity: Value,
+ id: Uuid,
+ invocation_id: Uuid,
+ payer: String,
+ seat: String,
+ start: DateTime<Utc>,
+ end: DateTime<Utc>,
+ revision: u64,
+ policy: UsagePolicy,
+ overage_enabled: bool,
+ overage_limit_cents: i64,
+ overage_suspended_at: Option<DateTime<Utc>>,
+ postpaid: PostpaidData,
+ sequence: u64,
+ maximum: u64,
+ available: [u64; 6],
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+enum PostpaidData {
+ Disabled,
+ Suspended,
+ Enabled(u64),
+}
+
+impl AdmissionData {
+ fn new(
+ identity: Value,
+ reservation: &Reservation,
+ available: FundingAvailability,
+ settings: &crate::domain::BillingSettings,
+ ) -> Self {
+ let auth = reservation.authorization();
+ Self {
+ identity,
+ id: auth.id.as_uuid(),
+ invocation_id: auth.invocation_id.as_uuid(),
+ payer: auth.payer.as_ref().to_owned(),
+ seat: auth.seat.as_ref().to_owned(),
+ start: auth.period.start,
+ end: auth.period.end,
+ revision: auth.settings_revision.raw(),
+ policy: auth.policy,
+ overage_enabled: settings.overage_enabled,
+ overage_limit_cents: settings.overage_limit_cents,
+ overage_suspended_at: settings.overage_suspended_at,
+ postpaid: match auth.postpaid {
+ PostpaidAuthorization::Disabled => PostpaidData::Disabled,
+ PostpaidAuthorization::Suspended => PostpaidData::Suspended,
+ PostpaidAuthorization::Enabled { limit } => PostpaidData::Enabled(limit.units()),
+ },
+ sequence: reservation.sequence().raw(),
+ maximum: reservation.maximum_public_usage().units(),
+ available: [
+ available.seat_public_used.units(),
+ available.seat_public_held.units(),
+ available.prepaid_available.units(),
+ available.prepaid_held.units(),
+ available.postpaid_incurred.units(),
+ available.postpaid_held.units(),
+ ],
+ }
+ }
+
+ fn authorization(&self) -> FinancialResult<FundingAuthorization> {
+ Ok(FundingAuthorization {
+ id: self.id.try_into()?,
+ invocation_id: self.invocation_id.try_into()?,
+ maximum_public_usage: PublicUsage::from_units(self.maximum),
+ })
+ }
+
+ fn reservation(&self) -> FinancialResult<Reservation> {
+ let [used, held, prepaid, prepaid_held, incurred, postpaid_held] = self.available;
+ reserve(
+ AuthorizationSnapshot {
+ id: self.id.try_into()?,
+ invocation_id: self.invocation_id.try_into()?,
+ payer: MacroUserIdStr::try_from(self.payer.clone())
+ .map_err(|_| FinancialError::InvalidIdentifier)?,
+ seat: MacroUserIdStr::try_from(self.seat.clone())
+ .map_err(|_| FinancialError::InvalidIdentifier)?,
+ period: BillingPeriod {
+ start: self.start,
+ end: self.end,
+ },
+ policy: self.policy,
+ settings_revision: AuthorizationRevision::from_raw(self.revision),
+ postpaid: match self.postpaid {
+ PostpaidData::Disabled => PostpaidAuthorization::Disabled,
+ PostpaidData::Suspended => PostpaidAuthorization::Suspended,
+ PostpaidData::Enabled(limit) => PostpaidAuthorization::Enabled {
+ limit: CustomerMoney::from_units(limit),
+ },
+ },
+ },
+ AllocationSequence::from_raw(self.sequence),
+ PublicUsage::from_units(self.maximum),
+ FundingAvailability {
+ seat_public_used: PublicUsage::from_units(used),
+ seat_public_held: PublicUsage::from_units(held),
+ prepaid_available: CustomerMoney::from_units(prepaid),
+ prepaid_held: CustomerMoney::from_units(prepaid_held),
+ postpaid_incurred: CustomerMoney::from_units(incurred),
+ postpaid_held: CustomerMoney::from_units(postpaid_held),
+ },
+ )
+ .map_err(funding_error)
+ }
+}
+
+fn tokens(value: TrustedTokenUsage) -> [u64; 5] {
+ [
+ value.input(),
+ value.output(),
+ value.cache_read(),
+ value.cache_write(),
+ value.reasoning(),
+ ]
+}
+
+// Minimal immutable handoff identities, not prompts, outputs or provider credentials.
+// Evidence remains owned by ai_usage; no cross-domain SQL or mutable analytics joins.
+fn admission_identity(request: &BeginInvocation, rate: &RateSnapshot) -> Value {
+ json!({
+ "run": request.run_id.as_uuid(), "invocation": request.invocation_id.as_uuid(),
+ "user": request.user.as_ref(), "feature": request.feature, "entity": request.entity,
+ "provider": request.model.provider(), "model": request.model.model(),
+ "occurred_at": request.occurred_at, "budget": tokens(request.token_budget),
+ "rate": rate.version.as_uuid(), "rate_effective_at": rate.effective_at,
+ "rates": [rate.tokens.input, rate.tokens.output, rate.tokens.cache_read, rate.tokens.cache_write, rate.tokens.reasoning],
+ })
+}
+
+fn completion_identity(state: &InvocationState) -> FinancialResult<Value> {
+ let (evidence, status, amount) = match state {
+ InvocationState::Priced {
+ evidence,
+ public_usage,
+ } => (evidence, "priced", Some(public_usage.units())),
+ InvocationState::Unresolved { evidence } => (evidence, "unresolved", None),
+ InvocationState::Unpriced { evidence, .. } => (evidence, "unpriced", None),
+ _ => return Err(FinancialError::FundingDenied),
+ };
+ let usage = match evidence.usage {
+ UsageEvidence::Reported(value) => json!({"reported": tokens(value)}),
+ UsageEvidence::Missing(reason) => json!({"missing": match reason {
+ UnresolvedReason::UsageNotReported => "not_reported",
+ UnresolvedReason::Interrupted => "interrupted",
+ UnresolvedReason::UnsupportedDimensions => "unsupported_dimensions",
+ }}),
+ };
+ let outcome = match evidence.outcome {
+ ProviderOutcome::Succeeded => "succeeded",
+ ProviderOutcome::Failed => "failed",
+ ProviderOutcome::Cancelled => "cancelled",
+ ProviderOutcome::Unknown => "unknown",
+ };
+ Ok(
+ json!({"invocation": evidence.invocation_id.as_uuid(), "occurred_at": evidence.occurred_at,
+ "request": evidence.provider_request_id.as_ref().map(ProviderRequestId::as_str),
+ "outcome": outcome, "usage": usage, "status": status, "public_usage": amount}),
+ )
+}
diff --git a/crates/ai_billing/src/outbound/pg_funding_repo/test.rs b/crates/ai_billing/src/outbound/pg_funding_repo/test.rs
new file mode 100644
index 0000000000..4188e0ac3e
--- /dev/null
+++ b/crates/ai_billing/src/outbound/pg_funding_repo/test.rs
@@ -0,0 +1,1072 @@
+use super::*;
+use crate::domain::ports::BillingRepo;
+use crate::domain::{SeatAllowance, SettlementPolicy};
+use crate::outbound::pg_billing_repo::PgBillingRepo;
+use ai_usage::AiFeature;
+use ai_usage::domain::ports::InvocationFunding;
+use chrono::Duration;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+
+const DOLLAR: u64 = 1_000_000_000_000;
+
+fn rollout_observation() -> (UsageRollout, SeatPeriodObservation) {
+ let window = period().period;
+ let rollout = UsageRollout {
+ effective_at: window.start + Duration::days(10),
+ price_id: "price_40".parse().unwrap(),
+ product_id: "prod_40".parse().unwrap(),
+ };
+ let observation = SeatPeriodObservation {
+ seat: user("seat"),
+ payer: user("payer"),
+ subscription: crate::domain::period::SubscriptionPeriod {
+ event_id: "evt_baseline".parse().unwrap(),
+ event_at: rollout.effective_at,
+ subscription_id: "sub_verified".parse().unwrap(),
+ subscription_created_at: window.start - Duration::days(90),
+ customer_id: "cus_verified".parse().unwrap(),
+ team_id: None,
+ quantity: 1,
+ item_count: 1,
+ item_id: "si_verified".parse().unwrap(),
+ price_id: rollout.price_id.clone(),
+ product_id: rollout.product_id.clone(),
+ unit_amount: Some(4000),
+ currency: "usd".into(),
+ monthly: true,
+ activity: crate::domain::period::SubscriptionActivity::Active,
+ period: window,
+ evidence: crate::domain::period::PeriodEvidence::Snapshot,
+ },
+ };
+ (rollout, observation)
+}
+
+fn next_renewal(mut observation: SeatPeriodObservation) -> SeatPeriodObservation {
+ let facts = &mut observation.subscription;
+ facts.period.start = facts.period.end;
+ facts.period.end += Duration::days(31);
+ facts.event_at = facts.period.start;
+ facts.event_id = format!("evt_{}", facts.period.start.timestamp())
+ .try_into()
+ .unwrap();
+ facts.evidence = crate::domain::period::PeriodEvidence::Renewal;
+ observation
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn verified_renewal_freezes_history_and_preserves_shared_money(pool: PgPool) {
+ let repo = PgFundingRepo::new(pool.clone());
+ let billing = PgBillingRepo::new(pool);
+ let (rollout, baseline) = rollout_observation();
+ billing
+ .update_overage(&user("payer"), true, 5000)
+ .await
+ .unwrap();
+ billing
+ .record_credit_purchase(&user("payer"), 1000, "cs_before_rollout")
+ .await
+ .unwrap();
+ let settings = billing.settings(&user("payer")).await.unwrap();
+ assert_eq!(
+ repo.observe(&rollout, baseline.clone(), true)
+ .await
+ .unwrap(),
+ PeriodDecision::Legacy
+ );
+ let old = repo
+ .period(user("seat"), baseline.subscription.period.start)
+ .await
+ .unwrap()
+ .unwrap();
+ let renewed = next_renewal(baseline.clone());
+ assert_eq!(
+ repo.observe(&rollout, renewed.clone(), true).await.unwrap(),
+ PeriodDecision::Activate
+ );
+ let rate = rate();
+ let mut request = request(&rate, 20 * DOLLAR);
+ request.occurred_at = renewed.subscription.period.end - Duration::seconds(1);
+ let funding = repo.authorize(request.clone(), rate.clone()).await.unwrap();
+ let admission = AuthorizedInvocation {
+ request,
+ rate,
+ funding,
+ };
+ let next = next_renewal(renewed.clone());
+ assert_eq!(
+ repo.observe(&rollout, next.clone(), true).await.unwrap(),
+ PeriodDecision::Activate
+ );
+ // An invocation admitted before the boundary finishes after it, against its
+ // original immutable authorization, not the newly published allowance.
+ let mut record = completed(admission.clone(), 20 * DOLLAR);
+ if let InvocationState::Priced { evidence, .. } = &mut record.state {
+ evidence.occurred_at = next.subscription.period.start + Duration::seconds(5);
+ }
+ repo.finalize(record).await.unwrap();
+ assert_eq!(
+ repo.allocation(admission.request.invocation_id)
+ .await
+ .unwrap()
+ .unwrap()
+ .included_public
+ .units(),
+ 20 * DOLLAR
+ );
+ assert_eq!(
+ repo.period(user("seat"), baseline.subscription.period.start)
+ .await
+ .unwrap(),
+ Some(old)
+ );
+ assert_eq!(
+ billing.credit_balance_cents(&user("payer")).await.unwrap(),
+ 1000
+ );
+ let after = billing.settings(&user("payer")).await.unwrap();
+ assert_eq!(after.overage_enabled, settings.overage_enabled);
+ assert_eq!(after.overage_limit_cents, settings.overage_limit_cents);
+ assert_eq!(
+ repo.observe(&rollout, next, true).await.unwrap(),
+ PeriodDecision::Activate
+ );
+ let mut delayed = baseline;
+ delayed.subscription.event_id = "evt_delayed".parse().unwrap();
+ assert_eq!(
+ repo.observe(&rollout, delayed, true).await.unwrap(),
+ PeriodDecision::Exception(ActivationException::Stale)
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn cancellation_departure_and_rejoin_cannot_replenish_allowance(pool: PgPool) {
+ let repo = PgFundingRepo::new(pool.clone());
+ let billing = PgBillingRepo::new(pool);
+ let (rollout, baseline) = rollout_observation();
+ repo.observe(&rollout, baseline.clone(), true)
+ .await
+ .unwrap();
+ let renewal = next_renewal(baseline);
+ repo.observe(&rollout, renewal.clone(), true).await.unwrap();
+ let rate = rate();
+ let mut request = request(&rate, 20 * DOLLAR);
+ request.occurred_at = renewal.subscription.period.start + Duration::seconds(1);
+ let funding = repo.authorize(request.clone(), rate.clone()).await.unwrap();
+ allocated(
+ &repo,
+ AuthorizedInvocation {
+ request: request.clone(),
+ rate: rate.clone(),
+ funding,
+ },
+ 20 * DOLLAR,
+ )
+ .await;
+ let mut canceled = renewal.clone();
+ canceled.subscription.event_id = "evt_cancel".parse().unwrap();
+ canceled.subscription.activity = crate::domain::period::SubscriptionActivity::Inactive;
+ assert_eq!(
+ repo.observe(&rollout, canceled, true).await.unwrap(),
+ PeriodDecision::Exception(ActivationException::Ineligible)
+ );
+ let open = renewal
+ .subscription
+ .period
+ .open_start(request.occurred_at)
+ .unwrap();
+ billing
+ .release_open_seat(&user("payer"), open, &user("seat"))
+ .await
+ .unwrap();
+ let mut rejoin = renewal.clone();
+ rejoin.subscription.event_id = "evt_rejoin".parse().unwrap();
+ repo.observe(&rollout, rejoin, true).await.unwrap();
+ request.invocation_id = InvocationId::new();
+ request.token_budget = TrustedTokenUsage::from_disjoint(1, 0, 0, 0, 0);
+ assert!(repo.authorize(request.clone(), rate.clone()).await.is_err());
+ // Only a distinct verified renewal resets included usage.
+ let next = next_renewal(renewal);
+ repo.observe(&rollout, next.clone(), true).await.unwrap();
+ request.invocation_id = InvocationId::new();
+ request.occurred_at = next.subscription.period.start;
+ assert!(repo.authorize(request, rate).await.is_ok());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn activation_exceptions_are_durable_and_mixed_policy_seats_stay_separate(pool: PgPool) {
+ let repo = PgFundingRepo::new(pool.clone());
+ let billing = PgBillingRepo::new(pool.clone());
+ let (rollout, baseline) = rollout_observation();
+ let mut delayed = baseline.clone();
+ delayed.subscription.event_id = "evt_pre_rollout".parse().unwrap();
+ delayed.subscription.event_at = rollout.effective_at - Duration::seconds(1);
+ assert_eq!(
+ repo.observe(&rollout, delayed, true).await.unwrap(),
+ PeriodDecision::Exception(ActivationException::Delayed)
+ );
+ let mut unknown = baseline.clone();
+ unknown.seat = user("max");
+ unknown.subscription.price_id = "price_unknown".parse().unwrap();
+ assert_eq!(
+ repo.observe(&rollout, unknown, true).await.unwrap(),
+ PeriodDecision::Exception(ActivationException::Ineligible)
+ );
+ assert_eq!(
+ repo.observe(&rollout, baseline.clone(), false)
+ .await
+ .unwrap(),
+ PeriodDecision::Exception(ActivationException::AmbiguousBinding)
+ );
+ let mut baseline = baseline;
+ baseline.subscription.event_id = "evt_verified_baseline".parse().unwrap();
+ repo.observe(&rollout, baseline.clone(), true)
+ .await
+ .unwrap();
+ let renewal = next_renewal(baseline);
+ let mut ordinary = renewal.clone();
+ ordinary.subscription.event_id = "evt_update".parse().unwrap();
+ ordinary.subscription.evidence = crate::domain::period::PeriodEvidence::Snapshot;
+ assert_eq!(
+ repo.observe(&rollout, ordinary, true).await.unwrap(),
+ PeriodDecision::Exception(ActivationException::UnverifiedRenewal)
+ );
+ repo.observe(&rollout, renewal.clone(), true).await.unwrap();
+ let seats = billing
+ .legacy_seats(
+ &user("payer"),
+ renewal.subscription.period,
+ vec![
+ SeatAllowance {
+ user: user("seat"),
+ included_cents: 4000,
+ },
+ SeatAllowance {
+ user: user("max"),
+ included_cents: 20000,
+ },
+ ],
+ )
+ .await
+ .unwrap();
+ assert_eq!(seats.len(), 1);
+ assert_eq!(seats[0].user, user("max"));
+ let count = sqlx::query_scalar!("SELECT COUNT(*) FROM ai_billing_usage_observation")
+ .fetch_one(&pool)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(count, 6);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn late_seat_uses_existing_item_proof_but_cannot_renew_it(pool: PgPool) {
+ let repo = PgFundingRepo::new(pool);
+ let (rollout, baseline) = rollout_observation();
+ repo.observe(&rollout, baseline.clone(), true)
+ .await
+ .unwrap();
+ let renewal = next_renewal(baseline);
+ repo.observe(&rollout, renewal.clone(), true).await.unwrap();
+ let mut joining = renewal.clone();
+ joining.seat = user("joining");
+ joining.subscription.event_id = "evt_join".parse().unwrap();
+ joining.subscription.evidence = crate::domain::period::PeriodEvidence::Snapshot;
+ assert_eq!(
+ repo.observe(&rollout, joining.clone(), true).await.unwrap(),
+ PeriodDecision::Activate
+ );
+ assert_eq!(
+ repo.period(user("joining"), renewal.subscription.period.start)
+ .await
+ .unwrap()
+ .unwrap()
+ .period,
+ renewal.subscription.period
+ );
+ let mut next = next_renewal(joining);
+ next.subscription.evidence = crate::domain::period::PeriodEvidence::Snapshot;
+ assert_eq!(
+ repo.observe(&rollout, next, true).await.unwrap(),
+ PeriodDecision::Exception(ActivationException::UnverifiedRenewal)
+ );
+ let mut changed_rollout = rollout;
+ changed_rollout.effective_at += Duration::days(1);
+ assert!(repo.observe(&changed_rollout, renewal, true).await.is_err());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn delayed_renewal_does_not_convert_a_legacy_period_already_in_use(pool: PgPool) {
+ let repo = PgFundingRepo::new(pool.clone());
+ let billing = PgBillingRepo::new(pool);
+ let (rollout, baseline) = rollout_observation();
+ repo.observe(&rollout, baseline.clone(), true)
+ .await
+ .unwrap();
+ let renewal = next_renewal(baseline);
+ let period = renewal.subscription.period;
+ let seats = vec![SeatAllowance {
+ user: user("seat"),
+ included_cents: 4000,
+ }];
+ billing
+ .store_open_allowance(
+ &user("payer"),
+ period.open_start(period.start).unwrap(),
+ &seats,
+ Default::default(),
+ )
+ .await
+ .unwrap();
+ let old = billing
+ .period_allowance(&user("payer"), period.start)
+ .await
+ .unwrap();
+ assert_eq!(
+ repo.observe(&rollout, renewal, true).await.unwrap(),
+ PeriodDecision::Exception(ActivationException::LegacyPeriodInUse)
+ );
+ assert!(
+ repo.period(user("seat"), period.start)
+ .await
+ .unwrap()
+ .is_none()
+ );
+ assert_eq!(
+ billing
+ .period_allowance(&user("payer"), period.start)
+ .await
+ .unwrap(),
+ old
+ );
+ // Older starts remain ignored; a same-period end correction changes only
+ // the legacy anchor, never the retained allowance or activation history.
+ billing
+ .set_period(&user("payer"), period.start, period.end)
+ .await
+ .unwrap();
+ billing
+ .set_period(
+ &user("payer"),
+ period.start - Duration::days(31),
+ period.start,
+ )
+ .await
+ .unwrap();
+ billing
+ .set_period(&user("payer"), period.start, period.end + Duration::days(1))
+ .await
+ .unwrap();
+ assert_eq!(
+ billing
+ .settings(&user("payer"))
+ .await
+ .unwrap()
+ .period_anchor,
+ Some((period.start, period.end + Duration::days(1)))
+ );
+ assert_eq!(
+ billing
+ .period_allowance(&user("payer"), period.start)
+ .await
+ .unwrap(),
+ old
+ );
+ assert!(
+ repo.period(user("seat"), period.start)
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
+
+fn user(name: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(format!("macro|{name}@example.com")).unwrap()
+}
+
+fn period() -> FundingPeriod {
+ let start = DateTime::from_timestamp(1_800_000_000, 0).unwrap();
+ FundingPeriod {
+ seat: user("seat"),
+ payer: user("payer"),
+ subscription: FundingSubscription::new("sub_verified".into()).unwrap(),
+ period: BillingPeriod {
+ start,
+ end: start + Duration::days(30),
+ },
+ policy: UsagePolicy::PublicAllowanceV1,
+ }
+}
+
+fn rate() -> RateSnapshot {
+ RateSnapshot {
+ version: RateVersion::new(),
+ model: ProviderModel::new("test", "model").unwrap(),
+ effective_at: period().period.start,
+ tokens: TokenRates {
+ input: 1,
+ output: 0,
+ cache_read: 0,
+ cache_write: 0,
+ reasoning: 0,
+ },
+ }
+}
+
+fn request(rate: &RateSnapshot, maximum: u64) -> BeginInvocation {
+ BeginInvocation {
+ run_id: RunId::new(),
+ invocation_id: InvocationId::new(),
+ user: user("seat"),
+ feature: AiFeature::Chat,
+ entity: None,
+ model: rate.model.clone(),
+ occurred_at: period().period.start + Duration::seconds(1),
+ token_budget: TrustedTokenUsage::from_disjoint(maximum, 0, 0, 0, 0),
+ }
+}
+
+async fn setup(
+ pool: &PgPool,
+ credits: i64,
+ enabled: bool,
+ cap: i64,
+) -> (PgFundingRepo, PgBillingRepo) {
+ let funding = PgFundingRepo::new(pool.clone());
+ let billing = PgBillingRepo::new(pool.clone());
+ funding.record_period(period()).await.unwrap();
+ billing
+ .update_overage(&user("payer"), enabled, cap)
+ .await
+ .unwrap();
+ if credits > 0 {
+ billing
+ .record_credit_purchase(&user("payer"), credits, "cs_initial")
+ .await
+ .unwrap();
+ }
+ (funding, billing)
+}
+
+async fn admit(repo: &PgFundingRepo, maximum: u64) -> AuthorizedInvocation {
+ let rate = rate();
+ let request = request(&rate, maximum);
+ let funding = repo.authorize(request.clone(), rate.clone()).await.unwrap();
+ AuthorizedInvocation {
+ request,
+ rate,
+ funding,
+ }
+}
+
+fn completed(admission: AuthorizedInvocation, actual: u64) -> InvocationRecord {
+ let evidence = FinalizeInvocation {
+ invocation_id: admission.request.invocation_id,
+ occurred_at: admission.request.occurred_at + Duration::seconds(1),
+ provider_request_id: None,
+ outcome: ProviderOutcome::Succeeded,
+ usage: UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(actual, 0, 0, 0, 0)),
+ };
+ InvocationRecord {
+ admission,
+ state: InvocationState::Priced {
+ evidence,
+ public_usage: PublicUsage::from_units(actual),
+ },
+ }
+}
+
+async fn allocated(
+ repo: &PgFundingRepo,
+ admission: AuthorizedInvocation,
+ actual: u64,
+) -> UsageAllocation {
+ let id = admission.request.invocation_id;
+ repo.finalize(completed(admission, actual)).await.unwrap();
+ repo.allocation(id).await.unwrap().unwrap()
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn threshold_split_is_credit_first_and_not_double_billed(pool: PgPool) {
+ let (repo, billing) = setup(&pool, 1_000, true, 5_000).await;
+ let invocation = admit(&repo, 30 * DOLLAR).await;
+ let record = completed(invocation.clone(), 30 * DOLLAR);
+ repo.finalize(record.clone()).await.unwrap();
+ // Simulate a lost acknowledgement and replay after settings/purchases change.
+ billing
+ .update_overage(&user("payer"), false, 1)
+ .await
+ .unwrap();
+ billing
+ .record_credit_purchase(&user("payer"), 2_500, "cs_later")
+ .await
+ .unwrap();
+ repo.finalize(record).await.unwrap();
+ let allocation = repo
+ .allocation(invocation.request.invocation_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(allocation.included_public.units(), 20 * DOLLAR);
+ assert_eq!(allocation.extra_public.units(), 10 * DOLLAR);
+ assert_eq!(
+ allocation.prepaid,
+ CustomerMoney::from_cents(1_000).unwrap()
+ );
+ assert_eq!(allocation.postpaid, CustomerMoney::from_cents(50).unwrap());
+ assert_eq!(allocation.macro_absorbed.units(), 0);
+ assert_eq!(
+ allocation.extra_money().unwrap(),
+ CustomerMoney::from_cents(1_050).unwrap()
+ );
+ assert_eq!(
+ billing.credit_balance_cents(&user("payer")).await.unwrap(),
+ 2_500
+ );
+ assert_eq!(
+ billing
+ .period_ledger(&user("payer"), period().period.start)
+ .await
+ .unwrap()
+ .credits_consumed_cents,
+ 0
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn opt_out_credit_only_and_exhaustion(pool: PgPool) {
+ let (repo, billing) = setup(&pool, 1_050, false, 5_000).await;
+ let first = admit(&repo, 30 * DOLLAR).await;
+ let denied_rate = rate();
+ let denied = request(&denied_rate, 1);
+ assert!(
+ repo.authorize(denied.clone(), denied_rate.clone())
+ .await
+ .is_err()
+ );
+ let allocation = allocated(&repo, first, 30 * DOLLAR).await;
+ assert_eq!(
+ allocation.prepaid,
+ CustomerMoney::from_cents(1_050).unwrap()
+ );
+ assert_eq!(allocation.postpaid.units(), 0);
+ // Enabling cannot create an allocation for an invocation never authorized.
+ billing
+ .update_overage(&user("payer"), true, 5_000)
+ .await
+ .unwrap();
+ assert!(
+ repo.authorize(denied.clone(), denied_rate.clone())
+ .await
+ .is_err()
+ );
+ let fresh = request(&denied_rate, 1);
+ assert!(repo.authorize(fresh, denied_rate.clone()).await.is_ok());
+ let unknown = AuthorizedInvocation {
+ request: denied,
+ rate: denied_rate,
+ funding: FundingAuthorization {
+ id: FundingAuthorizationId::new(),
+ invocation_id: InvocationId::new(),
+ maximum_public_usage: PublicUsage::from_units(1),
+ },
+ };
+ assert!(repo.finalize(completed(unknown, 1)).await.is_err());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn reversed_completions_release_allowance_before_pricing(pool: PgPool) {
+ let (repo, billing) = setup(&pool, 0, true, 5_000).await;
+ let first = admit(&repo, 20 * DOLLAR).await;
+ let second = admit(&repo, 10 * DOLLAR).await;
+ let second_id = second.request.invocation_id;
+ repo.finalize(completed(second, 10 * DOLLAR)).await.unwrap();
+ assert!(repo.allocation(second_id).await.unwrap().is_none());
+ // This toggle/cap reduction must not change the already captured authorization.
+ billing
+ .update_overage(&user("payer"), false, 1)
+ .await
+ .unwrap();
+ allocated(&repo, first, 5 * DOLLAR).await;
+ let allocation = repo.allocation(second_id).await.unwrap().unwrap();
+ assert_eq!(allocation.included_public.units(), 10 * DOLLAR);
+ assert_eq!(allocation.extra_money().unwrap().units(), 0);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn earlier_credit_releases_replace_only_eligible_postpaid(pool: PgPool) {
+ let (repo, billing) = setup(&pool, 1_050, true, 5_000).await;
+ let included = admit(&repo, 20 * DOLLAR).await;
+ allocated(&repo, included, 20 * DOLLAR).await;
+ let first = admit(&repo, 10 * DOLLAR).await;
+ let second = admit(&repo, 10 * DOLLAR).await;
+ let second_id = second.request.invocation_id;
+ allocated(&repo, first, 0).await;
+ // Released money is still owed to second, not spendable by newer attempts.
+ let third = admit(&repo, 10 * DOLLAR).await;
+ let third_id = third.request.invocation_id;
+ repo.finalize(completed(third, 10 * DOLLAR)).await.unwrap();
+ allocated(&repo, second, 10 * DOLLAR).await;
+ let second = repo.allocation(second_id).await.unwrap().unwrap();
+ let third = repo.allocation(third_id).await.unwrap().unwrap();
+ assert_eq!(second.prepaid, CustomerMoney::from_cents(1_050).unwrap());
+ assert_eq!(second.reclaimed_prepaid, second.prepaid);
+ assert_eq!(second.postpaid.units(), 0);
+ assert_eq!(third.prepaid.units(), 0);
+ assert_eq!(third.postpaid, CustomerMoney::from_cents(1_050).unwrap());
+ assert_eq!(
+ billing.credit_balance_cents(&user("payer")).await.unwrap(),
+ 0
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn later_purchase_and_disable_do_not_reclassify_authorized_liability(pool: PgPool) {
+ let (repo, billing) = setup(&pool, 0, true, 2_000).await;
+ let invocation = admit(&repo, 30 * DOLLAR).await;
+ billing
+ .update_overage(&user("payer"), false, 0)
+ .await
+ .unwrap();
+ billing
+ .record_credit_purchase(&user("payer"), 2_500, "cs_later")
+ .await
+ .unwrap();
+ let allocation = allocated(&repo, invocation, 30 * DOLLAR).await;
+ assert_eq!(allocation.prepaid.units(), 0);
+ assert_eq!(
+ allocation.postpaid,
+ CustomerMoney::from_cents(1_050).unwrap()
+ );
+ assert_eq!(
+ billing.credit_balance_cents(&user("payer")).await.unwrap(),
+ 2_500
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn unfunded_overshoot_is_absorbed_not_debt(pool: PgPool) {
+ let (repo, _) = setup(&pool, 0, false, 5_000).await;
+ let invocation = admit(&repo, 20 * DOLLAR).await;
+ let allocation = allocated(&repo, invocation, 30 * DOLLAR).await;
+ assert_eq!(allocation.prepaid.units(), 0);
+ assert_eq!(allocation.postpaid.units(), 0);
+ assert_eq!(
+ allocation.macro_absorbed,
+ CustomerMoney::from_cents(1_050).unwrap()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn pending_evidence_blocks_watermark_and_is_discoverable(pool: PgPool) {
+ let (repo, _) = setup(&pool, 0, true, 5_000).await;
+ let first = admit(&repo, 20 * DOLLAR).await;
+ let first_id = first.request.invocation_id;
+ let second = admit(&repo, DOLLAR).await;
+ let second_id = second.request.invocation_id;
+ let evidence = FinalizeInvocation {
+ invocation_id: first_id,
+ occurred_at: first.request.occurred_at,
+ provider_request_id: None,
+ outcome: ProviderOutcome::Unknown,
+ usage: UsageEvidence::Missing(UnresolvedReason::Interrupted),
+ };
+ repo.finalize(InvocationRecord {
+ admission: first,
+ state: InvocationState::Unresolved { evidence },
+ })
+ .await
+ .unwrap();
+ repo.finalize(completed(second, DOLLAR)).await.unwrap();
+ repo.reconcile(user("payer")).await.unwrap();
+ assert!(repo.allocation(second_id).await.unwrap().is_none());
+ let pending = repo
+ .pending(PendingInvocations {
+ after: None,
+ before: Utc::now() + Duration::days(1),
+ limit: 100.try_into().unwrap(),
+ })
+ .await
+ .unwrap();
+ assert!(pending.contains(&first_id));
+ assert!(pending.contains(&second_id));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn bounded_reconciliation_resumes_after_restart(pool: PgPool) {
+ let (repo, _) = setup(&pool, 0, false, 0).await;
+ let mut admissions = Vec::new();
+ for _ in 0..105 {
+ admissions.push(admit(&repo, 1).await);
+ }
+ let last = admissions.last().unwrap().request.invocation_id;
+ for admission in admissions.into_iter().rev() {
+ repo.finalize(completed(admission, 1)).await.unwrap();
+ }
+ assert!(repo.allocation(last).await.unwrap().is_none());
+ let restarted = PgFundingRepo::new(pool);
+ let pending = restarted
+ .pending(PendingInvocations {
+ after: None,
+ before: Utc::now() + Duration::days(1),
+ limit: 100.try_into().unwrap(),
+ })
+ .await
+ .unwrap();
+ assert_eq!(pending.len(), 5);
+ restarted.reconcile(user("payer")).await.unwrap();
+ assert_eq!(
+ restarted
+ .allocation(last)
+ .await
+ .unwrap()
+ .unwrap()
+ .included_public
+ .units(),
+ 1
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn admission_and_completion_conflicting_replays_fail(pool: PgPool) {
+ let (repo, billing) = setup(&pool, 0, false, 0).await;
+ let invocation = admit(&repo, DOLLAR).await;
+ let replay = repo
+ .authorize(invocation.request.clone(), invocation.rate.clone())
+ .await
+ .unwrap();
+ assert_eq!(replay, invocation.funding);
+ let mut changed = invocation.request.clone();
+ changed.run_id = RunId::new();
+ assert!(
+ repo.authorize(changed, invocation.rate.clone())
+ .await
+ .is_err()
+ );
+ allocated(&repo, invocation.clone(), DOLLAR).await;
+ assert!(
+ repo.finalize(completed(invocation.clone(), 0))
+ .await
+ .is_err()
+ );
+ billing
+ .update_overage(&user("payer"), true, 1_000)
+ .await
+ .unwrap();
+ assert_eq!(
+ repo.authorize(invocation.request, invocation.rate)
+ .await
+ .unwrap(),
+ replay
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn fractional_credit_cannot_be_spent_by_legacy_or_a_later_invocation(pool: PgPool) {
+ let (repo, billing) = setup(&pool, 1, false, 0).await;
+ let included = admit(&repo, 20 * DOLLAR).await;
+ allocated(&repo, included, 20 * DOLLAR).await;
+ let public = 1_000_000_000; // $.001 public = .105 cents customer money.
+ let first = admit(&repo, public).await;
+ allocated(&repo, first, public).await;
+ let policy = SettlementPolicy {
+ overage_active: false,
+ overage_limit_cents: 0,
+ charge_threshold_cents: 1_000,
+ period_ended: false,
+ };
+ assert_eq!(
+ billing
+ .apply_settlement(&user("payer"), period().period.start, 1, policy)
+ .await
+ .unwrap()
+ .consumed_credits_cents,
+ 0
+ );
+ for _ in 0..8 {
+ let attempt = admit(&repo, public).await;
+ allocated(&repo, attempt, public).await;
+ }
+ let rate = rate();
+ assert!(repo.authorize(request(&rate, public), rate).await.is_err());
+ let mut conn = pool.acquire().await.unwrap();
+ assert_eq!(
+ credit_commitments(&mut conn, user("payer").as_ref())
+ .await
+ .unwrap()
+ .remainder
+ .units(),
+ 945_000_000_000
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn racing_admissions_share_allowance_credits_and_cap(pool: PgPool) {
+ let (repo, _) = setup(&pool, 1_050, false, 0).await;
+ let mut tasks = tokio::task::JoinSet::new();
+ for _ in 0..12 {
+ let repo = repo.clone();
+ tasks.spawn(async move {
+ let rate = rate();
+ repo.authorize(request(&rate, 10 * DOLLAR), rate)
+ .await
+ .is_ok()
+ });
+ }
+ let mut admitted = 0;
+ while let Some(result) = tasks.join_next().await {
+ admitted += usize::from(result.unwrap());
+ }
+ assert_eq!(admitted, 3);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn duplicate_admissions_reserve_once_even_after_lost_acknowledgement(pool: PgPool) {
+ let (repo, _) = setup(&pool, 0, false, 0).await;
+ let rate = rate();
+ let request = request(&rate, 20 * DOLLAR);
+ let mut tasks = tokio::task::JoinSet::new();
+ for _ in 0..8 {
+ let (repo, request, rate) = (repo.clone(), request.clone(), rate.clone());
+ tasks.spawn(async move { repo.authorize(request, rate).await.unwrap() });
+ }
+ let first = tasks.join_next().await.unwrap().unwrap();
+ while let Some(result) = tasks.join_next().await {
+ assert_eq!(result.unwrap(), first);
+ }
+ assert_eq!(
+ repo.pending(PendingInvocations {
+ after: None,
+ before: Utc::now() + Duration::days(1),
+ limit: 100.try_into().unwrap(),
+ })
+ .await
+ .unwrap(),
+ vec![request.invocation_id]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn collected_new_liability_is_neither_legacy_coverage_nor_a_second_cap_debit(pool: PgPool) {
+ let (repo, billing) = setup(&pool, 0, true, 210).await;
+ let first = admit(&repo, 21 * DOLLAR).await;
+ let allocation = allocated(&repo, first, 21 * DOLLAR).await;
+ assert_eq!(allocation.postpaid, CustomerMoney::from_cents(105).unwrap());
+ let payer = user("payer");
+ sqlx::query!(
+ "INSERT INTO ai_overage_charge (id, user_id, period_start, amount_cents, status, accounting_policy)
+ VALUES ($1, $2, $3, 105, 'paid', 'public_allowance_v1')",
+ macro_uuid::generate_uuid_v7(), payer.as_ref(), period().period.start,
+ ).execute(&pool).await.unwrap();
+ let ledger = billing
+ .period_ledger(&user("payer"), period().period.start)
+ .await
+ .unwrap();
+ assert_eq!(ledger.overage_charged_cents, 0);
+ let next = admit(&repo, DOLLAR).await;
+ assert_eq!(
+ allocated(&repo, next, DOLLAR).await.postpaid,
+ CustomerMoney::from_cents(105).unwrap()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn racing_postpaid_admissions_never_exceed_the_cap(pool: PgPool) {
+ let (repo, _) = setup(&pool, 0, true, 105).await;
+ let included = admit(&repo, 20 * DOLLAR).await;
+ allocated(&repo, included, 20 * DOLLAR).await;
+ let mut tasks = tokio::task::JoinSet::new();
+ for _ in 0..8 {
+ let repo = repo.clone();
+ tasks.spawn(async move {
+ let rate = rate();
+ repo.authorize(request(&rate, DOLLAR), rate).await.is_ok()
+ });
+ }
+ let mut admitted = 0;
+ while let Some(result) = tasks.join_next().await {
+ admitted += usize::from(result.unwrap());
+ }
+ assert_eq!(admitted, 1);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn legacy_settlement_cannot_spend_new_holds_or_cap(pool: PgPool) {
+ let (repo, billing) = setup(&pool, 1_050, true, 1_050).await;
+ let _held = admit(&repo, 40 * DOLLAR).await;
+ let policy = SettlementPolicy {
+ overage_active: true,
+ overage_limit_cents: 1_050,
+ charge_threshold_cents: 1_000,
+ period_ended: false,
+ };
+ let outcome = billing
+ .apply_settlement(&user("payer"), period().period.start, 5_000, policy)
+ .await
+ .unwrap();
+ assert_eq!(outcome.consumed_credits_cents, 0);
+ assert!(outcome.pending_charge.is_none());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn mixed_policy_seats_and_immutable_period_binding(pool: PgPool) {
+ let (repo, billing) = setup(&pool, 0, false, 0).await;
+ let seats = vec![
+ SeatAllowance {
+ user: user("seat"),
+ included_cents: 2_000,
+ },
+ SeatAllowance {
+ user: user("legacy"),
+ included_cents: 2_000,
+ },
+ ];
+ let legacy = billing
+ .legacy_seats(&user("payer"), period().period, seats)
+ .await
+ .unwrap();
+ assert_eq!(legacy.len(), 1);
+ assert_eq!(legacy[0].user, user("legacy"));
+ repo.record_period(period()).await.unwrap();
+ let mut changed = period();
+ changed.payer = user("new-payer");
+ assert!(repo.record_period(changed).await.is_err());
+ let mut overlap = period();
+ overlap.period.start += Duration::days(1);
+ assert!(repo.record_period(overlap).await.is_err());
+ assert!(
+ repo.period(user("seat"), period().period.end)
+ .await
+ .unwrap()
+ .is_none()
+ );
+ // A missing verified renewal must not fall back to a guessed monthly period.
+ let rate = rate();
+ let mut request = request(&rate, DOLLAR);
+ request.occurred_at = period().period.end;
+ assert!(repo.authorize(request, rate).await.is_err());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn purchases_toggles_cap_reductions_and_admission_use_the_same_lock(pool: PgPool) {
+ let (repo, billing) = setup(&pool, 0, false, 1_050).await;
+ let mut tx = pool.begin().await.unwrap();
+ lock_payer(&mut tx, user("payer").as_ref()).await.unwrap();
+
+ let purchase_repo = billing.clone();
+ let purchase = tokio::spawn(async move {
+ purchase_repo
+ .record_credit_purchase(&user("payer"), 1_050, "cs_race")
+ .await
+ .unwrap()
+ });
+ let toggle_repo = billing.clone();
+ let toggle = tokio::spawn(async move {
+ toggle_repo
+ .update_overage(&user("payer"), true, 1_050)
+ .await
+ .unwrap()
+ });
+ let cap_repo = billing.clone();
+ let cap = tokio::spawn(async move {
+ cap_repo
+ .update_overage(&user("payer"), false, 0)
+ .await
+ .unwrap()
+ });
+ let funding_repo = repo.clone();
+ let admission = tokio::spawn(async move { admit(&funding_repo, 20 * DOLLAR).await });
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ assert!(!purchase.is_finished());
+ assert!(!toggle.is_finished());
+ assert!(!cap.is_finished());
+ assert!(!admission.is_finished());
+ tx.commit().await.unwrap();
+ assert!(purchase.await.unwrap());
+ toggle.await.unwrap();
+ cap.await.unwrap();
+ let admitted = admission.await.unwrap();
+ let captured = sqlx::query!(
+ r#"SELECT admission AS "admission: Json<AdmissionData>" FROM ai_funding_reservation WHERE invocation_id = $1"#,
+ admitted.request.invocation_id.as_uuid(),
+ ).fetch_one(&pool).await.unwrap().admission;
+ assert_eq!(captured.policy, UsagePolicy::PublicAllowanceV1);
+ assert_eq!(
+ captured.overage_enabled,
+ matches!(captured.postpaid, PostpaidData::Enabled(_))
+ );
+ assert!(captured.revision <= 3);
+ billing
+ .update_overage(&user("payer"), false, 0)
+ .await
+ .unwrap();
+ assert_eq!(
+ allocated(&repo, admitted, 20 * DOLLAR)
+ .await
+ .extra_money()
+ .unwrap()
+ .units(),
+ 0
+ );
+ assert_eq!(
+ billing.credit_balance_cents(&user("payer")).await.unwrap(),
+ 1_050
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn renewal_expires_only_allowance_and_preserves_old_authorizations(pool: PgPool) {
+ let (repo, billing) = setup(&pool, 1_050, false, 0).await;
+ let old = admit(&repo, 30 * DOLLAR).await;
+ let mut renewal = period();
+ renewal.period.start = renewal.period.end;
+ renewal.period.end += Duration::days(30);
+ repo.record_period(renewal.clone()).await.unwrap();
+ let rate = rate();
+ let mut request = request(&rate, 20 * DOLLAR);
+ request.occurred_at = renewal.period.start;
+ let funding = repo.authorize(request.clone(), rate.clone()).await.unwrap();
+ let new = AuthorizedInvocation {
+ request,
+ rate,
+ funding,
+ };
+ let new_id = new.request.invocation_id;
+ repo.finalize(completed(new, 20 * DOLLAR)).await.unwrap();
+ assert!(repo.allocation(new_id).await.unwrap().is_none());
+ // Unused old holds do not consume rolled-over credits, nor transfer old allowance.
+ allocated(&repo, old, 20 * DOLLAR).await;
+ assert_eq!(
+ repo.allocation(new_id)
+ .await
+ .unwrap()
+ .unwrap()
+ .included_public
+ .units(),
+ 20 * DOLLAR
+ );
+ assert_eq!(
+ billing.credit_balance_cents(&user("payer")).await.unwrap(),
+ 1_050
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn domain_facade_rejects_exemption_and_exclusion_on_billable_funding(pool: PgPool) {
+ let (repo, _) = setup(&pool, 0, false, 0).await;
+ let service = FundingService::new(repo.clone());
+ let rate = rate();
+ let mut request = request(&rate, DOLLAR);
+ request.feature = crate::domain::models::NON_BILLABLE_AI_FEATURES[0];
+ assert!(service.authorize(request, rate).await.is_err());
+ let admission = admit(&repo, DOLLAR).await;
+ let mut record = completed(admission, DOLLAR);
+ let InvocationState::Priced { evidence, .. } = record.state else {
+ unreachable!()
+ };
+ record.state = InvocationState::Excluded {
+ evidence,
+ reason: ExclusionReason::LegacyPolicy,
+ };
+ assert!(service.finalize(record).await.is_err());
+}
diff --git a/crates/ai_billing/src/outbound/settling_recorder/test.rs b/crates/ai_billing/src/outbound/settling_recorder/test.rs
index fc035801d8..ad58869a73 100644
--- a/crates/ai_billing/src/outbound/settling_recorder/test.rs
+++ b/crates/ai_billing/src/outbound/settling_recorder/test.rs
@@ -94,6 +94,7 @@ impl BillingService for FakeBilling {
_payer: &MacroUserIdStr<'_>,
_start: DateTime<Utc>,
_end: DateTime<Utc>,
+ _verified: Option<crate::domain::period::SubscriptionPeriod>,
) -> Result<()> {
unreachable!()
}
diff --git a/crates/ai_tools/src/subagent.rs b/crates/ai_tools/src/subagent.rs
index 24139360d3..bf0da8c373 100644
--- a/crates/ai_tools/src/subagent.rs
+++ b/crates/ai_tools/src/subagent.rs
@@ -8,6 +8,17 @@ use tokio::select;
use crate::ToolServiceContext;
+#[cfg(test)]
+mod test;
+
+fn usage_for_request(
+ inherited: &ai_usage::UsageContext,
+ request: &RequestContext,
+) -> ai_usage::UsageContext {
+ ai_usage::UsageContext::new(inherited.feature, request.user_id.clone())
+ .with_entity(inherited.entity)
+}
+
static SUBAGENT_MODEL: PredefinedModel = PredefinedModel::Smart;
static SUBAGENT_PROMPT: &str = include_str!("prompts/subagent.md");
@@ -50,12 +61,13 @@ impl AsyncTool<ToolServiceContext> for Subagent {
// Cooperative cancellation: race the completion against the request's
// cancel token. If the user cancels, drop the in-flight completion and
// report "cancelled" rather than a partial or errored result.
+ let usage = usage_for_request(&service_context.usage_context, &request_context);
let completion = agent::complete(
SUBAGENT_MODEL,
SUBAGENT_PROMPT,
&self.task,
service_context.recorder.as_ref(),
- service_context.usage_context.clone(),
+ usage,
);
select! {
diff --git a/crates/ai_tools/src/subagent/test.rs b/crates/ai_tools/src/subagent/test.rs
new file mode 100644
index 0000000000..488d2d465a
--- /dev/null
+++ b/crates/ai_tools/src/subagent/test.rs
@@ -0,0 +1,17 @@
+use super::*;
+use ai_usage::{AiFeature, SYSTEM_USER_ID, UsageContext};
+
+#[tokio::test]
+async fn shared_system_context_does_not_become_subagent_attribution() {
+ let inherited = UsageContext::system(AiFeature::Automation);
+ let first = RequestContext::new("macro|[email protected]".to_owned().try_into().unwrap());
+ let second = RequestContext::new("macro|[email protected]".to_owned().try_into().unwrap());
+ let (a, b) = tokio::join!(async { usage_for_request(&inherited, &first) }, async {
+ usage_for_request(&inherited, &second)
+ },);
+ assert_eq!(a.user, first.user_id);
+ assert_eq!(b.user, second.user_id);
+ assert_eq!(a.feature, AiFeature::Automation);
+ assert_eq!(b.feature, AiFeature::Automation);
+ assert_eq!(inherited.user, *SYSTEM_USER_ID);
+}
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 42897d8fb8..ee2d7cb514 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -1513,6 +1513,7 @@ pub struct ToolServiceContext {
pub crm_tool_context: ToolCrmToolContext,
pub skill_tool_context: ToolSkillToolContext,
pub schedule_tool_context: NoOpScheduleContext,
+ #[from_ref(skip)]
pub anthropic_tool_context: AnthropicToolContext,
/// Records token usage / cost for AI calls made with this context.
pub recorder: std::sync::Arc<dyn ai_usage::UsageRecorder>,
@@ -1522,6 +1523,15 @@ pub struct ToolServiceContext {
pub usage_context: ai_usage::UsageContext,
}
+impl FromRef<ToolServiceContext> for AnthropicToolContext {
+ fn from_ref(context: &ToolServiceContext) -> Self {
+ let mut tools = context.anthropic_tool_context.clone();
+ tools.recorder = context.recorder.clone();
+ tools.usage_context = context.usage_context.clone();
+ tools
+ }
+}
+
impl ToolServiceContext {
/// Run the mutating tools as `actor`, delegated for the requesting user,
/// instead of the default Macro AI bot. Hosts running a specific agent
diff --git a/crates/ai_usage/src/domain/financial.rs b/crates/ai_usage/src/domain/financial.rs
new file mode 100644
index 0000000000..7032ec8445
--- /dev/null
+++ b/crates/ai_usage/src/domain/financial.rs
@@ -0,0 +1,709 @@
+//! Financial invocation contracts, independent of mutable analytics pricing.
+//!
+//! One invocation is one actual provider attempt. Transport/delivery retries reuse
+//! its ID; another provider execution (including a fallback) requires a new ID.
+//! Only authenticated server-side adapters may construct trusted usage or select
+//! a nonfinancial mode. No prompt, output, credential, or raw token text belongs here.
+
+use std::num::NonZeroU16;
+use std::sync::Arc;
+
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::{Uuid, generate_uuid_v7};
+use thiserror::Error;
+
+use super::ports::{AiFeature, FinancialUsage};
+
+#[cfg(test)]
+mod test;
+
+macro_rules! financial_id {
+ ($name:ident, $doc:literal) => {
+ #[doc = $doc]
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+ pub struct $name(Uuid);
+
+ impl $name {
+ /// Allocate a UUIDv7 once, before the first delivery attempt.
+ pub fn new() -> Self {
+ Self(generate_uuid_v7())
+ }
+
+ /// The durable identifier, for persistence and transport adapters.
+ pub fn as_uuid(self) -> Uuid {
+ self.0
+ }
+ }
+
+ impl Default for $name {
+ fn default() -> Self {
+ Self::new()
+ }
+ }
+
+ impl TryFrom<Uuid> for $name {
+ type Error = FinancialError;
+
+ fn try_from(value: Uuid) -> FinancialResult<Self> {
+ if value.is_nil() {
+ return Err(FinancialError::InvalidIdentifier);
+ }
+ Ok(Self(value))
+ }
+ }
+ };
+}
+
+financial_id!(
+ RunId,
+ "Stable identity of a logical run across provider attempts."
+);
+financial_id!(
+ InvocationId,
+ "Stable identity of exactly one provider execution."
+);
+financial_id!(
+ RateVersion,
+ "Identity of an immutable provider-qualified rate snapshot."
+);
+financial_id!(
+ FundingAuthorizationId,
+ "Opaque reference to authorization facts owned by the funding domain."
+);
+
+/// Provider and exact API model identity. Never use analytics' bare-model normalization.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct ProviderModel {
+ provider: String,
+ model: String,
+}
+
+impl ProviderModel {
+ /// Provider keys are canonical lowercase ASCII identifiers. Model names retain
+ /// their exact spelling, including slashes; whitespace/control characters are rejected.
+ pub fn new(provider: impl Into<String>, model: impl Into<String>) -> FinancialResult<Self> {
+ let provider = provider.into();
+ let model = model.into();
+ if !valid_identifier(&provider)
+ || !provider
+ .bytes()
+ .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
+ || !valid_identifier(&model)
+ {
+ return Err(FinancialError::InvalidIdentifier);
+ }
+ Ok(Self { provider, model })
+ }
+
+ /// Canonical provider identity (including distinct compatible API providers).
+ pub fn provider(&self) -> &str {
+ &self.provider
+ }
+
+ /// Exact provider API model identifier, not a routing alias.
+ pub fn model(&self) -> &str {
+ &self.model
+ }
+}
+
+/// Provider request identity used to reconcile evidence, not as the invocation's idempotency key.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ProviderRequestId(String);
+
+impl ProviderRequestId {
+ /// Validate an opaque request identifier without normalizing it.
+ pub fn new(value: impl Into<String>) -> FinancialResult<Self> {
+ let value = value.into();
+ if !valid_identifier(&value) {
+ return Err(FinancialError::InvalidIdentifier);
+ }
+ Ok(Self(value))
+ }
+
+ /// Original provider request identifier.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+fn valid_identifier(value: &str) -> bool {
+ !value.is_empty() && !value.chars().any(|c| c.is_whitespace() || c.is_control())
+}
+
+/// Public-provider-price usage, in picodollars (10^-12 USD), not customer money.
+/// $1 per million tokens is 1,000,000 units per token. No floating point or rounding.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub struct PublicUsage(u64);
+
+impl PublicUsage {
+ /// Construct an exact nonnegative public usage quantity.
+ pub const fn from_units(units: u64) -> Self {
+ Self(units)
+ }
+
+ /// Exact picodollar quantity.
+ pub const fn units(self) -> u64 {
+ self.0
+ }
+
+ /// Add without wrapping or saturating.
+ pub fn checked_add(self, other: Self) -> FinancialResult<Self> {
+ self.0
+ .checked_add(other.0)
+ .map(Self)
+ .ok_or(FinancialError::ArithmeticOverflow)
+ }
+
+ /// Subtract without permitting negative usage.
+ pub fn checked_sub(self, other: Self) -> FinancialResult<Self> {
+ self.0
+ .checked_sub(other.0)
+ .map(Self)
+ .ok_or(FinancialError::ArithmeticOverflow)
+ }
+}
+
+/// Customer USD in hundredths of a picodollar (10^-14 USD). The extra two decimal
+/// places preserve percentage pricing, including 1.05, exactly for every public unit.
+/// This is distinct from public usage and from the whole-cent payment ledger.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub struct CustomerMoney(u64);
+
+impl CustomerMoney {
+ /// Customer-money units in one cent.
+ pub const UNITS_PER_CENT: u64 = 1_000_000_000_000;
+
+ /// Construct an exact nonnegative customer-money amount.
+ pub const fn from_units(units: u64) -> Self {
+ Self(units)
+ }
+
+ /// Exact hundredth-picodollar quantity.
+ pub const fn units(self) -> u64 {
+ self.0
+ }
+
+ /// Convert whole-cent ledger money without overflow.
+ pub fn from_cents(cents: u64) -> FinancialResult<Self> {
+ narrow(u128::from(cents) * u128::from(Self::UNITS_PER_CENT)).map(Self)
+ }
+
+ /// Convert public usage at an explicit rational price multiplier. Policy chooses
+ /// the ratio; this conversion never decides whether usage is included or extra.
+ /// Reject unrepresentable fractions rather than silently losing a remainder.
+ pub fn from_public_ratio(
+ usage: PublicUsage,
+ numerator: u64,
+ denominator: u64,
+ ) -> FinancialResult<Self> {
+ if denominator == 0 {
+ return Err(FinancialError::ZeroDenominator);
+ }
+ let scaled = u128::from(usage.units())
+ .checked_mul(100)
+ .and_then(|value| value.checked_mul(u128::from(numerator)))
+ .ok_or(FinancialError::ArithmeticOverflow)?;
+ let denominator = u128::from(denominator);
+ if scaled % denominator != 0 {
+ return Err(FinancialError::InsufficientPrecision);
+ }
+ narrow(scaled / denominator).map(Self)
+ }
+
+ /// Add without wrapping or saturating.
+ pub fn checked_add(self, other: Self) -> FinancialResult<Self> {
+ self.0
+ .checked_add(other.0)
+ .map(Self)
+ .ok_or(FinancialError::ArithmeticOverflow)
+ }
+
+ /// Subtract without permitting negative customer money.
+ pub fn checked_sub(self, other: Self) -> FinancialResult<Self> {
+ self.0
+ .checked_sub(other.0)
+ .map(Self)
+ .ok_or(FinancialError::ArithmeticOverflow)
+ }
+
+ /// Separate cents from the exact subcent remainder. This does not round;
+ /// settlement must retain the remainder and round only cumulative liability.
+ pub const fn split_cents(self) -> CentParts {
+ CentParts {
+ whole_cents: self.0 / Self::UNITS_PER_CENT,
+ subcent_units: self.0 % Self::UNITS_PER_CENT,
+ }
+ }
+}
+
+fn narrow(value: u128) -> FinancialResult<u64> {
+ u64::try_from(value).map_err(|_| FinancialError::ArithmeticOverflow)
+}
+
+/// Lossless decomposition of customer money for the whole-cent payment boundary.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct CentParts {
+ /// Whole USD cents, without rounding.
+ pub whole_cents: u64,
+ /// Remaining [`CustomerMoney`] units, strictly less than one cent.
+ pub subcent_units: u64,
+}
+
+/// Complete, trusted provider counters normalized into mutually exclusive buckets.
+/// Adapters must verify provider semantics: inclusive cache/reasoning counters are
+/// not additional tokens. Missing/estimated counters must not be filled with zero.
+/// Zero is allowed only when reported or known to be inapplicable to this model.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct TrustedTokenUsage {
+ input: u64,
+ output: u64,
+ cache_read: u64,
+ cache_write: u64,
+ reasoning: u64,
+}
+
+impl TrustedTokenUsage {
+ /// Construct verified, non-overlapping counters. Input excludes cache reads and
+ /// writes; output excludes reasoning. Do not pass unverified client counters.
+ pub const fn from_disjoint(
+ input: u64,
+ output: u64,
+ cache_read: u64,
+ cache_write: u64,
+ reasoning: u64,
+ ) -> Self {
+ Self {
+ input,
+ output,
+ cache_read,
+ cache_write,
+ reasoning,
+ }
+ }
+
+ /// Normalize providers whose input includes both cache buckets and whose output
+ /// includes reasoning. Other provider semantics must use `from_disjoint` instead.
+ pub fn from_inclusive_totals(
+ input: u64,
+ output: u64,
+ cache_read: u64,
+ cache_write: u64,
+ reasoning: u64,
+ ) -> FinancialResult<Self> {
+ let input = input
+ .checked_sub(cache_read)
+ .and_then(|value| value.checked_sub(cache_write))
+ .ok_or(FinancialError::InvalidTokenUsage)?;
+ let output = output
+ .checked_sub(reasoning)
+ .ok_or(FinancialError::InvalidTokenUsage)?;
+ Ok(Self::from_disjoint(
+ input,
+ output,
+ cache_read,
+ cache_write,
+ reasoning,
+ ))
+ }
+
+ /// Input excluding cache reads and writes.
+ pub const fn input(self) -> u64 {
+ self.input
+ }
+ /// Output excluding reasoning.
+ pub const fn output(self) -> u64 {
+ self.output
+ }
+ /// Cache-read tokens, not included in `input`.
+ pub const fn cache_read(self) -> u64 {
+ self.cache_read
+ }
+ /// Cache-write tokens, not included in `input`.
+ pub const fn cache_write(self) -> u64 {
+ self.cache_write
+ }
+ /// Reasoning tokens, not included in `output`.
+ pub const fn reasoning(self) -> u64 {
+ self.reasoning
+ }
+}
+
+/// Public picodollars per token, for each disjoint dimension. Different cache TTLs
+/// or pricing regimes require distinct immutable versions; never blend unknown rates.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct TokenRates {
+ /// Non-cache input rate.
+ pub input: u64,
+ /// Non-reasoning output rate.
+ pub output: u64,
+ /// Cache-read rate.
+ pub cache_read: u64,
+ /// Cache-write rate.
+ pub cache_write: u64,
+ /// Reasoning rate (often the output rate, but explicitly captured).
+ pub reasoning: u64,
+}
+
+impl TokenRates {
+ /// Price complete evidence exactly, using checked wider intermediates for products and sums.
+ pub fn price(self, usage: TrustedTokenUsage) -> FinancialResult<PublicUsage> {
+ let dimensions = [
+ (self.input, usage.input),
+ (self.output, usage.output),
+ (self.cache_read, usage.cache_read),
+ (self.cache_write, usage.cache_write),
+ (self.reasoning, usage.reasoning),
+ ];
+ let total = dimensions
+ .into_iter()
+ .try_fold(0_u128, |total, (rate, tokens)| {
+ total
+ .checked_add(u128::from(rate) * u128::from(tokens))
+ .ok_or(FinancialError::ArithmeticOverflow)
+ })?;
+ narrow(total).map(PublicUsage)
+ }
+}
+
+/// Immutable financial price facts. Repositories must enforce that a version is
+/// bound permanently to these fields; analytics repricing cannot mutate them.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct RateSnapshot {
+ /// Immutable rate identity, resolved before funding authorization.
+ pub version: RateVersion,
+ /// Actual provider and model to which the rates apply.
+ pub model: ProviderModel,
+ /// Inclusive start of this version's applicability.
+ pub effective_at: DateTime<Utc>,
+ /// Explicit rates for every normalized token dimension.
+ pub tokens: TokenRates,
+}
+
+impl RateSnapshot {
+ /// Reject another provider/model's rates even when the bare model names match.
+ pub fn require_model(&self, model: &ProviderModel) -> FinancialResult<()> {
+ if &self.model != model {
+ return Err(FinancialError::RateModelMismatch);
+ }
+ Ok(())
+ }
+}
+
+/// Trusted request to admit exactly one bounded provider attempt.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct BeginInvocation {
+ /// Logical run identity, retained across rounds and fallbacks.
+ pub run_id: RunId,
+ /// Provider attempt identity, retained only across delivery retries.
+ pub invocation_id: InvocationId,
+ /// Authenticated originating user; funding resolves payer/seat attribution.
+ pub user: MacroUserIdStr<'static>,
+ /// Calling feature, verified by the host.
+ pub feature: AiFeature,
+ /// Related entity, if any.
+ pub entity: Option<Uuid>,
+ /// Actual provider/model, not a router alias.
+ pub model: ProviderModel,
+ /// Occurrence time, retained on replay rather than replaced by ingestion time.
+ pub occurred_at: DateTime<Utc>,
+ /// Verified per-dimension execution ceiling, not a measurement of actual usage.
+ /// Unsupported/unbounded execution must not enter activated billable traffic.
+ pub token_budget: TrustedTokenUsage,
+}
+
+impl BeginInvocation {
+ /// All admission facts must match on delivery replay, not just the invocation ID.
+ pub fn check_replay(&self, replay: &Self) -> FinancialResult<()> {
+ if self != replay {
+ return Err(FinancialError::ReplayConflict {
+ invocation_id: self.invocation_id,
+ phase: ReplayPhase::Begin,
+ });
+ }
+ Ok(())
+ }
+}
+
+/// Funding facts are durably captured by the injected owning domain before success.
+/// The reference freezes payer, policy, period, settings revision and reserved sources
+/// there; callers must never reconstruct authorization from today's billing settings.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct FundingAuthorization {
+ /// Owning-domain authorization identity.
+ pub id: FundingAuthorizationId,
+ /// Invocation to which authorization is exclusively bound.
+ pub invocation_id: InvocationId,
+ /// Public-price budget admitted for this attempt, not customer liability.
+ pub maximum_public_usage: PublicUsage,
+}
+
+/// Admission facts acknowledged before contacting the provider.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct AuthorizedInvocation {
+ /// Immutable invocation context and execution bound.
+ pub request: BeginInvocation,
+ /// Immutable rates resolved before asking for funding.
+ pub rate: RateSnapshot,
+ /// Durable authorization from the funding domain.
+ pub funding: FundingAuthorization,
+}
+
+/// Provider outcome is independent of whether billable usage was incurred.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ProviderOutcome {
+ /// Provider execution completed successfully.
+ Succeeded,
+ /// Provider execution failed, possibly after incurring usage.
+ Failed,
+ /// Caller or provider cancelled execution, possibly after incurring usage.
+ Cancelled,
+ /// Execution outcome is unknown after loss of contact or process interruption.
+ Unknown,
+}
+
+/// Why usage cannot yet be trusted. None of these implies zero cost.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum UnresolvedReason {
+ /// Provider omitted reliable usage counters.
+ UsageNotReported,
+ /// Execution or stream was interrupted before complete evidence arrived.
+ Interrupted,
+ /// Provider counters could not be normalized without guessing.
+ UnsupportedDimensions,
+}
+
+/// Explicit distinction between a measured zero and missing provider evidence.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum UsageEvidence {
+ /// Complete server-verified provider usage, including legitimate zero usage.
+ Reported(TrustedTokenUsage),
+ /// No complete trusted counters; never synthesize zeros or estimate customer debt.
+ Missing(UnresolvedReason),
+}
+
+/// Final provider facts submitted by a trusted adapter, not a caller-supplied charge.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct FinalizeInvocation {
+ /// Identity of the previously admitted attempt.
+ pub invocation_id: InvocationId,
+ /// Provider occurrence time, not the delivery retry time.
+ pub occurred_at: DateTime<Utc>,
+ /// Provider correlation identity when supplied.
+ pub provider_request_id: Option<ProviderRequestId>,
+ /// Success, failure and cancellation can all carry usage.
+ pub outcome: ProviderOutcome,
+ /// Complete counters or an explicit unresolved reason.
+ pub usage: UsageEvidence,
+}
+
+impl FinalizeInvocation {
+ /// Duplicate evidence is a no-op; changed evidence requires explicit reconciliation,
+ /// never a last-write-wins overwrite or a second charge.
+ pub fn check_replay(&self, replay: &Self) -> FinancialResult<()> {
+ if self != replay {
+ return Err(FinancialError::ReplayConflict {
+ invocation_id: self.invocation_id,
+ phase: ReplayPhase::Finalize,
+ });
+ }
+ Ok(())
+ }
+}
+
+/// Explicit, policy-selected reasons for no new-policy financial charge.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ExclusionReason {
+ /// Historical/current legacy policy remains on its original accounting path.
+ LegacyPolicy,
+ /// Feature exemption resolved by the owning policy, not inferred from missing plumbing.
+ ExemptFeature,
+ /// Verified internal work has no customer liability.
+ InternalWork,
+}
+
+/// Why complete evidence cannot be priced. Preserve it; do not substitute zero.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum UnpricedReason {
+ /// No immutable rate matches the actual provider/model/dimensions.
+ MissingRate,
+ /// Evidence cannot be represented within checked financial arithmetic.
+ ArithmeticOverflow,
+}
+
+/// Durable financial evidence state. Priced/unpriced require reported usage;
+/// unresolved requires missing usage. The journal service validates those invariants
+/// and the evidence's invocation ID before persisting a transition from pending.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum InvocationState {
+ /// Begin persisted; no final evidence acknowledged. This is not zero usage.
+ Pending,
+ /// Complete evidence valued at the pinned public rate, not yet a customer charge.
+ Priced {
+ /// Immutable provider facts.
+ evidence: FinalizeInvocation,
+ /// Exact public-price usage.
+ public_usage: PublicUsage,
+ },
+ /// Evidence retained but explicitly excluded by the captured policy.
+ Excluded {
+ /// Immutable provider facts, possibly missing usage.
+ evidence: FinalizeInvocation,
+ /// Explicit exclusion decision.
+ reason: ExclusionReason,
+ },
+ /// Complete counters exist but cannot safely be valued.
+ Unpriced {
+ /// Immutable provider facts.
+ evidence: FinalizeInvocation,
+ /// Why pricing is unavailable.
+ reason: UnpricedReason,
+ },
+ /// Incomplete/untrusted evidence requires reconciliation, not invented debt.
+ Unresolved {
+ /// Immutable facts including the missing-usage reason.
+ evidence: FinalizeInvocation,
+ },
+}
+
+/// Queryable invocation journal entry. Funding allocation is owned by the injected
+/// funding domain, not inferred from this public-price record or current opt-in.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct InvocationRecord {
+ /// Acknowledged admission facts.
+ pub admission: AuthorizedInvocation,
+ /// Pending or finalized evidence and valuation.
+ pub state: InvocationState,
+}
+
+/// Outcome of an idempotent journal write.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum WriteDisposition {
+ /// This delivery durably inserted the facts for the first time.
+ Inserted,
+ /// Identical facts already existed. A begin replay must NOT execute the provider
+ /// again: execution may already have happened despite a lost acknowledgement.
+ Replayed,
+}
+
+/// Acknowledged journal value and replay disposition.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Recorded<T> {
+ /// Durable value, identical on successful replay.
+ pub value: T,
+ /// Whether this was a new write or an identical replay.
+ pub disposition: WriteDisposition,
+}
+
+/// Bounded, stable-ID scan for pending/unpriced/unresolved recovery work.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct PendingInvocations {
+ /// Exclusive cursor in ascending invocation-ID order.
+ pub after: Option<InvocationId>,
+ /// Include admissions strictly older than this cutoff.
+ pub before: DateTime<Utc>,
+ /// Maximum rows returned. Restart the scan to revisit unresolved entries.
+ pub limit: NonZeroU16,
+}
+
+/// Mode selected from trusted activation/policy facts, never from client input or
+/// purchasable plan names. Legacy analytics must not also enter new-policy settlement.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum FinancialMode {
+ /// Observe attempts without authorization, reservations, allocation or collection.
+ /// This is not a financial exemption and cannot later authorize historical debt.
+ TrackingOnly,
+ /// Requires awaited financial authorization before every provider execution.
+ Activated,
+ /// Preserve existing analytics/legacy accounting without reconstructing debt.
+ Legacy,
+ /// Explicitly exempt traffic; analytics may still be recorded.
+ NonFinancial(ExclusionReason),
+}
+
+/// Separate object-safe capability injected alongside `Arc<dyn UsageRecorder>`.
+/// There is deliberately no successful no-op financial implementation.
+#[derive(Clone)]
+pub enum FinancialCapability {
+ /// Host has not wired financial support; activated traffic must fail closed.
+ Unavailable,
+ /// Host-provided financial lifecycle facade.
+ Available(Arc<dyn FinancialUsage>),
+}
+
+impl FinancialCapability {
+ /// Select the financial path without silently treating unavailable support as
+ /// authorization. `None` is possible only for an explicitly nonfinancial/legacy mode.
+ pub fn for_mode(&self, mode: FinancialMode) -> FinancialResult<Option<&dyn FinancialUsage>> {
+ match (mode, self) {
+ (
+ FinancialMode::TrackingOnly
+ | FinancialMode::Legacy
+ | FinancialMode::NonFinancial(_),
+ _,
+ ) => Ok(None),
+ (FinancialMode::Activated, Self::Unavailable) => {
+ Err(FinancialError::CapabilityUnavailable)
+ }
+ (FinancialMode::Activated, Self::Available(service)) => Ok(Some(service.as_ref())),
+ }
+ }
+}
+
+/// Which immutable write was contradicted by a replay.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ReplayPhase {
+ /// Admission context, model or budget changed.
+ Begin,
+ /// Provider evidence changed.
+ Finalize,
+}
+
+/// Financial lifecycle failures. No error authorizes provider execution.
+#[derive(Debug, Error)]
+pub enum FinancialError {
+ /// Missing mandatory financial wiring for activated traffic.
+ #[error("financial capability unavailable")]
+ CapabilityUnavailable,
+ /// No applicable immutable financial rate; analytics prices are not a fallback.
+ #[error("immutable financial rate unavailable")]
+ RateUnavailable,
+ /// Rate belongs to a different qualified model.
+ #[error("financial rate provider/model mismatch")]
+ RateModelMismatch,
+ /// Funding domain refused the attempt (allowance/credit/cap/eligibility policy).
+ #[error("funding authorization denied")]
+ FundingDenied,
+ /// Finalization referenced an invocation that was never begun.
+ #[error("invocation not found")]
+ InvocationNotFound,
+ /// Invalid identifier shape or nil stable ID.
+ #[error("invalid financial identifier")]
+ InvalidIdentifier,
+ /// Inclusive totals cannot contain the claimed cache/reasoning counts.
+ #[error("inconsistent token usage")]
+ InvalidTokenUsage,
+ /// Financial operations never wrap, saturate, or permit negative balances.
+ #[error("financial arithmetic overflow or underflow")]
+ ArithmeticOverflow,
+ /// Unsupported precision must not be rounded away silently.
+ #[error("financial amount is below supported precision")]
+ InsufficientPrecision,
+ /// Invalid rational multiplier.
+ #[error("financial ratio denominator must be nonzero")]
+ ZeroDenominator,
+ /// An ID was reused with different immutable facts.
+ #[error("conflicting {phase:?} replay for invocation {invocation_id:?}")]
+ ReplayConflict {
+ /// Conflicting invocation identity.
+ invocation_id: InvocationId,
+ /// Conflicting stage.
+ phase: ReplayPhase,
+ },
+ /// Adapter failure, retaining the original error report.
+ #[error("financial infrastructure error: {0}")]
+ Infrastructure(rootcause::Report),
+}
+
+/// Result type for financial contracts, separate from best-effort analytics errors.
+pub type FinancialResult<T> = Result<T, FinancialError>;
diff --git a/crates/ai_usage/src/domain/financial/test.rs b/crates/ai_usage/src/domain/financial/test.rs
new file mode 100644
index 0000000000..53b090724d
--- /dev/null
+++ b/crates/ai_usage/src/domain/financial/test.rs
@@ -0,0 +1,278 @@
+use super::*;
+use crate::domain::ports::{FinancialFuture, FinancialUsage, NoOpUsageRecorder, UsageRecorder};
+use std::collections::HashMap;
+use std::sync::Arc;
+
+fn model(provider: &str) -> ProviderModel {
+ ProviderModel::new(provider, "shared/model-name").unwrap()
+}
+
+fn rate(provider: &str) -> RateSnapshot {
+ RateSnapshot {
+ version: RateVersion::new(),
+ model: model(provider),
+ effective_at: Utc::now(),
+ // Picodollars/token: $1, $2, $0.10, $1.25 and $2 per million.
+ tokens: TokenRates {
+ input: 1_000_000,
+ output: 2_000_000,
+ cache_read: 100_000,
+ cache_write: 1_250_000,
+ reasoning: 2_000_000,
+ },
+ }
+}
+
+fn begin() -> BeginInvocation {
+ BeginInvocation {
+ run_id: RunId::new(),
+ invocation_id: InvocationId::new(),
+ user: MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap(),
+ feature: AiFeature::Chat,
+ entity: None,
+ model: model("provider-a"),
+ occurred_at: Utc::now(),
+ token_budget: TrustedTokenUsage::from_disjoint(10, 20, 0, 0, 0),
+ }
+}
+
+fn finalize(invocation_id: InvocationId) -> FinalizeInvocation {
+ FinalizeInvocation {
+ invocation_id,
+ occurred_at: Utc::now(),
+ provider_request_id: Some(ProviderRequestId::new("request-123").unwrap()),
+ outcome: ProviderOutcome::Succeeded,
+ usage: UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(1, 2, 0, 0, 0)),
+ }
+}
+
+#[test]
+fn stable_ids_roundtrip_and_reject_nil() {
+ let id = InvocationId::new();
+ assert_eq!(id, InvocationId::try_from(id.as_uuid()).unwrap());
+ assert_eq!(id.as_uuid().get_version_num(), 7);
+ assert!(InvocationId::try_from(Uuid::nil()).is_err());
+ assert_ne!(InvocationId::new(), id);
+}
+
+#[test]
+fn qualified_models_do_not_collide_or_strip_nested_names() {
+ let first = rate("provider-a");
+ let second = rate("provider-b");
+ let rates = HashMap::from([
+ (first.model.clone(), first.version),
+ (second.model.clone(), second.version),
+ ]);
+ assert_eq!(rates.len(), 2);
+ assert_eq!(first.model.model(), "shared/model-name");
+ assert!(first.require_model(&second.model).is_err());
+ assert!(ProviderModel::new("", "model").is_err());
+ assert!(ProviderModel::new("Provider-A", "model").is_err());
+ assert!(ProviderModel::new("provider-a", " model ").is_err());
+ assert!(ProviderRequestId::new("\n").is_err());
+}
+
+#[test]
+fn pricing_preserves_fractional_cents_and_disjoint_dimensions() {
+ let tokens = TrustedTokenUsage::from_inclusive_totals(100, 50, 20, 10, 5).unwrap();
+ assert_eq!(tokens, TrustedTokenUsage::from_disjoint(70, 45, 20, 10, 5));
+ let usage = rate("provider-a").tokens.price(tokens).unwrap();
+ assert_eq!(usage.units(), 184_500_000);
+ let money = CustomerMoney::from_public_ratio(usage, 105, 100).unwrap();
+ assert_eq!(money.units(), 19_372_500_000);
+ assert_eq!(money.split_cents().whole_cents, 0);
+ assert_eq!(money.split_cents().subcent_units, money.units());
+}
+
+#[test]
+fn rejects_inconsistent_inclusive_token_counts() {
+ assert!(TrustedTokenUsage::from_inclusive_totals(5, 10, 4, 2, 0).is_err());
+ assert!(TrustedTokenUsage::from_inclusive_totals(5, 10, 0, 0, 11).is_err());
+ assert!(TrustedTokenUsage::from_inclusive_totals(u64::MAX, 0, u64::MAX, 1, 0).is_err());
+}
+
+#[test]
+fn overflow_is_explicit_and_wider_intermediates_preserve_valid_results() {
+ let max = PublicUsage::from_units(u64::MAX);
+ assert!(max.checked_add(PublicUsage::from_units(1)).is_err());
+ assert!(PublicUsage::from_units(0).checked_sub(max).is_err());
+ assert!(CustomerMoney::from_cents(u64::MAX).is_err());
+ assert!(
+ CustomerMoney::from_units(u64::MAX)
+ .checked_add(CustomerMoney::from_units(1))
+ .is_err()
+ );
+ assert!(
+ CustomerMoney::from_units(0)
+ .checked_sub(CustomerMoney::from_units(1))
+ .is_err()
+ );
+ assert!(CustomerMoney::from_public_ratio(max, 1, 1).is_err());
+ // Multiplication exceeds u64 before division, but the final result fits.
+ assert_eq!(
+ CustomerMoney::from_public_ratio(max, 1, 100)
+ .unwrap()
+ .units(),
+ u64::MAX
+ );
+ assert!(CustomerMoney::from_public_ratio(max, u64::MAX, 1).is_err());
+ assert!(CustomerMoney::from_public_ratio(max, 1, 0).is_err());
+ // Never silently discard precision below the money unit.
+ assert!(CustomerMoney::from_public_ratio(PublicUsage::from_units(1), 1, 3).is_err());
+ let rates = TokenRates {
+ input: u64::MAX,
+ output: u64::MAX,
+ cache_read: 0,
+ cache_write: 0,
+ reasoning: 0,
+ };
+ assert!(
+ rates
+ .price(TrustedTokenUsage::from_disjoint(
+ u64::MAX,
+ u64::MAX,
+ 0,
+ 0,
+ 0
+ ))
+ .is_err()
+ );
+}
+
+#[test]
+fn subcent_parts_recombine_without_per_invocation_rounding() {
+ let cent = CustomerMoney::from_cents(1).unwrap();
+ let fraction = CustomerMoney::from_units(cent.units() / 4);
+ let total = fraction
+ .checked_add(fraction)
+ .unwrap()
+ .checked_add(fraction)
+ .unwrap();
+ assert_eq!(total.split_cents().whole_cents, 0);
+ assert_eq!(
+ total.checked_add(fraction).unwrap().split_cents(),
+ CentParts {
+ whole_cents: 1,
+ subcent_units: 0
+ }
+ );
+ let total = cent.checked_add(fraction).unwrap();
+ let parts = total.split_cents();
+ assert_eq!(
+ CustomerMoney::from_cents(parts.whole_cents)
+ .unwrap()
+ .checked_add(CustomerMoney::from_units(parts.subcent_units))
+ .unwrap(),
+ total
+ );
+}
+
+#[test]
+fn replay_accepts_identical_evidence_but_rejects_changed_facts() {
+ let request = begin();
+ assert!(request.check_replay(&request.clone()).is_ok());
+ let mut changed = request.clone();
+ changed.model = model("provider-b");
+ assert!(matches!(
+ request.check_replay(&changed),
+ Err(FinancialError::ReplayConflict {
+ phase: ReplayPhase::Begin,
+ ..
+ })
+ ));
+ changed = request.clone();
+ changed.token_budget = TrustedTokenUsage::from_disjoint(11, 20, 0, 0, 0);
+ assert!(request.check_replay(&changed).is_err());
+
+ let evidence = finalize(request.invocation_id);
+ assert!(evidence.check_replay(&evidence.clone()).is_ok());
+ let mut changed = evidence.clone();
+ changed.usage = UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(2, 2, 0, 0, 0));
+ assert!(matches!(
+ evidence.check_replay(&changed),
+ Err(FinancialError::ReplayConflict {
+ phase: ReplayPhase::Finalize,
+ ..
+ })
+ ));
+ changed = evidence.clone();
+ changed.provider_request_id = None;
+ assert!(evidence.check_replay(&changed).is_err());
+ changed = evidence.clone();
+ changed.occurred_at += chrono::Duration::seconds(1);
+ assert!(evidence.check_replay(&changed).is_err());
+}
+
+#[test]
+fn missing_usage_is_not_reported_zero() {
+ let zero = UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(0, 0, 0, 0, 0));
+ let missing = UsageEvidence::Missing(UnresolvedReason::UsageNotReported);
+ assert_ne!(zero, missing);
+ let mut evidence = finalize(InvocationId::new());
+ evidence.usage = zero;
+ let mut replay = evidence.clone();
+ replay.usage = missing;
+ assert!(evidence.check_replay(&replay).is_err());
+ assert_eq!(
+ rate("provider-a")
+ .tokens
+ .price(TrustedTokenUsage::from_disjoint(0, 0, 0, 0, 0))
+ .unwrap(),
+ PublicUsage::from_units(0)
+ );
+}
+
+// Implementing the ports through boxed futures is a compile-time object-safety check.
+struct UnavailableFinancial;
+
+impl FinancialUsage for UnavailableFinancial {
+ fn begin(&self, _: BeginInvocation) -> FinancialFuture<'_, Recorded<AuthorizedInvocation>> {
+ Box::pin(async { Err(FinancialError::CapabilityUnavailable) })
+ }
+
+ fn finalize(&self, _: FinalizeInvocation) -> FinancialFuture<'_, Recorded<InvocationRecord>> {
+ Box::pin(async { Err(FinancialError::CapabilityUnavailable) })
+ }
+
+ fn get(&self, _: InvocationId) -> FinancialFuture<'_, Option<InvocationRecord>> {
+ Box::pin(async { Err(FinancialError::CapabilityUnavailable) })
+ }
+
+ fn pending(&self, _: PendingInvocations) -> FinancialFuture<'_, Vec<InvocationRecord>> {
+ Box::pin(async { Err(FinancialError::CapabilityUnavailable) })
+ }
+}
+
+#[tokio::test]
+async fn separate_object_safe_capability_fails_closed_for_activated_traffic() {
+ let _analytics: Arc<dyn UsageRecorder> = Arc::new(NoOpUsageRecorder);
+ let missing = FinancialCapability::Unavailable;
+ assert!(matches!(
+ missing.for_mode(FinancialMode::Activated),
+ Err(FinancialError::CapabilityUnavailable)
+ ));
+ assert!(missing.for_mode(FinancialMode::Legacy).unwrap().is_none());
+ assert!(
+ missing
+ .for_mode(FinancialMode::NonFinancial(ExclusionReason::ExemptFeature))
+ .unwrap()
+ .is_none()
+ );
+ let financial: Arc<dyn FinancialUsage> = Arc::new(UnavailableFinancial);
+ let capability = FinancialCapability::Available(financial);
+ assert!(matches!(
+ capability
+ .for_mode(FinancialMode::Activated)
+ .unwrap()
+ .unwrap()
+ .begin(begin())
+ .await,
+ Err(FinancialError::CapabilityUnavailable)
+ ));
+ fn assert_dyn_ports(
+ _: &dyn crate::domain::ports::FinancialRateResolver,
+ _: &dyn crate::domain::ports::InvocationFunding,
+ ) {
+ }
+ let _ = assert_dyn_ports;
+}
diff --git a/crates/ai_usage/src/domain/financial_service.rs b/crates/ai_usage/src/domain/financial_service.rs
new file mode 100644
index 0000000000..d60d5334be
--- /dev/null
+++ b/crates/ai_usage/src/domain/financial_service.rs
@@ -0,0 +1,292 @@
+//! Durable financial lifecycle. Funding policy remains in the injected owning domain.
+
+use std::sync::Arc;
+
+use chrono::{DateTime, Utc};
+
+use super::financial::*;
+use super::ports::{FinancialFuture, FinancialRateResolver, FinancialUsage, InvocationFunding};
+
+#[cfg(test)]
+mod test;
+
+/// Durable pre-authorization intent. A crash here is recoverable without executing a provider.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PreparedInvocation {
+ /// Immutable request and execution ceiling.
+ pub request: BeginInvocation,
+ /// Rate pinned before requesting funding.
+ pub rate: RateSnapshot,
+ /// Present only after the funding acknowledgement was journaled.
+ pub funding: Option<FundingAuthorization>,
+}
+
+/// Cache-write regime verified for this exact model and rate version.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CacheWritePolicy {
+ /// This model does not charge for cache writes.
+ NotApplicable,
+ /// Provider's documented default cache regime.
+ ProviderDefault,
+ /// Explicit five-minute cache writes.
+ FiveMinutes,
+ /// Explicit one-hour cache writes.
+ OneHour,
+}
+
+/// Provider counter semantics verified by the publisher, before normalization.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CounterSemantics {
+ /// All five dimensions are already disjoint.
+ Disjoint,
+ /// Input includes cache buckets; output includes reasoning.
+ InclusiveTotals,
+ /// Only input includes its cache buckets.
+ InputInclusive,
+ /// Only output includes reasoning.
+ OutputInclusive,
+}
+
+/// Reviewed rate provenance. Publication is trusted configuration, not an admin analytics edit.
+/// Only one execution/cache regime may be enabled for a provider/model at a given time;
+/// producers must match it or remain ineligible. No production rates are seeded implicitly.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct RatePublication {
+ /// Immutable price facts returned to funding authorization.
+ pub snapshot: RateSnapshot,
+ /// Exclusive end of validity; expiration blocks admission until another rate is reviewed.
+ pub valid_until: DateTime<Utc>,
+ /// Public pricing document reference, never credentials or request/response content.
+ pub source: String,
+ /// When these price and counter semantics were verified.
+ pub verified_at: DateTime<Utc>,
+ /// Cache-write regime to which the price applies.
+ pub cache_write_policy: CacheWritePolicy,
+ /// Semantics used by trusted adapters to produce disjoint counters.
+ pub counter_semantics: CounterSemantics,
+}
+
+impl RatePublication {
+ /// Reject incomplete provenance and ambiguous sub-microsecond activation boundaries.
+ pub fn validate(&self) -> FinancialResult<()> {
+ if self.source.trim().is_empty()
+ || self.source.len() > 2048
+ || self.valid_until <= self.snapshot.effective_at
+ || !self
+ .snapshot
+ .effective_at
+ .timestamp_subsec_nanos()
+ .is_multiple_of(1000)
+ || !self
+ .valid_until
+ .timestamp_subsec_nanos()
+ .is_multiple_of(1000)
+ {
+ return Err(FinancialError::RateUnavailable);
+ }
+ Ok(())
+ }
+}
+
+/// Owning-domain immutable rate catalog. New versions are append-only; replay must be identical.
+pub trait FinancialRateCatalog: FinancialRateResolver {
+ /// Publish reviewed facts; version or effective-time conflicts fail, never overwrite.
+ fn publish(&self, publication: RatePublication) -> FinancialFuture<'_, WriteDisposition>;
+ /// Retrieve the provenance and semantics pinned by an authorization's rate version.
+ fn publication(&self, version: RateVersion) -> FinancialFuture<'_, Option<RatePublication>>;
+}
+
+/// Journal storage port. All writes must be atomic and compare immutable facts on replay.
+/// Implementations retain interrupted preparation and unacknowledged funding handoff work.
+pub trait FinancialUsageRepo: Send + Sync {
+ /// Pin request/rate before funding. Concurrent identical preparations return the winning rate.
+ fn prepare(
+ &self,
+ request: BeginInvocation,
+ rate: RateSnapshot,
+ ) -> FinancialFuture<'_, PreparedInvocation>;
+ /// Fetch intent, including intents interrupted before authorization acknowledgement.
+ fn prepared(&self, id: InvocationId) -> FinancialFuture<'_, Option<PreparedInvocation>>;
+ /// Persist authorization; only the first acknowledgement returns `Inserted`.
+ fn admit(
+ &self,
+ admission: AuthorizedInvocation,
+ ) -> FinancialFuture<'_, Recorded<AuthorizedInvocation>>;
+ /// Store a validated terminal state, atomically scheduling its funding handoff.
+ fn finish(&self, record: InvocationRecord) -> FinancialFuture<'_, Recorded<InvocationRecord>>;
+ /// Mark successful owning-domain handoff. Must not remove unresolved evidence from recovery.
+ fn acknowledge_funding(&self, id: InvocationId) -> FinancialFuture<'_, ()>;
+ /// Fetch admitted facts, not inferred usage or analytics rows.
+ fn get(&self, id: InvocationId) -> FinancialFuture<'_, Option<InvocationRecord>>;
+ /// Scan pending, unresolved, unpriced, and finalized-but-unacknowledged funding handoffs.
+ fn pending(&self, query: PendingInvocations) -> FinancialFuture<'_, Vec<InvocationRecord>>;
+ /// Scan pinned intents without an acknowledged authorization; retry `begin`, never execution.
+ fn pending_admissions(
+ &self,
+ query: PendingInvocations,
+ ) -> FinancialFuture<'_, Vec<PreparedInvocation>>;
+}
+
+/// Awaited financial facade. Composition roots inject owning-domain capabilities.
+pub struct FinancialUsageService {
+ repo: Arc<dyn FinancialUsageRepo>,
+ rates: Arc<dyn FinancialRateResolver>,
+ funding: Arc<dyn InvocationFunding>,
+}
+
+impl FinancialUsageService {
+ /// Construct without introducing an ai_usage dependency on the billing implementation.
+ pub fn new(
+ repo: Arc<dyn FinancialUsageRepo>,
+ rates: Arc<dyn FinancialRateResolver>,
+ funding: Arc<dyn InvocationFunding>,
+ ) -> Self {
+ Self {
+ repo,
+ rates,
+ funding,
+ }
+ }
+
+ /// Restart-safe discovery of crashes between pinning rates and journaling authorization.
+ /// Recovery may retry admission, but must not execute the provider for an abandoned intent.
+ pub async fn pending_admissions(
+ &self,
+ query: PendingInvocations,
+ ) -> FinancialResult<Vec<PreparedInvocation>> {
+ self.repo.pending_admissions(query).await
+ }
+}
+
+impl FinancialUsage for FinancialUsageService {
+ fn begin(
+ &self,
+ request: BeginInvocation,
+ ) -> FinancialFuture<'_, Recorded<AuthorizedInvocation>> {
+ Box::pin(async move {
+ let prepared = match self.repo.prepared(request.invocation_id).await? {
+ Some(prepared) => {
+ prepared.request.check_replay(&request)?;
+ prepared
+ }
+ None => {
+ let rate = self
+ .rates
+ .resolve(request.model.clone(), request.occurred_at)
+ .await?;
+ rate.require_model(&request.model)?;
+ // Reject an unrepresentable reservation before any funding write.
+ rate.tokens.price(request.token_budget)?;
+ self.repo.prepare(request, rate).await?
+ }
+ };
+ if let Some(funding) = prepared.funding {
+ return Ok(Recorded {
+ value: AuthorizedInvocation {
+ request: prepared.request,
+ rate: prepared.rate,
+ funding,
+ },
+ disposition: WriteDisposition::Replayed,
+ });
+ }
+ let required_budget = prepared.rate.tokens.price(prepared.request.token_budget)?;
+ let funding = self
+ .funding
+ .authorize(prepared.request.clone(), prepared.rate.clone())
+ .await?;
+ if funding.invocation_id != prepared.request.invocation_id
+ || funding.maximum_public_usage < required_budget
+ {
+ return Err(FinancialError::FundingDenied);
+ }
+ self.repo
+ .admit(AuthorizedInvocation {
+ request: prepared.request,
+ rate: prepared.rate,
+ funding,
+ })
+ .await
+ })
+ }
+
+ fn finalize(
+ &self,
+ evidence: FinalizeInvocation,
+ ) -> FinancialFuture<'_, Recorded<InvocationRecord>> {
+ Box::pin(async move {
+ let existing = self
+ .repo
+ .get(evidence.invocation_id)
+ .await?
+ .ok_or(FinancialError::InvocationNotFound)?;
+ let state = price_evidence(&existing.admission.rate, evidence)?;
+ let recorded = self
+ .repo
+ .finish(InvocationRecord {
+ admission: existing.admission,
+ state,
+ })
+ .await?;
+ // Evidence commits first. Failure here remains discoverable in pending(), even for
+ // priced records. The funding owner deduplicates a lost acknowledgement.
+ self.funding.finalize(recorded.value.clone()).await?;
+ self.repo
+ .acknowledge_funding(recorded.value.admission.request.invocation_id)
+ .await?;
+ Ok(recorded)
+ })
+ }
+
+ fn get(&self, id: InvocationId) -> FinancialFuture<'_, Option<InvocationRecord>> {
+ self.repo.get(id)
+ }
+
+ fn pending(&self, query: PendingInvocations) -> FinancialFuture<'_, Vec<InvocationRecord>> {
+ self.repo.pending(query)
+ }
+}
+
+fn price_evidence(
+ rate: &RateSnapshot,
+ evidence: FinalizeInvocation,
+) -> FinancialResult<InvocationState> {
+ match evidence.usage {
+ UsageEvidence::Missing(_) => Ok(InvocationState::Unresolved { evidence }),
+ UsageEvidence::Reported(tokens) => match rate.tokens.price(tokens) {
+ Ok(public_usage) => Ok(InvocationState::Priced {
+ evidence,
+ public_usage,
+ }),
+ Err(FinancialError::ArithmeticOverflow) => Ok(InvocationState::Unpriced {
+ evidence,
+ reason: UnpricedReason::ArithmeticOverflow,
+ }),
+ Err(error) => Err(error),
+ },
+ }
+}
+
+/// Enforce terminal state invariants at the repository boundary as well as in the facade.
+/// An excluded state must come from a trusted policy caller, never from missing capability.
+pub fn validate_final_record(record: &InvocationRecord) -> FinancialResult<()> {
+ let evidence = match &record.state {
+ InvocationState::Pending => return Err(FinancialError::InvalidTokenUsage),
+ InvocationState::Priced { evidence, .. }
+ | InvocationState::Unpriced { evidence, .. }
+ | InvocationState::Unresolved { evidence }
+ | InvocationState::Excluded { evidence, .. } => evidence,
+ };
+ if evidence.invocation_id != record.admission.request.invocation_id {
+ return Err(FinancialError::ReplayConflict {
+ invocation_id: record.admission.request.invocation_id,
+ phase: ReplayPhase::Finalize,
+ });
+ }
+ if !matches!(record.state, InvocationState::Excluded { .. })
+ && price_evidence(&record.admission.rate, evidence.clone())? != record.state
+ {
+ return Err(FinancialError::InvalidTokenUsage);
+ }
+ Ok(())
+}
diff --git a/crates/ai_usage/src/domain/financial_service/test.rs b/crates/ai_usage/src/domain/financial_service/test.rs
new file mode 100644
index 0000000000..9649d8b7aa
--- /dev/null
+++ b/crates/ai_usage/src/domain/financial_service/test.rs
@@ -0,0 +1,341 @@
+use super::*;
+use crate::domain::{AiFeature, SYSTEM_USER_ID};
+use std::sync::{
+ Mutex,
+ atomic::{AtomicBool, AtomicUsize, Ordering},
+};
+
+fn request() -> BeginInvocation {
+ BeginInvocation {
+ run_id: RunId::new(),
+ invocation_id: InvocationId::new(),
+ user: SYSTEM_USER_ID.clone(),
+ feature: AiFeature::Chat,
+ entity: None,
+ model: ProviderModel::new("provider", "model").unwrap(),
+ occurred_at: Utc::now(),
+ token_budget: TrustedTokenUsage::from_disjoint(100, 20, 0, 0, 0),
+ }
+}
+
+fn rate(request: &BeginInvocation) -> RateSnapshot {
+ RateSnapshot {
+ version: RateVersion::new(),
+ model: request.model.clone(),
+ effective_at: request.occurred_at,
+ tokens: TokenRates {
+ input: 1,
+ output: 2,
+ cache_read: 1,
+ cache_write: 3,
+ reasoning: 2,
+ },
+ }
+}
+
+fn evidence(id: InvocationId, usage: UsageEvidence) -> FinalizeInvocation {
+ FinalizeInvocation {
+ invocation_id: id,
+ occurred_at: Utc::now(),
+ provider_request_id: None,
+ outcome: ProviderOutcome::Failed,
+ usage,
+ }
+}
+
+#[derive(Default)]
+struct Repo {
+ prepared: Mutex<Option<PreparedInvocation>>,
+ record: Mutex<Option<InvocationRecord>>,
+ acknowledged: AtomicBool,
+}
+
+impl FinancialUsageRepo for Repo {
+ fn prepare(
+ &self,
+ request: BeginInvocation,
+ rate: RateSnapshot,
+ ) -> FinancialFuture<'_, PreparedInvocation> {
+ Box::pin(async move {
+ let mut slot = self.prepared.lock().unwrap();
+ if let Some(existing) = slot.as_ref() {
+ existing.request.check_replay(&request)?;
+ return Ok(existing.clone());
+ }
+ let prepared = PreparedInvocation {
+ request,
+ rate,
+ funding: None,
+ };
+ *slot = Some(prepared.clone());
+ Ok(prepared)
+ })
+ }
+ fn prepared(&self, _: InvocationId) -> FinancialFuture<'_, Option<PreparedInvocation>> {
+ Box::pin(async { Ok(self.prepared.lock().unwrap().clone()) })
+ }
+ fn admit(
+ &self,
+ admission: AuthorizedInvocation,
+ ) -> FinancialFuture<'_, Recorded<AuthorizedInvocation>> {
+ Box::pin(async move {
+ let mut prepared = self.prepared.lock().unwrap();
+ let prepared = prepared.as_mut().unwrap();
+ prepared.request.check_replay(&admission.request)?;
+ let disposition = if prepared.funding.is_some() {
+ WriteDisposition::Replayed
+ } else {
+ WriteDisposition::Inserted
+ };
+ prepared.funding = Some(admission.funding.clone());
+ *self.record.lock().unwrap() = Some(InvocationRecord {
+ admission: admission.clone(),
+ state: InvocationState::Pending,
+ });
+ Ok(Recorded {
+ value: admission,
+ disposition,
+ })
+ })
+ }
+ fn finish(&self, record: InvocationRecord) -> FinancialFuture<'_, Recorded<InvocationRecord>> {
+ Box::pin(async move {
+ validate_final_record(&record)?;
+ let mut slot = self.record.lock().unwrap();
+ let existing = slot.as_ref().unwrap();
+ let disposition = if existing.state == InvocationState::Pending {
+ WriteDisposition::Inserted
+ } else {
+ if existing != &record {
+ return Err(FinancialError::ReplayConflict {
+ invocation_id: record.admission.request.invocation_id,
+ phase: ReplayPhase::Finalize,
+ });
+ }
+ WriteDisposition::Replayed
+ };
+ *slot = Some(record.clone());
+ Ok(Recorded {
+ value: record,
+ disposition,
+ })
+ })
+ }
+ fn acknowledge_funding(&self, _: InvocationId) -> FinancialFuture<'_, ()> {
+ Box::pin(async {
+ self.acknowledged.store(true, Ordering::SeqCst);
+ Ok(())
+ })
+ }
+ fn get(&self, _: InvocationId) -> FinancialFuture<'_, Option<InvocationRecord>> {
+ Box::pin(async { Ok(self.record.lock().unwrap().clone()) })
+ }
+ fn pending(&self, _: PendingInvocations) -> FinancialFuture<'_, Vec<InvocationRecord>> {
+ Box::pin(async {
+ Ok(self
+ .record
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|record| {
+ !self.acknowledged.load(Ordering::SeqCst)
+ || matches!(
+ record.state,
+ InvocationState::Pending
+ | InvocationState::Unresolved { .. }
+ | InvocationState::Unpriced { .. }
+ )
+ })
+ .cloned()
+ .collect())
+ })
+ }
+ fn pending_admissions(
+ &self,
+ _: PendingInvocations,
+ ) -> FinancialFuture<'_, Vec<PreparedInvocation>> {
+ Box::pin(async {
+ Ok(self
+ .prepared
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|p| p.funding.is_none())
+ .cloned()
+ .collect())
+ })
+ }
+}
+
+struct Rates(Mutex<Option<RateSnapshot>>);
+impl FinancialRateResolver for Rates {
+ fn resolve(&self, _: ProviderModel, _: DateTime<Utc>) -> FinancialFuture<'_, RateSnapshot> {
+ Box::pin(async {
+ self.0
+ .lock()
+ .unwrap()
+ .clone()
+ .ok_or(FinancialError::RateUnavailable)
+ })
+ }
+}
+
+#[derive(Default)]
+struct Funding {
+ deny: AtomicBool,
+ fail_handoff: AtomicBool,
+ authorizations: AtomicUsize,
+ handoffs: AtomicUsize,
+}
+impl InvocationFunding for Funding {
+ fn authorize(
+ &self,
+ request: BeginInvocation,
+ rate: RateSnapshot,
+ ) -> FinancialFuture<'_, FundingAuthorization> {
+ Box::pin(async move {
+ self.authorizations.fetch_add(1, Ordering::SeqCst);
+ if self.deny.load(Ordering::SeqCst) {
+ return Err(FinancialError::FundingDenied);
+ }
+ Ok(FundingAuthorization {
+ id: FundingAuthorizationId::new(),
+ invocation_id: request.invocation_id,
+ maximum_public_usage: rate.tokens.price(request.token_budget)?,
+ })
+ })
+ }
+ fn finalize(&self, _: InvocationRecord) -> FinancialFuture<'_, ()> {
+ Box::pin(async {
+ self.handoffs.fetch_add(1, Ordering::SeqCst);
+ if self.fail_handoff.load(Ordering::SeqCst) {
+ return Err(FinancialError::FundingDenied);
+ }
+ Ok(())
+ })
+ }
+}
+
+fn scan() -> PendingInvocations {
+ PendingInvocations {
+ after: None,
+ before: Utc::now(),
+ limit: 10.try_into().unwrap(),
+ }
+}
+
+#[tokio::test]
+async fn unknown_rate_never_authorizes_and_denied_admission_retains_pinned_rate() {
+ let request = request();
+ let original_rate = rate(&request);
+ let repo = Arc::new(Repo::default());
+ let rates = Arc::new(Rates(Mutex::new(None)));
+ let funding = Arc::new(Funding::default());
+ let service = FinancialUsageService::new(repo.clone(), rates.clone(), funding.clone());
+ assert!(matches!(
+ service.begin(request.clone()).await,
+ Err(FinancialError::RateUnavailable)
+ ));
+ assert_eq!(funding.authorizations.load(Ordering::SeqCst), 0);
+ *rates.0.lock().unwrap() = Some(original_rate.clone());
+ funding.deny.store(true, Ordering::SeqCst);
+ assert!(matches!(
+ service.begin(request.clone()).await,
+ Err(FinancialError::FundingDenied)
+ ));
+ assert_eq!(service.pending_admissions(scan()).await.unwrap().len(), 1);
+ // New publications or unavailable rates cannot change a previously pinned intent.
+ *rates.0.lock().unwrap() = None;
+ funding.deny.store(false, Ordering::SeqCst);
+ let admitted = service.begin(request.clone()).await.unwrap();
+ assert_eq!(admitted.value.rate, original_rate);
+ assert_eq!(admitted.disposition, WriteDisposition::Inserted);
+ assert!(service.pending_admissions(scan()).await.unwrap().is_empty());
+ assert_eq!(
+ service.begin(request.clone()).await.unwrap().disposition,
+ WriteDisposition::Replayed
+ );
+ assert_eq!(funding.authorizations.load(Ordering::SeqCst), 2);
+ let mut conflicting = request;
+ conflicting.feature = AiFeature::Memory;
+ assert!(matches!(
+ service.begin(conflicting).await,
+ Err(FinancialError::ReplayConflict {
+ phase: ReplayPhase::Begin,
+ ..
+ })
+ ));
+}
+
+#[tokio::test]
+async fn lost_handoff_acknowledgement_leaves_priced_evidence_discoverable() {
+ let request = request();
+ let repo = Arc::new(Repo::default());
+ let rates = Arc::new(Rates(Mutex::new(Some(rate(&request)))));
+ let funding = Arc::new(Funding::default());
+ let service = FinancialUsageService::new(repo, rates, funding.clone());
+ service.begin(request.clone()).await.unwrap();
+ let evidence = evidence(
+ request.invocation_id,
+ UsageEvidence::Reported(TrustedTokenUsage::from_inclusive_totals(10, 5, 2, 1, 2).unwrap()),
+ );
+ funding.fail_handoff.store(true, Ordering::SeqCst);
+ assert!(service.finalize(evidence.clone()).await.is_err());
+ let pending = service.pending(scan()).await.unwrap();
+ assert_eq!(pending.len(), 1);
+ assert!(
+ matches!(pending[0].state, InvocationState::Priced { public_usage, .. } if public_usage.units() == 22)
+ );
+ funding.fail_handoff.store(false, Ordering::SeqCst);
+ assert_eq!(
+ service
+ .finalize(evidence.clone())
+ .await
+ .unwrap()
+ .disposition,
+ WriteDisposition::Replayed
+ );
+ assert!(service.pending(scan()).await.unwrap().is_empty());
+ let mut conflict = evidence;
+ conflict.outcome = ProviderOutcome::Succeeded;
+ assert!(matches!(
+ service.finalize(conflict).await,
+ Err(FinancialError::ReplayConflict {
+ phase: ReplayPhase::Finalize,
+ ..
+ })
+ ));
+ assert_eq!(funding.handoffs.load(Ordering::SeqCst), 2);
+}
+
+#[test]
+fn missing_usage_and_overflow_are_preserved_not_zeroed() {
+ let request = request();
+ let rate = rate(&request);
+ let missing = evidence(
+ request.invocation_id,
+ UsageEvidence::Missing(UnresolvedReason::Interrupted),
+ );
+ assert!(matches!(
+ price_evidence(&rate, missing).unwrap(),
+ InvocationState::Unresolved { .. }
+ ));
+ let overflow = evidence(
+ request.invocation_id,
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(0, u64::MAX, 0, 0, 0)),
+ );
+ assert!(matches!(
+ price_evidence(&rate, overflow).unwrap(),
+ InvocationState::Unpriced {
+ reason: UnpricedReason::ArithmeticOverflow,
+ ..
+ }
+ ));
+ let zero = evidence(
+ request.invocation_id,
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(0, 0, 0, 0, 0)),
+ );
+ assert!(
+ matches!(price_evidence(&rate, zero).unwrap(), InvocationState::Priced { public_usage, .. } if public_usage.units() == 0)
+ );
+}
diff --git a/crates/ai_usage/src/domain/mod.rs b/crates/ai_usage/src/domain/mod.rs
index 9daaafa6bc..adce6c32a2 100644
--- a/crates/ai_usage/src/domain/mod.rs
+++ b/crates/ai_usage/src/domain/mod.rs
@@ -1,10 +1,14 @@
//! Domain layer: the cost model, ports, and the service that computes cost.
+pub mod financial;
+pub mod financial_service;
pub mod ports;
pub mod service;
+pub mod tracking;
pub use ports::{
- AiFeature, CompletionUsage, FeatureUsage, ModelPricing, NoOpUsageRecorder, Price, Result,
+ AiFeature, CompletionUsage, FeatureUsage, FinancialFuture, FinancialRateResolver,
+ FinancialUsage, InvocationFunding, ModelPricing, NoOpUsageRecorder, Price, Result,
SYSTEM_USER_ID, Usage, UsageAmount, UsageApiParams, UsageContext, UsageError, UsageEvent,
UsageRecorder, UsageRepo, UsageService, UsageSummary, normalize_model_id,
};
diff --git a/crates/ai_usage/src/domain/ports.rs b/crates/ai_usage/src/domain/ports.rs
index 1bedc29037..ea72c5568c 100644
--- a/crates/ai_usage/src/domain/ports.rs
+++ b/crates/ai_usage/src/domain/ports.rs
@@ -4,10 +4,17 @@ use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use serde::{Deserialize, Serialize};
+use std::pin::Pin;
use std::sync::LazyLock;
use thiserror::Error;
use utoipa::ToSchema;
+use super::financial::{
+ AuthorizedInvocation, BeginInvocation, FinalizeInvocation, FinancialResult,
+ FundingAuthorization, InvocationId, InvocationRecord, PendingInvocations, ProviderModel,
+ RateSnapshot, Recorded,
+};
+
/// The reserved system user recorded for completions with no originating
/// end-user (background tasks, internal summarization, subagents, …).
///
@@ -353,10 +360,17 @@ pub trait UsageRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<Vec<CompletionUsage>>> + Send;
}
-/// The recording port used by the agent crate. Recording is best-effort: a
-/// failure must never propagate into the originating call, so the method is
-/// infallible and fire-and-forget.
+/// The analytics recording port used by the agent crate. Recording is best-effort:
+/// a failure must never propagate into the originating call, so the method is
+/// infallible and fire-and-forget. This is NOT financial admission or evidence;
+/// activated traffic also requires the separate [`FinancialUsage`] capability.
pub trait UsageRecorder: Send + Sync {
+ /// Optional observational capability. Producers must explicitly scope each
+ /// operation and await per-attempt evidence; aggregate `record` is not coverage.
+ fn tracking(&self) -> Option<std::sync::Arc<dyn super::tracking::UsageTracking>> {
+ None
+ }
+
/// Record one completion round-trip.
fn record(&self, event: UsageEvent);
}
@@ -370,6 +384,76 @@ impl UsageRecorder for NoOpUsageRecorder {
fn record(&self, _event: UsageEvent) {}
}
+/// Boxed, awaited financial operation. Explicit boxing keeps financial capabilities
+/// object-safe without changing the existing `Arc<dyn UsageRecorder>` plumbing.
+pub type FinancialFuture<'a, T> = Pin<Box<dyn Future<Output = FinancialResult<T>> + Send + 'a>>;
+
+/// Owning-domain financial rate port. Implementations resolve immutable snapshots
+/// by actual provider AND model at occurrence time, before funding authorization.
+/// Unknown/unsupported rates fail closed; [`UsageRepo::get_pricing`] and mutable
+/// bare-model analytics prices must never implement this contract as a fallback.
+pub trait FinancialRateResolver: Send + Sync {
+ /// Resolve a version once and pin it for the invocation's entire lifetime.
+ /// An existing invocation replay uses its recorded snapshot, not a fresh lookup.
+ fn resolve(
+ &self,
+ model: ProviderModel,
+ occurred_at: DateTime<Utc>,
+ ) -> FinancialFuture<'_, RateSnapshot>;
+}
+
+/// Capability implemented by the funding owner and injected at composition roots.
+/// `ai_usage` neither imports billing adapters nor depends on `ai_billing`.
+pub trait InvocationFunding: Send + Sync {
+ /// Durably authorize bounded execution against the resolved immutable rate.
+ /// Serialize shared funding, capture policy/payer/period/settings and reserve
+ /// capacity before returning. Denial is an error, never a zero-budget approval.
+ /// Replay is keyed by invocation ID: identical requests return the original
+ /// authorization, even after settings change; conflicting requests fail visibly.
+ fn authorize(
+ &self,
+ request: BeginInvocation,
+ rate: RateSnapshot,
+ ) -> FinancialFuture<'_, FundingAuthorization>;
+
+ /// Idempotently reconcile evidence with its captured authorization. Acknowledgement
+ /// means durable handoff, not necessarily completed allocation or collection.
+ /// Missing/unpriced evidence stays unresolved. Unavoidable usage beyond authorized
+ /// funding must not become unauthorized customer debt. Never reauthorize history
+ /// from the current toggle or consume both prepaid and postpaid for the same amount.
+ fn finalize(&self, invocation: InvocationRecord) -> FinancialFuture<'_, ()>;
+}
+
+/// Awaited financial lifecycle, separate from best-effort analytics. Implementations
+/// persist begin before execution, resolve immutable rates before asking the injected
+/// funding capability for authorization, and make the cross-domain handoff replayable.
+/// These are trusted service ports, not unauthenticated customer query endpoints.
+pub trait FinancialUsage: Send + Sync {
+ /// Return only after begin, pinned rates and funding authorization are durable.
+ /// Only an inserted admission permits a new provider attempt. A replay may follow
+ /// lost acknowledgement after execution and must not execute the provider again.
+ /// Errors (including unavailable rates/capabilities) never permit billable execution.
+ fn begin(
+ &self,
+ request: BeginInvocation,
+ ) -> FinancialFuture<'_, Recorded<AuthorizedInvocation>>;
+
+ /// Persist evidence regardless of provider success/failure/cancellation. Identical
+ /// replays acknowledge the original result; changed evidence raises a replay conflict.
+ /// Acknowledgement guarantees durable evidence and discoverable funding handoff;
+ /// implementations must not lose work between the usage and funding domains.
+ fn finalize(
+ &self,
+ evidence: FinalizeInvocation,
+ ) -> FinancialFuture<'_, Recorded<InvocationRecord>>;
+
+ /// Query the original admission and evidence. Unknown identity is `None`, not zero usage.
+ fn get(&self, invocation_id: InvocationId) -> FinancialFuture<'_, Option<InvocationRecord>>;
+
+ /// Discover interrupted, unpriced and unresolved work for restart-safe reconciliation.
+ fn pending(&self, query: PendingInvocations) -> FinancialFuture<'_, Vec<InvocationRecord>>;
+}
+
/// The admin-facing query / pricing port, implemented by the domain service and
/// consumed by the inbound axum router.
pub trait UsageService: Send + Sync + 'static {
diff --git a/crates/ai_usage/src/domain/tracking.rs b/crates/ai_usage/src/domain/tracking.rs
new file mode 100644
index 0000000000..8f60bd9323
--- /dev/null
+++ b/crates/ai_usage/src/domain/tracking.rs
@@ -0,0 +1,75 @@
+//! Observational evidence, deliberately incapable of authorizing or settling usage.
+
+use super::financial::*;
+use super::ports::{AiFeature, FinancialFuture};
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use std::sync::Arc;
+
+/// Immutable attribution for an observation, not a funding request or reservation.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TrackedInvocation {
+ /// Logical operation identity.
+ pub run_id: RunId,
+ /// Unique provider execution identity; delivery retries retain this identity.
+ pub invocation_id: InvocationId,
+ /// Trusted originating user; the system identity is internal work, not a payer.
+ pub user: MacroUserIdStr<'static>,
+ /// Host-selected feature, including existing excluded features.
+ pub feature: AiFeature,
+ /// Related entity.
+ pub entity: Option<Uuid>,
+ /// Actual provider and wire model.
+ pub model: ProviderModel,
+ /// Time the attempt began.
+ pub occurred_at: DateTime<Utc>,
+}
+
+/// Awaited observation capability. No funding capability is accepted by this port.
+/// Failures must be reported, but must not deny or alter provider execution.
+pub trait UsageTracking: Send + Sync {
+ /// Persist an attempt before execution when storage is available.
+ fn begin(&self, request: TrackedInvocation) -> FinancialFuture<'_, WriteDisposition>;
+ /// Persist immutable evidence; identical delivery is idempotent.
+ fn finalize(&self, evidence: FinalizeInvocation) -> FinancialFuture<'_, WriteDisposition>;
+}
+
+/// Storage port owned by the observation domain. It never schedules financial handoffs.
+pub trait UsageTrackingRepo: UsageTracking {}
+
+/// Owning-domain observation service. There is intentionally no funding or collection
+/// dependency and no conversion from observations into authorized invocations.
+pub struct UsageTrackingService {
+ repo: Arc<dyn UsageTrackingRepo>,
+}
+
+impl UsageTrackingService {
+ /// Construct at a host composition root.
+ pub fn new(repo: Arc<dyn UsageTrackingRepo>) -> Self {
+ Self { repo }
+ }
+}
+
+impl UsageTracking for UsageTrackingService {
+ fn begin(&self, request: TrackedInvocation) -> FinancialFuture<'_, WriteDisposition> {
+ self.repo.begin(request)
+ }
+
+ fn finalize(&self, evidence: FinalizeInvocation) -> FinancialFuture<'_, WriteDisposition> {
+ self.repo.finalize(evidence)
+ }
+}
+
+/// Observations are not priced using mutable analytics rates or assumed billing
+/// profiles. Preserve counters as unpriced until a separately reviewed pricing path
+/// exists; absent counters remain unresolved, never measured zero.
+pub fn observation_state(evidence: FinalizeInvocation) -> InvocationState {
+ match evidence.usage {
+ UsageEvidence::Reported(_) => InvocationState::Unpriced {
+ evidence,
+ reason: UnpricedReason::MissingRate,
+ },
+ UsageEvidence::Missing(_) => InvocationState::Unresolved { evidence },
+ }
+}
diff --git a/crates/ai_usage/src/lib.rs b/crates/ai_usage/src/lib.rs
index 3917f3d18b..e1baaf0d85 100644
--- a/crates/ai_usage/src/lib.rs
+++ b/crates/ai_usage/src/lib.rs
@@ -10,26 +10,74 @@
//! service (DCS).
//!
//! The agent crate records usage through the [`UsageRecorder`](domain::UsageRecorder)
-//! port; recording is best-effort and never fails the originating call.
+//! port; analytics recording is best-effort and never fails the originating call.
+//! Activated billable traffic additionally requires the awaited, object-safe
+//! [`FinancialUsage`] capability. [`financial`] defines immutable provider evidence,
+//! exact public usage/customer money, and fail-closed capability selection.
pub mod domain;
pub mod inbound;
pub mod outbound;
+pub use domain::financial;
+pub use domain::financial_service::{
+ CacheWritePolicy, CounterSemantics, FinancialRateCatalog, FinancialUsageRepo,
+ FinancialUsageService, PreparedInvocation, RatePublication,
+};
+pub use domain::tracking::{
+ TrackedInvocation, UsageTracking, UsageTrackingRepo, UsageTrackingService,
+};
pub use domain::{
- AiFeature, CompletionUsage, FeatureUsage, ModelPricing, NoOpUsageRecorder, Price,
- SYSTEM_USER_ID, Usage, UsageAmount, UsageApiParams, UsageContext, UsageEvent, UsageRecorder,
- UsageRepo, UsageService, UsageSummary, normalize_model_id,
+ AiFeature, CompletionUsage, FeatureUsage, FinancialFuture, FinancialRateResolver,
+ FinancialUsage, InvocationFunding, ModelPricing, NoOpUsageRecorder, Price, SYSTEM_USER_ID,
+ Usage, UsageAmount, UsageApiParams, UsageContext, UsageEvent, UsageRecorder, UsageRepo,
+ UsageService, UsageSummary, normalize_model_id,
};
use std::sync::Arc;
-/// Build a [`UsageRecorder`] backed by Postgres over `pool`.
+/// Construct the owning-domain observational journal, without financial adapters.
+pub fn pg_tracking(pool: sqlx::PgPool) -> Arc<dyn UsageTracking> {
+ Arc::new(UsageTrackingService::new(Arc::new(
+ outbound::pg_tracking_repo::PgTrackingRepo::new(pool),
+ )))
+}
+
+/// Add per-attempt observation without changing the existing analytics/settlement
+/// path. Observations never call `record` and cannot trigger collection.
+pub fn with_tracking(
+ analytics: Arc<dyn UsageRecorder>,
+ tracking: Arc<dyn UsageTracking>,
+) -> Arc<dyn UsageRecorder> {
+ Arc::new(TrackingRecorder {
+ analytics,
+ tracking,
+ })
+}
+
+struct TrackingRecorder {
+ analytics: Arc<dyn UsageRecorder>,
+ tracking: Arc<dyn UsageTracking>,
+}
+
+impl UsageRecorder for TrackingRecorder {
+ fn record(&self, event: UsageEvent) {
+ self.analytics.record(event);
+ }
+
+ fn tracking(&self) -> Option<Arc<dyn UsageTracking>> {
+ Some(self.tracking.clone())
+ }
+}
+
+/// Build Postgres analytics with a separate awaited observational capability.
+/// Producers must bind that capability per operation; `record` remains analytics-only.
///
/// Services construct one of these and thread it into their tool/service
/// context (and into AI call sites) — there is no global recorder.
pub fn pg_recorder(pool: sqlx::PgPool) -> Arc<dyn UsageRecorder> {
- Arc::new(domain::service::UsageServiceImpl::new(
- outbound::PgUsageRepo::new(pool),
- ))
+ let analytics = Arc::new(domain::service::UsageServiceImpl::new(
+ outbound::PgUsageRepo::new(pool.clone()),
+ ));
+ with_tracking(analytics, pg_tracking(pool))
}
diff --git a/crates/ai_usage/src/outbound.rs b/crates/ai_usage/src/outbound.rs
index 838c184c55..ed9e7fc618 100644
--- a/crates/ai_usage/src/outbound.rs
+++ b/crates/ai_usage/src/outbound.rs
@@ -1,5 +1,8 @@
//! Outbound adapters.
+pub mod pg_financial_usage_repo;
+pub mod pg_tracking_repo;
pub mod pg_usage_repo;
+pub use pg_financial_usage_repo::PgFinancialUsageRepo;
pub use pg_usage_repo::PgUsageRepo;
diff --git a/crates/ai_usage/src/outbound/pg_financial_usage_repo.rs b/crates/ai_usage/src/outbound/pg_financial_usage_repo.rs
new file mode 100644
index 0000000000..53224cbd83
--- /dev/null
+++ b/crates/ai_usage/src/outbound/pg_financial_usage_repo.rs
@@ -0,0 +1,758 @@
+//! Append-only Postgres financial evidence, separate from the mutable analytics adapter.
+
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use serde::{Deserialize, Serialize};
+use sqlx::{PgPool, types::Json};
+
+use crate::domain::financial::*;
+use crate::domain::financial_service::*;
+use crate::domain::ports::{FinancialFuture, FinancialRateResolver};
+
+#[cfg(test)]
+mod test;
+
+/// Postgres implementation of the owning-domain journal and immutable rate ports.
+#[derive(Clone)]
+pub struct PgFinancialUsageRepo {
+ pool: PgPool,
+}
+
+impl PgFinancialUsageRepo {
+ /// Construct at a composition root; this adapter never constructs funding adapters.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+impl FinancialRateCatalog for PgFinancialUsageRepo {
+ fn publish(&self, publication: RatePublication) -> FinancialFuture<'_, WriteDisposition> {
+ Box::pin(async move {
+ publication.validate()?;
+ let data = Json(RateData::from(&publication));
+ let snapshot = &publication.snapshot;
+ let inserted = sqlx::query!(
+ r#"INSERT INTO ai_financial_rate
+ (version, provider, model, effective_at, valid_until, publication)
+ VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT DO NOTHING"#,
+ snapshot.version.as_uuid(),
+ snapshot.model.provider(),
+ snapshot.model.model(),
+ snapshot.effective_at,
+ publication.valid_until,
+ data as _,
+ )
+ .execute(&self.pool)
+ .await?
+ .rows_affected()
+ == 1;
+ if inserted {
+ return Ok(WriteDisposition::Inserted);
+ }
+ if self.publication(snapshot.version).await?.as_ref() != Some(&publication) {
+ return Err(FinancialError::Infrastructure(rootcause::report!(
+ "conflicting immutable financial rate publication"
+ )));
+ }
+ Ok(WriteDisposition::Replayed)
+ })
+ }
+
+ fn publication(&self, version: RateVersion) -> FinancialFuture<'_, Option<RatePublication>> {
+ Box::pin(async move {
+ let row = sqlx::query!(
+ r#"SELECT publication AS "publication: Json<RateData>"
+ FROM ai_financial_rate WHERE version = $1"#,
+ version.as_uuid(),
+ )
+ .fetch_optional(&self.pool)
+ .await?;
+ row.map(|row| row.publication.0.decode()).transpose()
+ })
+ }
+}
+
+impl FinancialRateResolver for PgFinancialUsageRepo {
+ fn resolve(
+ &self,
+ model: ProviderModel,
+ occurred_at: DateTime<Utc>,
+ ) -> FinancialFuture<'_, RateSnapshot> {
+ Box::pin(async move {
+ // Select the latest effective version FIRST, then test expiry. An expired
+ // replacement must never revive an older, possibly cheaper rate.
+ let row = sqlx::query!(
+ r#"SELECT publication AS "publication: Json<RateData>"
+ FROM ai_financial_rate
+ WHERE provider = $1 AND model = $2 AND effective_at <= $3
+ ORDER BY effective_at DESC LIMIT 1"#,
+ model.provider(),
+ model.model(),
+ occurred_at,
+ )
+ .fetch_optional(&self.pool)
+ .await?
+ .ok_or(FinancialError::RateUnavailable)?;
+ let publication = row.publication.0.decode()?;
+ if occurred_at >= publication.valid_until {
+ return Err(FinancialError::RateUnavailable);
+ }
+ Ok(publication.snapshot)
+ })
+ }
+}
+
+impl FinancialUsageRepo for PgFinancialUsageRepo {
+ fn prepare(
+ &self,
+ request: BeginInvocation,
+ rate: RateSnapshot,
+ ) -> FinancialFuture<'_, PreparedInvocation> {
+ Box::pin(async move {
+ rate.require_model(&request.model)?;
+ let publication = self
+ .publication(rate.version)
+ .await?
+ .ok_or(FinancialError::RateUnavailable)?;
+ if publication.snapshot != rate
+ || request.occurred_at < rate.effective_at
+ || request.occurred_at >= publication.valid_until
+ {
+ return Err(FinancialError::RateUnavailable);
+ }
+ let data = Json(RequestData::from(&request));
+ sqlx::query!(
+ r#"INSERT INTO ai_financial_invocation (invocation_id, rate_version, occurred_at, request)
+ VALUES ($1, $2, $3, $4) ON CONFLICT (invocation_id) DO NOTHING"#,
+ request.invocation_id.as_uuid(), rate.version.as_uuid(), request.occurred_at, data as _,
+ ).execute(&self.pool).await?;
+ let prepared = self
+ .prepared(request.invocation_id)
+ .await?
+ .ok_or(FinancialError::InvocationNotFound)?;
+ prepared.request.check_replay(&request)?;
+ Ok(prepared)
+ })
+ }
+
+ fn prepared(&self, id: InvocationId) -> FinancialFuture<'_, Option<PreparedInvocation>> {
+ Box::pin(async move {
+ let row = sqlx::query_as!(
+ JournalRow,
+ r#"SELECT j.request AS "request: Json<RequestData>",
+ r.publication AS "publication: Json<RateData>",
+ j.funding AS "funding: Json<FundingData>",
+ j.finalization AS "finalization: Json<StateData>"
+ FROM ai_financial_invocation j JOIN ai_financial_rate r ON r.version = j.rate_version
+ WHERE j.invocation_id = $1"#,
+ id.as_uuid(),
+ ).fetch_optional(&self.pool).await?;
+ row.map(JournalRow::prepared).transpose()
+ })
+ }
+
+ fn admit(
+ &self,
+ admission: AuthorizedInvocation,
+ ) -> FinancialFuture<'_, Recorded<AuthorizedInvocation>> {
+ Box::pin(async move {
+ if admission.funding.invocation_id != admission.request.invocation_id
+ || admission.funding.maximum_public_usage
+ < admission
+ .rate
+ .tokens
+ .price(admission.request.token_budget)?
+ {
+ return Err(FinancialError::FundingDenied);
+ }
+ let mut tx = self.pool.begin().await?;
+ let row = sqlx::query_as!(
+ JournalRow,
+ r#"SELECT j.request AS "request: Json<RequestData>",
+ r.publication AS "publication: Json<RateData>",
+ j.funding AS "funding: Json<FundingData>",
+ j.finalization AS "finalization: Json<StateData>"
+ FROM ai_financial_invocation j JOIN ai_financial_rate r ON r.version = j.rate_version
+ WHERE j.invocation_id = $1 FOR UPDATE OF j"#,
+ admission.request.invocation_id.as_uuid(),
+ ).fetch_optional(&mut *tx).await?.ok_or(FinancialError::InvocationNotFound)?;
+ let prepared = row.prepared()?;
+ prepared.request.check_replay(&admission.request)?;
+ if prepared.rate != admission.rate
+ || prepared
+ .funding
+ .as_ref()
+ .is_some_and(|funding| funding != &admission.funding)
+ {
+ return Err(conflict(
+ admission.request.invocation_id,
+ ReplayPhase::Begin,
+ ));
+ }
+ let disposition = if prepared.funding.is_some() {
+ WriteDisposition::Replayed
+ } else {
+ let data = Json(FundingData::from(&admission.funding));
+ sqlx::query!(
+ "UPDATE ai_financial_invocation SET funding = $2 WHERE invocation_id = $1",
+ admission.request.invocation_id.as_uuid(),
+ data as _,
+ )
+ .execute(&mut *tx)
+ .await?;
+ WriteDisposition::Inserted
+ };
+ tx.commit().await?;
+ Ok(Recorded {
+ value: admission,
+ disposition,
+ })
+ })
+ }
+
+ fn finish(&self, record: InvocationRecord) -> FinancialFuture<'_, Recorded<InvocationRecord>> {
+ Box::pin(async move {
+ validate_final_record(&record)?;
+ let id = record.admission.request.invocation_id;
+ let mut tx = self.pool.begin().await?;
+ let row = sqlx::query_as!(
+ JournalRow,
+ r#"SELECT j.request AS "request: Json<RequestData>",
+ r.publication AS "publication: Json<RateData>",
+ j.funding AS "funding: Json<FundingData>",
+ j.finalization AS "finalization: Json<StateData>"
+ FROM ai_financial_invocation j JOIN ai_financial_rate r ON r.version = j.rate_version
+ WHERE j.invocation_id = $1 FOR UPDATE OF j"#,
+ id.as_uuid(),
+ ).fetch_optional(&mut *tx).await?.ok_or(FinancialError::InvocationNotFound)?;
+ let existing = row.record()?.ok_or(FinancialError::InvocationNotFound)?;
+ if existing.admission != record.admission {
+ return Err(conflict(id, ReplayPhase::Begin));
+ }
+ let disposition = if existing.state == InvocationState::Pending {
+ let recovery_required = matches!(
+ record.state,
+ InvocationState::Unresolved { .. } | InvocationState::Unpriced { .. }
+ );
+ let data = Json(StateData::from_state(&record.state)?);
+ sqlx::query!(
+ r#"UPDATE ai_financial_invocation SET finalization = $2,
+ recovery_required = $3, finalized_at = now() WHERE invocation_id = $1"#,
+ id.as_uuid(),
+ data as _,
+ recovery_required,
+ )
+ .execute(&mut *tx)
+ .await?;
+ WriteDisposition::Inserted
+ } else {
+ if existing.state != record.state {
+ return Err(conflict(id, ReplayPhase::Finalize));
+ }
+ WriteDisposition::Replayed
+ };
+ tx.commit().await?;
+ Ok(Recorded {
+ value: record,
+ disposition,
+ })
+ })
+ }
+
+ fn acknowledge_funding(&self, id: InvocationId) -> FinancialFuture<'_, ()> {
+ Box::pin(async move {
+ let result = sqlx::query!(
+ r#"UPDATE ai_financial_invocation SET funding_acknowledged = true
+ WHERE invocation_id = $1 AND finalization IS NOT NULL"#,
+ id.as_uuid(),
+ )
+ .execute(&self.pool)
+ .await?;
+ if result.rows_affected() == 0 {
+ return Err(FinancialError::InvocationNotFound);
+ }
+ Ok(())
+ })
+ }
+
+ fn get(&self, id: InvocationId) -> FinancialFuture<'_, Option<InvocationRecord>> {
+ Box::pin(async move {
+ let row = sqlx::query_as!(
+ JournalRow,
+ r#"SELECT j.request AS "request: Json<RequestData>",
+ r.publication AS "publication: Json<RateData>",
+ j.funding AS "funding: Json<FundingData>",
+ j.finalization AS "finalization: Json<StateData>"
+ FROM ai_financial_invocation j JOIN ai_financial_rate r ON r.version = j.rate_version
+ WHERE j.invocation_id = $1"#,
+ id.as_uuid(),
+ ).fetch_optional(&self.pool).await?;
+ match row {
+ Some(row) => row.record(),
+ None => Ok(None),
+ }
+ })
+ }
+
+ fn pending(&self, query: PendingInvocations) -> FinancialFuture<'_, Vec<InvocationRecord>> {
+ Box::pin(async move {
+ let rows = sqlx::query_as!(
+ JournalRow,
+ r#"SELECT j.request AS "request: Json<RequestData>",
+ r.publication AS "publication: Json<RateData>",
+ j.funding AS "funding: Json<FundingData>",
+ j.finalization AS "finalization: Json<StateData>"
+ FROM ai_financial_invocation j JOIN ai_financial_rate r ON r.version = j.rate_version
+ WHERE j.funding IS NOT NULL AND (j.recovery_required OR NOT j.funding_acknowledged)
+ AND ($1::uuid IS NULL OR j.invocation_id > $1) AND j.occurred_at < $2
+ ORDER BY j.invocation_id LIMIT $3"#,
+ query.after.map(InvocationId::as_uuid), query.before, i64::from(query.limit.get()),
+ ).fetch_all(&self.pool).await?;
+ rows.into_iter()
+ .map(|row| row.record()?.ok_or(FinancialError::InvocationNotFound))
+ .collect()
+ })
+ }
+
+ fn pending_admissions(
+ &self,
+ query: PendingInvocations,
+ ) -> FinancialFuture<'_, Vec<PreparedInvocation>> {
+ Box::pin(async move {
+ let rows = sqlx::query_as!(
+ JournalRow,
+ r#"SELECT j.request AS "request: Json<RequestData>",
+ r.publication AS "publication: Json<RateData>",
+ j.funding AS "funding: Json<FundingData>",
+ j.finalization AS "finalization: Json<StateData>"
+ FROM ai_financial_invocation j JOIN ai_financial_rate r ON r.version = j.rate_version
+ WHERE j.funding IS NULL
+ AND ($1::uuid IS NULL OR j.invocation_id > $1) AND j.occurred_at < $2
+ ORDER BY j.invocation_id LIMIT $3"#,
+ query.after.map(InvocationId::as_uuid), query.before, i64::from(query.limit.get()),
+ ).fetch_all(&self.pool).await?;
+ rows.into_iter().map(JournalRow::prepared).collect()
+ })
+ }
+}
+
+fn conflict(invocation_id: InvocationId, phase: ReplayPhase) -> FinancialError {
+ FinancialError::ReplayConflict {
+ invocation_id,
+ phase,
+ }
+}
+
+impl From<sqlx::Error> for FinancialError {
+ fn from(error: sqlx::Error) -> Self {
+ Self::Infrastructure(rootcause::report!(error).into_dynamic())
+ }
+}
+
+// Explicit storage DTOs keep serialization outside the domain and preserve full u64
+// precision and nanosecond evidence timestamps. JSON contains only the typed facts
+// below, never arbitrary provider payloads. Decode through validated constructors.
+#[derive(Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RequestData {
+ run_id: Uuid,
+ invocation_id: Uuid,
+ user_id: String,
+ feature: crate::domain::AiFeature,
+ entity: Option<Uuid>,
+ provider: String,
+ model: String,
+ occurred_at: DateTime<Utc>,
+ token_budget: [u64; 5],
+}
+
+impl From<&BeginInvocation> for RequestData {
+ fn from(value: &BeginInvocation) -> Self {
+ Self {
+ run_id: value.run_id.as_uuid(),
+ invocation_id: value.invocation_id.as_uuid(),
+ user_id: value.user.as_ref().to_owned(),
+ feature: value.feature,
+ entity: value.entity,
+ provider: value.model.provider().to_owned(),
+ model: value.model.model().to_owned(),
+ occurred_at: value.occurred_at,
+ token_budget: token_array(value.token_budget),
+ }
+ }
+}
+
+impl RequestData {
+ fn decode(self) -> FinancialResult<BeginInvocation> {
+ Ok(BeginInvocation {
+ run_id: self.run_id.try_into()?,
+ invocation_id: self.invocation_id.try_into()?,
+ user: MacroUserIdStr::try_from(self.user_id).map_err(|error| {
+ FinancialError::Infrastructure(rootcause::report!(error).into_dynamic())
+ })?,
+ feature: self.feature,
+ entity: self.entity,
+ model: ProviderModel::new(self.provider, self.model)?,
+ occurred_at: self.occurred_at,
+ token_budget: tokens(self.token_budget),
+ })
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RateData {
+ version: Uuid,
+ provider: String,
+ model: String,
+ effective_at: DateTime<Utc>,
+ valid_until: DateTime<Utc>,
+ rates: [u64; 5],
+ source: String,
+ verified_at: DateTime<Utc>,
+ cache_write_policy: CachePolicyData,
+ counter_semantics: SemanticsData,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+enum CachePolicyData {
+ NotApplicable,
+ ProviderDefault,
+ FiveMinutes,
+ OneHour,
+}
+#[derive(Debug, Serialize, Deserialize)]
+enum SemanticsData {
+ Disjoint,
+ InclusiveTotals,
+ InputInclusive,
+ OutputInclusive,
+}
+
+impl From<&RatePublication> for RateData {
+ fn from(value: &RatePublication) -> Self {
+ let rate = &value.snapshot;
+ Self {
+ version: rate.version.as_uuid(),
+ provider: rate.model.provider().to_owned(),
+ model: rate.model.model().to_owned(),
+ effective_at: rate.effective_at,
+ valid_until: value.valid_until,
+ rates: [
+ rate.tokens.input,
+ rate.tokens.output,
+ rate.tokens.cache_read,
+ rate.tokens.cache_write,
+ rate.tokens.reasoning,
+ ],
+ source: value.source.clone(),
+ verified_at: value.verified_at,
+ cache_write_policy: match value.cache_write_policy {
+ CacheWritePolicy::NotApplicable => CachePolicyData::NotApplicable,
+ CacheWritePolicy::ProviderDefault => CachePolicyData::ProviderDefault,
+ CacheWritePolicy::FiveMinutes => CachePolicyData::FiveMinutes,
+ CacheWritePolicy::OneHour => CachePolicyData::OneHour,
+ },
+ counter_semantics: match value.counter_semantics {
+ CounterSemantics::Disjoint => SemanticsData::Disjoint,
+ CounterSemantics::InclusiveTotals => SemanticsData::InclusiveTotals,
+ CounterSemantics::InputInclusive => SemanticsData::InputInclusive,
+ CounterSemantics::OutputInclusive => SemanticsData::OutputInclusive,
+ },
+ }
+ }
+}
+
+impl RateData {
+ fn decode(self) -> FinancialResult<RatePublication> {
+ let [input, output, cache_read, cache_write, reasoning] = self.rates;
+ let publication = RatePublication {
+ snapshot: RateSnapshot {
+ version: self.version.try_into()?,
+ model: ProviderModel::new(self.provider, self.model)?,
+ effective_at: self.effective_at,
+ tokens: TokenRates {
+ input,
+ output,
+ cache_read,
+ cache_write,
+ reasoning,
+ },
+ },
+ valid_until: self.valid_until,
+ source: self.source,
+ verified_at: self.verified_at,
+ cache_write_policy: match self.cache_write_policy {
+ CachePolicyData::NotApplicable => CacheWritePolicy::NotApplicable,
+ CachePolicyData::ProviderDefault => CacheWritePolicy::ProviderDefault,
+ CachePolicyData::FiveMinutes => CacheWritePolicy::FiveMinutes,
+ CachePolicyData::OneHour => CacheWritePolicy::OneHour,
+ },
+ counter_semantics: match self.counter_semantics {
+ SemanticsData::Disjoint => CounterSemantics::Disjoint,
+ SemanticsData::InclusiveTotals => CounterSemantics::InclusiveTotals,
+ SemanticsData::InputInclusive => CounterSemantics::InputInclusive,
+ SemanticsData::OutputInclusive => CounterSemantics::OutputInclusive,
+ },
+ };
+ publication.validate()?;
+ Ok(publication)
+ }
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct FundingData {
+ id: Uuid,
+ invocation_id: Uuid,
+ maximum_public_usage: u64,
+}
+
+impl From<&FundingAuthorization> for FundingData {
+ fn from(value: &FundingAuthorization) -> Self {
+ Self {
+ id: value.id.as_uuid(),
+ invocation_id: value.invocation_id.as_uuid(),
+ maximum_public_usage: value.maximum_public_usage.units(),
+ }
+ }
+}
+
+impl FundingData {
+ fn decode(self) -> FinancialResult<FundingAuthorization> {
+ Ok(FundingAuthorization {
+ id: self.id.try_into()?,
+ invocation_id: self.invocation_id.try_into()?,
+ maximum_public_usage: PublicUsage::from_units(self.maximum_public_usage),
+ })
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub(super) struct EvidenceData {
+ invocation_id: Uuid,
+ occurred_at: DateTime<Utc>,
+ provider_request_id: Option<String>,
+ outcome: OutcomeData,
+ usage: UsageData,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+enum OutcomeData {
+ Succeeded,
+ Failed,
+ Cancelled,
+ Unknown,
+}
+#[derive(Debug, Serialize, Deserialize)]
+enum UsageData {
+ Reported([u64; 5]),
+ UsageNotReported,
+ Interrupted,
+ UnsupportedDimensions,
+}
+#[derive(Debug, Serialize, Deserialize)]
+pub(super) enum ExclusionData {
+ LegacyPolicy,
+ ExemptFeature,
+ InternalWork,
+}
+#[derive(Debug, Serialize, Deserialize)]
+pub(super) enum UnpricedData {
+ MissingRate,
+ ArithmeticOverflow,
+}
+
+impl From<&FinalizeInvocation> for EvidenceData {
+ fn from(value: &FinalizeInvocation) -> Self {
+ Self {
+ invocation_id: value.invocation_id.as_uuid(),
+ occurred_at: value.occurred_at,
+ provider_request_id: value
+ .provider_request_id
+ .as_ref()
+ .map(|id| id.as_str().to_owned()),
+ outcome: match value.outcome {
+ ProviderOutcome::Succeeded => OutcomeData::Succeeded,
+ ProviderOutcome::Failed => OutcomeData::Failed,
+ ProviderOutcome::Cancelled => OutcomeData::Cancelled,
+ ProviderOutcome::Unknown => OutcomeData::Unknown,
+ },
+ usage: match value.usage {
+ UsageEvidence::Reported(usage) => UsageData::Reported(token_array(usage)),
+ UsageEvidence::Missing(UnresolvedReason::UsageNotReported) => {
+ UsageData::UsageNotReported
+ }
+ UsageEvidence::Missing(UnresolvedReason::Interrupted) => UsageData::Interrupted,
+ UsageEvidence::Missing(UnresolvedReason::UnsupportedDimensions) => {
+ UsageData::UnsupportedDimensions
+ }
+ },
+ }
+ }
+}
+
+impl EvidenceData {
+ fn decode(self) -> FinancialResult<FinalizeInvocation> {
+ Ok(FinalizeInvocation {
+ invocation_id: self.invocation_id.try_into()?,
+ occurred_at: self.occurred_at,
+ provider_request_id: self
+ .provider_request_id
+ .map(ProviderRequestId::new)
+ .transpose()?,
+ outcome: match self.outcome {
+ OutcomeData::Succeeded => ProviderOutcome::Succeeded,
+ OutcomeData::Failed => ProviderOutcome::Failed,
+ OutcomeData::Cancelled => ProviderOutcome::Cancelled,
+ OutcomeData::Unknown => ProviderOutcome::Unknown,
+ },
+ usage: match self.usage {
+ UsageData::Reported(usage) => UsageEvidence::Reported(tokens(usage)),
+ UsageData::UsageNotReported => {
+ UsageEvidence::Missing(UnresolvedReason::UsageNotReported)
+ }
+ UsageData::Interrupted => UsageEvidence::Missing(UnresolvedReason::Interrupted),
+ UsageData::UnsupportedDimensions => {
+ UsageEvidence::Missing(UnresolvedReason::UnsupportedDimensions)
+ }
+ },
+ })
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub(super) enum StateData {
+ Priced {
+ evidence: EvidenceData,
+ public_usage: u64,
+ },
+ Unresolved {
+ evidence: EvidenceData,
+ },
+ Unpriced {
+ evidence: EvidenceData,
+ reason: UnpricedData,
+ },
+ Excluded {
+ evidence: EvidenceData,
+ reason: ExclusionData,
+ },
+}
+
+impl StateData {
+ pub(super) fn from_state(state: &InvocationState) -> FinancialResult<Self> {
+ Ok(match state {
+ InvocationState::Pending => return Err(FinancialError::InvalidTokenUsage),
+ InvocationState::Priced {
+ evidence,
+ public_usage,
+ } => Self::Priced {
+ evidence: evidence.into(),
+ public_usage: public_usage.units(),
+ },
+ InvocationState::Unresolved { evidence } => Self::Unresolved {
+ evidence: evidence.into(),
+ },
+ InvocationState::Unpriced { evidence, reason } => Self::Unpriced {
+ evidence: evidence.into(),
+ reason: match reason {
+ UnpricedReason::MissingRate => UnpricedData::MissingRate,
+ UnpricedReason::ArithmeticOverflow => UnpricedData::ArithmeticOverflow,
+ },
+ },
+ InvocationState::Excluded { evidence, reason } => Self::Excluded {
+ evidence: evidence.into(),
+ reason: match reason {
+ ExclusionReason::LegacyPolicy => ExclusionData::LegacyPolicy,
+ ExclusionReason::ExemptFeature => ExclusionData::ExemptFeature,
+ ExclusionReason::InternalWork => ExclusionData::InternalWork,
+ },
+ },
+ })
+ }
+
+ pub(super) fn decode(self) -> FinancialResult<InvocationState> {
+ Ok(match self {
+ Self::Priced {
+ evidence,
+ public_usage,
+ } => InvocationState::Priced {
+ evidence: evidence.decode()?,
+ public_usage: PublicUsage::from_units(public_usage),
+ },
+ Self::Unresolved { evidence } => InvocationState::Unresolved {
+ evidence: evidence.decode()?,
+ },
+ Self::Unpriced { evidence, reason } => InvocationState::Unpriced {
+ evidence: evidence.decode()?,
+ reason: match reason {
+ UnpricedData::MissingRate => UnpricedReason::MissingRate,
+ UnpricedData::ArithmeticOverflow => UnpricedReason::ArithmeticOverflow,
+ },
+ },
+ Self::Excluded { evidence, reason } => InvocationState::Excluded {
+ evidence: evidence.decode()?,
+ reason: match reason {
+ ExclusionData::LegacyPolicy => ExclusionReason::LegacyPolicy,
+ ExclusionData::ExemptFeature => ExclusionReason::ExemptFeature,
+ ExclusionData::InternalWork => ExclusionReason::InternalWork,
+ },
+ },
+ })
+ }
+}
+
+struct JournalRow {
+ request: Json<RequestData>,
+ publication: Json<RateData>,
+ funding: Option<Json<FundingData>>,
+ finalization: Option<Json<StateData>>,
+}
+
+impl JournalRow {
+ fn prepared(self) -> FinancialResult<PreparedInvocation> {
+ Ok(PreparedInvocation {
+ request: self.request.0.decode()?,
+ rate: self.publication.0.decode()?.snapshot,
+ funding: self.funding.map(|data| data.0.decode()).transpose()?,
+ })
+ }
+
+ fn record(self) -> FinancialResult<Option<InvocationRecord>> {
+ let state = self
+ .finalization
+ .map(|data| data.0.decode())
+ .transpose()?
+ .unwrap_or(InvocationState::Pending);
+ let prepared = Self {
+ finalization: None,
+ ..self
+ }
+ .prepared()?;
+ Ok(prepared.funding.map(|funding| InvocationRecord {
+ admission: AuthorizedInvocation {
+ request: prepared.request,
+ rate: prepared.rate,
+ funding,
+ },
+ state,
+ }))
+ }
+}
+
+fn token_array(tokens: TrustedTokenUsage) -> [u64; 5] {
+ [
+ tokens.input(),
+ tokens.output(),
+ tokens.cache_read(),
+ tokens.cache_write(),
+ tokens.reasoning(),
+ ]
+}
+
+fn tokens([input, output, cache_read, cache_write, reasoning]: [u64; 5]) -> TrustedTokenUsage {
+ TrustedTokenUsage::from_disjoint(input, output, cache_read, cache_write, reasoning)
+}
diff --git a/crates/ai_usage/src/outbound/pg_financial_usage_repo/test.rs b/crates/ai_usage/src/outbound/pg_financial_usage_repo/test.rs
new file mode 100644
index 0000000000..71b49da080
--- /dev/null
+++ b/crates/ai_usage/src/outbound/pg_financial_usage_repo/test.rs
@@ -0,0 +1,423 @@
+use super::*;
+use crate::domain::{
+ AiFeature, CompletionUsage, ModelPricing, Price, SYSTEM_USER_ID, Usage, UsageAmount,
+ UsageApiParams, UsageRepo,
+};
+use crate::outbound::PgUsageRepo;
+use chrono::Duration;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+
+fn publication() -> RatePublication {
+ let effective_at = DateTime::from_timestamp(1_800_000_000, 0).unwrap();
+ RatePublication {
+ snapshot: RateSnapshot {
+ version: RateVersion::new(),
+ model: ProviderModel::new("test-provider", "test-model").unwrap(),
+ effective_at,
+ tokens: TokenRates {
+ input: 1_000_000,
+ output: 2_000_000,
+ cache_read: 100_000,
+ cache_write: 1_250_000,
+ reasoning: 2_000_000,
+ },
+ },
+ valid_until: effective_at + Duration::days(30),
+ source: "https://example.com/public-prices".into(),
+ verified_at: effective_at,
+ cache_write_policy: CacheWritePolicy::FiveMinutes,
+ counter_semantics: CounterSemantics::InclusiveTotals,
+ }
+}
+
+fn request(rate: &RateSnapshot) -> BeginInvocation {
+ BeginInvocation {
+ run_id: RunId::new(),
+ invocation_id: InvocationId::new(),
+ user: SYSTEM_USER_ID.clone(),
+ feature: AiFeature::Chat,
+ entity: None,
+ model: rate.model.clone(),
+ // Preserve exact nanoseconds through evidence replay despite timestamptz precision.
+ occurred_at: rate.effective_at + Duration::nanoseconds(123_456_789),
+ token_budget: TrustedTokenUsage::from_disjoint(100, 50, 40, 30, 20),
+ }
+}
+
+fn admission(request: BeginInvocation, rate: RateSnapshot) -> AuthorizedInvocation {
+ let funding = FundingAuthorization {
+ id: FundingAuthorizationId::new(),
+ invocation_id: request.invocation_id,
+ maximum_public_usage: rate.tokens.price(request.token_budget).unwrap(),
+ };
+ AuthorizedInvocation {
+ request,
+ rate,
+ funding,
+ }
+}
+
+fn record(admission: AuthorizedInvocation) -> InvocationRecord {
+ let usage = TrustedTokenUsage::from_inclusive_totals(100, 50, 40, 30, 20).unwrap();
+ let evidence = FinalizeInvocation {
+ invocation_id: admission.request.invocation_id,
+ occurred_at: admission.request.occurred_at + Duration::seconds(1),
+ provider_request_id: Some(ProviderRequestId::new("provider-request-id").unwrap()),
+ outcome: ProviderOutcome::Cancelled,
+ usage: UsageEvidence::Reported(usage),
+ };
+ let public_usage = admission.rate.tokens.price(usage).unwrap();
+ InvocationRecord {
+ admission,
+ state: InvocationState::Priced {
+ evidence,
+ public_usage,
+ },
+ }
+}
+
+fn scan() -> PendingInvocations {
+ PendingInvocations {
+ after: None,
+ before: publication().valid_until,
+ limit: 100.try_into().unwrap(),
+ }
+}
+
+async fn prepare(repo: &PgFinancialUsageRepo) -> AuthorizedInvocation {
+ let publication = publication();
+ repo.publish(publication.clone()).await.unwrap();
+ let request = request(&publication.snapshot);
+ repo.prepare(request.clone(), publication.snapshot.clone())
+ .await
+ .unwrap();
+ admission(request, publication.snapshot)
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn rate_publications_are_immutable_qualified_and_expire_closed(pool: PgPool) {
+ let repo = PgFinancialUsageRepo::new(pool.clone());
+ let original = publication();
+ assert_eq!(
+ repo.publish(original.clone()).await.unwrap(),
+ WriteDisposition::Inserted
+ );
+ assert_eq!(
+ repo.publish(original.clone()).await.unwrap(),
+ WriteDisposition::Replayed
+ );
+ let mut changed = original.clone();
+ changed.snapshot.tokens.input += 1;
+ assert!(repo.publish(changed).await.is_err());
+ assert_eq!(
+ repo.publication(original.snapshot.version).await.unwrap(),
+ Some(original.clone())
+ );
+ assert!(matches!(
+ repo.resolve(
+ ProviderModel::new("other", "test-model").unwrap(),
+ original.snapshot.effective_at
+ )
+ .await,
+ Err(FinancialError::RateUnavailable)
+ ));
+ let mut other_provider = original.clone();
+ other_provider.snapshot.version = RateVersion::new();
+ other_provider.snapshot.model = ProviderModel::new("other", "test-model").unwrap();
+ other_provider.snapshot.tokens.input += 10;
+ repo.publish(other_provider.clone()).await.unwrap();
+ assert_eq!(
+ repo.resolve(
+ other_provider.snapshot.model.clone(),
+ original.snapshot.effective_at
+ )
+ .await
+ .unwrap(),
+ other_provider.snapshot
+ );
+ assert!(
+ repo.resolve(
+ original.snapshot.model.clone(),
+ original.snapshot.effective_at - Duration::microseconds(1)
+ )
+ .await
+ .is_err()
+ );
+ let mut replacement = original.clone();
+ replacement.snapshot.version = RateVersion::new();
+ replacement.snapshot.effective_at += Duration::days(1);
+ replacement.valid_until = replacement.snapshot.effective_at + Duration::days(1);
+ repo.publish(replacement.clone()).await.unwrap();
+ assert_eq!(
+ repo.resolve(
+ original.snapshot.model.clone(),
+ replacement.snapshot.effective_at
+ )
+ .await
+ .unwrap(),
+ replacement.snapshot
+ );
+ assert!(matches!(
+ repo.resolve(original.snapshot.model.clone(), replacement.valid_until)
+ .await,
+ Err(FinancialError::RateUnavailable)
+ ));
+ // A different UUID cannot introduce an ambiguous version for the same effective time.
+ let mut collision = original.clone();
+ collision.snapshot.version = RateVersion::new();
+ assert!(repo.publish(collision).await.is_err());
+ assert!(
+ sqlx::query!(
+ "UPDATE ai_financial_rate SET model = 'mutated' WHERE version = $1",
+ original.snapshot.version.as_uuid()
+ )
+ .execute(&pool)
+ .await
+ .is_err()
+ );
+ assert!(
+ sqlx::query!(
+ "DELETE FROM ai_financial_rate WHERE version = $1",
+ original.snapshot.version.as_uuid()
+ )
+ .execute(&pool)
+ .await
+ .is_err()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn lost_acknowledgements_and_concurrent_replays_write_once(pool: PgPool) {
+ let repo = PgFinancialUsageRepo::new(pool);
+ let admission = prepare(&repo).await;
+ let id = admission.request.invocation_id;
+ assert!(repo.get(id).await.unwrap().is_none());
+ assert_eq!(repo.pending_admissions(scan()).await.unwrap().len(), 1);
+ let (left, right) = tokio::join!(repo.admit(admission.clone()), repo.admit(admission.clone()));
+ let results = [left.unwrap(), right.unwrap()];
+ assert_eq!(
+ results
+ .iter()
+ .filter(|result| result.disposition == WriteDisposition::Inserted)
+ .count(),
+ 1
+ );
+ assert_eq!(
+ repo.admit(admission.clone()).await.unwrap().disposition,
+ WriteDisposition::Replayed
+ );
+ assert!(repo.pending_admissions(scan()).await.unwrap().is_empty());
+ assert_eq!(
+ repo.pending(scan()).await.unwrap()[0].state,
+ InvocationState::Pending
+ );
+ let record = record(admission);
+ let (left, right) = tokio::join!(repo.finish(record.clone()), repo.finish(record.clone()));
+ let results = [left.unwrap(), right.unwrap()];
+ assert_eq!(
+ results
+ .iter()
+ .filter(|result| result.disposition == WriteDisposition::Inserted)
+ .count(),
+ 1
+ );
+ // Crash after evidence commit is still discoverable for funding handoff.
+ assert_eq!(repo.pending(scan()).await.unwrap(), vec![record.clone()]);
+ assert_eq!(repo.get(id).await.unwrap(), Some(record.clone()));
+ repo.acknowledge_funding(id).await.unwrap();
+ repo.acknowledge_funding(id).await.unwrap();
+ assert!(repo.pending(scan()).await.unwrap().is_empty());
+ assert_eq!(
+ repo.finish(record).await.unwrap().disposition,
+ WriteDisposition::Replayed
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn conflicting_replays_and_direct_mutation_cannot_replace_facts(pool: PgPool) {
+ let repo = PgFinancialUsageRepo::new(pool.clone());
+ let admission = prepare(&repo).await;
+ repo.admit(admission.clone()).await.unwrap();
+ let mut changed = admission.request.clone();
+ changed.user = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();
+ assert!(matches!(
+ repo.prepare(changed, admission.rate.clone()).await,
+ Err(FinancialError::ReplayConflict {
+ phase: ReplayPhase::Begin,
+ ..
+ })
+ ));
+ let mut changed_funding = admission.clone();
+ changed_funding.funding.id = FundingAuthorizationId::new();
+ assert!(matches!(
+ repo.admit(changed_funding).await,
+ Err(FinancialError::ReplayConflict {
+ phase: ReplayPhase::Begin,
+ ..
+ })
+ ));
+ let original = record(admission.clone());
+ repo.finish(original.clone()).await.unwrap();
+ let mut changed = original.clone();
+ if let InvocationState::Priced { evidence, .. } = &mut changed.state {
+ evidence.outcome = ProviderOutcome::Succeeded;
+ }
+ assert!(matches!(
+ repo.finish(changed).await,
+ Err(FinancialError::ReplayConflict {
+ phase: ReplayPhase::Finalize,
+ ..
+ })
+ ));
+ let mut mispriced = original.clone();
+ if let InvocationState::Priced { public_usage, .. } = &mut mispriced.state {
+ *public_usage = PublicUsage::from_units(0);
+ }
+ assert!(matches!(
+ repo.finish(mispriced).await,
+ Err(FinancialError::InvalidTokenUsage)
+ ));
+ assert!(sqlx::query!("UPDATE ai_financial_invocation SET finalization = NULL, finalized_at = NULL WHERE invocation_id = $1", admission.request.invocation_id.as_uuid()).execute(&pool).await.is_err());
+ assert!(
+ sqlx::query!(
+ "UPDATE ai_financial_invocation SET request = '{}'::jsonb WHERE invocation_id = $1",
+ admission.request.invocation_id.as_uuid()
+ )
+ .execute(&pool)
+ .await
+ .is_err()
+ );
+ assert_eq!(
+ repo.get(admission.request.invocation_id).await.unwrap(),
+ Some(original)
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn interrupted_and_unpriced_invocations_remain_recoverable_with_bounded_scans(pool: PgPool) {
+ let repo = PgFinancialUsageRepo::new(pool);
+ let first = prepare(&repo).await;
+ repo.admit(first.clone()).await.unwrap();
+ let mut second_request = first.request.clone();
+ second_request.invocation_id = InvocationId::new();
+ repo.prepare(second_request.clone(), first.rate.clone())
+ .await
+ .unwrap();
+ let second = admission(second_request, first.rate.clone());
+ repo.admit(second.clone()).await.unwrap();
+ let missing = InvocationRecord {
+ admission: first.clone(),
+ state: InvocationState::Unresolved {
+ evidence: FinalizeInvocation {
+ invocation_id: first.request.invocation_id,
+ occurred_at: first.request.occurred_at,
+ provider_request_id: None,
+ outcome: ProviderOutcome::Unknown,
+ usage: UsageEvidence::Missing(UnresolvedReason::Interrupted),
+ },
+ },
+ };
+ repo.finish(missing.clone()).await.unwrap();
+ repo.acknowledge_funding(first.request.invocation_id)
+ .await
+ .unwrap();
+ let overflow = InvocationRecord {
+ admission: second.clone(),
+ state: InvocationState::Unpriced {
+ evidence: FinalizeInvocation {
+ invocation_id: second.request.invocation_id,
+ occurred_at: second.request.occurred_at,
+ provider_request_id: None,
+ outcome: ProviderOutcome::Failed,
+ usage: UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(
+ u64::MAX,
+ 0,
+ 0,
+ 0,
+ 0,
+ )),
+ },
+ reason: UnpricedReason::ArithmeticOverflow,
+ },
+ };
+ repo.finish(overflow.clone()).await.unwrap();
+ repo.acknowledge_funding(second.request.invocation_id)
+ .await
+ .unwrap();
+ assert_eq!(
+ repo.get(second.request.invocation_id).await.unwrap(),
+ Some(overflow)
+ );
+ assert_eq!(repo.pending(scan()).await.unwrap().len(), 2);
+ let mut query = scan();
+ query.limit = 1.try_into().unwrap();
+ let page = repo.pending(query).await.unwrap();
+ assert_eq!(page.len(), 1);
+ query.after = Some(page[0].admission.request.invocation_id);
+ assert_eq!(repo.pending(query).await.unwrap().len(), 1);
+ query.before = first.rate.effective_at;
+ assert!(repo.pending(query).await.unwrap().is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn legacy_analytics_writes_and_repricing_leave_financial_evidence_unchanged(pool: PgPool) {
+ let repo = PgFinancialUsageRepo::new(pool.clone());
+ let admission = prepare(&repo).await;
+ repo.admit(admission.clone()).await.unwrap();
+ let original = record(admission.clone());
+ repo.finish(original.clone()).await.unwrap();
+ let analytics = PgUsageRepo::new(pool);
+ let pricing = ModelPricing::Tokens {
+ input: 1.0,
+ output: 2.0,
+ };
+ let amount = UsageAmount::Tokens {
+ input: 1_000_000,
+ output: 0,
+ };
+ analytics
+ .insert_usage(&CompletionUsage {
+ feature: AiFeature::Chat,
+ user: SYSTEM_USER_ID.clone(),
+ entity: None,
+ cost: Usage {
+ amount,
+ model: "test-model".into(),
+ price: Price::compute(pricing, amount),
+ created_at: Utc::now(),
+ },
+ })
+ .await
+ .unwrap();
+ analytics
+ .set_pricing(
+ "test-model",
+ ModelPricing::Tokens {
+ input: 99.0,
+ output: 99.0,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ analytics
+ .query_usage(&UsageApiParams::default())
+ .await
+ .unwrap()[0]
+ .cost
+ .price
+ .unwrap()
+ .total,
+ 99.0
+ );
+ assert_eq!(
+ repo.get(admission.request.invocation_id).await.unwrap(),
+ Some(original)
+ );
+ assert_eq!(
+ repo.resolve(admission.rate.model.clone(), admission.request.occurred_at)
+ .await
+ .unwrap(),
+ admission.rate
+ );
+}
diff --git a/crates/ai_usage/src/outbound/pg_tracking_repo.rs b/crates/ai_usage/src/outbound/pg_tracking_repo.rs
new file mode 100644
index 0000000000..f16f4ac428
--- /dev/null
+++ b/crates/ai_usage/src/outbound/pg_tracking_repo.rs
@@ -0,0 +1,149 @@
+//! Durable observational journal, isolated from financial admission and settlement.
+
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use serde::{Deserialize, Serialize};
+use sqlx::{PgPool, types::Json};
+
+use super::pg_financial_usage_repo::StateData;
+use crate::domain::financial::*;
+use crate::domain::ports::{AiFeature, FinancialFuture};
+use crate::domain::tracking::{
+ TrackedInvocation, UsageTracking, UsageTrackingRepo, observation_state,
+};
+
+#[cfg(test)]
+mod test;
+
+/// Postgres observation adapter. Does not write financial or analytics tables.
+pub struct PgTrackingRepo {
+ pool: PgPool,
+}
+
+impl PgTrackingRepo {
+ /// Construct at a composition root.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+impl UsageTrackingRepo for PgTrackingRepo {}
+
+impl UsageTracking for PgTrackingRepo {
+ fn begin(&self, request: TrackedInvocation) -> FinancialFuture<'_, WriteDisposition> {
+ Box::pin(async move {
+ let data = Json(ObservationData::from(&request));
+ let inserted = sqlx::query!(
+ r#"INSERT INTO ai_usage_observation (invocation_id, occurred_at, request)
+ VALUES ($1, $2, $3) ON CONFLICT (invocation_id) DO NOTHING"#,
+ request.invocation_id.as_uuid(),
+ request.occurred_at,
+ data as _,
+ )
+ .execute(&self.pool)
+ .await?
+ .rows_affected()
+ == 1;
+ if inserted {
+ return Ok(WriteDisposition::Inserted);
+ }
+ let row = sqlx::query!(
+ r#"SELECT request AS "request: Json<ObservationData>"
+ FROM ai_usage_observation WHERE invocation_id = $1"#,
+ request.invocation_id.as_uuid(),
+ )
+ .fetch_one(&self.pool)
+ .await?;
+ if row.request.0.decode()? != request {
+ return Err(FinancialError::ReplayConflict {
+ invocation_id: request.invocation_id,
+ phase: ReplayPhase::Begin,
+ });
+ }
+ Ok(WriteDisposition::Replayed)
+ })
+ }
+
+ fn finalize(&self, evidence: FinalizeInvocation) -> FinancialFuture<'_, WriteDisposition> {
+ Box::pin(async move {
+ let id = evidence.invocation_id;
+ let state = observation_state(evidence);
+ let mut tx = self.pool.begin().await?;
+ let row = sqlx::query!(
+ r#"SELECT finalization AS "finalization: Json<StateData>"
+ FROM ai_usage_observation WHERE invocation_id = $1 FOR UPDATE"#,
+ id.as_uuid(),
+ )
+ .fetch_optional(&mut *tx)
+ .await?
+ .ok_or(FinancialError::InvocationNotFound)?;
+ let disposition = if let Some(existing) = row.finalization {
+ if existing.0.decode()? != state {
+ return Err(FinancialError::ReplayConflict {
+ invocation_id: id,
+ phase: ReplayPhase::Finalize,
+ });
+ }
+ WriteDisposition::Replayed
+ } else {
+ let data = Json(StateData::from_state(&state)?);
+ sqlx::query!(
+ r#"UPDATE ai_usage_observation SET finalization = $2, finalized_at = now()
+ WHERE invocation_id = $1"#,
+ id.as_uuid(),
+ data as _,
+ )
+ .execute(&mut *tx)
+ .await?;
+ WriteDisposition::Inserted
+ };
+ tx.commit().await?;
+ Ok(disposition)
+ })
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct ObservationData {
+ run_id: Uuid,
+ invocation_id: Uuid,
+ user_id: String,
+ feature: AiFeature,
+ entity: Option<Uuid>,
+ provider: String,
+ model: String,
+ occurred_at: DateTime<Utc>,
+}
+
+impl From<&TrackedInvocation> for ObservationData {
+ fn from(value: &TrackedInvocation) -> Self {
+ Self {
+ run_id: value.run_id.as_uuid(),
+ invocation_id: value.invocation_id.as_uuid(),
+ user_id: value.user.as_ref().to_owned(),
+ feature: value.feature,
+ entity: value.entity,
+ provider: value.model.provider().to_owned(),
+ model: value.model.model().to_owned(),
+ occurred_at: value.occurred_at,
+ }
+ }
+}
+
+impl ObservationData {
+ fn decode(self) -> FinancialResult<TrackedInvocation> {
+ Ok(TrackedInvocation {
+ run_id: self.run_id.try_into()?,
+ invocation_id: self.invocation_id.try_into()?,
+ user: MacroUserIdStr::try_from(self.user_id).map_err(|error| {
+ FinancialError::Infrastructure(rootcause::report!(error).into_dynamic())
+ })?,
+ feature: self.feature,
+ entity: self.entity,
+ model: ProviderModel::new(self.provider, self.model)?,
+ occurred_at: self.occurred_at,
+ })
+ }
+}
diff --git a/crates/ai_usage/src/outbound/pg_tracking_repo/test.rs b/crates/ai_usage/src/outbound/pg_tracking_repo/test.rs
new file mode 100644
index 0000000000..0f7145b692
--- /dev/null
+++ b/crates/ai_usage/src/outbound/pg_tracking_repo/test.rs
@@ -0,0 +1,112 @@
+use super::*;
+use crate::{SYSTEM_USER_ID, UsageTrackingService};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use std::sync::Arc;
+
+fn request() -> TrackedInvocation {
+ TrackedInvocation {
+ run_id: RunId::new(),
+ invocation_id: InvocationId::new(),
+ user: SYSTEM_USER_ID.clone(),
+ feature: AiFeature::ChatRename,
+ entity: None,
+ model: ProviderModel::new("anthropic", "unreviewed-model").unwrap(),
+ occurred_at: Utc::now(),
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn observations_are_idempotent_and_never_enter_financial_accounting(pool: PgPool) {
+ let service = UsageTrackingService::new(Arc::new(PgTrackingRepo::new(pool.clone())));
+ let request = request();
+ assert_eq!(
+ service.begin(request.clone()).await.unwrap(),
+ WriteDisposition::Inserted
+ );
+ assert_eq!(
+ service.begin(request.clone()).await.unwrap(),
+ WriteDisposition::Replayed
+ );
+ let mut changed = request.clone();
+ changed.feature = AiFeature::Chat;
+ assert!(matches!(
+ service.begin(changed).await,
+ Err(FinancialError::ReplayConflict { .. })
+ ));
+ let evidence = FinalizeInvocation {
+ invocation_id: request.invocation_id,
+ occurred_at: Utc::now(),
+ provider_request_id: Some(ProviderRequestId::new("response-1").unwrap()),
+ outcome: ProviderOutcome::Failed,
+ usage: UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(10, 2, 3, 4, 0)),
+ };
+ let (first, second) = tokio::join!(
+ service.finalize(evidence.clone()),
+ service.finalize(evidence.clone()),
+ );
+ let dispositions = [first.unwrap(), second.unwrap()];
+ assert!(dispositions.contains(&WriteDisposition::Inserted));
+ assert!(dispositions.contains(&WriteDisposition::Replayed));
+ assert_eq!(
+ service.finalize(evidence.clone()).await.unwrap(),
+ WriteDisposition::Replayed
+ );
+ let mut conflict = evidence.clone();
+ conflict.outcome = ProviderOutcome::Succeeded;
+ assert!(matches!(
+ service.finalize(conflict).await,
+ Err(FinancialError::ReplayConflict { .. })
+ ));
+ let row = sqlx::query!(
+ r#"SELECT finalization AS "finalization: Json<StateData>" FROM ai_usage_observation WHERE invocation_id = $1"#,
+ request.invocation_id.as_uuid(),
+ ).fetch_one(&pool).await.unwrap();
+ assert_eq!(
+ row.finalization.unwrap().0.decode().unwrap(),
+ observation_state(evidence)
+ );
+ let count = sqlx::query_scalar!("SELECT count(*) FROM ai_financial_invocation")
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(count, Some(0));
+ let count = sqlx::query_scalar!("SELECT count(*) FROM ai_usage")
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(count, Some(0));
+}
+
+#[test]
+fn missing_usage_is_not_measured_zero_or_exempt() {
+ for (usage, unresolved) in [
+ (UsageEvidence::Missing(UnresolvedReason::Interrupted), true),
+ (
+ UsageEvidence::Missing(UnresolvedReason::UsageNotReported),
+ true,
+ ),
+ (
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(0, 0, 0, 0, 0)),
+ false,
+ ),
+ ] {
+ let state = observation_state(FinalizeInvocation {
+ invocation_id: InvocationId::new(),
+ occurred_at: Utc::now(),
+ provider_request_id: None,
+ outcome: ProviderOutcome::Unknown,
+ usage,
+ });
+ if unresolved {
+ assert!(matches!(state, InvocationState::Unresolved { .. }));
+ } else {
+ assert!(matches!(
+ state,
+ InvocationState::Unpriced {
+ reason: UnpricedReason::MissingRate,
+ ..
+ }
+ ));
+ }
+ }
+}
diff --git a/crates/anthropic/Cargo.toml b/crates/anthropic/Cargo.toml
index 517415492d..b2e91ed82b 100644
--- a/crates/anthropic/Cargo.toml
+++ b/crates/anthropic/Cargo.toml
@@ -7,10 +7,11 @@ version = "0.2.0"
[features]
default = ["openai"]
openai = ["dep:async-openai"]
-toolset = ["dep:ai_toolset", "dep:async-trait", "dep:anyhow"]
+toolset = ["dep:ai_toolset", "dep:async-trait", "dep:anyhow", "dep:ai_usage"]
[dev-dependencies]
rand = { workspace = true }
+tokio = { workspace = true, features = ["test-util"] }
[dependencies]
@@ -31,6 +32,7 @@ chrono.workspace = true
lazy_static = {workspace = true}
regex = { workspace = true }
ai_toolset = { path = "../ai_toolset", optional = true }
+ai_usage = { path = "../ai_usage", optional = true }
async-trait = { workspace = true, optional = true }
anyhow = { workspace = true, optional = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/anthropic/src/client.rs b/crates/anthropic/src/client.rs
index 8cd68b68db..1e1b0c06c4 100644
--- a/crates/anthropic/src/client.rs
+++ b/crates/anthropic/src/client.rs
@@ -65,18 +65,28 @@ impl Client {
}
impl Client {
- pub(crate) async fn post<I, O>(&self, path: &str, request: I) -> Result<O, AnthropicError>
- where
- I: Serialize + std::fmt::Debug,
- O: DeserializeOwned,
- {
- let response = self
+ /// Execute once and expose the response before SDK parsing so trusted tool
+ /// adapters can retain usage on HTTP and result-parsing failures.
+ pub(crate) async fn post_response<I: Serialize>(
+ &self,
+ path: &str,
+ request: I,
+ ) -> Result<reqwest::Response, AnthropicError> {
+ Ok(self
.http_client
.post(format!("{}{}", self.config.api_base, path))
.headers(self.config.headers.clone())
.json(&request)
.send()
- .await?;
+ .await?)
+ }
+
+ pub(crate) async fn post<I, O>(&self, path: &str, request: I) -> Result<O, AnthropicError>
+ where
+ I: Serialize + std::fmt::Debug,
+ O: DeserializeOwned,
+ {
+ let response = self.post_response(path, request).await?;
let status = response.status();
let body = response.text().await.map_err(AnthropicError::Reqwest)?;
diff --git a/crates/anthropic/src/toolset.rs b/crates/anthropic/src/toolset.rs
index 05d247c8a0..5e73a040b8 100644
--- a/crates/anthropic/src/toolset.rs
+++ b/crates/anthropic/src/toolset.rs
@@ -15,7 +15,13 @@ use crate::types::request::{
CreateMessageRequestBody, RequestContent, RequestMessage, Role, ServerTool, SystemPrompt, Tool,
};
use crate::types::response::{Content, MessageResponse, ResponseContentKind};
-use ai_toolset::{AsyncToolCollection, ToolCallError};
+use ai_toolset::{AsyncToolCollection, RequestContext, ToolCallError};
+use ai_usage::financial::{
+ FinalizeInvocation, InvocationId, ProviderModel, ProviderOutcome, ProviderRequestId, RunId,
+ TrustedTokenUsage, UnresolvedReason, UsageEvidence,
+};
+use ai_usage::{TrackedInvocation, UsageContext, UsageRecorder};
+use chrono::Utc;
use std::sync::Arc;
/// Service context for Anthropic server tools.
@@ -24,6 +30,10 @@ pub struct AnthropicToolContext {
pub client: Arc<Client>,
/// The model to use for server tool invocations.
pub model: String,
+ /// Analytics injection also exposes the separate observational journal.
+ pub recorder: Arc<dyn UsageRecorder>,
+ /// Inherited feature/entity only; each call replaces the user from RequestContext.
+ pub usage_context: UsageContext,
}
impl Clone for AnthropicToolContext {
@@ -31,6 +41,8 @@ impl Clone for AnthropicToolContext {
Self {
client: self.client.clone(),
model: self.model.clone(),
+ recorder: self.recorder.clone(),
+ usage_context: self.usage_context.clone(),
}
}
}
@@ -41,10 +53,53 @@ impl AnthropicToolContext {
Self {
client: Arc::new(client),
model,
+ recorder: Arc::new(ai_usage::NoOpUsageRecorder),
+ usage_context: UsageContext::system(ai_usage::AiFeature::Chat),
}
}
}
+fn tool_error(error: impl Into<anyhow::Error>) -> ToolCallError {
+ let error = error.into();
+ ToolCallError {
+ description: format!("Anthropic API error: {error:?}"),
+ internal_error: error,
+ }
+}
+
+fn response_usage(value: &serde_json::Value) -> UsageEvidence {
+ let Some(usage) = value.get("usage").filter(|usage| !usage.is_null()) else {
+ return UsageEvidence::Missing(UnresolvedReason::UsageNotReported);
+ };
+ let tokens = (|| {
+ let optional = |key| match usage.get(key) {
+ None | Some(serde_json::Value::Null) => Some(0),
+ Some(value) => value.as_u64(),
+ };
+ if let Some(cache) = usage.get("cache_creation").filter(|cache| !cache.is_null()) {
+ let cache = cache.as_object()?;
+ if cache
+ .get("ephemeral_1h_input_tokens")
+ .is_some_and(|value| !value.is_null() && value.as_u64() != Some(0))
+ {
+ return None;
+ }
+ }
+ Some(TrustedTokenUsage::from_disjoint(
+ usage.get("input_tokens")?.as_u64()?,
+ usage.get("output_tokens")?.as_u64()?,
+ optional("cache_read_input_tokens")?,
+ optional("cache_creation_input_tokens")?,
+ 0, // Anthropic output already includes thinking.
+ ))
+ })();
+ tokens
+ .map(UsageEvidence::Reported)
+ .unwrap_or(UsageEvidence::Missing(
+ UnresolvedReason::UnsupportedDimensions,
+ ))
+}
+
/// Create the Anthropic server tools toolset.
pub fn anthropic_toolset() -> AsyncToolCollection<AnthropicToolContext> {
AsyncToolCollection::new()
@@ -55,13 +110,13 @@ pub fn anthropic_toolset() -> AsyncToolCollection<AnthropicToolContext> {
}
pub(crate) async fn invoke_server_tool(
- client: &Client,
- model: &str,
+ context: &AnthropicToolContext,
+ request_context: &RequestContext,
server_tool: ServerTool,
input: &str,
) -> Result<Vec<ResponseContentKind>, ToolCallError> {
let request = CreateMessageRequestBody {
- model: model.to_string(),
+ model: context.model.clone(),
messages: vec![RequestMessage {
role: Role::User,
content: RequestContent::Text(input.to_string()),
@@ -74,15 +129,124 @@ pub(crate) async fn invoke_server_tool(
..Default::default()
};
- let response: MessageResponse =
- client
- .chat()
- .create(request)
- .await
- .map_err(|e| ToolCallError {
- description: format!("Anthropic API error: {e:?}"),
- internal_error: e.into(),
- })?;
+ let client = context.client.clone();
+ let (tracking, model) = match (
+ context.recorder.tracking(),
+ ProviderModel::new("anthropic", &context.model),
+ ) {
+ (Some(tracking), Ok(model)) => (tracking, model),
+ (_, model) => {
+ let _ = model.inspect_err(|error| {
+ tracing::error!(error = ?error, "cannot identify tool provider; observation not persisted");
+ });
+ let response = client.chat().create(request).await.map_err(tool_error)?;
+ return Ok(match response.content {
+ Some(Content::Array(blocks)) => blocks,
+ _ => Vec::new(),
+ });
+ }
+ };
+ let attribution = TrackedInvocation {
+ run_id: RunId::new(),
+ invocation_id: InvocationId::new(),
+ user: request_context.user_id.clone(),
+ feature: context.usage_context.feature,
+ entity: context.usage_context.entity,
+ model,
+ occurred_at: Utc::now(),
+ };
+ let _ = tracking.begin(attribution.clone()).await.inspect_err(|error| {
+ tracing::error!(error = ?error, invocation_id = ?attribution.invocation_id, "tool observation begin failed");
+ });
+ // The client performs one HTTP execution, with no hidden retries. Keep it
+ // alive after tool cancellation so already-incurred usage can be recorded.
+ let (caller_alive, cancelled) = tokio::sync::oneshot::channel::<()>();
+ let response = tokio::spawn(async move {
+ let request = crate::types::request::transform_request_web_fetch(request);
+ let execution = async {
+ let response = client.post_response("/v1/messages", request).await?;
+ let status = response.status();
+ let request_id = response
+ .headers()
+ .get("request-id")
+ .and_then(|id| id.to_str().ok())
+ .and_then(|id| ProviderRequestId::new(id).ok());
+ let value = response.json::<serde_json::Value>().await?;
+ Ok::<_, anyhow::Error>((status, request_id, value))
+ };
+ tokio::pin!(execution);
+ let result = tokio::select! {
+ result = &mut execution => result,
+ _ = cancelled => match tokio::time::timeout(
+ std::time::Duration::from_secs(300), execution
+ ).await {
+ Ok(result) => result,
+ Err(error) => Err(error.into()),
+ },
+ };
+ let (usage, provider_request_id, outcome) = match &result {
+ Ok((status, request_id, value)) => {
+ let request_id = request_id.clone().or_else(|| {
+ value
+ .get("id")
+ .and_then(serde_json::Value::as_str)
+ .and_then(|id| ProviderRequestId::new(id).ok())
+ });
+ let outcome = if status.is_success() {
+ ProviderOutcome::Succeeded
+ } else {
+ ProviderOutcome::Failed
+ };
+ (response_usage(value), request_id, outcome)
+ }
+ Err(_) => (
+ UsageEvidence::Missing(UnresolvedReason::Interrupted),
+ None,
+ ProviderOutcome::Unknown,
+ ),
+ };
+ let evidence = FinalizeInvocation {
+ invocation_id: attribution.invocation_id,
+ occurred_at: Utc::now(),
+ provider_request_id,
+ outcome,
+ usage,
+ };
+ for _ in 0..3 {
+ let recorded = match tracking.begin(attribution.clone()).await {
+ Ok(_) => tracking.finalize(evidence.clone()).await,
+ Err(error) => Err(error),
+ };
+ if recorded
+ .inspect_err(|error| {
+ tracing::error!(
+ error = ?error,
+ invocation_id = ?attribution.invocation_id,
+ "tool observation delivery failed"
+ );
+ })
+ .is_ok()
+ {
+ break;
+ }
+ }
+ let (status, _, value) = result?;
+ if !status.is_success() {
+ let api_error = serde_json::from_value::<crate::prelude::ApiError>(value)?;
+ return Err(crate::error::AnthropicError::ApiError {
+ api_error,
+ status_code: status,
+ }
+ .into());
+ }
+ Ok::<_, anyhow::Error>(value)
+ })
+ .await
+ .map_err(tool_error)?
+ .map_err(tool_error)?;
+ drop(caller_alive);
+ // Observe before result parsing: a malformed tool result can still incur tokens.
+ let response: MessageResponse = serde_json::from_value(response).map_err(tool_error)?;
match response.content {
Some(Content::Array(blocks)) => Ok(blocks),
diff --git a/crates/anthropic/src/toolset/bash_code_execution.rs b/crates/anthropic/src/toolset/bash_code_execution.rs
index 5acf1a392e..a907d4972f 100644
--- a/crates/anthropic/src/toolset/bash_code_execution.rs
+++ b/crates/anthropic/src/toolset/bash_code_execution.rs
@@ -32,12 +32,12 @@ impl AsyncTool<AnthropicToolContext> for BashCodeExecution {
async fn call(
&self,
service_context: ServiceContext<AnthropicToolContext>,
- _request_context: RequestContext,
+ request_context: RequestContext,
) -> ToolResult<Self::Output> {
let ctx = &*service_context;
let blocks = super::invoke_server_tool(
- &ctx.client,
- &ctx.model,
+ ctx,
+ &request_context,
CODE_EXECUTION_TOOL.clone(),
&self.input,
)
diff --git a/crates/anthropic/src/toolset/test.rs b/crates/anthropic/src/toolset/test.rs
index 2401c73b3f..171eb849b0 100644
--- a/crates/anthropic/src/toolset/test.rs
+++ b/crates/anthropic/src/toolset/test.rs
@@ -1,4 +1,281 @@
+use super::*;
use crate::types::response::{Content, MessageResponse, ResponseContentKind};
+use ai_usage::financial::{FinancialError, WriteDisposition};
+use ai_usage::{FinancialFuture, UsageTracking};
+use std::sync::Mutex;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+#[derive(Default)]
+struct Observations {
+ begins: Mutex<Vec<TrackedInvocation>>,
+ finals: Mutex<Vec<FinalizeInvocation>>,
+ fail: bool,
+}
+
+impl UsageTracking for Observations {
+ fn begin(&self, request: TrackedInvocation) -> FinancialFuture<'_, WriteDisposition> {
+ Box::pin(async move {
+ self.begins.lock().unwrap().push(request);
+ if self.fail {
+ return Err(FinancialError::CapabilityUnavailable);
+ }
+ Ok(WriteDisposition::Inserted)
+ })
+ }
+ fn finalize(&self, evidence: FinalizeInvocation) -> FinancialFuture<'_, WriteDisposition> {
+ Box::pin(async move {
+ self.finals.lock().unwrap().push(evidence);
+ Ok(WriteDisposition::Inserted)
+ })
+ }
+}
+
+async fn context_with_response(body: &str, journal: Arc<Observations>) -> AnthropicToolContext {
+ context_with_status(body, journal, 200).await
+}
+
+async fn context_with_status(
+ body: &str,
+ journal: Arc<Observations>,
+ status: u16,
+) -> AnthropicToolContext {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let response = format!(
+ "HTTP/1.1 {status} Response\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ body.len(),
+ body
+ );
+ tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut data = vec![0; 8192];
+ let received = socket.read(&mut data).await.unwrap();
+ assert!(received > 0, "client sent a request before the response");
+ socket.write_all(response.as_bytes()).await.unwrap();
+ });
+ let mut context = AnthropicToolContext::new(
+ Client::with_config(crate::config::Config {
+ api_base: format!("http://{address}"),
+ ..Default::default()
+ }),
+ "claude-haiku-4-5".into(),
+ );
+ context.recorder = ai_usage::with_tracking(Arc::new(ai_usage::NoOpUsageRecorder), journal);
+ context.usage_context = UsageContext::system(ai_usage::AiFeature::Automation);
+ context
+}
+
+#[tokio::test]
+async fn independent_tool_uses_authenticated_user_and_records_before_parsing() {
+ let journal = Arc::new(Observations::default());
+ // Deliberately malformed tool content: usage must survive SDK/result failure.
+ let context = context_with_response(r#"{"id":"msg-1","content":42,"usage":{"input_tokens":10,"output_tokens":5,"cache_read_input_tokens":2,"cache_creation_input_tokens":3,"server_tool_use":{"web_search_requests":1}}}"#, journal.clone()).await;
+ let request = RequestContext::new(
+ .to_owned()
+ .try_into()
+ .unwrap(),
+ );
+ assert!(
+ invoke_server_tool(
+ &context,
+ &request,
+ crate::types::request::WEB_SEARCH_TOOL.clone(),
+ "query"
+ )
+ .await
+ .is_err()
+ );
+ let begins = journal.begins.lock().unwrap();
+ assert!(
+ begins.iter().all(|begin| begin.user == request.user_id
+ && begin.feature == ai_usage::AiFeature::Automation)
+ );
+ assert_eq!(begins[0].model.provider(), "anthropic");
+ assert_eq!(begins[0].model.model(), "claude-haiku-4-5");
+ let finals = journal.finals.lock().unwrap();
+ assert_eq!(finals.len(), 1);
+ assert_eq!(
+ finals[0].usage,
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(10, 5, 2, 3, 0))
+ );
+}
+
+#[tokio::test]
+async fn recorder_failure_does_not_fail_tool_execution() {
+ let journal = Arc::new(Observations {
+ fail: true,
+ ..Default::default()
+ });
+ let context = context_with_response(
+ r#"{"content":[],"usage":{"input_tokens":1,"output_tokens":2}}"#,
+ journal.clone(),
+ )
+ .await;
+ let request = RequestContext::new(
+ .to_owned()
+ .try_into()
+ .unwrap(),
+ );
+ invoke_server_tool(
+ &context,
+ &request,
+ crate::types::request::WEB_SEARCH_TOOL.clone(),
+ "query",
+ )
+ .await
+ .unwrap();
+ assert!(journal.finals.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn failed_http_response_preserves_reported_usage() {
+ let journal = Arc::new(Observations::default());
+ let context = context_with_status(
+ r#"{"error":{"type":"overloaded_error"},"usage":{"input_tokens":3,"output_tokens":2}}"#,
+ journal.clone(),
+ 503,
+ )
+ .await;
+ let request = RequestContext::new(
+ .to_owned()
+ .try_into()
+ .unwrap(),
+ );
+ assert!(
+ invoke_server_tool(
+ &context,
+ &request,
+ crate::types::request::WEB_SEARCH_TOOL.clone(),
+ "query"
+ )
+ .await
+ .is_err()
+ );
+ let finals = journal.finals.lock().unwrap();
+ assert_eq!(finals.len(), 1);
+ assert_eq!(finals[0].outcome, ProviderOutcome::Failed);
+ assert_eq!(
+ finals[0].usage,
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(3, 2, 0, 0, 0))
+ );
+}
+
+#[test]
+fn absent_usage_is_not_zero_and_unknown_cache_ttl_is_unresolved() {
+ assert_eq!(
+ response_usage(&serde_json::json!({})),
+ UsageEvidence::Missing(UnresolvedReason::UsageNotReported)
+ );
+ assert_eq!(
+ response_usage(&serde_json::json!({"usage":{"input_tokens":1}})),
+ UsageEvidence::Missing(UnresolvedReason::UnsupportedDimensions)
+ );
+ assert_eq!(
+ response_usage(
+ &serde_json::json!({"usage":{"input_tokens":1,"output_tokens":2,"cache_creation":{"ephemeral_1h_input_tokens":1}}})
+ ),
+ UsageEvidence::Missing(UnresolvedReason::UnsupportedDimensions)
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn live_tool_has_no_deadline_but_cancelled_tool_drain_is_bounded() {
+ use std::time::Duration;
+ for cancel in [false, true] {
+ let journal = Arc::new(Observations::default());
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let (started_tx, started_rx) = tokio::sync::oneshot::channel();
+ let (release_tx, release_rx) = tokio::sync::oneshot::channel();
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut data = vec![0; 8192];
+ assert!(socket.read(&mut data).await.unwrap() > 0);
+ started_tx.send(()).unwrap();
+ let _ = release_rx.await;
+ let body = r#"{"content":[],"usage":{"input_tokens":10,"output_tokens":2}}"#;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = socket.write_all(response.as_bytes()).await;
+ });
+ let mut context = AnthropicToolContext::new(
+ Client::with_config(crate::config::Config {
+ api_base: format!("http://{address}"),
+ ..Default::default()
+ }),
+ "claude-haiku-4-5".into(),
+ );
+ context.recorder =
+ ai_usage::with_tracking(Arc::new(ai_usage::NoOpUsageRecorder), journal.clone());
+ let caller = tokio::spawn(async move {
+ let request =
+ RequestContext::new("macro|[email protected]".to_owned().try_into().unwrap());
+ invoke_server_tool(
+ &context,
+ &request,
+ crate::types::request::WEB_SEARCH_TOOL.clone(),
+ "query",
+ )
+ .await
+ });
+ started_rx.await.unwrap();
+ // A live operation can already be older than the detached drain budget.
+ tokio::time::advance(Duration::from_secs(301)).await;
+ assert!(!caller.is_finished());
+ assert!(journal.finals.lock().unwrap().is_empty());
+ if cancel {
+ caller.abort();
+ let _ = caller.await;
+ tokio::task::yield_now().await;
+ tokio::time::advance(Duration::from_secs(299)).await;
+ assert!(journal.finals.lock().unwrap().is_empty());
+ tokio::time::advance(Duration::from_secs(2)).await;
+ for _ in 0..20 {
+ tokio::task::yield_now().await;
+ }
+ assert_eq!(
+ journal.finals.lock().unwrap()[0].usage,
+ UsageEvidence::Missing(UnresolvedReason::Interrupted)
+ );
+ } else {
+ release_tx.send(()).unwrap();
+ caller.await.unwrap().unwrap();
+ assert_eq!(
+ journal.finals.lock().unwrap()[0].usage,
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(10, 2, 0, 0, 0))
+ );
+ }
+ server.abort();
+ }
+}
+
+#[test]
+fn nullable_cache_counters_are_absent_but_malformed_usage_is_unresolved() {
+ use serde_json::json;
+ assert_eq!(
+ response_usage(&json!({"usage": {
+ "input_tokens": 10, "output_tokens": 2, "cache_creation": null,
+ "cache_read_input_tokens": null, "cache_creation_input_tokens": null
+ }})),
+ UsageEvidence::Reported(TrustedTokenUsage::from_disjoint(10, 2, 0, 0, 0))
+ );
+ for usage in [
+ json!({"input_tokens": 10, "output_tokens": null}),
+ json!({"input_tokens": 10, "output_tokens": 2, "cache_creation": 3}),
+ json!({"input_tokens": 10, "output_tokens": 2, "cache_read_input_tokens": -1}),
+ json!({"input_tokens": 10, "output_tokens": 2, "cache_creation_input_tokens": "3"}),
+ ] {
+ assert_eq!(
+ response_usage(&json!({"usage": usage})),
+ UsageEvidence::Missing(UnresolvedReason::UnsupportedDimensions)
+ );
+ }
+}
#[test]
fn deserialize_web_search_response() {
diff --git a/crates/anthropic/src/toolset/text_editor_code_execution.rs b/crates/anthropic/src/toolset/text_editor_code_execution.rs
index 1e910bba79..cd8aaea519 100644
--- a/crates/anthropic/src/toolset/text_editor_code_execution.rs
+++ b/crates/anthropic/src/toolset/text_editor_code_execution.rs
@@ -32,12 +32,12 @@ impl AsyncTool<AnthropicToolContext> for TextEditorCodeExecution {
async fn call(
&self,
service_context: ServiceContext<AnthropicToolContext>,
- _request_context: RequestContext,
+ request_context: RequestContext,
) -> ToolResult<Self::Output> {
let ctx = &*service_context;
let blocks = super::invoke_server_tool(
- &ctx.client,
- &ctx.model,
+ ctx,
+ &request_context,
CODE_EXECUTION_TOOL.clone(),
&self.input,
)
diff --git a/crates/anthropic/src/toolset/web_fetch.rs b/crates/anthropic/src/toolset/web_fetch.rs
index b120315c8b..de36ea9bdb 100644
--- a/crates/anthropic/src/toolset/web_fetch.rs
+++ b/crates/anthropic/src/toolset/web_fetch.rs
@@ -33,11 +33,11 @@ impl AsyncTool<AnthropicToolContext> for WebFetch {
async fn call(
&self,
service_context: ServiceContext<AnthropicToolContext>,
- _request_context: RequestContext,
+ request_context: RequestContext,
) -> ToolResult<Self::Output> {
let ctx = &*service_context;
let blocks =
- super::invoke_server_tool(&ctx.client, &ctx.model, WEB_FETCH_TOOL.clone(), &self.input)
+ super::invoke_server_tool(ctx, &request_context, WEB_FETCH_TOOL.clone(), &self.input)
.await?;
blocks
diff --git a/crates/anthropic/src/toolset/web_search.rs b/crates/anthropic/src/toolset/web_search.rs
index 252e62bd22..bc0cb46895 100644
--- a/crates/anthropic/src/toolset/web_search.rs
+++ b/crates/anthropic/src/toolset/web_search.rs
@@ -33,16 +33,12 @@ impl AsyncTool<AnthropicToolContext> for WebSearch {
async fn call(
&self,
service_context: ServiceContext<AnthropicToolContext>,
- _request_context: RequestContext,
+ request_context: RequestContext,
) -> ToolResult<Self::Output> {
let ctx = &*service_context;
- let blocks = super::invoke_server_tool(
- &ctx.client,
- &ctx.model,
- WEB_SEARCH_TOOL.clone(),
- &self.input,
- )
- .await?;
+ let blocks =
+ super::invoke_server_tool(ctx, &request_context, WEB_SEARCH_TOOL.clone(), &self.input)
+ .await?;
blocks
.into_iter()
diff --git a/crates/macro_db_client/migrations/20260928130346_ai_financial_usage.sql b/crates/macro_db_client/migrations/20260928130346_ai_financial_usage.sql
new file mode 100644
index 0000000000..3ff2caafcb
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260928130346_ai_financial_usage.sql
@@ -0,0 +1,80 @@
+-- Prospective financial evidence only. Never backfill from mutable ai_usage/ai_pricing.
+-- No user/entity FK: account deletion must not cascade away financial evidence.
+-- Retention: keep finalized evidence at least seven years and while any funding work,
+-- dispute, or legal hold is outstanding; keep unresolved work and referenced rates
+-- indefinitely. No automatic purge is enabled. A separately reviewed archival process
+-- must preserve replay identity before any future retention migration permits deletion.
+CREATE TABLE ai_financial_rate (
+ version UUID PRIMARY KEY,
+ provider TEXT NOT NULL,
+ model TEXT NOT NULL,
+ effective_at TIMESTAMPTZ NOT NULL,
+ valid_until TIMESTAMPTZ NOT NULL CHECK (valid_until > effective_at),
+ publication JSONB NOT NULL CHECK (jsonb_typeof(publication) = 'object'),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (provider, model, effective_at)
+);
+COMMENT ON TABLE ai_financial_rate IS
+ 'Append-only reviewed public rates and cache/reasoning provenance, never analytics pricing. No seeded or inferred rates.';
+
+CREATE TABLE ai_financial_invocation (
+ invocation_id UUID PRIMARY KEY,
+ rate_version UUID NOT NULL REFERENCES ai_financial_rate(version) ON DELETE RESTRICT,
+ occurred_at TIMESTAMPTZ NOT NULL,
+ request JSONB NOT NULL CHECK (jsonb_typeof(request) = 'object'),
+ funding JSONB CHECK (jsonb_typeof(funding) = 'object'),
+ finalization JSONB CHECK (jsonb_typeof(finalization) = 'object'),
+ recovery_required BOOLEAN NOT NULL DEFAULT true,
+ funding_acknowledged BOOLEAN NOT NULL DEFAULT false,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ finalized_at TIMESTAMPTZ,
+ CHECK (finalization IS NULL OR funding IS NOT NULL),
+ CHECK ((finalization IS NULL) = (finalized_at IS NULL)),
+ CHECK (NOT funding_acknowledged OR finalization IS NOT NULL),
+ CHECK (finalization IS NOT NULL OR recovery_required)
+);
+COMMENT ON TABLE ai_financial_invocation IS
+ 'Immutable typed request, disjoint token counts and valuation. No prompts, outputs, raw token text or credentials. No historical debt backfill.';
+
+-- Stable-ID bounded recovery scans, including crashes before authorization and after
+-- evidence commit but before the funding owner acknowledges the handoff.
+CREATE INDEX ai_financial_invocation_recovery_idx
+ ON ai_financial_invocation (invocation_id, occurred_at)
+ WHERE funding IS NOT NULL AND (recovery_required OR NOT funding_acknowledged);
+CREATE INDEX ai_financial_invocation_admission_idx
+ ON ai_financial_invocation (invocation_id, occurred_at) WHERE funding IS NULL;
+
+CREATE FUNCTION ai_financial_rate_immutable() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ RAISE EXCEPTION 'financial rate publications are immutable';
+END;
+$$;
+CREATE TRIGGER ai_financial_rate_immutable
+ BEFORE UPDATE OR DELETE ON ai_financial_rate
+ FOR EACH ROW EXECUTE FUNCTION ai_financial_rate_immutable();
+
+CREATE FUNCTION ai_financial_invocation_immutable() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ IF TG_OP = 'DELETE' THEN
+ RAISE EXCEPTION 'financial invocation retention requires explicit archival';
+ END IF;
+ IF NEW.invocation_id IS DISTINCT FROM OLD.invocation_id
+ OR NEW.rate_version IS DISTINCT FROM OLD.rate_version
+ OR NEW.occurred_at IS DISTINCT FROM OLD.occurred_at
+ OR NEW.request IS DISTINCT FROM OLD.request
+ OR NEW.created_at IS DISTINCT FROM OLD.created_at
+ OR (OLD.funding IS NOT NULL AND NEW.funding IS DISTINCT FROM OLD.funding)
+ OR (OLD.finalization IS NOT NULL AND
+ (NEW.finalization IS DISTINCT FROM OLD.finalization
+ OR NEW.finalized_at IS DISTINCT FROM OLD.finalized_at
+ OR NEW.recovery_required IS DISTINCT FROM OLD.recovery_required))
+ OR (OLD.funding_acknowledged AND NOT NEW.funding_acknowledged)
+ THEN
+ RAISE EXCEPTION 'financial invocation facts are immutable';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+CREATE TRIGGER ai_financial_invocation_immutable
+ BEFORE UPDATE OR DELETE ON ai_financial_invocation
+ FOR EACH ROW EXECUTE FUNCTION ai_financial_invocation_immutable();
diff --git a/crates/macro_db_client/migrations/20260928132202_ai_billing_usage_allocations.sql b/crates/macro_db_client/migrations/20260928132202_ai_billing_usage_allocations.sql
new file mode 100644
index 0000000000..de3491a2d8
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260928132202_ai_billing_usage_allocations.sql
@@ -0,0 +1,98 @@
+-- Additive, prospective accounting only. No historical usage or debt is backfilled.
+-- Financial records deliberately RESTRICT deletion: retention/redaction must be an
+-- explicit audited operation, never a cascade from membership or account deletion.
+ALTER TABLE ai_billing_account ADD COLUMN authorization_revision BIGINT NOT NULL DEFAULT 0;
+CREATE FUNCTION ai_billing_bump_authorization_revision() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ IF (NEW.overage_enabled, NEW.overage_limit_cents, NEW.overage_suspended_at)
+ IS DISTINCT FROM (OLD.overage_enabled, OLD.overage_limit_cents, OLD.overage_suspended_at) THEN
+ NEW.authorization_revision := OLD.authorization_revision + 1;
+ END IF;
+ RETURN NEW;
+END;
+$$;
+CREATE TRIGGER ai_billing_authorization_revision BEFORE UPDATE ON ai_billing_account
+FOR EACH ROW EXECUTE FUNCTION ai_billing_bump_authorization_revision();
+
+CREATE TABLE ai_billing_usage_period (
+ user_id TEXT NOT NULL,
+ period_start TIMESTAMPTZ NOT NULL,
+ period_end TIMESTAMPTZ NOT NULL CHECK (period_end > period_start),
+ payer_id TEXT NOT NULL REFERENCES ai_billing_account(user_id) ON DELETE RESTRICT,
+ subscription_id TEXT NOT NULL CHECK (length(subscription_id) > 0),
+ policy TEXT NOT NULL CHECK (policy IN ('legacy', 'public_allowance_v1')),
+ PRIMARY KEY (user_id, period_start)
+);
+CREATE INDEX ai_billing_usage_period_payer ON ai_billing_usage_period(payer_id, period_start);
+
+CREATE TABLE ai_funding_state (
+ user_id TEXT PRIMARY KEY REFERENCES ai_billing_account(user_id) ON DELETE RESTRICT,
+ next_sequence BIGINT NOT NULL DEFAULT 0 CHECK (next_sequence >= 0),
+ watermark BIGINT NOT NULL DEFAULT 0 CHECK (watermark BETWEEN 0 AND next_sequence),
+ -- Whole cents have already been debited from the existing ledger. This exact
+ -- remainder is still unavailable; it must not become spendable after a restart.
+ prepaid_remainder BIGINT NOT NULL DEFAULT 0 CHECK (prepaid_remainder >= 0 AND prepaid_remainder < 1000000000000)
+);
+
+-- An explicit funding rejection is terminal for this invocation identity. Retrying
+-- after a purchase/toggle requires a NEW provider attempt, never funding old history.
+-- Infrastructure failures roll back and remain safely retryable through the journal.
+CREATE TABLE ai_funding_intent (
+ invocation_id UUID PRIMARY KEY,
+ identity JSONB NOT NULL,
+ denied BOOLEAN NOT NULL DEFAULT FALSE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE TABLE ai_funding_reservation (
+ invocation_id UUID PRIMARY KEY REFERENCES ai_funding_intent(invocation_id) ON DELETE RESTRICT,
+ authorization_id UUID NOT NULL UNIQUE,
+ payer_id TEXT NOT NULL REFERENCES ai_funding_state(user_id) ON DELETE RESTRICT,
+ sequence BIGINT NOT NULL CHECK (sequence >= 0),
+ user_id TEXT NOT NULL,
+ period_start TIMESTAMPTZ NOT NULL,
+ -- Immutable original availability, settings, budget and request/rate identity.
+ admission JSONB NOT NULL,
+ included_hold BIGINT NOT NULL CHECK (included_hold >= 0),
+ prepaid_hold BIGINT NOT NULL CHECK (prepaid_hold >= 0),
+ postpaid_hold BIGINT NOT NULL CHECK (postpaid_hold >= 0),
+ -- Completion is a write-once handoff receipt. NULL actual is unresolved, NOT zero.
+ completion JSONB,
+ actual_public BIGINT CHECK (actual_public >= 0),
+ allocated BOOLEAN NOT NULL DEFAULT FALSE,
+ included_public BIGINT NOT NULL DEFAULT 0 CHECK (included_public >= 0),
+ extra_public BIGINT NOT NULL DEFAULT 0 CHECK (extra_public >= 0),
+ prepaid BIGINT NOT NULL DEFAULT 0 CHECK (prepaid >= 0),
+ reclaimed_prepaid BIGINT NOT NULL DEFAULT 0 CHECK (reclaimed_prepaid BETWEEN 0 AND prepaid),
+ postpaid BIGINT NOT NULL DEFAULT 0 CHECK (postpaid >= 0),
+ macro_absorbed BIGINT NOT NULL DEFAULT 0 CHECK (macro_absorbed >= 0),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (payer_id, sequence),
+ FOREIGN KEY (user_id, period_start) REFERENCES ai_billing_usage_period(user_id, period_start) ON DELETE RESTRICT,
+ CHECK (NOT allocated OR (completion IS NOT NULL AND actual_public IS NOT NULL)),
+ CHECK (NOT allocated OR actual_public = included_public + extra_public)
+);
+CREATE INDEX ai_funding_reservation_period ON ai_funding_reservation(payer_id, period_start);
+CREATE INDEX ai_funding_reservation_work ON ai_funding_reservation(invocation_id) WHERE NOT allocated;
+CREATE INDEX ai_funding_reservation_holds ON ai_funding_reservation(payer_id, sequence) WHERE NOT allocated;
+
+-- Released prepaid holds are kept unavailable to new admissions until all the
+-- admissions that could reclaim them have passed the allocation watermark.
+CREATE TABLE ai_funding_prepaid_release (
+ payer_id TEXT NOT NULL REFERENCES ai_funding_state(user_id) ON DELETE RESTRICT,
+ sequence BIGINT NOT NULL,
+ through_sequence BIGINT NOT NULL CHECK (through_sequence >= sequence),
+ units BIGINT NOT NULL CHECK (units > 0),
+ PRIMARY KEY (payer_id, sequence),
+ FOREIGN KEY (payer_id, sequence) REFERENCES ai_funding_reservation(payer_id, sequence) ON DELETE RESTRICT
+);
+
+-- Keep new consumption out of legacy aggregate coverage. Old writers retain
+-- their original semantics and defaults. The invocation key prevents duplicate debit.
+ALTER TABLE ai_credit_ledger ADD COLUMN funding_invocation_id UUID UNIQUE
+ REFERENCES ai_funding_reservation(invocation_id) ON DELETE RESTRICT;
+
+-- The collection worker must label invoices backed by V1 allocations. Those
+-- invoices must not also become legacy coverage or count twice against the cap.
+ALTER TABLE ai_overage_charge ADD COLUMN accounting_policy TEXT NOT NULL DEFAULT 'legacy'
+ CHECK (accounting_policy IN ('legacy', 'public_allowance_v1'));
diff --git a/crates/macro_db_client/migrations/20260928140027_ai_billing_verified_renewal.sql b/crates/macro_db_client/migrations/20260928140027_ai_billing_verified_renewal.sql
new file mode 100644
index 0000000000..5df110d02a
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260928140027_ai_billing_verified_renewal.sql
@@ -0,0 +1,31 @@
+-- Prospective activation facts only. Never backfill/reprice historical usage.
+-- These audit records deliberately have no membership/user cascade: departure
+-- and cancellation must not destroy the rollout baseline or financial attribution.
+CREATE TABLE ai_billing_usage_rollout (
+ policy TEXT PRIMARY KEY CHECK (policy = 'public_allowance_v1'),
+ configuration JSONB NOT NULL
+);
+
+CREATE TABLE ai_billing_usage_eligibility (
+ user_id TEXT NOT NULL,
+ subscription_id TEXT NOT NULL,
+ item_id TEXT NOT NULL,
+ identity JSONB NOT NULL,
+ state JSONB NOT NULL,
+ PRIMARY KEY (user_id, subscription_id, item_id)
+);
+
+CREATE TABLE ai_billing_usage_observation (
+ event_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ subscription_id TEXT NOT NULL,
+ item_id TEXT NOT NULL,
+ facts JSONB NOT NULL,
+ decision JSONB NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (event_id, user_id, subscription_id, item_id)
+);
+-- Operational review of quarantined bindings and replayed/delayed events.
+CREATE INDEX ai_billing_usage_observation_subscription
+ ON ai_billing_usage_observation (subscription_id, created_at);
+
diff --git a/crates/macro_db_client/migrations/20260928145631_ai_usage_observations.sql b/crates/macro_db_client/migrations/20260928145631_ai_usage_observations.sql
new file mode 100644
index 0000000000..0a871a9f1c
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260928145631_ai_usage_observations.sql
@@ -0,0 +1,20 @@
+-- Observational evidence is physically separate from authorized financial usage.
+-- No funding references, handoff work, credit mutations or collection triggers.
+CREATE TABLE ai_usage_observation (
+ invocation_id uuid PRIMARY KEY,
+ occurred_at timestamptz NOT NULL,
+ request jsonb NOT NULL,
+ finalization jsonb,
+ finalized_at timestamptz
+);
+
+-- Discover interrupted attempts without scanning completed observations.
+CREATE INDEX ai_usage_observation_pending_idx
+ ON ai_usage_observation (occurred_at, invocation_id)
+ WHERE finalization IS NULL;
+
+-- Attribution is retained independently of user deletion, like the financial
+-- journal. Retention/erasure is an explicit administrative operation, not a
+-- cascading financial mutation. No prompts, responses or credentials are stored.
+COMMENT ON TABLE ai_usage_observation IS
+ 'Nonfinancial per-attempt evidence; never a source of authorization or debt. Retain until explicit reviewed retention/erasure policy is applied.';
diff --git a/docs/AI_BILLING_ROLLOUT.md b/docs/AI_BILLING_ROLLOUT.md
new file mode 100644
index 0000000000..321f1241b0
--- /dev/null
+++ b/docs/AI_BILLING_ROLLOUT.md
@@ -0,0 +1,146 @@
+# AI usage tracking rollout
+
+## Current scope: observation, not billing activation
+
+T07 installs **observational per-provider-attempt tracking** for the Rust paths
+below. It does not activate the new allowance policy, authorization, credit holds,
+credit debits, postpaid liability, or collection. The existing $40 subscription,
+legacy analytics/settlement behavior, feature exclusions, and existing enforcement
+remain unchanged. Observations must never be replayed as financial authorizations
+or converted into historical customer debt.
+
+`UsageRecorder::tracking()` explicitly bridges the existing analytics injection to
+an object-safe `UsageTracking` capability. `agent::complete`, history/image and
+structured completions, and `AgentLoop` sessions bind immutable operation context;
+`MeteredHttpClient` records each actual HTTP execution, including SDK retries.
+Injection alone is **not** coverage: code bypassing those boundaries remains outside
+this accounting view. `rig_engine` explicitly carries task-local context into its
+spawned turn; each session still binds its trusted owner/feature independently.
+
+Composition roots use `ai_usage::pg_recorder`, which constructs the owning-domain
+observation service and adapter alongside the existing analytics service. DCS wraps
+its existing settling recorder with `with_tracking(..., pg_tracking(...))` instead
+of replacing its legacy behavior. The observation service accepts **no funding or
+rate-authorization capability**. No host selects `FinancialMode::Activated` here;
+its strict admission, budget validation, and error propagation remain intact.
+
+### Persistence and failure semantics
+
+Deploy migration `20260928145631_ai_usage_observations.sql` before these services.
+`ai_usage_observation` is physically separate from `ai_financial_invocation`, the
+analytics `ai_usage` table, and funding/collection work queues:
+
+- Begin is awaited before supported provider attempts. Final evidence is awaited
+ before returning the response to SDK/tool-result parsing. Delivery retries retain
+ identical invocation IDs, timestamps and evidence; new provider executions get
+ new IDs. Conflicting deliveries fail visibly rather than overwrite facts.
+- Request budgets, bodies and headers are unchanged in tracking-only mode. Missing
+ provider billing profiles, rates, balances and opt-in do not deny execution.
+- Reported disjoint token dimensions are **unpriced (`MissingRate`)**, not free or
+ exempt. This path intentionally does not consult mutable analytics rates or claim
+ that existing financial rate publications qualify all observed request regimes.
+ There is no observational pricing resolver to fail or deny requests. Reviewing
+ public rates/cache regimes and adding snapshot-based observational valuation is
+ follow-up work; no current/live provider rate verification is claimed.
+- Missing, interrupted, unsupported or inconsistent counters remain **unresolved**,
+ never zero. Anthropic thinking is included in output; OpenAI inclusive cache and
+ reasoning counts are normalized without double counting. Unknown dimensions,
+ one-hour cache regimes and compatible-provider zero sentinels are not guessed.
+- Storage failures are logged with the invocation ID and error. Begin and final
+ delivery are retried on finalization (three attempts); failure is not reported as
+ successful persistence and does not block later provider calls. There is no
+ durable delivery queue during a database outage: those losses require operational
+ follow-up. Pending rows identify process interruptions; they are not funding work.
+- Once an HTTP execution starts, provider/evidence exchange survives consumer
+ cancellation in an owned task, with a bounded 300-second drain starting only
+ when the caller future or stream receiver is dropped. Live requests and live
+ consumer streams have no metering-imposed deadline. A process exit
+ can still strand a pending observation; a failed begin can leave no row. Missing
+ terminal stream evidence is retained as interrupted, not inferred from provisional
+ counters. Evidence failures do not add a stream error in tracking-only mode.
+- No prompts, tool inputs, outputs, credentials or raw provider response bodies are
+ stored in the journal. Attribution is retained independently of user deletion;
+ reviewed retention/erasure and pending/unresolved operations tooling remain open.
+
+Analytics aggregates and per-attempt observations are **different accounting
+views**. Do not sum them together. Existing final-success aggregates still feed
+legacy analytics exactly as before; the observational journal never calls analytics
+`record` or the settlement trigger. Independent Anthropic tools add observations,
+not new legacy aggregate rows or separate tool fees.
+
+## Producer / host matrix
+
+“Journal” below means awaited, idempotent `ai_usage_observation` evidence, subject
+to the explicitly reported outage/process-exit limits above. Tests listed are local
+regressions, not live-provider or deployment verification.
+
+| Producer / host | Trusted attribution and injection site | Attempt vs aggregate coverage / evidence | Tests and remaining gaps |
+| --- | --- | --- | --- |
+| DCS chat, dynamic/structured completion, rename | Per-operation `UsageContext` from existing authenticated handlers; `services/document_cognition_service/src/main.rs` wraps its settling recorder | Rig HTTP attempts → journal, including failed parsing/retries; legacy final aggregates unchanged | `agent` metering/structured tests, DCS package tests; billing activation off |
+| Subagent in any common-context host | `crates/ai_tools/src/subagent.rs` replaces shared-context user with `RequestContext.user_id`, retains parent feature/entity | `agent::complete` binds a fresh or matching inherited scope → journal; no shared mutable user | `ai_tools` subagent isolation; `agent` scope/independent recorder tests. Shared system identity is not an authenticated payer |
+| MCP native Anthropic tools and subagent | `AuthenticatedToolService` builds `RequestContext` from authenticated HTTP extensions; `services/mcp_service/src/context.rs` injects `pg_recorder`; `ToolServiceContext::FromRef` supplies inherited feature/entity and recorder | Independent Anthropic HTTP attempts and subagent attempts → journal, not merely successful tool aggregates; default feature remains Chat | Anthropic authenticated attribution/malformed-result/failure tests; MCP auth tests. MCP client's own model and remote MCP servers are not covered |
+| Anthropic WebSearch, WebFetch, BashCodeExecution, TextEditorCodeExecution in all common hosts | Manual per-operation `FromRef<ToolServiceContext>` copies recorder + feature/entity; tool call always uses authenticated `RequestContext.user_id` | One journal attempt per independent native Messages HTTP execution. Counters recorded before SDK/result parsing, including non-2xx evidence; cancellation retains execution/evidence task. No separate tool fees | `anthropic --features toolset` tests. Native client has no application retry loop; any future retries must create fresh attempt IDs. Server-tool-specific non-token fees are intentionally not priced |
+| In-memory harness sessions | `services/agent_harness_service/src/main.rs` common context → `RigTurnEngine`; trusted `TurnRequest.owner`, AgentSession feature | Captured scope carried into spawned turn; AgentLoop binds immutable owner scope; Rig attempts → journal, final analytics retained | `agent` spawned scope/cancellation tests; `agent_inmem` package tests. Non-user owners remain rejected by existing behavior |
+| Harness session naming | Independent `pg_recorder` supplied to `HaikuAgentSessionNameGenerator` in harness `main.rs`; session owner, ChatRename feature/entity | One-shot model attempts → journal (feature classification unchanged) | Existing name-generator/host tests plus shared completion tests; not covered merely by common-context injection |
+| Harness repository selection | Independent `pg_recorder` passed to `CursorContainerManager` in harness `main.rs`; repository chooser's trusted owner, AgentRepositoryChoice feature | Rust selection completion attempts → journal | Shared completion tests and host tests. Does not cover Cursor's external agent runtime |
+| Harness trigger classifier + image captions | Independent recorder in `services/agent_harness_service/src/trigger.rs` passed to `FastModelTriggerJudge` and `VisionImageCaptioner`; authenticated message sender, Automation feature | Structured/image HTTP attempts → journal before existing errors are handled | `agent_trigger` caption tests + `agent` image-budget/cancellation/evidence tests. Non-user fallback remains system/internal, never an authenticated payer |
+| Standalone trigger classifier + captions | Same explicit injection in `services/agent_trigger_service/src/main.rs` | Same journal attempt boundary, separate from harness and DCS | Standalone service and shared trigger tests. Caption timeout/error-to-None behavior retained; funding-denial propagation deferred |
+| DSS channel responder | `services/document_storage_service/src/main.rs` builds common context; responder binds requesting user, ChannelBot feature | AgentLoop HTTP attempts, native tools and subagents → journal; legacy aggregate retained | Shared agent/tool tests, DSS package tests |
+| DSS channel classifier | Separate `pg_recorder` supplied to `FastModelTriggerClassifier` in DSS `main.rs`; requesting user, ChannelBot | One-shot classification attempts → journal | Shared completion/structured tests. This is distinct from the responder's common context |
+| DSS call summarizer, import duplicate judges | Independent `pg_recorder` injections already present in DSS `main.rs`; existing user/feature supplied by each producer | Calls using shared Rust completion APIs now produce journal attempts | Shared agent tests and DSS tests; this change does not change their attribution policy |
+| Scheduled actions | `services/scheduled_action/src/bins/service.rs` common context; executor binds stored authenticated owner, Automation feature | AgentLoop attempts + native tools/subagents → journal | Scheduled-action package and shared scope tests; remote execution outside this process remains separate |
+| DCS imports | DCS `main.rs` passes wrapped recorder to import service; import `drive_session` binds user, Import feature | Rust gather/Notion AgentLoop attempts → journal | Shared agent tests / DCS tests. Remote connector internals are not local model attempts |
+| Memory and AI projections | Common host recorder (DCS; memory's own context also uses `pg_recorder`), with existing user-specific Memory / AiProjection contexts | Shared completion/AgentLoop attempts → journal, including native tool subcalls where available | Shared agent/tool regressions; no claim of new end-to-end producer deployment tests |
+| Managed harness sandboxes (local/Daytona), external Cursor/Codex/Claude agents | Harness passes provider credentials / external account credentials directly to the runtime | **Not covered** by Rust common-context injection; runtime model calls bypass this HTTP adapter. Rust session naming/selection and calls back to authenticated MCP are the only covered portions | Future runtime-owned producer instrumentation must emit trusted per-attempt provider/model/counter/response IDs and immutable authenticated session attribution to an idempotent journal ingress. No credential/proxy redesign or enforcement is introduced here |
+| AI editing worker, dictation/audio, arbitrary raw-provider callers, remote MCP internals | Separate producer ownership; multipart requests explicitly warn when scoped but unsupported | **Not covered by this token-attempt adapter.** Existing aggregate/audio behavior is not per-attempt evidence | Separate worker/audio integrations and trusted ingress required. Do not enable new-policy charging for these paths based on this matrix |
+
+## Verification and future activation gates
+
+Focused regressions cover immutable concurrent-user scopes, inherited/independent
+recorders, spawned scope propagation, exact request-budget preservation without
+funding capability or support profiles, recorder failures, retry delivery identity,
+partial failures, cancellations, excluded feature classification, missing usage and
+duplicate delivery. Financial-mode regression tests remain in place. Database tests
+prove observations do not enter the financial journal or analytics accounting.
+
+Run affected package tests with `SQLX_OFFLINE` unset; regenerate SQLx metadata from
+the repository root. Record actual commands/results in the task handoff. No hosted
+mutations, provider calls, Stripe provisioning, flag activation, or UI changes are
+part of this rollout.
+
+### Observation deployment gate: identity lifecycle
+
+The current journal stores user and entity identity in `request` JSONB, without a
+user foreign key or deletion hook (`20260928145631_ai_usage_observations.sql`).
+Deleting an account does not remove that attribution. No retention/erasure worker
+or administrative erasure operation is supplied by this change. This is a current
+privacy lifecycle gap, not something made safe by leaving billing disabled.
+
+Before deploying this observational wiring to real-user traffic, the data owner
+must approve retention and erasure handling (including already-deleted users),
+identify the operator responsible, and verify an executable process against the
+observation table. Until that gate is satisfied, do not deploy the wiring to
+real-user environments. Do not infer a retention duration here, reuse financial
+retention requirements for observations, or cascade-delete financial history.
+Schema/application merge and test-environment verification are not evidence that
+this deployment gate has passed.
+
+Before a future **billing/enforcement** release, separately review/implement:
+
+1. Verified rates, request-regime support, authenticated payer/seat resolution,
+ renewal policy activation, and the existing financial admission contract.
+2. Coverage or explicit activation blocks for external runtimes, workers, audio,
+ remote producers, unsupported dimensions and unresolved evidence. This document
+ is not proof of total production coverage.
+3. Crash/outage recovery and retention operations; trusted runtime/worker evidence
+ ingress; financial-mode cancellation and funding-denial propagation.
+4. Credit-first allocation, opt-in/caps, collection idempotency and rollout gates.
+ Tracking-only observations are never retroactive funding authorization.
+5. An authorized, auditable resolution/release transition for unresolved financial
+ attempts. `FinancialUsage::pending` and funding scans only discover work;
+ reconciliation stops at missing actual usage, and conflicting finalization
+ replays cannot overwrite immutable evidence. Before enabling admission, test
+ operator authorization, retained original evidence, idempotent resolution and
+ recovery of payer ordering/holds. Never treat missing evidence as zero or
+ release a hold merely because a request timed out. This gap may remain deferred
+ only while financial admission and policy activation remain unwired.
diff --git a/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs b/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs
index 20f60284a4..aa2ab9a3f1 100644
--- a/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs
+++ b/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs
@@ -5,9 +5,7 @@ use crate::api::context::ApiContext;
use crate::api::user::stripe::PaidPlan;
use ai_billing::BillingService;
-use ai_billing::outbound::stripe_gateway::{
- PAYER_METADATA_KEY, PURPOSE_AI_CREDITS, PURPOSE_AI_OVERAGE, PURPOSE_METADATA_KEY,
-};
+use ai_billing::outbound::stripe_gateway::{PURPOSE_AI_OVERAGE, PURPOSE_METADATA_KEY};
use analytics_client::{AnalyticsClient, MetaActionSource, MetaUserData};
use anyhow::Context;
use axum::{
@@ -16,7 +14,6 @@ use axum::{
http::{HeaderMap, StatusCode},
response::{IntoResponse, Json, Response},
};
-use chrono::{DateTime, Utc};
use gtm_invite::domain::ports::GtmInviteService;
use macro_user_id::email::Email;
use macro_user_id::user_id::MacroUserIdStr;
@@ -33,8 +30,13 @@ use stripe_webhook::{EventObject, EventType};
use teams::domain::team_repo::TeamService;
use tracing::Instrument;
+mod billing;
#[cfg(test)]
mod test;
+use billing::{
+ BillingEvent, TeamPlanSync, handle_checkout_session_completed, period_from_timestamps,
+ subscription_periods, sync_personal_billing_period, sync_team_billing_period,
+};
/// Extracts the previous status from the previous_attributes JSON value.
fn extract_previous_status(previous_attributes: &Option<JsonValue>) -> Option<String> {
@@ -158,6 +160,10 @@ pub async fn handler(
"processing stripe event"
);
+ let billing_event = BillingEvent::from_verified_payload(payload).map_err(|error| {
+ tracing::error!(?error, "invalid verified billing event");
+ (StatusCode::BAD_REQUEST, "invalid billing event").into_response()
+ })?;
let event_type = event.type_.clone();
let previous_attributes = event.data.previous_attributes.clone();
match event.type_ {
@@ -170,12 +176,15 @@ pub async fn handler(
event.data.object,
event_type,
previous_attributes,
+ &billing_event,
)
.await
}
EventType::InvoicePaymentFailed
| EventType::InvoicePaymentSucceeded
- | EventType::InvoicePaid => handle_payment_event(&ctx, event.data.object, event_type).await,
+ | EventType::InvoicePaid => {
+ handle_payment_event(&ctx, event.data.object, event_type, &billing_event).await
+ }
// A credit pack paid with a delayed method (bank debit, etc.) completes
// its session unpaid and reports the money later; both events book
// through the same idempotent path.
@@ -195,11 +204,12 @@ pub async fn handler(
Ok(StatusCode::OK.into_response())
}
-#[tracing::instrument(skip(ctx, event_object), err, ret)]
+#[tracing::instrument(skip(ctx, event_object, billing_event), err, ret)]
async fn handle_payment_event(
ctx: &ApiContext,
event_object: EventObject,
event_type: EventType,
+ billing_event: &BillingEvent,
) -> anyhow::Result<()> {
let invoice = match event_object {
EventObject::InvoicePaymentFailed(invoice) => invoice,
@@ -320,6 +330,11 @@ async fn handle_payment_event(
subscription.current_period_start,
subscription.current_period_end,
);
+ let verified = subscription_periods(
+ billing_event,
+ &serde_json::to_value(&subscription)?,
+ Some(&billing_event.object),
+ );
if let Some(team_id) = subscription.metadata.get("team_id") {
let team_id = macro_uuid::string_to_uuid(team_id)?;
@@ -333,7 +348,11 @@ async fn handle_payment_event(
subscription_status,
&team_id,
&email,
- TeamPlanSync { owner, period },
+ TeamPlanSync {
+ owner,
+ period,
+ verified,
+ },
SubscriptionTrackingData {
ga_client_id: ga_client_id.clone(),
fbp: fbp.clone(),
@@ -384,123 +403,18 @@ async fn handle_payment_event(
.unwrap_or(ProductTier::Opus),
)
.await?;
- sync_personal_billing_period(ctx, &email, period).await?;
+ sync_personal_billing_period(ctx, &email, period, verified).await?;
Ok(())
}
-/// The period a subscription is currently in, from Stripe's unix timestamps.
-fn period_from_timestamps(start: i64, end: i64) -> Option<(DateTime<Utc>, DateTime<Utc>)> {
- DateTime::from_timestamp(start, 0).zip(DateTime::from_timestamp(end, 0))
-}
-
-/// Anchor a personal subscriber's AI allowance to their Stripe period.
-///
-/// A storage failure fails the webhook so Stripe redelivers it: until the
-/// anchor lands the allowance is metered against the calendar month, which
-/// is the wrong window for anyone who did not subscribe on the 1st. Every
-/// step of the handler before this is idempotent, so the retry is safe. An
-/// email that cannot become a user id is not transient and is only logged.
-async fn sync_personal_billing_period(
- ctx: &ApiContext,
- email: &Email<Lowercase<'_>>,
- period: Option<(DateTime<Utc>, DateTime<Utc>)>,
-) -> anyhow::Result<()> {
- let Some((start, end)) = period else {
- return Ok(());
- };
- let Ok(user_id) = MacroUserIdStr::try_from_email(email.as_ref()) else {
- tracing::warn!("could not derive a macro user id for billing period sync");
- return Ok(());
- };
- ctx.ai_billing_service
- .sync_period(&user_id, start, end)
- .await
- .context("failed to sync ai billing period")
-}
-
-/// What a team subscription event tells us about the team's billing period.
-///
-/// Seat plans are per member (recorded on the membership and re-stamped as
-/// roles by the teams service), so the subscription's prices say nothing the
-/// team does not already know; only the period anchor is taken from Stripe.
-#[derive(Debug, Clone)]
-struct TeamPlanSync {
- /// The team owner (the payer), from subscription metadata.
- owner: Option<MacroUserIdStr<'static>>,
- /// The subscription's current period.
- period: Option<(DateTime<Utc>, DateTime<Utc>)>,
-}
-
-/// Anchor the team's per-seat AI allowances to the subscription's period. As
-/// with [`sync_personal_billing_period`], a storage failure fails the webhook
-/// so Stripe redelivers it; a subscription with no `owner_id` metadata is
-/// not transient and is only logged.
-async fn sync_team_billing_period(ctx: &ApiContext, sync: &TeamPlanSync) -> anyhow::Result<()> {
- let Some(owner) = sync.owner.as_ref() else {
- tracing::warn!("team subscription without owner_id metadata; skipping period sync");
- return Ok(());
- };
- let Some((start, end)) = sync.period else {
- return Ok(());
- };
- ctx.ai_billing_service
- .sync_period(owner, start, end)
- .await
- .context("failed to sync team billing period")
-}
-
-/// Book a paid credit-pack purchase, from `checkout.session.completed` or,
-/// for delayed payment methods, `checkout.session.async_payment_succeeded`.
-/// Subscription checkouts also arrive here and are ignored; the subscription
-/// events carry those. Idempotent on the session id.
-#[tracing::instrument(skip(ctx, event_object), err, ret)]
-async fn handle_checkout_session_completed(
- ctx: &ApiContext,
- event_object: EventObject,
-) -> anyhow::Result<()> {
- let session = match event_object {
- EventObject::CheckoutSessionCompleted(session)
- | EventObject::CheckoutSessionAsyncPaymentSucceeded(session) => session,
- _ => anyhow::bail!("expected checkout session"),
- };
- let metadata = session.metadata.clone().unwrap_or_default();
- if metadata.get(PURPOSE_METADATA_KEY).map(String::as_str) != Some(PURPOSE_AI_CREDITS) {
- tracing::info!(session_id = %session.id, "checkout session is not a credit purchase");
- return Ok(());
- }
- if session.payment_status.as_str() != "paid" {
- tracing::info!(
- session_id = %session.id,
- payment_status = ?session.payment_status,
- "credit purchase not paid yet; waiting for checkout.session.async_payment_succeeded"
- );
- return Ok(());
- }
- let payer = metadata
- .get(PAYER_METADATA_KEY)
- .cloned()
- .context("credit checkout session is missing the payer")?;
- let payer = MacroUserIdStr::try_from(payer).context("invalid payer id on checkout session")?;
- let amount_cents = session
- .amount_total
- .or_else(|| metadata.get("amount_cents").and_then(|a| a.parse().ok()))
- .context("credit checkout session has no amount")?;
-
- ctx.ai_billing_service
- .apply_credit_purchase(&payer, amount_cents, session.id.as_str())
- .await
- .context("failed to book credit purchase")?;
- tracing::info!(payer = %payer, amount_cents, "booked ai credit purchase");
- Ok(())
-}
-
-#[tracing::instrument(skip(ctx, event_object, previous_attributes), err, ret)]
+#[tracing::instrument(skip(ctx, event_object, previous_attributes, billing_event), err, ret)]
async fn handle_customer_subscription_event(
ctx: &ApiContext,
event_object: EventObject,
event_type: EventType,
previous_attributes: Option<JsonValue>,
+ billing_event: &BillingEvent,
) -> anyhow::Result<()> {
let subscription = match event_object {
EventObject::CustomerSubscriptionCreated(subscription) => subscription,
@@ -636,6 +550,7 @@ async fn handle_customer_subscription_event(
let period = subscription.items.data.first().and_then(|item| {
period_from_timestamps(item.current_period_start, item.current_period_end)
});
+ let verified = subscription_periods(billing_event, &billing_event.object, None);
// Get subscription metadata, if this is a team subscription then we need to handle it
// separately.
@@ -652,7 +567,11 @@ async fn handle_customer_subscription_event(
subscription_status,
&team_id,
&email,
- TeamPlanSync { owner, period },
+ TeamPlanSync {
+ owner,
+ period,
+ verified,
+ },
SubscriptionTrackingData {
ga_client_id: ga_client_id.clone(),
fbp: fbp.clone(),
@@ -763,7 +682,7 @@ async fn handle_customer_subscription_event(
product_tier,
)
.await?;
- sync_personal_billing_period(ctx, &email, period).await?;
+ sync_personal_billing_period(ctx, &email, period, verified).await?;
// Track conversion events to GA and Meta (fire-and-forget)
let subscription_id = stripe::SubscriptionId::from_str(subscription_id).unwrap();
@@ -864,54 +783,61 @@ async fn handle_team_subscription_event<'a>(
macro_db_client::user::patch::update_macro_user_has_trialed(&ctx.db, email, true).await?;
}
- let subscription_id = stripe::SubscriptionId::from_str(subscription_id).unwrap();
- ctx.teams_service
- .patch_team_subscription_id(team_id, &subscription_id)
- .await?;
-
- match subscription_status {
- "active" | "trialing" => {
- // Restore stamps every member (owner included) with the team
- // subscriber role and the tier role of their own seat's plan.
- ctx.teams_service
- .restore_permissions_for_team_members(team_id)
- .await?;
- sync_team_billing_period(ctx, &plan_sync).await?;
-
- ctx.teams_service
- .patch_team_payment_status(team_id, true)
- .await?;
-
- track_stripe_subscription(
- ctx.analytics_client.clone(),
- &subscription_id,
- tracking_data,
- );
- Ok(())
- }
- "canceled" | "incomplete" | "incomplete_expired" | "past_due" | "paused" | "unpaid" => {
+ billing::complete_subscription_webhook(
+ billing::sync_team_usage_policy(ctx, &plan_sync),
+ async {
+ let subscription_id = stripe::SubscriptionId::from_str(subscription_id).unwrap();
ctx.teams_service
- .revoke_permissions_for_team_members(team_id)
- .await?;
- sync_team_billing_period(ctx, &plan_sync).await?;
- ctx.teams_service
- .patch_team_payment_status(team_id, false)
+ .patch_team_subscription_id(team_id, &subscription_id)
.await?;
- track_stripe_subscription(
- ctx.analytics_client.clone(),
- &subscription_id,
- SubscriptionTrackingData {
- is_new: false,
- ..tracking_data
- },
- );
- Ok(())
- }
- _ => {
- anyhow::bail!("unexpected subscription status for team subscription");
- }
- }
+ match subscription_status {
+ "active" | "trialing" => {
+ // Restore stamps every member (owner included) with the team
+ // subscriber role and the tier role of their own seat's plan.
+ ctx.teams_service
+ .restore_permissions_for_team_members(team_id)
+ .await?;
+ sync_team_billing_period(ctx, &plan_sync).await?;
+
+ ctx.teams_service
+ .patch_team_payment_status(team_id, true)
+ .await?;
+
+ track_stripe_subscription(
+ ctx.analytics_client.clone(),
+ &subscription_id,
+ tracking_data,
+ );
+ Ok(())
+ }
+ "canceled" | "incomplete" | "incomplete_expired" | "past_due" | "paused"
+ | "unpaid" => {
+ ctx.teams_service
+ .revoke_permissions_for_team_members(team_id)
+ .await?;
+ sync_team_billing_period(ctx, &plan_sync).await?;
+ ctx.teams_service
+ .patch_team_payment_status(team_id, false)
+ .await?;
+
+ track_stripe_subscription(
+ ctx.analytics_client.clone(),
+ &subscription_id,
+ SubscriptionTrackingData {
+ is_new: false,
+ ..tracking_data
+ },
+ );
+ Ok(())
+ }
+ _ => {
+ anyhow::bail!("unexpected subscription status for team subscription");
+ }
+ }
+ },
+ )
+ .await
}
#[derive(Debug, Clone, Serialize)]
diff --git a/services/authentication_service/src/api/webhooks/user/stripe_webhook/billing.rs b/services/authentication_service/src/api/webhooks/user/stripe_webhook/billing.rs
new file mode 100644
index 0000000000..1c87acd274
--- /dev/null
+++ b/services/authentication_service/src/api/webhooks/user/stripe_webhook/billing.rs
@@ -0,0 +1,296 @@
+//! Billing-only Stripe translation. The dispatcher and base subscription handlers
+//! stay in the parent module; activation policy lives in ai_billing's domain.
+
+use ai_billing::BillingService;
+use ai_billing::domain::BillingPeriod;
+use ai_billing::domain::period::{PeriodEvidence, SubscriptionActivity, SubscriptionPeriod};
+use ai_billing::outbound::stripe_gateway::{
+ PAYER_METADATA_KEY, PURPOSE_AI_CREDITS, PURPOSE_METADATA_KEY,
+};
+use anyhow::Context;
+use chrono::{DateTime, Utc};
+use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};
+use serde_json::Value;
+use stripe_webhook::EventObject;
+
+use crate::api::context::ApiContext;
+
+#[cfg(test)]
+mod test;
+
+/// Retain occurrence time and raw versioned period fields only after signature
+/// verification. Delivery time cannot establish rollout eligibility.
+pub(super) struct BillingEvent {
+ pub id: String,
+ pub at: DateTime<Utc>,
+ pub object: Value,
+}
+
+impl BillingEvent {
+ pub fn from_verified_payload(payload: &str) -> anyhow::Result<Self> {
+ let event: Value = serde_json::from_str(payload)?;
+ Ok(Self {
+ id: event["id"]
+ .as_str()
+ .context("missing verified event id")?
+ .to_owned(),
+ at: timestamp(&event["created"]).context("invalid verified event time")?,
+ object: event["data"]["object"].clone(),
+ })
+ }
+}
+
+fn timestamp(value: &Value) -> Option<DateTime<Utc>> {
+ DateTime::from_timestamp(value.as_i64()?, 0)
+}
+
+pub(super) fn period_from_timestamps(
+ start: i64,
+ end: i64,
+) -> Option<(DateTime<Utc>, DateTime<Utc>)> {
+ if start >= end {
+ return None;
+ }
+ DateTime::from_timestamp(start, 0).zip(DateTime::from_timestamp(end, 0))
+}
+
+fn object_id(value: &Value) -> Option<&str> {
+ value.as_str().or_else(|| value["id"].as_str())
+}
+
+fn period(subscription: &Value, item: &Value) -> Option<BillingPeriod> {
+ // If an item supplies either boundary, require both. Never mix versions or
+ // synthesize a monthly end for an incomplete/custom interval.
+ let source =
+ if item.get("current_period_start").is_some() || item.get("current_period_end").is_some() {
+ item
+ } else {
+ subscription
+ };
+ let (start, end) = period_from_timestamps(
+ source["current_period_start"].as_i64()?,
+ source["current_period_end"].as_i64()?,
+ )?;
+ Some(BillingPeriod { start, end })
+}
+
+fn invoice_evidence(
+ invoice: &Value,
+ subscription: &Value,
+ item: &Value,
+ period: BillingPeriod,
+) -> PeriodEvidence {
+ let subscription_id = object_id(&subscription["id"]);
+ let invoice_subscription = object_id(&invoice["subscription"])
+ .or_else(|| object_id(&invoice["parent"]["subscription_details"]["subscription"]));
+ if subscription_id.is_none()
+ || invoice_subscription != subscription_id
+ || object_id(&invoice["customer"]) != object_id(&subscription["customer"])
+ || invoice["status"].as_str() != Some("paid")
+ || invoice["lines"]["has_more"].as_bool() != Some(false)
+ {
+ return PeriodEvidence::Snapshot;
+ }
+ let evidence = match invoice["billing_reason"].as_str() {
+ Some("subscription_create") => PeriodEvidence::Initial,
+ Some("subscription_cycle") => PeriodEvidence::Renewal,
+ _ => return PeriodEvidence::Snapshot,
+ };
+ let Some(lines) = invoice["lines"]["data"].as_array() else {
+ return PeriodEvidence::Snapshot;
+ };
+ let matches = lines
+ .iter()
+ .filter(|line| {
+ let details = &line["parent"]["subscription_item_details"];
+ let item_id = object_id(&line["subscription_item"])
+ .or_else(|| object_id(&details["subscription_item"]));
+ let price_id = object_id(&line["price"])
+ .or_else(|| object_id(&line["pricing"]["price_details"]["price"]));
+ item_id == object_id(&item["id"])
+ && price_id == object_id(&item["price"])
+ && line["proration"]
+ .as_bool()
+ .or_else(|| details["proration"].as_bool())
+ == Some(false)
+ && timestamp(&line["period"]["start"]) == Some(period.start)
+ && timestamp(&line["period"]["end"]) == Some(period.end)
+ })
+ .count();
+ if matches == 1 {
+ evidence
+ } else {
+ PeriodEvidence::Snapshot
+ }
+}
+
+/// Translate complete verified subscription/item/price facts. Unknown fields or
+/// missing boundaries remain activation exceptions, never calendar fallbacks.
+pub(super) fn subscription_periods(
+ event: &BillingEvent,
+ subscription: &Value,
+ invoice: Option<&Value>,
+) -> Vec<SubscriptionPeriod> {
+ if subscription["items"]["has_more"].as_bool() != Some(false) {
+ return vec![];
+ }
+ let Some(items) = subscription["items"]["data"].as_array() else {
+ return vec![];
+ };
+ items
+ .iter()
+ .filter_map(|item| {
+ let Some(period) = period(subscription, item) else {
+ tracing::warn!(subscription_id = ?object_id(&subscription["id"]), item_id = ?object_id(&item["id"]), "usage policy activation exception: missing or invalid period anchors");
+ return None;
+ };
+ let price = &item["price"];
+ let team_id = match subscription["metadata"].get("team_id") {
+ Some(value) => Some(value.as_str()?.parse().ok()?),
+ None => None,
+ };
+ Some(SubscriptionPeriod {
+ event_id: event.id.parse().ok()?,
+ event_at: event.at,
+ subscription_id: object_id(&subscription["id"])?.parse().ok()?,
+ subscription_created_at: timestamp(&subscription["created"])?,
+ customer_id: object_id(&subscription["customer"])?.parse().ok()?,
+ team_id,
+ quantity: item["quantity"].as_u64()?,
+ item_count: items.len(),
+ item_id: object_id(&item["id"])?.parse().ok()?,
+ price_id: object_id(price)?.parse().ok()?,
+ product_id: object_id(&price["product"])?.parse().ok()?,
+ unit_amount: price["unit_amount"].as_i64(),
+ currency: price["currency"].as_str()?.to_owned(),
+ monthly: price["type"].as_str() == Some("recurring")
+ && price["recurring"]["interval"].as_str() == Some("month")
+ && price["recurring"]["interval_count"].as_u64() == Some(1),
+ activity: match subscription["status"].as_str() {
+ Some("active") => SubscriptionActivity::Active,
+ Some("trialing") => SubscriptionActivity::Trialing,
+ _ => SubscriptionActivity::Inactive,
+ },
+ period,
+ evidence: invoice
+ .map(|invoice| invoice_evidence(invoice, subscription, item, period))
+ .unwrap_or(PeriodEvidence::Snapshot),
+ })
+ })
+ .collect()
+}
+
+pub(super) async fn sync_personal_billing_period(
+ ctx: &ApiContext,
+ email: &Email<Lowercase<'_>>,
+ period: Option<(DateTime<Utc>, DateTime<Utc>)>,
+ verified: Vec<SubscriptionPeriod>,
+) -> anyhow::Result<()> {
+ let Ok(user_id) = MacroUserIdStr::try_from_email(email.as_ref()) else {
+ tracing::warn!("could not derive a candidate for billing period sync");
+ return Ok(());
+ };
+ sync_periods(ctx, &user_id, period, verified).await
+}
+
+#[derive(Debug, Clone)]
+pub(super) struct TeamPlanSync {
+ pub owner: Option<MacroUserIdStr<'static>>,
+ pub period: Option<(DateTime<Utc>, DateTime<Utc>)>,
+ pub verified: Vec<SubscriptionPeriod>,
+}
+
+pub(super) async fn sync_team_billing_period(
+ ctx: &ApiContext,
+ sync: &TeamPlanSync,
+) -> anyhow::Result<()> {
+ let Some(owner) = sync.owner.as_ref() else {
+ tracing::warn!("team subscription without owner candidate; skipping period sync");
+ return Ok(());
+ };
+ sync_periods(ctx, owner, sync.period, Vec::new()).await
+}
+
+/// Check the owning team's existing subscription binding before the base handler
+/// patches it. Otherwise that write would make the identity check tautological.
+pub(super) async fn sync_team_usage_policy(
+ ctx: &ApiContext,
+ sync: &TeamPlanSync,
+) -> anyhow::Result<()> {
+ let Some(owner) = sync.owner.as_ref() else {
+ return Ok(());
+ };
+ sync_periods(ctx, owner, None, sync.verified.clone()).await
+}
+
+/// Preserve the pre-update identity check without letting its failure skip base
+/// subscription work. Still fail the webhook afterwards so Stripe retries policy
+/// persistence; acknowledging the event here would lose that retry.
+pub(super) async fn complete_subscription_webhook(
+ policy: impl Future<Output = anyhow::Result<()>>,
+ subscription: impl Future<Output = anyhow::Result<()>>,
+) -> anyhow::Result<()> {
+ let policy_result = policy.await.inspect_err(|error| {
+ tracing::warn!(error = ?error, "usage policy sync failed; completing base subscription work before retry");
+ });
+ subscription.await?;
+ policy_result
+}
+
+async fn sync_periods(
+ ctx: &ApiContext,
+ payer: &MacroUserIdStr<'_>,
+ period: Option<(DateTime<Utc>, DateTime<Utc>)>,
+ verified: Vec<SubscriptionPeriod>,
+) -> anyhow::Result<()> {
+ if let Some((start, end)) = period {
+ ctx.ai_billing_service
+ .sync_period(payer, start, end, None)
+ .await
+ .context("failed to sync legacy billing anchor")?;
+ }
+ for facts in verified {
+ ctx.ai_billing_service
+ .sync_period(payer, facts.period.start, facts.period.end, Some(facts))
+ .await
+ .context("failed to sync verified usage policy period")?;
+ }
+ Ok(())
+}
+
+/// Credit checkout behavior is unchanged; T10 extends this single handler.
+#[tracing::instrument(skip(ctx, event_object), err, ret)]
+pub(super) async fn handle_checkout_session_completed(
+ ctx: &ApiContext,
+ event_object: EventObject,
+) -> anyhow::Result<()> {
+ let session = match event_object {
+ EventObject::CheckoutSessionCompleted(session)
+ | EventObject::CheckoutSessionAsyncPaymentSucceeded(session) => session,
+ _ => anyhow::bail!("expected checkout session"),
+ };
+ let metadata = session.metadata.clone().unwrap_or_default();
+ if metadata.get(PURPOSE_METADATA_KEY).map(String::as_str) != Some(PURPOSE_AI_CREDITS) {
+ tracing::info!(session_id = %session.id, "checkout session is not a credit purchase");
+ return Ok(());
+ }
+ if session.payment_status.as_str() != "paid" {
+ tracing::info!(session_id = %session.id, payment_status = ?session.payment_status, "credit purchase not paid yet; waiting for checkout.session.async_payment_succeeded");
+ return Ok(());
+ }
+ let payer = metadata
+ .get(PAYER_METADATA_KEY)
+ .cloned()
+ .context("credit checkout session is missing the payer")?;
+ let payer = MacroUserIdStr::try_from(payer).context("invalid payer id on checkout session")?;
+ let amount_cents = session
+ .amount_total
+ .or_else(|| metadata.get("amount_cents").and_then(|a| a.parse().ok()))
+ .context("credit checkout session has no amount")?;
+ ctx.ai_billing_service
+ .apply_credit_purchase(&payer, amount_cents, session.id.as_str())
+ .await
+ .context("failed to book credit purchase")?;
+ tracing::info!(payer = %payer, amount_cents, "booked ai credit purchase");
+ Ok(())
+}
diff --git a/services/authentication_service/src/api/webhooks/user/stripe_webhook/billing/test.rs b/services/authentication_service/src/api/webhooks/user/stripe_webhook/billing/test.rs
new file mode 100644
index 0000000000..9f158c9e57
--- /dev/null
+++ b/services/authentication_service/src/api/webhooks/user/stripe_webhook/billing/test.rs
@@ -0,0 +1,161 @@
+use super::*;
+use serde_json::json;
+
+#[tokio::test]
+async fn policy_failure_preserves_base_work_and_requests_webhook_retry() {
+ let events = std::cell::RefCell::new(Vec::new());
+ let result = complete_subscription_webhook(
+ async {
+ events
+ .borrow_mut()
+ .push("policy checked against original binding");
+ anyhow::bail!("policy storage unavailable")
+ },
+ async {
+ events
+ .borrow_mut()
+ .extend(["subscription", "permissions", "payment"]);
+ Ok(())
+ },
+ )
+ .await;
+ assert!(
+ result
+ .unwrap_err()
+ .to_string()
+ .contains("policy storage unavailable")
+ );
+ assert_eq!(
+ *events.borrow(),
+ vec![
+ "policy checked against original binding",
+ "subscription",
+ "permissions",
+ "payment"
+ ]
+ );
+}
+
+#[tokio::test]
+async fn disabled_policy_preserves_legacy_success_and_base_failure() {
+ for fail_base in [false, true] {
+ let called = std::cell::Cell::new(false);
+ let result = complete_subscription_webhook(async { Ok(()) }, async {
+ called.set(true);
+ if fail_base {
+ anyhow::bail!("base failed");
+ }
+ Ok(())
+ })
+ .await;
+ assert!(called.get());
+ assert_eq!(result.is_err(), fail_base);
+ }
+}
+
+fn subscription() -> Value {
+ json!({
+ "id": "sub_verified", "created": 1_700_000_000, "customer": "cus_verified",
+ "status": "active", "metadata": {}, "current_period_start": 1_800_000_000,
+ "current_period_end": 1_802_678_400,
+ "items": {"has_more": false, "data": [{"id": "si_verified", "quantity": 1,
+ "price": {"id": "price_40", "product": "prod_40", "unit_amount": 4000,
+ "currency": "usd", "type": "recurring", "recurring": {"interval": "month", "interval_count": 1}}}]}
+ })
+}
+
+fn invoice() -> Value {
+ json!({
+ "subscription": "sub_verified", "customer": "cus_verified", "status": "paid",
+ "billing_reason": "subscription_cycle", "amount_paid": 0,
+ "lines": {"has_more": false, "data": [{"subscription_item": "si_verified",
+ "price": {"id": "price_40"}, "proration": false,
+ "period": {"start": 1_800_000_000, "end": 1_802_678_400}}]}
+ })
+}
+
+fn event(object: Value) -> BillingEvent {
+ BillingEvent {
+ id: "evt_paid".into(),
+ at: DateTime::from_timestamp(1_800_000_010, 0).unwrap(),
+ object,
+ }
+}
+
+#[test]
+fn supports_both_period_versions_without_fallback() {
+ let old = subscription();
+ let mut new = old.clone();
+ new["items"]["data"][0]["current_period_start"] = new["current_period_start"].take();
+ new["items"]["data"][0]["current_period_end"] = new["current_period_end"].take();
+ let event = event(invoice());
+ assert_eq!(
+ subscription_periods(&event, &old, None),
+ subscription_periods(&event, &new, None)
+ );
+ new["items"]["data"][0]
+ .as_object_mut()
+ .unwrap()
+ .remove("current_period_end");
+ assert!(subscription_periods(&event, &new, None).is_empty());
+}
+
+#[test]
+fn discounted_paid_renewal_uses_price_not_invoice_total() {
+ let invoice = invoice();
+ let event = event(invoice.clone());
+ let facts = subscription_periods(&event, &subscription(), Some(&invoice));
+ assert_eq!(facts.len(), 1);
+ assert_eq!(facts[0].evidence, PeriodEvidence::Renewal);
+ assert_eq!(facts[0].unit_amount, Some(4000));
+ assert_eq!(facts[0].product_id.as_str(), "prod_40");
+}
+
+#[test]
+fn ordinary_updates_and_wrong_or_delayed_invoice_lines_never_prove_renewal() {
+ let sub = subscription();
+ let event = event(invoice());
+ assert_eq!(
+ subscription_periods(&event, &sub, None)[0].evidence,
+ PeriodEvidence::Snapshot
+ );
+ let mut invoices = vec![invoice(); 7];
+ invoices[0]["billing_reason"] = json!("subscription_update");
+ invoices[1]["lines"]["data"][0]["proration"] = json!(true);
+ invoices[2]["lines"]["data"][0]["period"]["start"] = json!(1_700_000_000);
+ invoices[3]["lines"]["data"][0]["subscription_item"] = json!("si_other");
+ invoices[4]["status"] = json!("open");
+ invoices[5]["customer"] = json!("cus_other");
+ invoices[6]["lines"]["has_more"] = json!(true);
+ for invoice in invoices {
+ assert_eq!(
+ subscription_periods(&event, &sub, Some(&invoice))[0].evidence,
+ PeriodEvidence::Snapshot
+ );
+ }
+}
+
+#[test]
+fn unknown_recurrence_is_not_assumed_monthly() {
+ let mut sub = subscription();
+ sub["items"]["data"][0]["price"]["recurring"] = Value::Null;
+ let facts = subscription_periods(&event(invoice()), &sub, None);
+ assert!(!facts[0].monthly);
+}
+
+#[test]
+fn newer_invoice_parent_fields_are_matched_by_item_and_price() {
+ let mut invoice = invoice();
+ invoice["parent"]["subscription_details"]["subscription"] = invoice["subscription"].take();
+ let line = &mut invoice["lines"]["data"][0];
+ line["parent"]["subscription_item_details"] =
+ json!({"subscription_item": "si_verified", "proration": false});
+ line["pricing"]["price_details"]["price"] = json!("price_40");
+ for key in ["subscription_item", "price", "proration"] {
+ line.as_object_mut().unwrap().remove(key);
+ }
+ assert_eq!(
+ subscription_periods(&event(invoice.clone()), &subscription(), Some(&invoice))[0].evidence,
+ PeriodEvidence::Renewal
+ );
+}
diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rs
index 2b4c1d255f..cb14747198 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -499,6 +499,10 @@ async fn main() -> anyhow::Result<()> {
config.environment,
));
+ // Keep existing analytics/legacy settlement unchanged. Per-attempt observations
+ // use a separate journal and never feed this settlement trigger.
+ let recorder = ai_usage::with_tracking(recorder, ai_usage::pg_tracking(db.clone()));
+
// The import pipeline: staged/imported external items, gather jobs over
// the user's connectors, and the Haiku import job. Built before the tool
// service context so the chat toolset gets a wired import context.