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_dedupe.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_dedupe.py · 21.9 KB · 437 lines
1"""The four "has this already been written?" keys, declared `unique`, and
2the gates around them reading strictly.
3
4tests/test_findings_money_gates.py holds the reproductions: two
5overlapping requests both passing a hook's look-before-write check, and a
6gate that passed because its own read failed. This file covers what the
7fix must not have broken and what it newly guarantees below the hooks:
8
9 * the schemas declare exactly the keys the hooks and importers already
10 dedupe on -- so a writer that was correct before is correct now;
11 * every writer is bound, including the ones that never reach a hook;
12 * the things that are NOT duplicates still land (two owners with the
13 same receipt, two genuine same-day twins on one statement, a scan
14 with no bytes, a setting edited in place);
15 * the hooks' own messages still answer the ordinary, serial case.
16"""
17
18import contextlib
19import json
20import sys
21
22import pytest
23
24import object_banking
25import object_records
26from test_findings_money_gates import ( # noqa: F401 (fresh_handler_index is autouse)
27 BANK_LINE, PACKAGES, SETTING, banking_site, billing_site, build_site, failing_reads,
28 fresh_handler_index, must, ok,
29)
30
31
32@contextlib.contextmanager
33def hook_sees_nothing(collection, hook_file):
34 """Put one request where an overlapping one would be: past its hook
35 (whose look-before-write read finds no rows) and into the write lock.
36 Only the named hook's read of the named collection is emptied; the
37 write path reads the real file."""
38 real = object_records.read_collection_records
39
40 def read(name, *args, **kwargs):
41 if name == collection and sys._getframe(1).f_code.co_filename.endswith(hook_file):
42 return []
43 return real(name, *args, **kwargs)
44
45 object_records.read_collection_records = read
46 try:
47 yield
48 finally:
49 object_records.read_collection_records = real
50
51
52def schema(package, collection):
53 return json.loads((PACKAGES / package / "schemas" / f"{collection}.json").read_text())
54
55
56def keys(package, collection):
57 return [(rule["fields"], rule.get("scope", [])) for rule in schema(package, collection)["unique"]]
58
59
60def test_each_schema_declares_the_key_its_gate_dedupes_on():
61 """The constraint and the hook must be the same rule. A constraint
62 wider than the hook's check would refuse writes the importers were
63 right to make; a narrower one would leave the race open."""
64 assert keys("app-billing", "usage_events") == [(["event_id"], ["owner_id"])]
65 assert keys("app-intake", "scans") == [(["content_sha256"], ["owner_id"])]
66 assert keys("app-settings", "app_settings") == [(["key"], [])]
67 # object_banking.is_duplicate_line: the bank's id when there is one,
68 # OR the content hash -- each per bank account.
69 assert keys("app-banking", "bank_lines") == [
70 (["external_id"], ["bank_account_id"]), (["line_hash"], ["bank_account_id"])]
71
72
73# --- usage events --------------------------------------------------------------------
74
75
76def usage(site, who, record_id, event, quantity="10"):
77 return site.post("usage_events", who, {"id": record_id, "event_id": event,
78 "metric": "api_calls", "quantity": quantity})
79
80
81def test_one_event_key_is_one_event_per_owner_not_across_owners(tmp_path, monkeypatch):
82 """event_id is the CALLER's idempotency key. Two customers who both
83 number their requests from 1 are not retrying each other."""
84 site = build_site(tmp_path, monkeypatch,
85 ["app-views", "app-settings", "app-entities", "app-finance",
86 "app-invoices", "app-payments", "app-billing"], users=("ann", "bob"))
87
88 ok(usage(site, "ann", "u1", "evt-1"), "ann's event")
89 ok(usage(site, "bob", "u2", "evt-1"), "bob's event with the same key")
90 status, body = usage(site, "ann", "u3", "evt-1")
91
92 assert status == 409 and body["code"] == "unique_violation", body
93 assert sorted(row["id"] for row in site.rows("usage_events", event_id="evt-1")) == ["u1", "u2"]
94
95
96def test_a_storage_level_writer_cannot_record_a_usage_event_twice(tmp_path, monkeypatch):
97 """A metering agent or importer writing through object_records never
98 reaches hook_usage_events. The key holds for it anyway."""
99 site = billing_site(tmp_path, monkeypatch)
100 event = {"event_id": "evt-9", "metric": "api_calls", "quantity": "10", "owner_id": "ann"}
101 object_records.create_collection_record("usage_events", {"id": "u1", **event},
102 base_dir=site.data, actor="meter")
103
104 with pytest.raises(object_records.UniqueConstraintError) as refusal:
105 object_records.create_collection_record("usage_events", {"id": "u2", **event},
106 base_dir=site.data, actor="meter")
107
108 assert refusal.value.existing_id == "u1" and "billed twice" in str(refusal.value)
109 assert [row["id"] for row in site.rows("usage_events")] == ["u1"]
110
111
112def test_the_rollup_can_still_mark_an_event_rated(tmp_path, monkeypatch):
113 """system_usage_rollup updates {"rated": "true"} on events it has
114 folded. An update is checked only for a key it changes."""
115 site = billing_site(tmp_path, monkeypatch)
116 ok(usage(site, "ann", "u1", "evt-1"), "event")
117
118 rated = object_records.update_collection_record(
119 "usage_events", "u1", {"rated": "true"}, base_dir=site.data, actor="usage_rollup")
120
121 assert rated["rated"] == "true"
122
123
124def test_the_loser_of_an_overlap_is_told_it_was_a_duplicate(tmp_path, monkeypatch):
125 """What the retrying client sees when it loses the race inside the
126 lock: a 409 it can treat as "it landed", with the constraint's fields."""
127 site = billing_site(tmp_path, monkeypatch)
128 ok(usage(site, "ann", "u1", "evt-1"), "event")
129 with hook_sees_nothing("usage_events", "hook/usage_events.py"):
130 status, body = usage(site, "ann", "u2", "evt-1")
131
132 assert status == 409 and body["code"] == "unique_violation", body
133 assert body["fields"] == ["event_id"] and body["scope"] == ["owner_id"]
134 assert [row["id"] for row in site.rows("usage_events")] == ["u1"]
135
136
137# --- scans ---------------------------------------------------------------------------
138
139
140def scan(site, who, record_id, digest):
141 return site.post("scans", who, {"id": record_id, "filename": f"{record_id}.jpg",
142 "content_sha256": digest})
143
144
145def test_the_same_document_received_by_two_owners_is_two_scans(tmp_path, monkeypatch):
146 site = build_site(tmp_path, monkeypatch, ["app-views", "app-entities", "app-intake"],
147 users=("ann", "bob"))
148
149 ok(scan(site, "ann", "s1", "aaaa"), "ann's copy")
150 ok(scan(site, "bob", "s2", "aaaa"), "bob's copy of the same invoice PDF")
151
152 assert sorted(row["id"] for row in site.rows("scans")) == ["s1", "s2"]
153
154
155def test_scans_without_bytes_are_never_each_others_duplicates(tmp_path, monkeypatch):
156 """Text-only intake has no content hash. A blank key is no key: it is
157 exempt, as it always was in the hook."""
158 site = build_site(tmp_path, monkeypatch, ["app-views", "app-entities", "app-intake"])
159
160 for record_id in ("t1", "t2", "t3"):
161 ok(site.post("scans", "ann", {"id": record_id, "filename": f"{record_id}.txt"}), record_id)
162
163 assert len(site.rows("scans")) == 3
164
165
166def test_a_storage_level_writer_cannot_store_one_document_twice(tmp_path, monkeypatch):
167 """action_scan_ingest writes scans through object_records after its own
168 look-before-write check -- the same shape as the hook, with the same
169 gap. The key now holds underneath it."""
170 site = build_site(tmp_path, monkeypatch, ["app-views", "app-entities", "app-intake"])
171 row = {"filename": "receipt.jpg", "content_sha256": "cccc", "owner_id": "ann"}
172 object_records.create_collection_record("scans", {"id": "s1", **row},
173 base_dir=site.data, actor="action_scan_ingest")
174
175 with pytest.raises(object_records.UniqueConstraintError):
176 object_records.create_collection_record("scans", {"id": "s2", **row},
177 base_dir=site.data, actor="action_scan_ingest")
178 assert [r["id"] for r in site.rows("scans")] == ["s1"]
179
180
181def test_the_scan_processor_can_still_move_a_scan_through_its_states(tmp_path, monkeypatch):
182 site = build_site(tmp_path, monkeypatch, ["app-views", "app-entities", "app-intake"])
183 ok(scan(site, "ann", "s1", "dddd"), "scan")
184
185 for status in ("processing", "extracted"):
186 object_records.update_collection_record(
187 "scans", "s1", {"status": status, "ocr_text": "TOTAL 12.50"},
188 base_dir=site.data, actor="scan_processor")
189
190 assert site.get("scans", "s1")["status"] == "extracted"
191
192
193# --- bank lines ------------------------------------------------------------------------
194
195
196def test_two_genuine_same_day_twins_on_one_statement_both_land(tmp_path, monkeypatch):
197 """Two identical 4.50 coffees on one day are both real. The importers
198 give the second an ordinal so its line_hash differs; the constraint is
199 on that hash, so it does not collapse them."""
200 site = banking_site(tmp_path, monkeypatch)
201 twins = object_banking.assign_line_hashes([
202 {"posted_on": "2026-07-03", "amount_cents": -450, "description": "COFFEE"},
203 {"posted_on": "2026-07-03", "amount_cents": -450, "description": "COFFEE"}])
204 must(twins[0]["line_hash"] != twins[1]["line_hash"], "the ordinal did not disambiguate")
205
206 for index, line in enumerate(twins):
207 object_records.create_collection_record(
208 "bank_lines", {"id": f"b{index}", "bank_account_id": "bank-1",
209 "posted_on": line["posted_on"], "amount_cents": str(line["amount_cents"]),
210 "description": line["description"], "line_hash": line["line_hash"],
211 "owner_id": "ann"},
212 base_dir=site.data, actor="action_import_bank_csv")
213
214 assert len(site.rows("bank_lines")) == 2
215
216
217def test_an_importer_working_from_stale_keys_cannot_put_a_line_on_file_twice(
218 tmp_path, monkeypatch):
219 """object_banking.land_lines dedupes against keys its caller read before
220 writing anything. Two retries of one interrupted import each read
221 those keys and then both try to write the same missing lines -- the
222 case the importers' own note left open, because a read cannot close
223 it. Here the second runs with the keys as they were before the first
224 wrote: every one of its writes is refused inside the lock, and it
225 counts them as duplicates instead of landing them."""
226 site = banking_site(tmp_path, monkeypatch)
227 account = site.get("value_accounts", "bank-1")
228 lines = object_banking.assign_line_hashes([
229 {"posted_on": "2026-07-02", "amount_cents": 150000, "description": "ACME CORP",
230 "external_id": "", "raw": "07/02/2026\tACME CORP\t1500.00"},
231 {"posted_on": "2026-07-05", "amount_cents": -2500, "description": "MONTHLY SERVICE FEE",
232 "external_id": "", "raw": "07/05/2026\tMONTHLY SERVICE FEE\t-25.00"}])
233 stale = object_banking.existing_line_keys("bank-1", base_dir=site.data, strict=True)
234 must(stale == (set(), set()), f"expected an empty ledger to start from: {stale}")
235
236 def land():
237 return object_banking.land_lines(
238 "", "bank-1", lines, account=account, user_id="ann", base_dir=site.data,
239 actor="action_import_bank_csv", known=stale)
240
241 assert land() == {"imported": 2, "duplicates": 0}
242 assert land() == {"imported": 0, "duplicates": 2}
243 assert sorted(int(row["amount_cents"]) for row in site.rows("bank_lines")) == [-2500, 150000]
244
245
246def test_the_same_line_on_two_bank_accounts_is_two_lines(tmp_path, monkeypatch):
247 site = banking_site(tmp_path, monkeypatch)
248 ok(site.post("value_accounts", "ann", {"id": "bank-2", "name": "Savings", "kind": "bank"}),
249 "second account")
250
251 ok(site.post("bank_lines", "ann", {"id": "b1", **BANK_LINE}), "on checking")
252 ok(site.post("bank_lines", "ann", {"id": "b2", **BANK_LINE, "bank_account_id": "bank-2"}),
253 "the same transfer seen from savings")
254
255 assert len(site.rows("bank_lines")) == 2
256
257
258def test_a_bank_transaction_id_lands_once_even_if_the_bank_rewords_the_memo(tmp_path, monkeypatch):
259 """The FITID is the stronger key: it survives the bank re-wording a
260 description, which a content hash does not. Enforced below the hook,
261 for the OFX importer's storage-level writes."""
262 site = banking_site(tmp_path, monkeypatch)
263 base = {"bank_account_id": "bank-1", "posted_on": "2026-07-02", "amount_cents": "150000",
264 "external_id": "FITID-0001", "owner_id": "ann"}
265 object_records.create_collection_record(
266 "bank_lines", {"id": "b1", **base, "description": "ACME CORP", "line_hash": "h1"},
267 base_dir=site.data, actor="action_import_ofx")
268
269 with pytest.raises(object_records.UniqueConstraintError) as refusal:
270 object_records.create_collection_record(
271 "bank_lines", {"id": "b2", **base, "description": "ACME CORPORATION PMT",
272 "line_hash": "h2"},
273 base_dir=site.data, actor="action_import_ofx")
274
275 assert refusal.value.fields == ["external_id"]
276 assert [row["id"] for row in site.rows("bank_lines")] == ["b1"]
277
278
279def test_reconciling_a_line_does_not_trip_its_own_keys(tmp_path, monkeypatch):
280 """The matcher and resolve_bank_line update match_status, matched_to,
281 suggestions on lines that hold a key. Keeping your own key is not a
282 collision."""
283 site = banking_site(tmp_path, monkeypatch)
284 ok(site.post("bank_lines", "ann", {"id": "b1", **BANK_LINE}), "line")
285
286 object_records.update_collection_record(
287 "bank_lines", "b1", {"match_status": "suggested", "suggestions": "[]"},
288 base_dir=site.data, actor="bank_matcher")
289 ok(site.put("bank_lines", "b1", "ann", {"match_status": "matched",
290 "matched_to": "payments/p1"}), "confirm the match")
291
292 assert site.get("bank_lines", "b1")["match_status"] == "matched"
293
294
295def duplicate_on_disk(site, collection, record_id, new_id):
296 """A second copy of a stored row, the way a box installed before the
297 constraint holds one: written straight into the file."""
298 path = object_records.collection_records_file(collection, base_dir=site.data)
299 header, *rows = path.read_text().rstrip("\n").split("\n")
300 names = header.split("\t")
301 cells = next(dict(zip(names, row.split("\t"))) for row in rows
302 if row.split("\t")[names.index("id")] == record_id)
303 cells["id"] = new_id
304 with path.open("a") as handle:
305 handle.write("\t".join(cells[name] for name in names) + "\n")
306
307
308def test_bank_lines_already_on_file_twice_are_still_read_and_reconciled(tmp_path, monkeypatch):
309 """A box that took a duplicate statement line before v2 keeps both rows:
310 the constraint does not pick a winner, and neither row is frozen. Each
311 can still be matched -- by the matcher (storage level) and by a person
312 -- because keeping your own key is not taking one. A third copy is
313 refused."""
314 site = banking_site(tmp_path, monkeypatch)
315 ok(site.post("bank_lines", "ann", {"id": "b1", **BANK_LINE}), "line")
316 duplicate_on_disk(site, "bank_lines", "b1", "b2")
317 must(len(site.rows("bank_lines")) == 2, "the duplicate did not read back")
318
319 found = object_records.find_unique_violations("bank_lines", base_dir=site.data)
320 assert [sorted(entry["ids"]) for entry in found] == [["b1", "b2"]]
321
322 object_records.update_collection_record(
323 "bank_lines", "b2", {"match_status": "suggested", "suggestions": "[]"},
324 base_dir=site.data, actor="bank_matcher")
325 ok(site.put("bank_lines", "b1", "ann", {"match_status": "matched",
326 "matched_to": "payments/p1"}), "match one copy")
327 ok(site.put("bank_lines", "b2", "ann", {"match_status": "matched",
328 "matched_to": "payments/p1"}), "and the other")
329 assert [row["match_status"] for row in site.rows("bank_lines")] == ["matched", "matched"]
330
331 line = {key: site.get("bank_lines", "b1")[key]
332 for key in ("bank_account_id", "posted_on", "amount_cents", "description", "line_hash")}
333 with pytest.raises(object_records.UniqueConstraintError):
334 object_records.create_collection_record(
335 "bank_lines", {"id": "b3", **line, "raw": "again", "owner_id": "ann"},
336 base_dir=site.data, actor="some_importer")
337
338
339def test_usage_events_already_recorded_twice_can_still_be_rated(tmp_path, monkeypatch):
340 """The rollup marks events rated with a storage-level update; a pair
341 that was metered twice before v2 is still read and still marked, not
342 stranded unrated forever."""
343 site = billing_site(tmp_path, monkeypatch)
344 ok(usage(site, "ann", "u1", "evt-1"), "event")
345 duplicate_on_disk(site, "usage_events", "u1", "u2")
346 must(len(site.rows("usage_events", event_id="evt-1")) == 2, "the duplicate did not read back")
347
348 for event in ("u1", "u2"):
349 object_records.update_collection_record(
350 "usage_events", event, {"rated": "true"}, base_dir=site.data, actor="usage_rollup")
351 assert [row["rated"] for row in site.rows("usage_events")] == ["true", "true"]
352
353
354def test_an_unreadable_ledger_is_no_longer_the_bank_hooks_to_answer(tmp_path, monkeypatch):
355 """The hook used to read bank_lines and refuse (503) when it could not,
356 because the helper answered "none on file" and the duplicate passed. It
357 reads nothing now: the duplicate is `unique`'s, inside the lock, and a
358 hook that cannot look cannot fail open. What still holds is the outcome
359 the old test existed for: with the helper's read failing, the repeat of
360 a line already on file is refused and nothing lands."""
361 site = banking_site(tmp_path, monkeypatch)
362 ok(site.post("bank_lines", "ann", {"id": "b0", **BANK_LINE}), "first line")
363
364 with failing_reads("bank_lines", "object_banking.py") as fired:
365 status, body = site.post("bank_lines", "ann", {"id": "b1", **BANK_LINE})
366
367 assert fired == [], f"something still reads the ledger before the lock: {fired}"
368 assert status == 409 and body.get("code") == "unique_violation", (status, body)
369 assert [row["id"] for row in site.rows("bank_lines")] == ["b0"]
370
371
372# --- settings --------------------------------------------------------------------------
373
374
375def test_a_setting_is_still_edited_in_place_and_may_be_renamed_to_a_free_key(tmp_path, monkeypatch):
376 site = build_site(tmp_path, monkeypatch, ["app-settings"])
377 ok(site.post("app_settings", "admin", {"id": "s1", **SETTING, "value": "1300"}), "first row")
378 ok(site.post("app_settings", "admin", {"id": "s2", "key": "payments.overpayment_policy",
379 "value": "reject"}), "another key")
380
381 ok(site.put("app_settings", "s1", "admin", {"value": "1400"}), "edit the value")
382 ok(site.put("app_settings", "s2", "admin", {"key": "payments.some_other_policy"}), "rename")
383 status, body = site.put("app_settings", "s2", "admin", {"key": SETTING["key"]})
384
385 assert status == 409 and body["code"] == "unique_violation", body
386 assert site.get("app_settings", "s1")["value"] == "1400"
387 assert site.get("app_settings", "s2")["key"] == "payments.some_other_policy"
388
389
390def test_a_storage_level_writer_cannot_configure_a_key_twice(tmp_path, monkeypatch):
391 """Seeds, migrations and setup scripts write app_settings through
392 object_records. Readers take the first row for a key, so their second
393 row would have been silently ignored too."""
394 site = build_site(tmp_path, monkeypatch, ["app-settings"])
395 object_records.create_collection_record(
396 "app_settings", {"id": "s1", **SETTING, "value": "1300"}, base_dir=site.data, actor="setup")
397
398 with pytest.raises(object_records.UniqueConstraintError) as refusal:
399 object_records.create_collection_record(
400 "app_settings", {"id": "s2", **SETTING, "value": "1400"},
401 base_dir=site.data, actor="setup")
402
403 assert "already configured" in str(refusal.value) and refusal.value.existing_id == "s1"
404
405
406def test_duplicate_keys_already_on_a_box_are_reported_not_broken(tmp_path, monkeypatch):
407 """An installed box may already hold two rows for one key (that is the
408 incident). Declaring the constraint over them does not fail and does
409 not remove either; find_unique_violations is how they are found. The
410 way out is the one the hook has always pointed at -- it refuses an
411 edit to either row while the other holds the key -- so the operator
412 DELETES the stale one, and that must still work. The survivor is then
413 an ordinary setting again."""
414 site = build_site(tmp_path, monkeypatch, ["app-settings"])
415 ok(site.post("app_settings", "admin", {"id": "old", **SETTING, "value": "1300"}), "first row")
416 # The second row arrives the way it did on the live box: before
417 # anything refused it. Written straight into the file.
418 path = object_records.collection_records_file("app_settings", base_dir=site.data)
419 header, first = path.read_text().rstrip("\n").split("\n")
420 cells = dict(zip(header.split("\t"), first.split("\t")))
421 cells.update({"id": "new", "value": "1400"})
422 path.write_text("\n".join([header, first, "\t".join(cells[name] for name in header.split("\t"))]) + "\n")
423 must(len(site.rows("app_settings", key=SETTING["key"])) == 2, "the duplicate did not read back")
424
425 found = object_records.find_unique_violations("app_settings", base_dir=site.data)
426 assert [sorted(entry["ids"]) for entry in found] == [["new", "old"]]
427
428 # `unique` judges only a key an update CHANGES: editing the value of
429 # either duplicate is allowed (the hook used to refuse it, as a side
430 # effect of looking the key up), renaming one onto the key is not.
431 ok(site.put("app_settings", "new", "admin", {"value": "1450"}), "edit a duplicate")
432 ok(site.put("app_settings", "new", "admin", {"value": "1400"}), "and back")
433
434 ok(site.delete("app_settings", "old", "admin"), "delete the stale one")
435 assert object_records.find_unique_violations("app_settings", base_dir=site.data) == []
436 ok(site.put("app_settings", "new", "admin", {"value": "1500"}), "the survivor is editable")
437 assert [(row["id"], row["value"]) for row in site.rows("app_settings")] == [("new", "1500")]