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_money_gates_ceiling_races.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, 19 minutes ago History
test_money_gates_ceiling_races.py · 20.9 KB · 446 lines
1"""Two payments at once, two refunds at once: the ceilings hold under
2overlap.
3
4A pre-write hook runs before the write lock (AGENTS.md: "hooks cannot
5close a race"). hook_payments and hook_refunds each check a SUM -- received
6against the invoice, refunded against the payment -- so two requests
7submitted together each summed a ledger that did not contain the other,
8both passed, and together went over. `unique` cannot express a sum.
9
10v3 of the schemas closed that for hooked writers with a per-parent
11sequence (payments.invoice_seq, refunds.payment_seq) declared unique. v4
12closes it for every writer with a schema `locked_checks` entry:
13object_records calls hook_payments.LOCKED_CHECK / hook_refunds.LOCKED_CHECK
14inside the write lock, holding the "ledger" check lock that every write to
15payments, refunds, invoices, invoice_lines and app_settings takes. The
16sequence columns are retired (kept, blank, unconstrained). What v3 did not
17cover -- writers below the hook, admin edits, inputs in other collections
18-- is in tests/test_money_gates_locked_ceilings.py.
19
20Three kinds of evidence, because each alone would be weak:
21
22 * the deterministic overlap through the real HTTP path (request B runs
23 start to finish between A's hook and A's persist) -- the exact window;
24 * real threads, all through the hook on one snapshot before any of them
25 writes -- the worst case, where without a check in the lock every one
26 lands;
27 * separate processes hammering one invoice with no choreography at all
28 -- the shape of a worker pool -- where the only claim is the invariant.
29
30Each was run with no check in the lock (before v3) and seen to fail: both
31payments of the overlap landed, all twelve threads landed, and the six
32processes left 14300 received against the 10000 invoice.
33"""
34
35import importlib.util
36import json
37import subprocess
38import sys
39import threading
40import time
41
42import pytest
43
44import object_records
45from test_findings_money_gates import ( # noqa: F401 (fresh_handler_index is autouse)
46 PACKAGES, REPO_ROOT, fresh_handler_index, must, net_received, ok, overlap_two_creates, pay,
47 payments_site, refund,
48)
49
50
51# --- the schema ------------------------------------------------------------------
52
53
54def test_the_ceilings_are_locked_checks_and_the_sequences_are_retired():
55 payments = json.loads((PACKAGES / "app-payments" / "schemas" / "payments.json").read_text())
56 refunds = json.loads((PACKAGES / "app-payments" / "schemas" / "refunds.json").read_text())
57
58 (overpayment,) = payments["locked_checks"]
59 assert (overpayment["object"], overpayment["function"], overpayment["lock"]) == (
60 "hook_payments", "LOCKED_CHECK", "ledger")
61 # invoice_credits since payments v7: a credit note cancels debt, so the
62 # ceiling subtracts it, under the same lock.
63 assert sorted(overpayment["reads"]) == ["app_settings", "invoice_credits", "invoice_lines",
64 "invoices", "refunds"]
65 (refundable,) = refunds["locked_checks"]
66 assert (refundable["object"], refundable["function"], refundable["lock"]) == (
67 "hook_refunds", "LOCKED_CHECK", "ledger")
68 # payments for the headroom; the rest since refunds v6 for the line a
69 # refund cites (on the bill's order, never more than was sold).
70 assert refundable["reads"] == ["payments", "order_lines", "orders", "invoices",
71 "invoice_lines", "goodwill"]
72 # The v3 sequence columns stay (no data dropped); nothing constrains them.
73 for schema, name in ((payments, "invoice_seq"), (refunds, "payment_seq")):
74 assert "unique" not in schema
75 (field,) = [f for f in schema["fields"] if f["name"] == name]
76 assert field["type"] == "integer"
77 assert name not in schema["forms"]["default"]["fields"]
78
79
80# --- payments: the exact window, over HTTP ----------------------------------------
81
82
83def test_two_overlapping_payments_cannot_together_pass_the_ceiling(tmp_path, monkeypatch):
84 """A 10000 invoice. Request A (6000) passes its hook; before A's
85 persist, request B (6000) runs start to finish; then A persists.
86
87 With nothing in the lock: both 201, 12000 received against 10000. Now
88 B lands and A is refused inside the lock, by the ceiling itself,
89 measured against the ledger B is already in."""
90 site = payments_site(tmp_path, monkeypatch)
91
92 first, second = overlap_two_creates(monkeypatch, "payments",
93 lambda: pay(site, "p1", 6000),
94 lambda: pay(site, "p2", 6000))
95
96 assert second[0] in (200, 201), second
97 assert first[0] == 409 and first[1]["code"] == "check_refused", first
98 assert first[1]["check"] == "overpayment"
99 assert "remaining balance of 4000" in first[1]["error"]
100 assert net_received(site) == 6000
101 assert [row["id"] for row in site.rows("payments")] == ["p2"]
102
103
104def test_the_refused_payment_is_refused_the_same_way_when_it_is_tried_again(
105 tmp_path, monkeypatch):
106 """Tried again, A gets the same sentence from the lock (the hook no
107 longer answers early) and what is actually still owed fits."""
108 site = payments_site(tmp_path, monkeypatch)
109 overlap_two_creates(monkeypatch, "payments",
110 lambda: pay(site, "p1", 6000), lambda: pay(site, "p2", 6000))
111
112 status, body = pay(site, "p1", 6000)
113 assert status == 409 and body["code"] == "check_refused", body
114 assert "remaining balance of 4000" in body["error"]
115 ok(pay(site, "p3", 4000), "what is actually still owed")
116
117 assert net_received(site) == 10000
118
119
120def test_two_overlapping_payments_that_both_fit_both_land(tmp_path, monkeypatch):
121 """v3's cost is gone: the sequence refused the loser of an overlap even
122 when both fitted, because nothing had checked it against the ledger it
123 would land on. The locked check does exactly that, so both land."""
124 site = payments_site(tmp_path, monkeypatch)
125
126 first, second = overlap_two_creates(monkeypatch, "payments",
127 lambda: pay(site, "p1", 3000),
128 lambda: pay(site, "p2", 3000))
129
130 assert first[0] in (200, 201) and second[0] in (200, 201), (first, second)
131 assert net_received(site) == 6000
132
133
134def test_overlapping_payments_on_different_invoices_do_not_get_in_each_others_way(
135 tmp_path, monkeypatch):
136 """Payments on two invoices both land. (They do wait for each other --
137 the ledger lock is one lock, not one per invoice -- for the length of
138 one check and one append.)"""
139 site = payments_site(tmp_path, monkeypatch)
140 object_records.create_collection_record(
141 "invoices", {"id": "inv2", "number": "INV-2", "customer_name": "Other",
142 "total_cents": "5000", "owner_id": "ann"},
143 base_dir=site.data, actor="billing_runner")
144
145 first, second = overlap_two_creates(monkeypatch, "payments",
146 lambda: pay(site, "p1", 6000),
147 lambda: pay(site, "p2", 5000, invoice_id="inv2"))
148
149 assert first[0] in (200, 201) and second[0] in (200, 201), (first, second)
150
151
152def test_a_client_cannot_put_a_number_in_the_retired_sequence(tmp_path, monkeypatch):
153 """A value in the retired column would only look meaningful. On create
154 the hook blanks it; after that it is frozen like the rest of the
155 payment, for an admin too."""
156 site = payments_site(tmp_path, monkeypatch)
157
158 created = ok(site.post("payments", "ann", {
159 "id": "p1", "invoice_id": "inv1", "amount_cents": "1000", "received_on": "2026-07-24",
160 "invoice_seq": "999"}), "payment with a typed sequence")
161 assert created["invoice_seq"] == ""
162
163 for who in ("ann", "admin"):
164 status, body = site.put("payments", "p1", who, {"invoice_seq": "7"})
165 assert status == 409 and body["code"] == "hook_rejected", (who, body)
166 assert site.get("payments", "p1")["invoice_seq"] == ""
167
168
169def test_under_the_allow_policy_overlapping_payments_both_land(tmp_path, monkeypatch):
170 """payments.overpayment_policy=allow means no ceiling: two payments at
171 once do not refuse each other, and neither does a trusted writer."""
172 site = payments_site(tmp_path, monkeypatch)
173 ok(site.post("app_settings", "admin", {"id": "s1", "key": "payments.overpayment_policy",
174 "value": "allow"}), "policy")
175
176 first, second = overlap_two_creates(
177 monkeypatch, "payments",
178 lambda: site.post("payments", "ann", {"id": "p1", "invoice_id": "inv1",
179 "amount_cents": "9000", "received_on": "2026-07-24",
180 "invoice_seq": "5"}),
181 lambda: pay(site, "p2", 9000))
182 assert first[0] in (200, 201) and second[0] in (200, 201), (first, second)
183
184 object_records.create_collection_record(
185 "payments", {"id": "p-stripe", "invoice_id": "inv1", "amount_cents": "100",
186 "method": "card", "received_on": "2026-07-24", "owner_id": "ann"},
187 base_dir=site.data, actor="webhook_stripe")
188 assert [row["invoice_seq"] for row in site.rows("payments")] == ["", "", ""]
189 assert net_received(site) == 18100
190
191
192def test_an_admin_moving_a_payment_is_checked_against_the_invoice_it_joins(
193 tmp_path, monkeypatch):
194 """Moving a payment adds it to another invoice, and that invoice's
195 ceiling decides -- in the lock, as for a new payment there."""
196 site = payments_site(tmp_path, monkeypatch)
197 object_records.create_collection_record(
198 "invoices", {"id": "inv2", "number": "INV-2", "customer_name": "Other",
199 "total_cents": "9000", "owner_id": "ann"},
200 base_dir=site.data, actor="billing_runner")
201 ok(pay(site, "p1", 1000), "first on inv1")
202 ok(pay(site, "p2", 2000), "second on inv1")
203 ok(pay(site, "q1", 3000, invoice_id="inv2"), "first on inv2")
204 ok(pay(site, "q2", 3000, invoice_id="inv2"), "second on inv2")
205
206 ok(site.put("payments", "p2", "admin", {"invoice_id": "inv2"}), "admin moves p2 to inv2")
207 assert net_received(site, "inv2") == 8000
208
209 with pytest.raises(object_records.CheckRefusedError) as refused:
210 object_records.update_collection_record(
211 "payments", "p2", {"amount_cents": "4000"}, base_dir=site.data, actor="admin")
212 assert "remaining balance of 3000" in str(refused.value) # 9000 less the other two
213 ok(pay(site, "p3", 500), "inv1 carries on")
214 assert net_received(site, "inv2") == 8000 and net_received(site, "inv1") == 1500
215
216
217# --- refunds: the exact window, over HTTP ------------------------------------------
218
219
220def test_two_overlapping_refunds_cannot_together_exceed_the_payment(tmp_path, monkeypatch):
221 """A 10000 payment. Two refunds of 6000 overlap.
222
223 With nothing in the lock: both 201, 12000 refunded against 10000."""
224 site = payments_site(tmp_path, monkeypatch)
225 ok(pay(site, "p1", 10000), "payment")
226
227 first, second = overlap_two_creates(monkeypatch, "refunds",
228 lambda: refund(site, "r1", "p1", 6000),
229 lambda: refund(site, "r2", "p1", 6000))
230
231 assert second[0] in (200, 201), second
232 assert first[0] == 409 and first[1]["code"] == "check_refused", first
233 assert first[1]["check"] == "refundable"
234 assert "exceeds the refundable 4000" in first[1]["error"]
235 refunded = sum(int(row["amount_cents"]) for row in site.rows("refunds", payment_id="p1"))
236 assert refunded == 6000
237
238 status, body = refund(site, "r1", "p1", 6000)
239 assert status == 409 and "exceeds the refundable 4000" in body["error"], body
240 ok(refund(site, "r3", "p1", 4000), "what is actually left")
241
242
243def test_the_actions_refund_is_checked_where_it_lands(tmp_path, monkeypatch):
244 """action_resolve_dispute and action_disposition_return call the hook
245 with action "create" and write its record at the storage level. The
246 locked check meets that write too: here the action asked the hook
247 first, an HTTP refund landed, and the action's write is refused."""
248 site = payments_site(tmp_path, monkeypatch)
249 ok(pay(site, "p1", 10000), "payment")
250 hook = load_hook("refunds")
251 candidate = {"id": "r-action", "payment_id": "p1", "amount_cents": "6000",
252 "refunded_on": "2026-07-25", "owner_id": "ann"}
253
254 verdict = hook.BEFORE_WRITE({"action": "create", "collection": "refunds", "record": candidate})
255 must(verdict["record"]["invoice_id"] == "inv1", f"the hook did not stamp: {verdict}")
256 ok(refund(site, "r-http", "p1", 6000), "an HTTP refund lands in between")
257
258 with pytest.raises(object_records.CheckRefusedError):
259 object_records.create_collection_record("refunds", verdict["record"],
260 base_dir=site.data, actor="action_resolve_dispute")
261 assert [row["id"] for row in site.rows("refunds")] == ["r-http"]
262
263
264def test_an_admin_repointing_a_refund_is_checked_against_the_payment_it_joins(
265 tmp_path, monkeypatch):
266 site = payments_site(tmp_path, monkeypatch)
267 ok(pay(site, "p1", 5000), "payment one")
268 ok(pay(site, "p2", 5000), "payment two")
269 ok(refund(site, "a1", "p1", 100), "refund of p1")
270 ok(refund(site, "b1", "p2", 4800), "refund of p2")
271
272 ok(site.put("refunds", "a1", "admin", {"payment_id": "p2"}), "admin re-points a1 at p2")
273 assert site.get("refunds", "a1")["invoice_id"] == "inv1"
274
275 with pytest.raises(object_records.CheckRefusedError) as refused:
276 object_records.update_collection_record(
277 "refunds", "a1", {"amount_cents": "300"}, base_dir=site.data, actor="admin")
278 assert "exceeds the refundable 200" in str(refused.value)
279 status, body = site.put("refunds", "a1", "admin", {"payment_seq": "9"})
280 assert status == 409 and body["code"] == "hook_rejected", body
281
282
283# --- real threads: every hook on one snapshot, then every write --------------------
284
285
286def load_hook(name):
287 path = PACKAGES / "app-payments" / "objects" / "hook" / f"{name}.py"
288 spec = importlib.util.spec_from_file_location(f"race_hook_{name}", path)
289 module = importlib.util.module_from_spec(spec)
290 spec.loader.exec_module(module)
291 return module
292
293
294def race(writers, attempt):
295 """Run `attempt(n, hooks_done)` on `writers` threads. Each calls
296 hooks_done.wait() between its hook and its write, so every hook has
297 answered -- on a ledger with none of the others in it -- before any
298 write happens. That is the worst case for a look-before-write check."""
299 hooks_done = threading.Barrier(writers)
300 outcomes = []
301
302 def run(n):
303 try:
304 outcomes.append(attempt(n, hooks_done))
305 except threading.BrokenBarrierError:
306 outcomes.append("barrier broke")
307
308 threads = [threading.Thread(target=run, args=(n,)) for n in range(writers)]
309 for thread in threads:
310 thread.start()
311 for thread in threads:
312 thread.join(timeout=60)
313 return outcomes
314
315
316def test_twelve_payments_checked_on_one_snapshot_land_only_what_fits(tmp_path, monkeypatch):
317 """Twelve writers each pay 3000 on a 10000 invoice. All twelve hooks run
318 before any write, so each sees nothing received and passes -- which is
319 correct for each alone. With nothing in the lock all twelve land: 36000
320 on a 10000 invoice. With the locked check, exactly the three that fit
321 land and nine are refused where they would have landed."""
322 site = payments_site(tmp_path, monkeypatch)
323 hook = load_hook("payments")
324
325 def attempt(n, hooks_done):
326 record = {"id": f"p{n}", "invoice_id": "inv1", "amount_cents": "3000",
327 "received_on": "2026-07-24", "status": "received", "owner_id": "ann"}
328 verdict = hook.BEFORE_WRITE({"action": "create", "collection": "payments",
329 "record": record, "existing": None, "changes": record,
330 "subject": {"user_id": "ann", "roles": []}}) or {}
331 hooks_done.wait(timeout=30)
332 if verdict.get("error"):
333 return "refused by the hook"
334 try:
335 object_records.create_collection_record("payments", verdict.get("record", record),
336 base_dir=site.data, actor="ann")
337 except object_records.CheckRefusedError:
338 return "refused in the lock"
339 return "landed"
340
341 outcomes = race(12, attempt)
342
343 assert sorted(outcomes) == ["landed"] * 3 + ["refused in the lock"] * 9
344 assert net_received(site) == 9000
345
346
347def test_twelve_refunds_checked_on_one_snapshot_land_only_what_fits(tmp_path, monkeypatch):
348 site = payments_site(tmp_path, monkeypatch)
349 ok(pay(site, "p1", 10000), "payment")
350 hook = load_hook("refunds")
351
352 def attempt(n, hooks_done):
353 record = {"id": f"r{n}", "payment_id": "p1", "amount_cents": "3000",
354 "refunded_on": "2026-07-25", "owner_id": "ann"}
355 verdict = hook.BEFORE_WRITE({"action": "create", "collection": "refunds",
356 "record": record, "existing": None, "changes": record,
357 "subject": {"user_id": "ann", "roles": []}}) or {}
358 hooks_done.wait(timeout=30)
359 if verdict.get("error"):
360 return "refused by the hook"
361 try:
362 object_records.create_collection_record("refunds", verdict.get("record", record),
363 base_dir=site.data, actor="ann")
364 except object_records.CheckRefusedError:
365 return "refused in the lock"
366 return "landed"
367
368 outcomes = race(12, attempt)
369
370 assert sorted(outcomes) == ["landed"] * 3 + ["refused in the lock"] * 9
371 assert sum(int(row["amount_cents"]) for row in site.rows("refunds")) == 9000
372
373
374# --- separate processes, no choreography --------------------------------------------
375
376_PAYER = """\
377import importlib.util, os, random, sys, time
378from pathlib import Path
379repo, data_dir, who, tries, barrier = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4]), Path(sys.argv[5])
380sys.path.insert(0, repo)
381os.environ["DBBASIC_DATA_DIR"] = data_dir
382os.environ["DBBASIC_OBJECTS_DIR"] = sys.argv[6]
383import object_records
384spec = importlib.util.spec_from_file_location("payer_hook", Path(repo) / "packages/app-payments/objects/hook/payments.py")
385hook = importlib.util.module_from_spec(spec)
386spec.loader.exec_module(hook)
387random.seed(who)
388while not barrier.exists():
389 time.sleep(0.001)
390landed = 0
391for n in range(tries):
392 amount = random.choice((700, 1300, 2100))
393 record = {"id": f"{who}-{n}", "invoice_id": "inv1", "amount_cents": str(amount),
394 "received_on": "2026-07-24", "status": "received", "owner_id": "ann"}
395 verdict = hook.BEFORE_WRITE({"action": "create", "collection": "payments", "record": record,
396 "existing": None, "changes": record,
397 "subject": {"user_id": "ann", "roles": []}}) or {}
398 if verdict.get("error"):
399 continue # over the ceiling as of this read
400 try:
401 object_records.create_collection_record("payments", verdict.get("record", record),
402 base_dir=data_dir, actor=who)
403 landed += amount
404 except object_records.CheckRefusedError:
405 continue # over the ceiling as it is where it would land
406print(landed)
407"""
408
409
410def test_processes_hammering_one_invoice_never_take_it_past_its_total(tmp_path, monkeypatch):
411 """Separate interpreters, cold caches, nothing shared but the files: six
412 processes each try fifteen payments of 700/1300/2100 against one 10000
413 invoice. Far more is offered than is owed. Whatever the interleaving,
414 the ledger must end at or under 10000 -- and must still be RIGHT about
415 what is left: exactly the remaining balance is accepted afterwards, and
416 one cent more is not."""
417 site = payments_site(tmp_path, monkeypatch)
418 script = tmp_path / "_payer.py"
419 script.write_text(_PAYER)
420 barrier = tmp_path / "go"
421 running = [
422 subprocess.Popen(
423 [sys.executable, str(script), str(REPO_ROOT), str(site.data), f"w{p}", "15", str(barrier),
424 str(site.root)],
425 stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
426 for p in range(6)
427 ]
428 time.sleep(0.5) # let every interpreter reach its wait
429 barrier.write_text("go")
430 claimed = 0
431 for process in running:
432 out, err = process.communicate(timeout=180)
433 assert process.returncode == 0, err
434 claimed += int(out.strip())
435
436 object_records._RECORDS_CACHE.clear()
437 rows = site.rows("payments", invoice_id="inv1")
438 received = sum(int(row["amount_cents"]) for row in rows)
439 assert received == claimed, "a process believed a payment landed that is not on file"
440 assert received <= 10000, f"{received} received against a 10000 invoice"
441 assert len(rows) >= 5, f"only {len(rows)} payments landed: the race was not exercised"
442
443 if received < 10000:
444 ok(pay(site, "the-rest", 10000 - received), "exactly what is left")
445 status, body = pay(site, "one-more", 1)
446 assert status == 409 and "remaining balance of 0 cents" in body["error"], body