askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_wallet.py · 16.5 KB · 362 lines
| 1 | """Wallets: the ledger IS the balance, and the cap is the safety. |
| 2 | |
| 3 | Two claims under test. First, that a wallet's balance cannot drift from |
| 4 | its entries -- the predecessor's mutable balance column beside a |
| 5 | transaction table is the failure this design exists to prevent, and when |
| 6 | those two disagree the customer is right and you cannot prove otherwise. |
| 7 | Second, that auto top-up is bounded: autopay plus one runaway metering |
| 8 | bug is a four-figure surprise, and a monthly cap turns that into |
| 9 | something a human notices instead. |
| 10 | """ |
| 11 | |
| 12 | import json |
| 13 | import pathlib |
| 14 | |
| 15 | import pytest |
| 16 | |
| 17 | from conftest import stage_collection |
| 18 | |
| 19 | import object_execution |
| 20 | import object_records |
| 21 | import python_object_runtime |
| 22 | |
| 23 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 24 | PACKAGES = REPO_ROOT / "packages" |
| 25 | BILLING_OBJECTS = PACKAGES / "app-billing" / "objects" |
| 26 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 27 | |
| 28 | |
| 29 | def setup_env(tmp_path, monkeypatch, *, settings=()): |
| 30 | data_dir = tmp_path / "data" |
| 31 | for pkg, name in (("app-billing", "wallets"), ("app-billing", "wallet_entries"), |
| 32 | ("app-finance", "denominations"), ("app-settings", "app_settings")): |
| 33 | stage_collection(data_dir, pkg, name, |
| 34 | seed=(name == "denominations")) |
| 35 | rows = "" |
| 36 | for i, (k, v) in enumerate(settings): |
| 37 | rows += f"s{i}\t{k}\t{v}\t\n" |
| 38 | if rows: |
| 39 | stage_collection(data_dir, "app-settings", "app_settings", rows=rows) |
| 40 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 41 | monkeypatch.delenv("DBBASIC_STRIPE_SECRET_KEY", raising=False) |
| 42 | monkeypatch.delenv("DBBASIC_STRIPE_WEBHOOK_SECRET", raising=False) |
| 43 | return data_dir |
| 44 | |
| 45 | |
| 46 | def make_wallet(data_dir, wid="w1", **fields): |
| 47 | record = {"id": wid, "owner_id": "dan", "is_active": "true"} |
| 48 | record.update(fields) |
| 49 | return object_records.create_collection_record("wallets", record, base_dir=data_dir) |
| 50 | |
| 51 | |
| 52 | def entry(data_dir, wid, amount, *, kind="topup", eid=None, generated_from="", |
| 53 | created_at=None): |
| 54 | record = {"id": eid or f"e-{abs(amount)}-{kind}-{object_records.new_record_id()}" |
| 55 | if hasattr(object_records, "new_record_id") else (eid or f"e{amount}{kind}"), |
| 56 | "wallet_id": wid, "amount_minor": str(amount), "kind": kind, |
| 57 | "generated_from": generated_from, "owner_id": "dan"} |
| 58 | if created_at: |
| 59 | record["created_at"] = created_at |
| 60 | return object_records.create_collection_record( |
| 61 | "wallet_entries", record, base_dir=data_dir) |
| 62 | |
| 63 | |
| 64 | def wallet(data_dir, wid="w1"): |
| 65 | return object_records.get_collection_record("wallets", wid, base_dir=data_dir) |
| 66 | |
| 67 | |
| 68 | def hook(record, action="create"): |
| 69 | return object_execution.execute_object( |
| 70 | RUNTIME, |
| 71 | object_execution.ObjectExecutionRequest( |
| 72 | "hook_wallet_entries", method="BEFORE_WRITE", |
| 73 | payload={"action": action, "collection": "wallet_entries", "record": record}), |
| 74 | roots=[BILLING_OBJECTS]).result |
| 75 | |
| 76 | |
| 77 | def replenish(payload=None): |
| 78 | return object_execution.execute_object( |
| 79 | RUNTIME, |
| 80 | object_execution.ObjectExecutionRequest( |
| 81 | "system_wallet_replenish", method="POST", payload=payload or {}), |
| 82 | roots=[BILLING_OBJECTS]).result |
| 83 | |
| 84 | |
| 85 | # --- the ledger is the balance ------------------------------------------------ |
| 86 | |
| 87 | def test_balance_is_the_sum_of_entries_and_nothing_writes_it(tmp_path, monkeypatch): |
| 88 | data_dir = setup_env(tmp_path, monkeypatch) |
| 89 | make_wallet(data_dir) |
| 90 | entry(data_dir, "w1", 5000, kind="topup", eid="e1") |
| 91 | assert wallet(data_dir)["balance_minor"] == "5000" |
| 92 | entry(data_dir, "w1", -1250, kind="debit", eid="e2") |
| 93 | assert wallet(data_dir)["balance_minor"] == "3750" |
| 94 | entry(data_dir, "w1", 1250, kind="refund", eid="e3") |
| 95 | assert wallet(data_dir)["balance_minor"] == "5000" |
| 96 | |
| 97 | |
| 98 | def test_the_balance_field_cannot_be_written_by_anyone(tmp_path, monkeypatch): |
| 99 | """The predecessor's drift bug is impossible here by construction: the |
| 100 | field is computed, and the write path refuses it.""" |
| 101 | data_dir = setup_env(tmp_path, monkeypatch) |
| 102 | make_wallet(data_dir) |
| 103 | entry(data_dir, "w1", 1000, eid="e1") |
| 104 | try: |
| 105 | object_records.update_collection_record( |
| 106 | "wallets", "w1", {"balance_minor": "999999"}, base_dir=data_dir) |
| 107 | raise AssertionError("a computed balance must not be writable") |
| 108 | except object_records.InvalidRecordPayloadError as exc: |
| 109 | assert "computed" in str(exc) or "read-only" in str(exc) |
| 110 | assert wallet(data_dir)["balance_minor"] == "1000" |
| 111 | |
| 112 | |
| 113 | # --- the debit gate ------------------------------------------------------------- |
| 114 | |
| 115 | def test_a_debit_beyond_the_balance_is_refused_with_402(tmp_path, monkeypatch): |
| 116 | data_dir = setup_env(tmp_path, monkeypatch) |
| 117 | make_wallet(data_dir) |
| 118 | entry(data_dir, "w1", 1000, eid="e1") |
| 119 | ok = hook({"wallet_id": "w1", "amount_minor": "-1000", "kind": "debit"}) |
| 120 | assert ok is None # exactly to zero is allowed |
| 121 | over = hook({"wallet_id": "w1", "amount_minor": "-1001", "kind": "debit"}) |
| 122 | assert over["status"] == 402 # Payment Required, the honest code |
| 123 | assert "Insufficient wallet balance" in over["error"] |
| 124 | |
| 125 | |
| 126 | def test_credits_are_never_gated(tmp_path, monkeypatch): |
| 127 | data_dir = setup_env(tmp_path, monkeypatch) |
| 128 | make_wallet(data_dir) |
| 129 | assert hook({"wallet_id": "w1", "amount_minor": "5000", "kind": "topup"}) is None |
| 130 | |
| 131 | |
| 132 | def test_an_overdraft_floor_can_be_allowed_deliberately(tmp_path, monkeypatch): |
| 133 | """A high-frequency workload may prefer a few cents of race over |
| 134 | failing a customer's request mid-flight -- but it must be a decision.""" |
| 135 | data_dir = setup_env(tmp_path, monkeypatch, |
| 136 | settings=(("billing.wallet.overdraft_minor", "500"),)) |
| 137 | make_wallet(data_dir) |
| 138 | entry(data_dir, "w1", 100, eid="e1") |
| 139 | assert hook({"wallet_id": "w1", "amount_minor": "-600", "kind": "debit"}) is None |
| 140 | assert hook({"wallet_id": "w1", "amount_minor": "-601", |
| 141 | "kind": "debit"})["status"] == 402 |
| 142 | |
| 143 | |
| 144 | def test_a_zero_entry_is_refused(tmp_path, monkeypatch): |
| 145 | setup_env(tmp_path, monkeypatch) |
| 146 | assert hook({"wallet_id": "w1", "amount_minor": "0", "kind": "debit"})["status"] == 400 |
| 147 | |
| 148 | |
| 149 | # --- auto top-up, and the cap that bounds it ------------------------------------ |
| 150 | |
| 151 | def test_the_monthly_cap_stops_a_runaway(tmp_path, monkeypatch): |
| 152 | """The scenario: metering goes wrong and drains the wallet repeatedly. |
| 153 | Without a cap, autopay follows it down forever.""" |
| 154 | data_dir = setup_env(tmp_path, monkeypatch) |
| 155 | make_wallet(data_dir, auto_replenish_enabled="true", |
| 156 | auto_replenish_threshold_minor="1000", |
| 157 | auto_replenish_amount_minor="2000", |
| 158 | auto_replenish_monthly_cap_minor="3000", |
| 159 | stripe_customer_id="cus_1", payment_method_ref="pm_1") |
| 160 | # The real runaway shape: an auto top-up already happened this month, |
| 161 | # then metering drained the wallet back below the threshold. Without a |
| 162 | # cap the pass would top up again, and again, following the bug down. |
| 163 | # The test's calendar is DERIVED from the wall clock, because it has |
| 164 | # no choice: the cap fold counts seeded entries by their created_at |
| 165 | # month, and created_at is computed at write time -- deliberately |
| 166 | # unwritable by any caller, this test included. Hardcoding |
| 167 | # "2026-07-25" here held only during July 2026: at the first month |
| 168 | # rollover the seed landed in August, the July fold saw nothing, and |
| 169 | # the "cap reached" path silently became the "already attempted" |
| 170 | # skip. A test about a calendar window must run in the month its |
| 171 | # records actually carry. |
| 172 | from datetime import datetime, timezone |
| 173 | # UTC, not local: created_at is stamped in UTC, and for a few hours |
| 174 | # around every month boundary the two disagree about what month it |
| 175 | # is -- which is precisely when this test first failed. |
| 176 | period = datetime.now(timezone.utc).strftime("%Y-%m") |
| 177 | entry(data_dir, "w1", 2000, kind="auto_topup", eid="e1", |
| 178 | generated_from=f"auto_topup/w1/{period}/2000") |
| 179 | entry(data_dir, "w1", -1800, kind="debit", eid="e2") # balance now 200 |
| 180 | |
| 181 | result = replenish({"today": f"{period}-25"}) |
| 182 | capped = [r for r in result["results"] if r.get("skipped") == "monthly cap reached"] |
| 183 | assert capped, result |
| 184 | assert capped[0]["capped_at_minor"] == 3000 |
| 185 | assert capped[0]["already_this_month_minor"] == 2000 |
| 186 | assert result["charged"] == 0 |
| 187 | |
| 188 | |
| 189 | def test_a_zero_cap_means_auto_topup_is_off(tmp_path, monkeypatch): |
| 190 | """A blank number must never read as 'unlimited' -- the safe default.""" |
| 191 | data_dir = setup_env(tmp_path, monkeypatch) |
| 192 | make_wallet(data_dir, auto_replenish_enabled="true", |
| 193 | auto_replenish_threshold_minor="1000", |
| 194 | auto_replenish_amount_minor="2000", |
| 195 | stripe_customer_id="cus_1", payment_method_ref="pm_1") |
| 196 | entry(data_dir, "w1", 0 + 500, eid="e1") |
| 197 | result = replenish({"today": "2026-07-25"}) |
| 198 | assert result["charged"] == 0 |
| 199 | assert any("cap is zero" in str(r.get("skipped", "")) for r in result["results"]) |
| 200 | |
| 201 | |
| 202 | def test_a_healthy_balance_is_left_alone(tmp_path, monkeypatch): |
| 203 | data_dir = setup_env(tmp_path, monkeypatch) |
| 204 | make_wallet(data_dir, auto_replenish_enabled="true", |
| 205 | auto_replenish_threshold_minor="1000", |
| 206 | auto_replenish_amount_minor="2000", |
| 207 | auto_replenish_monthly_cap_minor="10000", |
| 208 | stripe_customer_id="cus_1", payment_method_ref="pm_1") |
| 209 | entry(data_dir, "w1", 5000, eid="e1") |
| 210 | result = replenish({"today": "2026-07-25"}) |
| 211 | assert result["charged"] == 0 and result["results"] == [] |
| 212 | |
| 213 | |
| 214 | def test_without_stripe_it_reports_what_it_would_charge(tmp_path, monkeypatch): |
| 215 | """The rule can be tuned before any money moves.""" |
| 216 | data_dir = setup_env(tmp_path, monkeypatch) |
| 217 | make_wallet(data_dir, auto_replenish_enabled="true", |
| 218 | auto_replenish_threshold_minor="1000", |
| 219 | auto_replenish_amount_minor="2000", |
| 220 | auto_replenish_monthly_cap_minor="10000") |
| 221 | entry(data_dir, "w1", 100, eid="e1") |
| 222 | result = replenish({"today": "2026-07-25"}) |
| 223 | assert result["charged"] == 0 |
| 224 | would = [r for r in result["results"] if r.get("would_charge_minor")] |
| 225 | assert would and would[0]["would_charge_minor"] == 2000 |
| 226 | assert "not configured" in would[0]["reason"] |
| 227 | |
| 228 | |
| 229 | def test_a_wallet_without_a_saved_card_is_skipped_not_failed(tmp_path, monkeypatch): |
| 230 | data_dir = setup_env(tmp_path, monkeypatch) |
| 231 | monkeypatch.setenv("DBBASIC_STRIPE_SECRET_KEY", "sk_test") |
| 232 | monkeypatch.setenv("DBBASIC_STRIPE_WEBHOOK_SECRET", "whsec_test") |
| 233 | make_wallet(data_dir, auto_replenish_enabled="true", |
| 234 | auto_replenish_threshold_minor="1000", |
| 235 | auto_replenish_amount_minor="2000", |
| 236 | auto_replenish_monthly_cap_minor="10000") |
| 237 | entry(data_dir, "w1", 100, eid="e1") |
| 238 | result = replenish({"today": "2026-07-25"}) |
| 239 | assert result["failed"] == 0 |
| 240 | assert any("no saved card" in str(r.get("skipped", "")) for r in result["results"]) |
| 241 | |
| 242 | |
| 243 | def test_billing_not_installed_is_a_graceful_skip(tmp_path, monkeypatch): |
| 244 | data_dir = tmp_path / "data" |
| 245 | data_dir.mkdir() |
| 246 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 247 | assert replenish()["skipped"].startswith("billing not installed") |
| 248 | |
| 249 | |
| 250 | # --- rule 2: a provenance marker is used once --------------------------------- |
| 251 | # |
| 252 | # Doctrine #7 says a replayed event posts nothing twice, and every money |
| 253 | # writer here already honours it -- by READING the ledger, looking for its |
| 254 | # marker, then writing. That is check-then-write, and it is only as good |
| 255 | # as the absence of a second writer in between. system_wallet_replenish |
| 256 | # runs on a daily schedule AND by hand; the Stripe charge is safe because |
| 257 | # that pass sends its marker as Stripe's idempotency_key, but the wallet |
| 258 | # credit that follows had nothing protecting it, so the customer could be |
| 259 | # credited twice for one card charge and the shop ate the difference. |
| 260 | |
| 261 | def test_a_marker_cannot_be_posted_to_the_ledger_twice(tmp_path, monkeypatch): |
| 262 | """No hook any more: wallet_entries declares `generated_from` unique, so |
| 263 | the ledger refuses a marker used before inside the write lock, for every |
| 264 | writer.""" |
| 265 | data_dir = setup_env(tmp_path, monkeypatch) |
| 266 | make_wallet(data_dir) |
| 267 | entry(data_dir, "w1", 500, kind="auto_topup", |
| 268 | generated_from="auto_topup/w1/2026-07/500") |
| 269 | |
| 270 | with pytest.raises(object_records.UniqueConstraintError) as refused: |
| 271 | entry(data_dir, "w1", 500, kind="auto_topup", |
| 272 | generated_from="auto_topup/w1/2026-07/500", eid="again") |
| 273 | assert "already been posted" in str(refused.value) |
| 274 | assert refused.value.fields == ["generated_from"] |
| 275 | |
| 276 | |
| 277 | def test_the_duplicate_check_covers_credits_which_is_the_case_it_exists_for(tmp_path, monkeypatch): |
| 278 | """A duplicated credit is money leaving the business exactly as a |
| 279 | duplicated debit is money leaving a customer; the unique key does not |
| 280 | care which direction the entry moves.""" |
| 281 | data_dir = setup_env(tmp_path, monkeypatch) |
| 282 | make_wallet(data_dir) |
| 283 | entry(data_dir, "w1", 2000, kind="topup", generated_from="checkout/o-1") |
| 284 | |
| 285 | with pytest.raises(object_records.UniqueConstraintError): |
| 286 | entry(data_dir, "w1", 2000, kind="topup", generated_from="checkout/o-1", |
| 287 | eid="again-credit") |
| 288 | with pytest.raises(object_records.UniqueConstraintError): |
| 289 | entry(data_dir, "w1", -2000, kind="debit", generated_from="checkout/o-1", |
| 290 | eid="again-debit") |
| 291 | |
| 292 | |
| 293 | def test_a_blank_marker_is_never_a_collision(tmp_path, monkeypatch): |
| 294 | data_dir = setup_env(tmp_path, monkeypatch) |
| 295 | """Most entries carry none: a manual top-up, an adjustment, an |
| 296 | ordinary debit. Uniqueness is a property of the markers that exist, |
| 297 | not a requirement that every entry have one -- the same view |
| 298 | hook_wallets takes of a blank gift-card code.""" |
| 299 | make_wallet(data_dir) |
| 300 | for n in range(3): |
| 301 | entry(data_dir, "w1", 100, kind="topup", generated_from="", |
| 302 | eid=f"blank-{n}") |
| 303 | assert hook({"wallet_id": "w1", "amount_minor": "100", |
| 304 | "kind": "topup", "generated_from": ""}) is None |
| 305 | assert hook({"wallet_id": "w1", "amount_minor": "100", |
| 306 | "kind": "topup"}) is None |
| 307 | |
| 308 | |
| 309 | def test_a_different_marker_from_the_same_source_still_posts(tmp_path, monkeypatch): |
| 310 | data_dir = setup_env(tmp_path, monkeypatch) |
| 311 | """The template runner writes release and charge as two legs of one |
| 312 | settlement, with distinct markers. Refusing the second because it |
| 313 | shares a prefix would break every multi-leg settlement on the box.""" |
| 314 | make_wallet(data_dir) |
| 315 | entry(data_dir, "w1", 5000, kind="topup") |
| 316 | entry(data_dir, "w1", 50, kind="release", |
| 317 | generated_from="template_run/r1/release") |
| 318 | assert hook({"wallet_id": "w1", "amount_minor": "-50", "kind": "debit", |
| 319 | "generated_from": "template_run/r1/charge"}) is None |
| 320 | |
| 321 | |
| 322 | def test_an_unreadable_ledger_still_refuses_a_debit_and_a_credit_asks_it_nothing( |
| 323 | tmp_path, monkeypatch): |
| 324 | """A debit against an unknown balance is refused (the hook still sums the |
| 325 | ledger). A credit needs no balance, and the marker it carries is checked |
| 326 | by the unique key inside the write lock -- which cannot pass what it |
| 327 | cannot read -- so the hook no longer reads anything for it.""" |
| 328 | data_dir = setup_env(tmp_path, monkeypatch) |
| 329 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir / "gone")) |
| 330 | refused = hook({"wallet_id": "w1", "amount_minor": "-500", |
| 331 | "kind": "debit", "generated_from": "x/1"}) |
| 332 | assert refused["status"] == 409 |
| 333 | assert "unreadable" in refused["error"] |
| 334 | assert hook({"wallet_id": "w1", "amount_minor": "500", |
| 335 | "kind": "topup", "generated_from": "auto_topup/w1/x"}) is None |
| 336 | |
| 337 | |
| 338 | def test_two_overlapping_topups_credit_the_wallet_once(tmp_path, monkeypatch): |
| 339 | data_dir = setup_env(tmp_path, monkeypatch) |
| 340 | """The reproduction. Both passes find no marker and both try to |
| 341 | credit; the ledger accepts one. Before this rule the wallet ended up |
| 342 | with 1000 against a single 500 charge at the card.""" |
| 343 | make_wallet(data_dir) |
| 344 | marker = "auto_topup/w1/2026-07/500" |
| 345 | credit = {"wallet_id": "w1", "amount_minor": "500", "kind": "auto_topup", |
| 346 | "generated_from": marker, "owner_id": "dan"} |
| 347 | |
| 348 | landed = 0 |
| 349 | for n in range(2): |
| 350 | try: |
| 351 | object_records.create_collection_record( |
| 352 | "wallet_entries", {"id": f"c{n}", **credit}, base_dir=data_dir) |
| 353 | landed += 1 |
| 354 | except object_records.UniqueConstraintError: |
| 355 | pass |
| 356 | |
| 357 | assert landed == 1 |
| 358 | total = sum(int(r["amount_minor"]) for r in |
| 359 | object_records.read_collection_records("wallet_entries", |
| 360 | base_dir=data_dir) |
| 361 | if r["wallet_id"] == "w1") |
| 362 | assert total == 500 |