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_money_gates_locked_ceilings.py · 24.7 KB · 562 lines
| 1 | """The overpayment ceiling and the refundable headroom hold for EVERY writer. |
| 2 | |
| 3 | tests/test_money_gates_ceiling_races.py closed overlapping writes that both |
| 4 | come through the hooks. What it left open (bug report 2026-11-29 07:22, |
| 5 | "Still racy after the fix") is reproduced here, each case against the real |
| 6 | packages: |
| 7 | |
| 8 | * a payment written BELOW the hook -- the Stripe webhook, checkout's |
| 9 | gift-card payment, any storage-level create -- landing while a hooked |
| 10 | payment is between its hook and its write, or racing it; |
| 11 | * an admin's edit of an amount, or an admin's delete, overlapping another |
| 12 | writer; |
| 13 | * an input of the ceiling that lives in ANOTHER collection moving while a |
| 14 | payment or refund is in flight: an invoice line lowered, a payment |
| 15 | bounced. |
| 16 | |
| 17 | The claim every test makes is the invariant, read back from the files: at |
| 18 | no point does a payment land on more than its invoice is worth at the |
| 19 | moment it lands, nor a refund on more than is left of its payment. Each was |
| 20 | run against the tree before the locked checks existed (246b3e5) and seen to |
| 21 | fail on that assertion; the numbers are in each docstring. |
| 22 | |
| 23 | How the races are driven is the same as in the sibling file: a write is |
| 24 | paused at the exact point between its hook and object_records (patched |
| 25 | entry), the other writer runs on its own thread and is joined, then the |
| 26 | first write continues. A mechanism that holds a lock across hook and write |
| 27 | would make the second writer wait for the first, not deadlock the test. |
| 28 | Real threads behind a barrier and real processes with no choreography give |
| 29 | the same claim without any patching. |
| 30 | |
| 31 | Stripe is never called: the webhook only verifies a signature and writes, |
| 32 | DBBASIC_STRIPE_API_BASE points at a closed local port regardless, and the |
| 33 | events are signed here with a test secret. |
| 34 | """ |
| 35 | |
| 36 | import hashlib |
| 37 | import hmac |
| 38 | import json |
| 39 | import subprocess |
| 40 | import sys |
| 41 | import threading |
| 42 | import time |
| 43 | |
| 44 | import object_execution |
| 45 | import object_records |
| 46 | import python_object_runtime |
| 47 | from test_findings_money_gates import ( # noqa: F401 (fresh_handler_index is autouse) |
| 48 | PACKAGES, REPO_ROOT, fresh_handler_index, must, net_received, ok, pay, payments_site, refund, |
| 49 | ) |
| 50 | |
| 51 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 52 | SECRET = "whsec_locked_ceiling_test" |
| 53 | |
| 54 | |
| 55 | # --- helpers --------------------------------------------------------------------- |
| 56 | |
| 57 | |
| 58 | def overlap(monkeypatch, entry, collection, first, between): |
| 59 | """Run `first()`; when it reaches object_records.<entry> for |
| 60 | `collection`, run `between()` to completion on another thread, then let |
| 61 | `first` continue. Returns (first's result, between's result).""" |
| 62 | real = getattr(object_records, entry) |
| 63 | state = {"armed": True, "between": None, "thread": None, "error": None} |
| 64 | |
| 65 | def run_between(): |
| 66 | try: |
| 67 | state["between"] = between() |
| 68 | except Exception as exc: # noqa: BLE001 -- reported below |
| 69 | state["error"] = exc |
| 70 | |
| 71 | def patched(name, *args, **kwargs): |
| 72 | if name == collection and state["armed"]: |
| 73 | state["armed"] = False |
| 74 | worker = threading.Thread(target=run_between) |
| 75 | state["thread"] = worker |
| 76 | worker.start() |
| 77 | worker.join(timeout=20) |
| 78 | return real(name, *args, **kwargs) |
| 79 | |
| 80 | monkeypatch.setattr(object_records, entry, patched) |
| 81 | try: |
| 82 | first_result = first() |
| 83 | must(state["thread"] is not None, f"the first write never reached {entry}: no overlap") |
| 84 | state["thread"].join(timeout=20) |
| 85 | finally: |
| 86 | monkeypatch.setattr(object_records, entry, real) |
| 87 | must(state["error"] is None, f"the overlapping writer failed: {state['error']!r}") |
| 88 | return first_result, state["between"] |
| 89 | |
| 90 | |
| 91 | def storage_payment(site, payment_id, amount, *, invoice_id="inv1", actor="webhook_stripe"): |
| 92 | """A payment written the way the trusted writers write one: straight to |
| 93 | object_records, no hook. Returns "landed" or "refused".""" |
| 94 | try: |
| 95 | object_records.create_collection_record( |
| 96 | "payments", |
| 97 | {"id": payment_id, "invoice_id": invoice_id, "amount_cents": str(amount), |
| 98 | "method": "card", "received_on": "2026-07-24", "status": "received", |
| 99 | "reference": f"evt_{payment_id}", "owner_id": "ann"}, |
| 100 | base_dir=site.data, actor=actor) |
| 101 | except Exception: # noqa: BLE001 -- any refusal; the ledger is what is asserted |
| 102 | return "refused" |
| 103 | return "landed" |
| 104 | |
| 105 | |
| 106 | def refunded_against(site, payment_id): |
| 107 | return sum(int(row["amount_cents"]) for row in site.rows("refunds", payment_id=payment_id)) |
| 108 | |
| 109 | |
| 110 | def invoice_ceiling(site, invoice_id="inv1"): |
| 111 | """What the invoice is worth now, by the hook's own definition.""" |
| 112 | hook = load_hook("payments") |
| 113 | invoice = site.get("invoices", invoice_id) |
| 114 | ceiling, refusal = hook._invoice_ceiling(invoice, str(site.data)) |
| 115 | must(refusal is None, f"the ceiling cannot be computed: {refusal}") |
| 116 | return ceiling |
| 117 | |
| 118 | |
| 119 | def load_hook(name): |
| 120 | import importlib.util |
| 121 | path = PACKAGES / "app-payments" / "objects" / "hook" / f"{name}.py" |
| 122 | spec = importlib.util.spec_from_file_location(f"locked_ceiling_hook_{name}", path) |
| 123 | module = importlib.util.module_from_spec(spec) |
| 124 | spec.loader.exec_module(module) |
| 125 | return module |
| 126 | |
| 127 | |
| 128 | def hook_create(hook, collection, record): |
| 129 | return hook.BEFORE_WRITE({"action": "create", "collection": collection, "record": record, |
| 130 | "existing": None, "changes": record, |
| 131 | "subject": {"user_id": "ann", "roles": []}}) |
| 132 | |
| 133 | |
| 134 | def signed(payload, when=None): |
| 135 | ts = when if when is not None else int(time.time()) |
| 136 | mac = hmac.new(SECRET.encode(), f"{ts}.".encode() + payload, hashlib.sha256).hexdigest() |
| 137 | return f"t={ts},v1={mac}" |
| 138 | |
| 139 | |
| 140 | def stripe_event(event_id, amount, invoice_id="inv1"): |
| 141 | return json.dumps({ |
| 142 | "id": event_id, "type": "checkout.session.completed", "created": 1785000000, |
| 143 | "data": {"object": {"id": f"cs_{event_id}", "amount_total": amount, |
| 144 | "payment_status": "paid", "currency": "usd", |
| 145 | "metadata": {"invoice_id": invoice_id}}}, |
| 146 | }).encode() |
| 147 | |
| 148 | |
| 149 | def stripe_site(tmp_path, monkeypatch): |
| 150 | site = payments_site(tmp_path, monkeypatch) |
| 151 | monkeypatch.setenv("DBBASIC_STRIPE_SECRET_KEY", "sk_test_locked_ceiling") |
| 152 | monkeypatch.setenv("DBBASIC_STRIPE_WEBHOOK_SECRET", SECRET) |
| 153 | monkeypatch.setenv("DBBASIC_STRIPE_API_BASE", "http://127.0.0.1:9") # nothing listens |
| 154 | must(site.get("invoices", "inv1").get("currency") == "USD", "invoice currency is not USD") |
| 155 | return site |
| 156 | |
| 157 | |
| 158 | def deliver(site, event_id, amount): |
| 159 | raw = stripe_event(event_id, amount) |
| 160 | return object_execution.execute_object( |
| 161 | RUNTIME, |
| 162 | object_execution.ObjectExecutionRequest( |
| 163 | "webhook_stripe", method="POST", |
| 164 | payload={"_raw_body": raw.decode(), "_headers": {"stripe-signature": signed(raw)}}), |
| 165 | roots=[site.root]).result |
| 166 | |
| 167 | |
| 168 | # --- a writer below the hook, racing a hooked one ---------------------------------- |
| 169 | |
| 170 | |
| 171 | def test_a_stripe_payment_landing_inside_an_http_payment_cannot_overpay(tmp_path, monkeypatch): |
| 172 | """A 10000 invoice. An HTTP payment of 6000 passes its hook; before its |
| 173 | write, the real Stripe webhook records 6000 for the same invoice. |
| 174 | |
| 175 | Before: both landed -- the webhook's row carries no sequence number, so |
| 176 | the HTTP payment's number was still free -- and 12000 was received.""" |
| 177 | site = stripe_site(tmp_path, monkeypatch) |
| 178 | |
| 179 | http, webhook = overlap(monkeypatch, "create_collection_record", "payments", |
| 180 | lambda: pay(site, "p-http", 6000), |
| 181 | lambda: deliver(site, "evt_a", 6000)) |
| 182 | |
| 183 | assert webhook["status"] == 200 and webhook.get("payment_id"), webhook |
| 184 | assert net_received(site) <= 10000, f"{net_received(site)} received against 10000" |
| 185 | assert http[0] == 409, http |
| 186 | assert "remaining balance of 4000" in http[1]["error"], http |
| 187 | |
| 188 | |
| 189 | def test_a_stripe_payment_over_the_ceiling_is_not_recorded_and_is_not_acknowledged( |
| 190 | tmp_path, monkeypatch): |
| 191 | """The webhook records money that has already moved, so refusing it |
| 192 | must not lose it: the event is answered non-2xx (Stripe redelivers it |
| 193 | and shows the endpoint failing) and says a person has to look. |
| 194 | |
| 195 | Before: it was recorded, and 15000 stood against a 10000 invoice.""" |
| 196 | site = stripe_site(tmp_path, monkeypatch) |
| 197 | ok(pay(site, "p-first", 9000), "the first payment") |
| 198 | |
| 199 | result = deliver(site, "evt_over", 6000) |
| 200 | |
| 201 | assert net_received(site) == 9000, f"{net_received(site)} received against 10000" |
| 202 | assert result["status"] == 409, result |
| 203 | assert result.get("needs_attention"), result |
| 204 | # A redelivery after a person makes room is recorded normally. |
| 205 | ok(site.put("payments", "p-first", "ann", {"status": "bounced"}), "the first one bounced") |
| 206 | again = deliver(site, "evt_over", 6000) |
| 207 | assert again["status"] == 200 and again.get("payment_id"), again |
| 208 | assert net_received(site) == 6000 |
| 209 | |
| 210 | |
| 211 | def test_threads_mixing_hooked_and_storage_level_payments_never_overpay(tmp_path, monkeypatch): |
| 212 | """Six hooked writers (hook, barrier, write) and six storage-level |
| 213 | writers (barrier, write) each pay 3000 on one 10000 invoice. Every hook |
| 214 | answered on an empty ledger. |
| 215 | |
| 216 | Before: exactly one hooked payment landed (the sequence) and all six |
| 217 | storage-level ones did: 21000 received against 10000.""" |
| 218 | site = payments_site(tmp_path, monkeypatch) |
| 219 | hook = load_hook("payments") |
| 220 | writers = 12 |
| 221 | go = threading.Barrier(writers) |
| 222 | outcomes = [] |
| 223 | |
| 224 | def hooked(n): |
| 225 | record = {"id": f"h{n}", "invoice_id": "inv1", "amount_cents": "3000", |
| 226 | "received_on": "2026-07-24", "status": "received", "owner_id": "ann"} |
| 227 | verdict = hook_create(hook, "payments", record) or {} |
| 228 | go.wait(timeout=30) |
| 229 | if verdict.get("error"): |
| 230 | return "refused by the hook" |
| 231 | try: |
| 232 | object_records.create_collection_record("payments", verdict.get("record", record), |
| 233 | base_dir=site.data, actor="ann") |
| 234 | except Exception: # noqa: BLE001 |
| 235 | return "refused" |
| 236 | return "landed" |
| 237 | |
| 238 | def below(n): |
| 239 | go.wait(timeout=30) |
| 240 | return storage_payment(site, f"s{n}", 3000) |
| 241 | |
| 242 | threads = [threading.Thread(target=lambda n=n: outcomes.append((hooked if n % 2 else below)(n))) |
| 243 | for n in range(writers)] |
| 244 | for thread in threads: |
| 245 | thread.start() |
| 246 | for thread in threads: |
| 247 | thread.join(timeout=60) |
| 248 | |
| 249 | assert len(outcomes) == writers, outcomes |
| 250 | assert net_received(site) <= 10000, f"{net_received(site)} received against 10000" |
| 251 | assert outcomes.count("landed") == 3, outcomes # 3 x 3000 fits, a fourth does not |
| 252 | |
| 253 | |
| 254 | _MIXED_PAYER = """\ |
| 255 | import importlib.util, os, random, sys, time |
| 256 | from pathlib import Path |
| 257 | repo, data_dir, who, tries, barrier, mode = (sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4]), |
| 258 | Path(sys.argv[5]), sys.argv[6]) |
| 259 | sys.path.insert(0, repo) |
| 260 | os.environ["DBBASIC_DATA_DIR"] = data_dir |
| 261 | os.environ["DBBASIC_OBJECTS_DIR"] = sys.argv[7] |
| 262 | import object_records |
| 263 | spec = importlib.util.spec_from_file_location("payer_hook", Path(repo) / "packages/app-payments/objects/hook/payments.py") |
| 264 | hook = importlib.util.module_from_spec(spec) |
| 265 | spec.loader.exec_module(hook) |
| 266 | random.seed(who) |
| 267 | while not barrier.exists(): |
| 268 | time.sleep(0.001) |
| 269 | landed = 0 |
| 270 | for n in range(tries): |
| 271 | amount = random.choice((700, 1300, 2100)) |
| 272 | record = {"id": f"{who}-{n}", "invoice_id": "inv1", "amount_cents": str(amount), "method": "card", |
| 273 | "received_on": "2026-07-24", "status": "received", "owner_id": "ann"} |
| 274 | for retry in range(200): |
| 275 | if mode == "hooked": |
| 276 | verdict = hook.BEFORE_WRITE({"action": "create", "collection": "payments", "record": record, |
| 277 | "existing": None, "changes": record, |
| 278 | "subject": {"user_id": "ann", "roles": []}}) or {} |
| 279 | if verdict.get("error"): |
| 280 | break # over the ceiling as of this read |
| 281 | candidate = verdict.get("record", record) |
| 282 | else: |
| 283 | candidate = record # the webhook's shape: no hook at all |
| 284 | try: |
| 285 | object_records.create_collection_record("payments", candidate, base_dir=data_dir, actor=who) |
| 286 | landed += amount |
| 287 | break |
| 288 | except object_records.UniqueConstraintError: |
| 289 | continue # the ledger moved since our read: read again |
| 290 | except Exception: |
| 291 | break # refused for what it is |
| 292 | print(landed) |
| 293 | """ |
| 294 | |
| 295 | |
| 296 | def test_processes_mixing_hooked_and_storage_level_payments_never_overpay(tmp_path, monkeypatch): |
| 297 | """Three processes pay through the hook, three write like the webhook, |
| 298 | fifteen payments each against one 10000 invoice, no choreography. |
| 299 | |
| 300 | Before: 62500 received against 10000 (the storage-level writers were |
| 301 | never checked at all).""" |
| 302 | site = payments_site(tmp_path, monkeypatch) |
| 303 | script = tmp_path / "_mixed_payer.py" |
| 304 | script.write_text(_MIXED_PAYER) |
| 305 | barrier = tmp_path / "go" |
| 306 | running = [ |
| 307 | subprocess.Popen( |
| 308 | [sys.executable, str(script), str(REPO_ROOT), str(site.data), f"w{p}", "15", |
| 309 | str(barrier), "hooked" if p % 2 else "below", str(site.root)], |
| 310 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) |
| 311 | for p in range(6) |
| 312 | ] |
| 313 | time.sleep(0.5) |
| 314 | barrier.write_text("go") |
| 315 | claimed = 0 |
| 316 | for process in running: |
| 317 | out, err = process.communicate(timeout=180) |
| 318 | assert process.returncode == 0, err |
| 319 | claimed += int(out.strip()) |
| 320 | |
| 321 | object_records._RECORDS_CACHE.clear() |
| 322 | rows = site.rows("payments", invoice_id="inv1") |
| 323 | received = sum(int(row["amount_cents"]) for row in rows) |
| 324 | assert received == claimed, "a process believed a payment landed that is not on file" |
| 325 | assert received <= 10000, f"{received} received against a 10000 invoice" |
| 326 | assert len(rows) >= 5, f"only {len(rows)} payments landed: the race was not exercised" |
| 327 | if received < 10000: |
| 328 | assert storage_payment(site, "the-rest", 10000 - received) == "landed" |
| 329 | assert storage_payment(site, "one-more", 1) == "refused" |
| 330 | |
| 331 | |
| 332 | # --- the ceiling's inputs in other collections ---------------------------------------- |
| 333 | |
| 334 | |
| 335 | def test_an_invoice_line_lowered_while_a_payment_is_in_flight(tmp_path, monkeypatch): |
| 336 | """A 10000 invoice (one line). An HTTP payment of 10000 passes its hook; |
| 337 | before its write the line is cut to 4000 (and the total restamped). |
| 338 | |
| 339 | Before: the payment landed on an invoice worth 4000.""" |
| 340 | site = payments_site(tmp_path, monkeypatch) |
| 341 | |
| 342 | paid, cut = overlap(monkeypatch, "create_collection_record", "payments", |
| 343 | lambda: pay(site, "p1", 10000), |
| 344 | lambda: site.put("invoice_lines", "l1", "ann", {"unit_price_cents": "4000"})) |
| 345 | |
| 346 | must(cut[0] == 200, f"the line was not lowered: {cut}") |
| 347 | assert invoice_ceiling(site) == 4000 |
| 348 | assert net_received(site) <= 4000, f"{net_received(site)} received on an invoice worth 4000" |
| 349 | assert paid[0] == 409, paid |
| 350 | |
| 351 | |
| 352 | def test_an_invoice_line_lowered_while_a_storage_level_payment_is_in_flight(tmp_path, monkeypatch): |
| 353 | """The same with a writer that has no hook at all: the check runs where |
| 354 | the write lands, so what it sees is the invoice as it is then.""" |
| 355 | site = payments_site(tmp_path, monkeypatch) |
| 356 | ok(site.put("invoice_lines", "l1", "ann", {"unit_price_cents": "4000"}), "line lowered") |
| 357 | |
| 358 | assert storage_payment(site, "s1", 10000) == "refused" |
| 359 | assert storage_payment(site, "s2", 4000) == "landed" |
| 360 | assert net_received(site) == 4000 |
| 361 | |
| 362 | |
| 363 | def test_a_payment_bounced_while_a_refund_of_it_is_in_flight(tmp_path, monkeypatch): |
| 364 | """A 10000 payment. A refund of 3000 passes its hook; before its write |
| 365 | the payment is bounced (what resolve_bank_line's nsf does: a storage |
| 366 | update of status). |
| 367 | |
| 368 | Before: the refund landed against a bounced payment -- money sent back |
| 369 | that never arrived.""" |
| 370 | site = payments_site(tmp_path, monkeypatch) |
| 371 | ok(pay(site, "p1", 10000), "payment") |
| 372 | |
| 373 | def bounce(): |
| 374 | return object_records.update_collection_record( |
| 375 | "payments", "p1", {"status": "bounced"}, base_dir=site.data, actor="action_resolve_bank_line") |
| 376 | |
| 377 | refunded, _ = overlap(monkeypatch, "create_collection_record", "refunds", |
| 378 | lambda: refund(site, "r1", "p1", 3000), bounce) |
| 379 | |
| 380 | assert site.get("payments", "p1")["status"] == "bounced" |
| 381 | assert refunded_against(site, "p1") == 0, "a bounced payment was refunded" |
| 382 | assert refunded[0] == 409, refunded |
| 383 | |
| 384 | |
| 385 | def test_a_refund_written_below_the_hook_inside_an_http_refund(tmp_path, monkeypatch): |
| 386 | """A 10000 payment. An HTTP refund of 6000 passes its hook; before its |
| 387 | write a storage-level refund of 6000 (no hook, so no number) lands. |
| 388 | |
| 389 | Before: both landed, 12000 refunded on 10000.""" |
| 390 | site = payments_site(tmp_path, monkeypatch) |
| 391 | ok(pay(site, "p1", 10000), "payment") |
| 392 | |
| 393 | def below(): |
| 394 | try: |
| 395 | object_records.create_collection_record( |
| 396 | "refunds", {"id": "r-below", "payment_id": "p1", "invoice_id": "inv1", |
| 397 | "amount_cents": "6000", "refunded_on": "2026-07-25", "owner_id": "ann"}, |
| 398 | base_dir=site.data, actor="some_action") |
| 399 | except Exception: # noqa: BLE001 |
| 400 | return "refused" |
| 401 | return "landed" |
| 402 | |
| 403 | http, storage = overlap(monkeypatch, "create_collection_record", "refunds", |
| 404 | lambda: refund(site, "r-http", "p1", 6000), below) |
| 405 | |
| 406 | assert storage == "landed" |
| 407 | assert refunded_against(site, "p1") <= 10000, f"{refunded_against(site, 'p1')} refunded on 10000" |
| 408 | assert http[0] == 409, http |
| 409 | |
| 410 | |
| 411 | def test_a_storage_level_refund_cannot_exceed_its_payment_or_name_another_invoice( |
| 412 | tmp_path, monkeypatch): |
| 413 | site = payments_site(tmp_path, monkeypatch) |
| 414 | ok(pay(site, "p1", 10000), "payment") |
| 415 | |
| 416 | def write(refund_id, amount, invoice_id="inv1"): |
| 417 | try: |
| 418 | object_records.create_collection_record( |
| 419 | "refunds", {"id": refund_id, "payment_id": "p1", "invoice_id": invoice_id, |
| 420 | "amount_cents": str(amount), "refunded_on": "2026-07-25", |
| 421 | "owner_id": "ann"}, |
| 422 | base_dir=site.data, actor="some_action") |
| 423 | except Exception: # noqa: BLE001 |
| 424 | return "refused" |
| 425 | return "landed" |
| 426 | |
| 427 | assert write("r1", 12000) == "refused" |
| 428 | assert write("r2", 100, invoice_id="") == "refused" # the payment's invoice, or nothing |
| 429 | assert write("r3", 10000) == "landed" |
| 430 | assert write("r4", 1) == "refused" |
| 431 | assert refunded_against(site, "p1") == 10000 |
| 432 | |
| 433 | |
| 434 | # --- an admin's edit or delete, overlapping another writer ---------------------------- |
| 435 | |
| 436 | |
| 437 | def test_an_admin_raising_a_payment_while_another_payment_lands(tmp_path, monkeypatch): |
| 438 | """p1 is 4000 on a 10000 invoice. An admin raises it to 9000 (the hook |
| 439 | allows it: 9000 fits once p1's own 4000 is excluded); before the write, |
| 440 | another payment of 5000 lands (it fits beside 4000). |
| 441 | |
| 442 | Before: both landed, 14000 received -- an edit kept its old number, so |
| 443 | nothing serialized it.""" |
| 444 | site = payments_site(tmp_path, monkeypatch) |
| 445 | ok(pay(site, "p1", 4000), "p1") |
| 446 | |
| 447 | edit, other = overlap(monkeypatch, "update_collection_record", "payments", |
| 448 | lambda: site.put("payments", "p1", "admin", {"amount_cents": "9000"}), |
| 449 | lambda: pay(site, "p2", 5000)) |
| 450 | |
| 451 | must(other[0] in (200, 201), f"p2 did not land: {other}") |
| 452 | assert net_received(site) <= 10000, f"{net_received(site)} received against 10000" |
| 453 | assert edit[0] == 409, edit |
| 454 | assert site.get("payments", "p1")["amount_cents"] == "4000" |
| 455 | |
| 456 | |
| 457 | def test_an_admin_deleting_a_payment_while_a_refund_of_it_lands(tmp_path, monkeypatch): |
| 458 | """The hook refuses to delete a payment that has refunds. An admin's |
| 459 | delete passes it (none yet); before the delete, a refund lands. |
| 460 | |
| 461 | Before: the payment was deleted from under its refund.""" |
| 462 | site = payments_site(tmp_path, monkeypatch) |
| 463 | ok(pay(site, "p1", 5000), "p1") |
| 464 | |
| 465 | deleted, refunded = overlap(monkeypatch, "delete_collection_record", "payments", |
| 466 | lambda: site.delete("payments", "p1", "admin"), |
| 467 | lambda: refund(site, "r1", "p1", 2000)) |
| 468 | |
| 469 | must(refunded[0] in (200, 201), f"the refund did not land: {refunded}") |
| 470 | assert site.exists("payments", "p1"), "a refunded payment was deleted from under its refund" |
| 471 | assert deleted[0] == 409, deleted |
| 472 | |
| 473 | |
| 474 | def test_an_admin_lowering_a_payment_while_a_refund_of_it_lands(tmp_path, monkeypatch): |
| 475 | """p1 is 5000. An admin lowers it to 3000 (nothing refunded yet, so the |
| 476 | hook allows it); before the write a refund of 4000 lands. |
| 477 | |
| 478 | Before: 4000 refunded against a 3000 payment.""" |
| 479 | site = payments_site(tmp_path, monkeypatch) |
| 480 | ok(pay(site, "p1", 5000), "p1") |
| 481 | |
| 482 | edit, refunded = overlap(monkeypatch, "update_collection_record", "payments", |
| 483 | lambda: site.put("payments", "p1", "admin", {"amount_cents": "3000"}), |
| 484 | lambda: refund(site, "r1", "p1", 4000)) |
| 485 | |
| 486 | must(refunded[0] in (200, 201), f"the refund did not land: {refunded}") |
| 487 | paid = int(site.get("payments", "p1")["amount_cents"]) |
| 488 | assert refunded_against(site, "p1") <= paid, f"{refunded_against(site, 'p1')} refunded on {paid}" |
| 489 | assert edit[0] == 409, edit |
| 490 | |
| 491 | |
| 492 | # --- checkout's gift-card payment, and a check that cannot read ----------------------- |
| 493 | |
| 494 | |
| 495 | def test_a_gift_card_payment_that_no_longer_fits_is_refused_and_the_card_is_given_back( |
| 496 | tmp_path, monkeypatch): |
| 497 | """checkout raises the invoice, debits the card, then records the card's |
| 498 | payment at the storage level. Here, between the debit and that write, |
| 499 | the whole bill is paid by another door (a storage-level payment of the |
| 500 | full total), so the card's payment would take the invoice past it. |
| 501 | |
| 502 | Before: it landed (14000 received on an 11000 invoice) and the card |
| 503 | stayed debited. Now it is refused where it lands, and checkout's own |
| 504 | compensation gives the card its money back.""" |
| 505 | import test_promotions as shop |
| 506 | |
| 507 | data_dir, objects_root = shop.setup_env(tmp_path, monkeypatch, settings=shop.TAXED) |
| 508 | shop.basket_of(objects_root, data_dir) |
| 509 | shop.wallet(data_dir) |
| 510 | shop.credit(data_dir, "gc1", 3000) |
| 511 | |
| 512 | def the_whole_bill_paid_elsewhere(): |
| 513 | (invoice,) = object_records.read_collection_records("invoices", base_dir=data_dir) |
| 514 | object_records.create_collection_record( |
| 515 | "payments", {"id": "p-elsewhere", "invoice_id": invoice["id"], |
| 516 | "amount_cents": invoice["total_cents"], "method": "card", |
| 517 | "received_on": shop.TODAY, "status": "received", |
| 518 | "owner_id": invoice.get("owner_id", "")}, |
| 519 | base_dir=data_dir, actor="webhook_stripe") |
| 520 | return invoice |
| 521 | |
| 522 | placed, invoice = overlap(monkeypatch, "create_collection_record", "payments", |
| 523 | lambda: shop.checkout(objects_root, customer_email="ada@example.com", |
| 524 | gift_card_code="GC-TEST"), |
| 525 | the_whole_bill_paid_elsewhere) |
| 526 | |
| 527 | received = sum(int(row["amount_cents"]) for row in shop.rows(data_dir, "payments") |
| 528 | if row["invoice_id"] == invoice["id"]) |
| 529 | assert received <= int(invoice["total_cents"]), f"{received} on {invoice['total_cents']}" |
| 530 | assert placed["gift_card_applied_cents"] == 0, placed |
| 531 | assert "reversed" in placed["gift_card_error"], placed |
| 532 | assert object_records.get_collection_record( |
| 533 | "wallets", "gc1", base_dir=data_dir)["balance_minor"] == "3000" |
| 534 | |
| 535 | |
| 536 | def test_the_locked_check_fails_closed_when_it_cannot_read(tmp_path, monkeypatch): |
| 537 | """The check's own read of the ledger fails: the write is refused |
| 538 | (503, retry), never let through as "nothing received yet".""" |
| 539 | site = payments_site(tmp_path, monkeypatch) |
| 540 | real = object_records.read_collection_records_where |
| 541 | |
| 542 | def failing(collection, *args, **kwargs): |
| 543 | if collection == "payments": |
| 544 | raise OSError("simulated: payments is unreadable") |
| 545 | return real(collection, *args, **kwargs) |
| 546 | |
| 547 | monkeypatch.setattr(object_records, "read_collection_records_where", failing) |
| 548 | outcome = storage_payment(site, "s1", 100) |
| 549 | try: |
| 550 | storage_payment_error = None |
| 551 | object_records.create_collection_record( |
| 552 | "payments", {"id": "s2", "invoice_id": "inv1", "amount_cents": "100", |
| 553 | "method": "card", "received_on": "2026-07-24", "owner_id": "ann"}, |
| 554 | base_dir=site.data, actor="webhook_stripe") |
| 555 | except Exception as exc: # noqa: BLE001 |
| 556 | storage_payment_error = exc |
| 557 | monkeypatch.setattr(object_records, "read_collection_records_where", real) |
| 558 | |
| 559 | assert outcome == "refused" |
| 560 | assert site.rows("payments") == [], "a payment landed on a ledger nobody could read" |
| 561 | assert getattr(storage_payment_error, "status", None) == 503, storage_payment_error |
| 562 | assert getattr(storage_payment_error, "code", None) == "check_unavailable" |