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_online_reservations.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_online_reservations.py · 21.0 KB · 493 lines
1"""An online order holds its goods from checkout (the owner's decision).
2
3"if i order online and drive to the damn store i expect it to still be
4there when i arrive" -- Dan, 2026-11-30.
5
6Found by a simulated race (a Haiku shopper swarm): action_checkout's stock
7gate summed stock_moves and subtracted no open order, and stock moves only
8when money arrives, so ONE unit was sold to two orders and THREE to ten --
9not only under a race, sequential checkouts did it too.
10
11Everything here goes through the HTTP API in-process
12(scripts/try_package.py's Sandbox, permission enforcement on), the way a
13shopper and an operator would. The races run real threads released by a
14barrier; the window between the gate's read and the line's write is
15widened with a short sleep where the natural one is too narrow to hit, so
16the lock -- not luck -- is what each passing run proves.
17"""
18
19from __future__ import annotations
20
21import json
22import threading
23import time
24from datetime import datetime, timedelta, timezone
25from decimal import Decimal
26from pathlib import Path
27
28import pytest
29
30import object_pickup
31import object_records
32import object_reservations
33import object_stock
34from scripts.try_package import Sandbox
35
36ROOT = Path(__file__).resolve().parents[1]
37
38
39# --- the shop -------------------------------------------------------------------
40
41
42@pytest.fixture()
43def shop():
44 with Sandbox(["app-shop", "app-pickup", "app-payments", "app-settings"]) as box:
45 _put(box, "locations", id="shelf", name="Shelf", location_type="warehouse")
46 _put(box, "locations", id="cust", name="Customers", location_type="customer")
47 _stock_product(box, "mug", on_hand=1)
48 yield box
49
50
51def _put(box, collection, **row):
52 row.setdefault("owner_id", "shop")
53 return object_records.create_collection_record(collection, row, base_dir=box.data_dir)
54
55
56def _stock_product(box, product_id, *, on_hand, **fields):
57 _put(box, "products", id=product_id, name=product_id.title(), price_cents="1000",
58 product_type="physical", is_active="true", **fields)
59 if on_hand:
60 _put(box, "stock_moves", product_id=product_id, to_location_id="shelf",
61 quantity=str(on_hand), reason="purchase", unit_cost_cents="400")
62
63
64def _setting(box, key, value):
65 status, body = box.call("admin", "POST", "/collections/app_settings/records",
66 {"key": key, "value": value})
67 assert status == 201, body
68
69
70def _buy(box, product_id="mug", quantity="1", **checkout):
71 """One shopper: a fresh basket, one line, a checkout. (status, body)."""
72 status, cart = box.call("anon", "POST", "/objects/action_cart",
73 {"action": "add", "product_id": product_id,
74 "quantity": quantity})
75 assert status == 200, cart
76 checkout.setdefault("customer_email", "buyer@example.test")
77 return box.call("anon", "POST", "/objects/action_checkout",
78 {"session_token": cart["session_token"], **checkout})
79
80
81def _rows(box, collection):
82 return object_records.read_collection_records(collection, base_dir=box.data_dir)
83
84
85def _orders(box):
86 return [row for row in _rows(box, "orders") if row.get("reserves_stock") == "true"]
87
88
89def _available(box, product_id="mug"):
90 on_hand = object_stock.total_quantity(product_id, base_dir=box.data_dir)
91 held = object_reservations.read_holds(box.data_dir).get(product_id, Decimal(0))
92 return on_hand - held
93
94
95def _age(box, order_id, minutes):
96 raised = datetime.now(timezone.utc) - timedelta(minutes=minutes)
97 object_records.update_collection_record(
98 "orders", order_id, {"created_at": raised.isoformat().replace("+00:00", "Z")},
99 base_dir=box.data_dir, preserve_read_only=True)
100
101
102def _slot(box, slot_id, *, starts_in, length=15):
103 start = (datetime.now() + timedelta(minutes=starts_in)).replace(microsecond=0)
104 _put(box, "pickup_slots", id=slot_id, starts_at=start.isoformat(),
105 ends_at=(start + timedelta(minutes=length)).isoformat(),
106 capacity="50", orders_taken="0", is_open="true")
107
108
109# --- the bug, sequentially -------------------------------------------------------
110
111
112def test_the_last_unit_is_not_sold_to_a_second_online_order(shop):
113 """The bug as found: two shoppers, one after the other, one mug. The
114 first order is unpaid -- its stock has not moved -- and the second
115 shopper was sold the same mug."""
116 status, first = _buy(shop)
117 assert status == 200, first
118 status, second = _buy(shop)
119 assert status == 409, second
120 assert second["unavailable"][0]["product_id"] == "mug"
121 assert second["unavailable"][0]["available"] == "0"
122 assert len(_orders(shop)) == 1
123
124
125def test_three_units_go_to_three_of_ten_shoppers(shop):
126 _stock_product(shop, "lamp", on_hand=3)
127 answers = [_buy(shop, "lamp") for _ in range(10)]
128 assert [status for status, _ in answers].count(200) == 3
129 assert [status for status, _ in answers].count(409) == 7
130 assert _available(shop, "lamp") == 0
131
132
133def test_the_order_is_stamped_as_reserving(shop):
134 status, body = _buy(shop)
135 assert status == 200
136 order = object_records.get_collection_record("orders", body["order_id"],
137 base_dir=shop.data_dir)
138 assert order["reserves_stock"] == "true"
139
140
141def test_two_lines_of_one_product_share_one_shelf(shop):
142 """A basket of one mug with a note and one without: two lines, one
143 shelf. Each line used to be checked against the whole of it."""
144 status, cart = shop.call("anon", "POST", "/objects/action_cart",
145 {"action": "add", "product_id": "mug"})
146 token = cart["session_token"]
147 status, cart = shop.call("anon", "POST", "/objects/action_cart",
148 {"action": "add", "product_id": "mug",
149 "line_note": "gift wrap", "session_token": token})
150 assert len(cart["lines"]) == 2
151 status, body = shop.call("anon", "POST", "/objects/action_checkout",
152 {"session_token": token,
153 "customer_email": "b@example.test"})
154 assert status == 409, body
155 assert _orders(shop) == []
156
157
158# --- the race --------------------------------------------------------------------
159
160
161def race(n, fn):
162 barrier = threading.Barrier(n)
163 results = [None] * n
164 errors = []
165
166 def worker(i):
167 try:
168 barrier.wait(timeout=20)
169 results[i] = fn(i)
170 except BaseException as exc: # noqa: BLE001
171 errors.append(exc)
172
173 threads = [threading.Thread(target=worker, args=(i,)) for i in range(n)]
174 for thread in threads:
175 thread.start()
176 for thread in threads:
177 thread.join(timeout=120)
178 assert not any(t.is_alive() for t in threads), "a racing thread hung"
179 if errors:
180 raise errors[0]
181 return results
182
183
184@pytest.fixture()
185def widened(monkeypatch):
186 """Sleep after every read of the holds: the gate's read and the line's
187 write are where the race lived. The locked check reads them too, but
188 under the lock, so it only gets slower there. And let ten checkouts in
189 at once: the server's default of 8 concurrent executions would answer
190 the ninth "busy" before it ever reached the shelf."""
191 monkeypatch.setenv("DBBASIC_MAX_CONCURRENT_EXECUTIONS", "32")
192 real = object_reservations.read_holds
193
194 def slow(*args, **kwargs):
195 held = real(*args, **kwargs)
196 time.sleep(0.05)
197 return held
198
199 monkeypatch.setattr(object_reservations, "read_holds", slow)
200
201
202def _baskets(box, n, product_id, quantity="1"):
203 tokens = []
204 for _ in range(n):
205 status, cart = box.call("anon", "POST", "/objects/action_cart",
206 {"action": "add", "product_id": product_id,
207 "quantity": quantity})
208 assert status == 200
209 tokens.append(cart["session_token"])
210 return tokens
211
212
213def _checkout(box, token):
214 return box.call("anon", "POST", "/objects/action_checkout",
215 {"session_token": token, "customer_email": "r@example.test"})
216
217
218@pytest.mark.parametrize("buyers", [2, 5, 10])
219def test_racing_buyers_for_one_unit_exactly_one_gets_it(shop, widened, buyers):
220 tokens = _baskets(shop, buyers, "mug")
221 answers = race(buyers, lambda i: _checkout(shop, tokens[i]))
222
223 statuses = [status for status, _ in answers]
224 assert statuses.count(200) == 1, answers
225 assert statuses.count(409) == buyers - 1, answers
226 orders = _orders(shop)
227 assert len(orders) == 1, f"{len(orders)} orders for one mug"
228 lines = [line for line in _rows(shop, "order_lines")
229 if line["order_id"] == orders[0]["id"]]
230 assert len(lines) == 1
231 # The losers left nothing behind: no orphan order, line or invoice, and
232 # their baskets can be checked out again.
233 assert len(_rows(shop, "order_lines")) == 1
234 assert len(_rows(shop, "invoices")) == 1
235 open_carts = [c for c in _rows(shop, "carts") if c.get("status") == "open"]
236 assert len(open_carts) == buyers - 1
237 assert not any(c.get("checkout_claim") for c in open_carts)
238 assert _available(shop) == 0
239
240
241@pytest.mark.parametrize("units,buyers", [(3, 8), (5, 10)])
242def test_racing_buyers_for_n_units_n_get_one_and_stock_never_goes_negative(
243 shop, widened, units, buyers):
244 _stock_product(shop, "lamp", on_hand=units)
245 tokens = _baskets(shop, buyers, "lamp")
246 answers = race(buyers, lambda i: _checkout(shop, tokens[i]))
247
248 assert [status for status, _ in answers].count(200) == units, answers
249 assert len(_orders(shop)) == units
250 assert _available(shop, "lamp") == 0
251
252 # And when every one of them is paid and fulfilled, the shelf ends at
253 # zero: the holds became the moves, one for one.
254 for status, body in answers:
255 if status == 200:
256 _pay(shop, body)
257 assert object_stock.total_quantity("lamp", base_dir=shop.data_dir) == 0
258 assert _available(shop, "lamp") == 0
259
260
261# --- what ends a hold ------------------------------------------------------------
262
263
264def _pay(box, checkout_body):
265 """Pay the order's invoice and run the shop's reaction to it -- the
266 payment handler, in process, as the change dispatcher would."""
267 import object_execution
268 import python_object_runtime
269 _setting_once(box, "shop.stock_location", "shelf")
270 _setting_once(box, "shop.customer_location", "cust")
271 payment = object_records.create_collection_record(
272 "payments", {"invoice_id": checkout_body["invoice_id"],
273 "amount_cents": str(checkout_body["total_cents"]),
274 "status": "received", "method": "card",
275 "received_on": datetime.now().date().isoformat(),
276 "owner_id": "shop"},
277 base_dir=box.data_dir)
278 outcome = object_execution.execute_object(
279 python_object_runtime.PythonObjectRuntime(),
280 object_execution.ObjectExecutionRequest(
281 "system_shop_fulfillment", method="EVENT",
282 payload={"collection": "payments", "record_id": payment["id"]}))
283 assert outcome.ok, outcome.error
284 assert outcome.result.get("shipped") is True, outcome.result
285 return outcome.result
286
287
288def _setting_once(box, key, value):
289 if not any(row.get("key") == key for row in _rows(box, "app_settings")):
290 _put(box, "app_settings", key=key, value=value)
291
292
293def test_paying_turns_the_hold_into_the_stock_move_without_counting_twice(shop):
294 _stock_product(shop, "lamp", on_hand=2)
295 status, first = _buy(shop, "lamp")
296 assert status == 200
297 assert _available(shop, "lamp") == 1
298
299 _pay(shop, first)
300 sale_moves = [m for m in _rows(shop, "stock_moves")
301 if m.get("product_id") == "lamp" and m.get("reason") == "sale"]
302 assert len(sale_moves) == 1
303 assert object_stock.total_quantity("lamp", base_dir=shop.data_dir) == 1
304 # Not 0 (moved AND still held) and not 2 (released before it moved).
305 assert _available(shop, "lamp") == 1
306 assert _buy(shop, "lamp")[0] == 200
307 assert _buy(shop, "lamp")[0] == 409
308
309
310def test_cancelling_an_order_gives_its_goods_back(shop):
311 status, first = _buy(shop)
312 assert status == 200
313 assert _buy(shop)[0] == 409
314 # The order's owner (the shop) cancels it: the transition ladder asks
315 # for the owner, not for an admin.
316 shop.add_user("shop")
317 status, body = shop.call("shop", "PUT",
318 f"/collections/orders/records/{first['order_id']}",
319 {"status": "cancelled"})
320 assert status == 200, body
321 assert _buy(shop)[0] == 200
322
323
324def test_an_unpaid_online_order_lets_go_after_the_hold(shop):
325 status, first = _buy(shop)
326 assert status == 200
327 _age(shop, first["order_id"], 29)
328 assert _buy(shop)[0] == 409
329 _age(shop, first["order_id"], 31) # pickup.hold_minutes, default 30
330 assert _buy(shop)[0] == 200
331
332
333def test_a_paid_order_holds_however_old_until_its_goods_move(shop):
334 _setting(shop, "shop.auto_fulfill", "false")
335 status, first = _buy(shop)
336 assert status == 200
337 object_records.create_collection_record(
338 "payments", {"invoice_id": first["invoice_id"], "amount_cents": "1000",
339 "status": "received", "method": "card",
340 "received_on": "2026-11-30", "owner_id": "shop"},
341 base_dir=shop.data_dir)
342 _age(shop, first["order_id"], 6000)
343 assert _buy(shop)[0] == 409
344
345
346# --- pay at pickup ----------------------------------------------------------------
347
348
349def test_pay_at_pickup_holds_until_the_window_closes_plus_the_grace(shop):
350 """The drive to the store: the shopper pays at the counter, so the age
351 of their order means nothing; the window they were promised does."""
352 _setting(shop, "pickup.pay_at_pickup", "true")
353 _slot(shop, "s1", starts_in=120)
354 status, first = _buy(shop, fulfillment_method="pickup", pickup_slot_id="s1",
355 pay_at_pickup=True)
356 assert status == 200, first
357 order = object_records.get_collection_record("orders", first["order_id"],
358 base_dir=shop.data_dir)
359 assert order["pay_at_pickup"] == "true"
360 assert first["held_until"].startswith(
361 (datetime.now() + timedelta(minutes=120 + 15 + 30)).isoformat()[:13])
362
363 _age(shop, first["order_id"], 600) # long past the 30-minute hold
364 assert _buy(shop)[0] == 409, "a pay-at-pickup order lost its goods by age"
365
366 # The window has closed and the grace (default 30) has run out.
367 past = datetime.now() - timedelta(minutes=50)
368 object_records.update_collection_record(
369 "pickup_slots", "s1", {"starts_at": (past - timedelta(minutes=15)).isoformat(),
370 "ends_at": past.isoformat()},
371 base_dir=shop.data_dir)
372 assert _buy(shop)[0] == 200
373
374
375def test_pay_at_pickup_is_refused_where_the_shop_does_not_offer_it(shop):
376 _slot(shop, "s1", starts_in=120)
377 status, body = _buy(shop, fulfillment_method="pickup", pickup_slot_id="s1",
378 pay_at_pickup=True)
379 assert status == 409 and "pickup.pay_at_pickup" in body["error"]
380 _setting(shop, "pickup.pay_at_pickup", "true")
381 status, body = _buy(shop, pay_at_pickup=True)
382 assert status == 409 and "only for collection orders" in body["error"]
383 assert _orders(shop) == []
384
385
386def test_the_window_and_the_shelf_agree_on_whether_an_order_still_holds():
387 """Pure: object_pickup.hold_lapsed is the one rule."""
388 now = datetime(2026, 11, 30, 12, 0, tzinfo=timezone.utc)
389 paid = {"paid-inv"}
390 online = {"status": "draft", "invoice_id": "i1", "created_at": "2026-11-30T11:00:00Z"}
391 assert object_pickup.hold_lapsed(online, paid_invoice_ids=paid, now=now, minutes=30)
392 assert not object_pickup.hold_lapsed(online, paid_invoice_ids=None, now=now, minutes=30)
393 at_counter = {**online, "pay_at_pickup": "true", "notes": "[pickup_slots/s1]"}
394 ends = {"s1": "2026-11-30T11:45:00+00:00"}
395 assert not object_pickup.hold_lapsed(at_counter, paid_invoice_ids=paid, now=now,
396 minutes=30, grace=30, slot_ends=ends)
397 assert object_pickup.hold_lapsed(at_counter, paid_invoice_ids=paid, now=now,
398 minutes=30, grace=10, slot_ends=ends)
399 # No window to read: kept (fails closed).
400 assert not object_pickup.hold_lapsed({**at_counter, "notes": ""},
401 paid_invoice_ids=paid, now=now, minutes=30)
402 assert object_pickup.hold_lapsed({"status": "cancelled"}, paid_invoice_ids=None,
403 now=now, minutes=30)
404
405
406def test_what_is_held_is_ordered_less_moved_for_live_reserving_orders():
407 """Pure: the fold."""
408 now = datetime(2026, 11, 30, 12, 0, tzinfo=timezone.utc)
409 fresh = "2026-11-30T11:59:00Z"
410 orders = [
411 {"id": "a", "status": "draft", "reserves_stock": "true", "created_at": fresh},
412 {"id": "b", "status": "partial", "reserves_stock": "true"},
413 {"id": "c", "status": "shipped", "reserves_stock": "true"},
414 {"id": "d", "status": "confirmed"}, # back office
415 {"id": "e", "status": "confirmed", "reserves_stock": "true",
416 "fulfillment_source": "dropship"},
417 {"id": "f", "status": "cancelled", "reserves_stock": "true"},
418 ]
419 lines = [{"id": f"l{o['id']}", "order_id": o["id"], "product_id": "p",
420 "quantity": "3"} for o in orders]
421 moves = [{"reference": "shipments/s9:line/sl1 WEB-1"}]
422 shipment_lines = [{"id": "sl1", "order_line_id": "lb", "quantity": "2"},
423 {"id": "sl2", "order_line_id": "lb", "quantity": "1"}]
424 moved = object_reservations.moved_by_line(moves, shipment_lines)
425 assert moved == {"lb": Decimal("2")} # sl2 has not moved yet
426 held = object_reservations.held_by_product(
427 orders, lines, moved=moved, paid_invoice_ids=set(), now=now,
428 minutes=30, grace=30)
429 assert held == {"p": Decimal("4")} # a: 3, b: 3 - 2
430
431
432# --- backorders, other writers, the declaration ---------------------------------
433
434
435def test_a_backorder_records_what_is_short_of_what_is_available(shop):
436 """Backorder-allowed products still sell; what is recorded as owed is
437 measured against what is AVAILABLE, not what is on the shelf."""
438 _stock_product(shop, "kettle", on_hand=1, backorder_policy="allow")
439 assert _buy(shop, "kettle")[0] == 200
440 status, body = _buy(shop, "kettle", quantity="2")
441 assert status == 200, body
442 assert body["backordered"][0]["short_by"] == "2"
443 owed = [row for row in _rows(shop, "backorders") if row["product_id"] == "kettle"]
444 assert [row["quantity"] for row in owed] == ["2"]
445
446
447def test_a_back_office_order_does_not_reserve_and_is_not_refused(shop):
448 status, order = shop.call("admin", "POST", "/collections/orders/records",
449 {"doc_type": "sale", "number": "BO-1",
450 "customer_name": "Walk-in", "status": "confirmed",
451 "owner_id": "shop"})
452 assert status == 201, order
453 assert order["record"].get("reserves_stock") in ("false", "", None)
454 status, line = shop.call("admin", "POST", "/collections/order_lines/records",
455 {"order_id": order["record"]["id"], "product_id": "mug",
456 "quantity": "5", "unit_price_cents": "1000", "description": "Mug",
457 "owner_id": "shop"})
458 assert status == 201, line
459 assert _buy(shop)[0] == 200
460
461
462def test_the_hold_is_enforced_for_every_writer_of_an_order_line(shop):
463 status, first = _buy(shop)
464 assert status == 200
465 status, body = shop.call("admin", "POST", "/collections/order_lines/records",
466 {"order_id": first["order_id"], "product_id": "mug",
467 "quantity": "1", "unit_price_cents": "1000", "description": "Mug",
468 "owner_id": "shop"})
469 assert status == 409, body
470 assert body["code"] == "check_refused" and body["check"] == "stock_hold"
471
472
473def test_a_client_cannot_switch_an_orders_hold_off(shop):
474 status, first = _buy(shop)
475 status, body = shop.call("admin", "PUT",
476 f"/collections/orders/records/{first['order_id']}",
477 {"reserves_stock": "false"})
478 assert status >= 400, body
479 order = object_records.get_collection_record("orders", first["order_id"],
480 base_dir=shop.data_dir)
481 assert order["reserves_stock"] == "true"
482
483
484def test_order_lines_declare_the_stock_hold_and_its_reads():
485 """AGENTS.md: a check is wired by the SCHEMA. And everything the verdict
486 reads must be in `reads`, or a writer to it is not held still."""
487 schema = json.loads((ROOT / "packages/app-orders/schemas/order_lines.json").read_text())
488 (check,) = [c for c in schema["locked_checks"] if c["name"] == "stock_hold"]
489 assert check["object"] == "system_stock_hold" and check["lock"] == "stock"
490 assert {"orders", "products", "stock_moves", "locations", "shipment_lines",
491 "payments", "invoices", "pickup_slots", "app_settings"} <= set(check["reads"])
492 manifest = json.loads((ROOT / "packages/app-orders/dbbasic-package.json").read_text())
493 assert "system_stock_hold" in {o["id"] for o in manifest["objects"]}