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_commerce_action_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_commerce_action_races.py · 13.3 KB · 304 lines
1"""The commerce-action races of 2026-11-28, raced for real.
2
3tests/test_findings_actions.py reproduces each race deterministically by
4running the second request INSIDE a patched write of the first. That pins
5the interleaving the fix has to survive, but it is one interleaving. Here
6the same actions are run from several threads released together by a
7barrier, against one data directory, repeated a few rounds; where the
8natural window is too narrow to hit reliably, it is widened with a short
9sleep at the exact point the old code was exposed (between its read and its
10write), which is called out where it is done. Every test here was run
11against the unfixed action and failed.
12
13NO NETWORK. The Stripe-shaped calls are stubbed, and an autouse fixture
14replaces socket.connect and urllib's opener so that anything that tried to
15leave the machine fails the test instead of reaching a provider.
16"""
17
18from __future__ import annotations
19
20import socket
21import threading
22import time
23import urllib.request
24
25import pytest
26
27import object_execution
28import object_records
29import object_stripe
30import test_findings_actions as tfa
31import test_findings_money_gates as tmg
32
33ROUNDS = 3
34
35
36@pytest.fixture(autouse=True)
37def no_network(monkeypatch):
38 def refuse(*args, **kwargs):
39 raise AssertionError("a test in this file tried to reach the network")
40
41 monkeypatch.setattr(socket.socket, "connect", refuse)
42 monkeypatch.setattr(socket.socket, "connect_ex", refuse)
43 monkeypatch.setattr(socket, "create_connection", refuse)
44 monkeypatch.setattr(urllib.request, "urlopen", refuse)
45 monkeypatch.setattr(urllib.request.OpenerDirector, "open", refuse)
46
47
48def race(n, fn):
49 """Run fn(i) on n threads released together; return results by index.
50 An exception in a thread is re-raised here, not lost."""
51 barrier = threading.Barrier(n)
52 results = [None] * n
53 errors = []
54
55 def worker(i):
56 try:
57 barrier.wait(timeout=10)
58 results[i] = fn(i)
59 except BaseException as exc: # noqa: BLE001
60 errors.append(exc)
61
62 threads = [threading.Thread(target=worker, args=(i,)) for i in range(n)]
63 for thread in threads:
64 thread.start()
65 for thread in threads:
66 thread.join(timeout=60)
67 assert not any(t.is_alive() for t in threads), "a racing thread hung"
68 if errors:
69 raise errors[0]
70 return results
71
72
73def widen(monkeypatch, collection, seconds=0.05, fn_name="read_collection_records"):
74 """Sleep after every read of `collection`: the gap between a writer's
75 read and its write is where these races lived."""
76 real = getattr(object_records, fn_name)
77
78 def slow(coll, *args, **kwargs):
79 rows = real(coll, *args, **kwargs)
80 if coll == collection:
81 time.sleep(seconds)
82 return rows
83
84 monkeypatch.setattr(object_records, fn_name, slow)
85
86
87# --- checkout -------------------------------------------------------------------
88
89@pytest.mark.parametrize("round_", range(ROUNDS))
90def test_racing_submits_of_one_cart_raise_exactly_one_order(tmp_path, monkeypatch, round_):
91 data_dir, root = tfa.shop(tmp_path, monkeypatch)
92 tfa.add_to_cart(root, "tok-1", "2")
93 widen(monkeypatch, "cart_items") # between reading the open cart and writing
94
95 results = race(4, lambda i: tfa.checkout(root, "tok-1"))
96
97 assert all(r and r.get("ok") for r in results), results
98 orders = tfa.rows(data_dir, "orders")
99 assert len(orders) == 1, f"{len(orders)} orders for one cart"
100 assert len(tfa.rows(data_dir, "invoices")) == 1
101 assert {r["order_id"] for r in results} == {orders[0]["id"]}
102 assert sum(1 for r in results if not r.get("duplicate")) == 1
103
104
105@pytest.mark.parametrize("round_", range(ROUNDS))
106def test_racing_orders_on_one_pickup_slot_are_all_counted(tmp_path, monkeypatch, round_):
107 from datetime import datetime, timedelta
108 now = datetime(2026, 7, 27, 12, 0, 0)
109 data_dir, root = tfa.shop(tmp_path, monkeypatch)
110 tfa.make(data_dir, "pickup_slots", id="s1",
111 starts_at=(now + timedelta(minutes=60)).isoformat(),
112 ends_at=(now + timedelta(minutes=75)).isoformat(),
113 capacity=10, orders_taken=0, is_open="true", location_id="", owner_id="")
114 n = 4
115 for i in range(n):
116 tfa.add_to_cart(root, f"tok-{i}")
117 args = dict(fulfillment_method="pickup", pickup_slot_id="s1", now=now.isoformat())
118 # Between reading orders_taken and writing it back.
119 real_get = object_records.get_collection_record
120
121 def slow_get(collection, *a, **k):
122 row = real_get(collection, *a, **k)
123 if collection == "pickup_slots":
124 time.sleep(0.03)
125 return row
126
127 monkeypatch.setattr(object_records, "get_collection_record", slow_get)
128
129 results = race(n, lambda i: tfa.checkout(root, f"tok-{i}", **args))
130
131 assert all(r and r.get("ok") and not r.get("pickup_slot_error") for r in results), results
132 assert len(tfa.rows(data_dir, "orders")) == n
133 taken = tfa.rows(data_dir, "pickup_slots")[0]["orders_taken"]
134 assert taken == str(n), f"{n} orders hold the slot but orders_taken={taken}"
135
136
137@pytest.mark.parametrize("round_", range(ROUNDS))
138def test_racing_checkouts_cannot_overspend_one_gift_card(tmp_path, monkeypatch, round_):
139 data_dir, root = tfa.gift_card_shop(tmp_path, monkeypatch, balance=1000)
140 tfa.add_to_cart(root, "tok-c")
141 widen(monkeypatch, "wallet_entries", 0.03)
142
143 tokens = ["tok-a", "tok-b", "tok-c"]
144 results = race(3, lambda i: tfa.checkout(root, tokens[i], gift_card_code="GC-TEST"))
145
146 applied = sum(int(r.get("gift_card_applied_cents") or 0) for r in results if r)
147 assert tfa.balance(data_dir) >= 0, f"card balance is {tfa.balance(data_dir)}"
148 assert applied == 1000 - tfa.balance(data_dir) <= 1000, (applied, results)
149 # Whatever the card did not pay is still owed, on every order.
150 for r in results:
151 if r and r.get("ok"):
152 assert r["amount_due_cents"] == r["total_cents"] - r["credit_applied_cents"]
153 assert r["credit_applied_cents"] == r["gift_card_applied_cents"]
154
155
156# --- wallet writers -------------------------------------------------------------
157
158@pytest.mark.parametrize("round_", range(ROUNDS))
159def test_racing_auto_topup_passes_credit_one_charge_once(tmp_path, monkeypatch, round_):
160 from datetime import datetime, timezone
161 data = tmg.wallet_env(tmp_path, monkeypatch)
162 monkeypatch.setenv("DBBASIC_STRIPE_SECRET_KEY", "sk_test_stub")
163 monkeypatch.setenv("DBBASIC_STRIPE_WEBHOOK_SECRET", "whsec_test_stub")
164 object_records.create_collection_record("wallets", {
165 "id": "w1", "owner_id": "dan", "is_active": "true",
166 "auto_replenish_enabled": "true", "auto_replenish_threshold_minor": "1000",
167 "auto_replenish_amount_minor": "500", "auto_replenish_monthly_cap_minor": "10000",
168 "stripe_customer_id": "cus_1", "payment_method_ref": "pm_1"}, base_dir=data)
169 today = datetime.now(timezone.utc).strftime("%Y-%m") + "-25"
170 charges = {}
171 lock = threading.Lock()
172
173 def stripe(config, method, path, params=None, **kwargs):
174 # Stripe's own idempotency: one intent per key. The sleep is the
175 # provider round trip both passes wait through.
176 time.sleep(0.05)
177 with lock:
178 return charges.setdefault(kwargs.get("idempotency_key"),
179 {"id": f"pi_{len(charges) + 1}",
180 "amount": params["amount"]})
181
182 monkeypatch.setattr(object_stripe, "api_request", stripe)
183 results = race(3, lambda i: tmg.run_object(
184 "system_wallet_replenish", {"today": today}, "app-billing"))
185
186 assert all(r.ok for r in results), [r.error for r in results]
187 assert len(charges) == 1 and sum(c["amount"] for c in charges.values()) == 500
188 credited = sum(int(row["amount_minor"]) for row in tmg.ledger(data, wallet_id="w1"))
189 assert credited == 500, f"one 500 charge credited {credited}"
190
191
192@pytest.mark.parametrize("round_", range(ROUNDS))
193def test_racing_deliveries_of_one_payment_open_one_gift_card(tmp_path, monkeypatch, round_):
194 data = tmg.wallet_env(tmp_path, monkeypatch)
195
196 def make(collection, record):
197 return object_records.create_collection_record(collection, record, base_dir=data)
198
199 make("products", {"id": "gc", "name": "Gift Card $50", "price_cents": "5000",
200 "is_gift_card": "true", "product_type": "digital", "owner_id": "shop"})
201 make("invoices", {"id": "inv1", "number": "INV-1", "customer_name": "Ada",
202 "total_cents": "5000", "status": "sent", "owner_id": "shop"})
203 make("orders", {"id": "o1", "number": "SO-1", "customer_name": "Ada",
204 "invoice_id": "inv1", "owner_id": "shop"})
205 make("order_lines", {"id": "ol1", "order_id": "o1", "product_id": "gc",
206 "description": "Gift Card $50", "quantity": "1",
207 "unit_price_cents": "5000", "line_total_cents": "5000",
208 "owner_id": "shop"})
209 payment = make("payments", {"id": "pay1", "invoice_id": "inv1", "amount_cents": "5000",
210 "method": "card", "received_on": "2026-07-24",
211 "status": "received", "owner_id": "shop"})
212 event = {"event": "payments.record.created", "collection": "payments",
213 "record_id": "pay1", "action": "create", "record": payment}
214 widen(monkeypatch, "wallets", 0.05) # between the marker look and the writes
215
216 results = race(3, lambda i: tmg.run_object(
217 "system_gift_card_issue", dict(event), "app-billing", method="EVENT"))
218
219 assert all(r.ok for r in results), [r.error for r in results]
220 cards = [w for w in object_records.read_collection_records("wallets", base_dir=data)
221 if w.get("kind") == "gift_card"]
222 credit = sum(int(e["amount_minor"]) for e in tmg.ledger(data))
223 assert len(cards) == 1 and credit == 5000, (
224 f"{len(cards)} gift cards and {credit} of credit for one 5000 sale")
225 assert sum(r.result.get("issued", 0) for r in results) == 1
226
227
228# --- buy_label with a PAID carrier (stub connector, no network) -----------------
229
230@pytest.mark.parametrize("round_", range(ROUNDS))
231def test_racing_clicks_buy_one_paid_label(tmp_path, monkeypatch, round_):
232 import test_tracking as ttr
233 data_dir, root, purchases = tfa.paid_carrier_shop(tmp_path, monkeypatch)
234 # Between reading the shipment (no label yet) and calling the carrier.
235 real_get = object_records.get_collection_record
236
237 def slow_get(collection, *a, **k):
238 row = real_get(collection, *a, **k)
239 if collection == "shipments":
240 time.sleep(0.05)
241 return row
242
243 monkeypatch.setattr(object_records, "get_collection_record", slow_get)
244
245 results = race(4, lambda i: ttr.buy_label(root, shipment_id="shp-1"))
246
247 assert purchases() == 1, f"{purchases()} paid labels bought for one shipment"
248 assert sum(1 for r in results if r.get("ok")) == 1, results
249 assert all(r.get("ok") or r.get("status") == 409 for r in results), results
250 assert ttr.read(data_dir)["tracking_number"] == "PAID-1"
251
252
253# --- resolve_dispute ------------------------------------------------------------
254
255@pytest.mark.parametrize("kind", ["refund", "credit"])
256@pytest.mark.parametrize("round_", range(ROUNDS))
257def test_racing_resolutions_of_one_dispute_compensate_once(
258 tmp_path, monkeypatch, round_, kind):
259 import test_disputes as td
260 data_dir, root = td.shop_with_a_dispute(tmp_path, monkeypatch, cents=3600)
261 td.wallet(data_dir)
262 # Between the "already compensated?" look and the write.
263 widen(monkeypatch, "refunds" if kind == "refund" else "wallet_entries", 0.03)
264
265 results = race(4, lambda i: td.resolve(root, dispute_id="dis-1",
266 resolution_kind=kind, amount_cents="1200"))
267
268 if kind == "refund":
269 sent = [int(r["amount_cents"]) for r in td.refunds(data_dir)]
270 else:
271 sent = [int(e["amount_minor"]) for e in td.entries(data_dir)]
272 assert sent == [1200], f"{len(sent)} compensations ({sum(sent)}) for one dispute"
273 assert all(r.get("ok") or r.get("code") == "in_progress" for r in results), results
274 assert td.disputes(data_dir)[0]["status"] == "resolved"
275
276
277# --- stripe_checkout (transport stubbed; the fixture refuses sockets) -----------
278
279@pytest.mark.parametrize("round_", range(ROUNDS))
280def test_racing_clicks_on_pay_send_one_idempotency_key(tmp_path, monkeypatch, round_):
281 import json as _json
282 tfa.stripe_shop(tmp_path, monkeypatch)
283 keys = []
284 lock = threading.Lock()
285
286 def fake_transport(url, data, headers, method):
287 assert url.startswith("https://api.stripe.com/"), url
288 with lock:
289 keys.append(dict(headers).get("Idempotency-Key"))
290 time.sleep(0.02)
291 return 200, _json.dumps({"id": "cs_1",
292 "url": "https://checkout.stripe.com/pay/x"}).encode()
293
294 monkeypatch.setattr(
295 object_stripe, "create_checkout_session",
296 lambda config, **kw: tfa._REAL_CREATE_SESSION(config, transport=fake_transport, **kw))
297 results = race(3, lambda i: object_execution.execute_object(
298 tfa.RUNTIME, object_execution.ObjectExecutionRequest(
299 "action_stripe_checkout", method="POST",
300 payload={"token": "tok-abcdefghijklmnop"}),
301 roots=[tfa.tsw.PAYMENTS_OBJECTS]).result)
302
303 assert all(r["status"] == 200 for r in results), results
304 assert len(keys) == 3 and len(set(keys)) == 1 and keys[0], keys