Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_usage_metering.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
test_usage_metering.py · 10.7 KB · 241 lines
1"""Metering: measure, fold, rate at close.
2
3The three failures this design exists to prevent, each with a test:
4a retried request billed twice; an allowance that never applies because
5each event was priced as it landed; and a bill a customer can dispute but
6not check.
7"""
8
9import json
10import pathlib
11
12import pytest
13
14from conftest import stage_collection
15
16import object_billing
17import object_execution
18import object_records
19import python_object_runtime
20
21REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
22PACKAGES = REPO_ROOT / "packages"
23BILLING_OBJECTS = PACKAGES / "app-billing" / "objects"
24RUNTIME = python_object_runtime.PythonObjectRuntime()
25
26PRICES = json.dumps({"ai.tokens": {"included": 100000, "unit_minor": 2}})
27
28
29def setup_env(tmp_path, monkeypatch, *, prices=PRICES, base_minor="4900"):
30 data_dir = tmp_path / "data"
31 for pkg, name in (("app-billing", "billing_plans"), ("app-billing", "subscriptions"),
32 ("app-billing", "usage_events"), ("app-billing", "usage_summaries"),
33 ("app-billing", "wallets"), ("app-billing", "wallet_entries"),
34 ("app-invoices", "invoices"), ("app-invoices", "invoice_lines"),
35 ("app-settings", "app_settings"), ("app-finance", "denominations")):
36 stage_collection(data_dir, pkg, name, seed=(name == "denominations"))
37 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
38 object_records.create_collection_record(
39 "billing_plans",
40 {"id": "plan-ai", "name": "AI Team", "code": "ai", "period": "month",
41 "base_minor": base_minor, "prices": prices, "is_active": "true",
42 "owner_id": "dan"}, base_dir=data_dir)
43 object_records.create_collection_record(
44 "subscriptions",
45 {"id": "sub-1", "customer_name": "Acme", "plan_id": "plan-ai",
46 "billing_mode": "hybrid", "status": "active",
47 "current_period_start": "2026-06-01", "current_period_end": "2026-06-30",
48 "owner_id": "dan"}, base_dir=data_dir)
49 return data_dir
50
51
52def meter(data_dir, event_id, quantity, *, metric="ai.tokens", cost=0, eid=None):
53 return object_records.create_collection_record(
54 "usage_events",
55 {"id": eid or f"ue-{event_id}", "event_id": event_id, "subscription_id": "sub-1",
56 "metric": metric, "quantity": str(quantity), "unit": "tokens",
57 "cost_minor": str(cost), "occurred_at": "2026-06-15", "owner_id": "dan"},
58 base_dir=data_dir)
59
60
61def run(object_id, payload=None):
62 return object_execution.execute_object(
63 RUNTIME,
64 object_execution.ObjectExecutionRequest(
65 object_id, method="POST", payload=payload or {}),
66 roots=[BILLING_OBJECTS]).result
67
68
69def summaries(data_dir):
70 return object_records.read_collection_records("usage_summaries", base_dir=data_dir)
71
72
73def lines(data_dir):
74 return object_records.read_collection_records("invoice_lines", base_dir=data_dir)
75
76
77# --- pure rating ----------------------------------------------------------------
78
79def test_the_allowance_applies_to_the_period_not_to_each_call():
80 """Rating per event would charge the first call at retail and never
81 reach the included quantity -- the classic metered-billing bug."""
82 spec = {"included": 100000, "unit_minor": 2}
83 assert object_billing.rate_metric(80000, spec)["amount_minor"] == 0
84 assert object_billing.rate_metric(100000, spec)["amount_minor"] == 0
85 # 20k over at 2 minor units each
86 assert object_billing.rate_metric(120000, spec)["amount_minor"] == 40000
87
88
89def test_tiers_price_bands_of_the_overage():
90 spec = {"included": 100, "tiers": [{"upto": 1000, "unit_minor": 2},
91 {"unit_minor": 1}]}
92 # 1600 used, 100 included -> 1500 overage: 1000 @2 + 500 @1
93 assert object_billing.rate_metric(1600, spec)["amount_minor"] == 2500
94
95
96def test_rounding_happens_once_for_the_metric():
97 spec = {"included": 0, "unit_minor": "0.4"}
98 # 5 * 0.4 = 2.0 exactly; 6 * 0.4 = 2.4 -> 2 (half-up on the total, not
99 # per unit, which would have rounded 0.4 to 0 six times and billed 0)
100 assert object_billing.rate_metric(5, spec)["amount_minor"] == 2
101 assert object_billing.rate_metric(6, spec)["amount_minor"] == 2
102
103
104def test_a_metric_with_no_price_is_reported_not_silently_billed():
105 rated = object_billing.rate_period(
106 [{"metric": "mystery", "quantity": "500"}], {"ai.tokens": {"unit_minor": 1}})
107 assert rated["total_minor"] == 0
108 assert rated["unpriced"] == ["mystery"]
109
110
111def test_unparseable_plan_prices_yield_no_charges_not_a_crash():
112 """A malformed plan must fail as 'nothing to charge', never as a
113 billing run that dies halfway through the customer base."""
114 assert object_billing.parse_prices("{not json") == {}
115 assert object_billing.parse_prices(None) == {}
116
117
118def test_margin_is_a_fold_over_stored_facts():
119 m = object_billing.margin(revenue_minor=40000, cost_minor=15000)
120 assert m["gross_minor"] == 25000 and m["gross_pct"] == 62.5
121
122
123# --- the dedup gate --------------------------------------------------------------
124
125def test_a_retried_request_is_not_billed_twice(tmp_path, monkeypatch):
126 data_dir = setup_env(tmp_path, monkeypatch)
127 meter(data_dir, "req-abc", 1000)
128 # The schema's `unique` (event_id per owner), inside the write lock; the
129 # hook that looked it up first is gone.
130 with pytest.raises(object_records.UniqueConstraintError, match="already recorded"):
131 meter(data_dir, "req-abc", 1000, eid="ue-retry")
132
133
134def test_usage_that_is_not_positive_is_refused_for_every_writer(tmp_path, monkeypatch):
135 """The schema's `validation.exclusive_min: 0` on quantity (the hook that
136 said so is gone): zero and negative usage are refused by the write path
137 itself, so a handler or an import meets the same rule as a form, and a
138 fraction of a unit is still a measurement."""
139 data_dir = setup_env(tmp_path, monkeypatch)
140 for n, quantity in enumerate(("-5", "0", "0.0")):
141 with pytest.raises(object_records.InvalidRecordPayloadError,
142 match="'quantity' must be greater than 0"):
143 meter(data_dir, f"req-{n}", quantity, eid=f"ue-bad-{n}")
144 meter(data_dir, "req-tiny", "0.0000001")
145 assert [row["event_id"] for row in object_records.read_collection_records(
146 "usage_events", base_dir=data_dir)] == ["req-tiny"]
147
148
149# --- the fold ---------------------------------------------------------------------
150
151def test_events_fold_into_one_bucket_per_metric_and_period(tmp_path, monkeypatch):
152 data_dir = setup_env(tmp_path, monkeypatch)
153 meter(data_dir, "e1", 40000, cost=300)
154 meter(data_dir, "e2", 30000, cost=200)
155 result = run("system_usage_rollup", {"today": "2026-06-20"})
156 assert result["events_folded"] == 2 and result["summaries_written"] == 1
157 bucket = summaries(data_dir)[0]
158 assert bucket["quantity"] == "70000"
159 assert bucket["event_count"] == "2"
160 assert bucket["cost_minor"] == "500" # margin is a read, not a project
161
162
163def test_folding_twice_counts_nothing_twice(tmp_path, monkeypatch):
164 data_dir = setup_env(tmp_path, monkeypatch)
165 meter(data_dir, "e1", 40000)
166 run("system_usage_rollup", {"today": "2026-06-20"})
167 again = run("system_usage_rollup", {"today": "2026-06-20"})
168 assert again["events_folded"] == 0
169 assert summaries(data_dir)[0]["quantity"] == "40000"
170
171
172def test_usage_with_no_subscription_stays_visible_and_unrated(tmp_path, monkeypatch):
173 """Unpriceable usage must not be folded somewhere wrong."""
174 data_dir = setup_env(tmp_path, monkeypatch)
175 object_records.create_collection_record(
176 "usage_events",
177 {"id": "ue-orphan", "event_id": "orphan", "metric": "ai.tokens",
178 "quantity": "500", "owner_id": "dan"}, base_dir=data_dir)
179 result = run("system_usage_rollup", {"today": "2026-06-20"})
180 assert result["orphaned_events"] == 1 and summaries(data_dir) == []
181
182
183# --- rating into the invoice --------------------------------------------------------
184
185def test_overage_becomes_a_line_a_customer_can_check(tmp_path, monkeypatch):
186 data_dir = setup_env(tmp_path, monkeypatch)
187 meter(data_dir, "e1", 120000, cost=1200) # 20k over the 100k allowance
188 run("system_usage_rollup", {"today": "2026-06-20"})
189 result = run("system_billing_runner", {"today": "2026-07-01"})
190 assert result["invoiced"] == 2 # June's base in advance (late), then the close
191
192 totals = sorted(int(i["total_cents"]) for i in
193 object_records.read_collection_records("invoices", base_dir=data_dir))
194 # The close: July's 4900 base in advance + June's 40000 overage in arrears.
195 assert totals == [4900, 44900]
196
197 rows = sorted(lines(data_dir), key=lambda r: int(r["line_total_cents"]))
198 assert len(rows) == 3
199 usage_line = rows[-1]
200 # The line shows used / included / billable, not one opaque number.
201 assert "120000 used" in usage_line["description"]
202 assert "100000 included" in usage_line["description"]
203 assert "20000 billable" in usage_line["description"]
204 assert usage_line["line_total_cents"] == "40000"
205
206
207def test_usage_within_the_allowance_bills_only_the_base(tmp_path, monkeypatch):
208 data_dir = setup_env(tmp_path, monkeypatch)
209 meter(data_dir, "e1", 50000)
210 run("system_usage_rollup", {"today": "2026-06-20"})
211 run("system_billing_runner", {"today": "2026-07-01"})
212 totals = [i["total_cents"] for i in
213 object_records.read_collection_records("invoices", base_dir=data_dir)]
214 assert totals == ["4900", "4900"] # June's and July's base fees, no overage
215 assert len(lines(data_dir)) == 2
216
217
218def test_a_summary_is_never_billed_in_two_periods(tmp_path, monkeypatch):
219 data_dir = setup_env(tmp_path, monkeypatch)
220 meter(data_dir, "e1", 120000)
221 run("system_usage_rollup", {"today": "2026-06-20"})
222 run("system_billing_runner", {"today": "2026-07-01"})
223 assert summaries(data_dir)[0]["invoiced"] == "true"
224 # Next period closes with no new usage: the base only, and the overage
225 # already billed does not ride along a second time.
226 run("system_billing_runner", {"today": "2026-08-01"})
227 totals = sorted(int(i["total_cents"]) for i in
228 object_records.read_collection_records("invoices", base_dir=data_dir))
229 assert totals == [4900, 4900, 44900]
230
231
232def test_pure_metered_plan_with_no_base_still_bills_usage(tmp_path, monkeypatch):
233 """base 0 + usage is a real shape: pay-as-you-go with an invoice."""
234 data_dir = setup_env(tmp_path, monkeypatch, base_minor="0")
235 meter(data_dir, "e1", 150000)
236 run("system_usage_rollup", {"today": "2026-06-20"})
237 result = run("system_billing_runner", {"today": "2026-07-01"})
238 assert result["invoiced"] == 1
239 invoice = object_records.read_collection_records("invoices", base_dir=data_dir)[0]
240 assert invoice["total_cents"] == "100000" # 50k over at 2
241 assert len(lines(data_dir)) == 1