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_unique_constraints.py · 27.8 KB · 637 lines
| 1 | """Schema `unique` constraints: enforced inside the write lock. |
| 2 | |
| 3 | Why this exists. A duplicate check in a pre-write hook reads the |
| 4 | collection, finds nothing, and lets the write through -- but the hook runs |
| 5 | BEFORE the write lock, so two overlapping requests both read "nothing" and |
| 6 | both land (AGENTS.md: "hooks cannot close a race"). Storage-level writers |
| 7 | (the daemon, handlers) never reach a hook at all. One usage event was |
| 8 | billed twice, one wallet top-up credited twice, one bank line stored twice, |
| 9 | one setting key configured twice, all by this window. |
| 10 | |
| 11 | A constraint declared in the schema is checked by object_records under the |
| 12 | same lock that performs the append, for EVERY writer: |
| 13 | |
| 14 | "unique": [ |
| 15 | {"fields": ["event_id"], "scope": ["owner_id"]}, |
| 16 | {"fields": ["code"], "ignore_case": true} |
| 17 | ] |
| 18 | |
| 19 | - `fields` is the key. A row whose key has a blank part is exempt: most |
| 20 | wallets have no code, and that is not a collision. |
| 21 | - `scope` narrows it ("unique per owner"). A blank scope is an ordinary |
| 22 | value: two ownerless rows with the same key DO collide. |
| 23 | - Values are compared trimmed; `ignore_case` also folds case. |
| 24 | - A violation raises object_records.UniqueConstraintError; over HTTP it is |
| 25 | a 409 with code "unique_violation". |
| 26 | """ |
| 27 | |
| 28 | import json |
| 29 | import subprocess |
| 30 | import sys |
| 31 | import threading |
| 32 | import time |
| 33 | from pathlib import Path |
| 34 | |
| 35 | import pytest |
| 36 | |
| 37 | import object_record_changes |
| 38 | import object_records |
| 39 | import object_schemas |
| 40 | import object_server |
| 41 | from test_object_server import TEST_ADMIN_TOKEN, enable_admin_token, request |
| 42 | |
| 43 | REPO_ROOT = str(Path(__file__).resolve().parents[1]) |
| 44 | AUTH = [("authorization", f"Token {TEST_ADMIN_TOKEN}")] |
| 45 | |
| 46 | FIELDS = [ |
| 47 | {"name": "id"}, |
| 48 | {"name": "owner_id", "type": "text"}, |
| 49 | {"name": "event_id", "type": "text"}, |
| 50 | {"name": "code", "type": "text"}, |
| 51 | {"name": "quantity", "type": "integer"}, |
| 52 | ] |
| 53 | PER_OWNER = [{"fields": ["event_id"], "scope": ["owner_id"]}] |
| 54 | |
| 55 | |
| 56 | def stage(tmp_path, unique, *, storage=None, collection="events", fields=FIELDS): |
| 57 | data_dir = tmp_path / "data" |
| 58 | schema = {"name": collection, "version": 1, "fields": fields, "unique": unique} |
| 59 | if storage: |
| 60 | schema["storage"] = storage |
| 61 | schema_dir = data_dir / "schemas" |
| 62 | schema_dir.mkdir(parents=True, exist_ok=True) |
| 63 | (schema_dir / f"{collection}.json").write_text(json.dumps(schema)) |
| 64 | return data_dir |
| 65 | |
| 66 | |
| 67 | def create(data_dir, record_id, collection="events", **fields): |
| 68 | return object_records.create_collection_record( |
| 69 | collection, {"id": record_id, **fields}, base_dir=data_dir, roots=[]) |
| 70 | |
| 71 | |
| 72 | def update(data_dir, record_id, collection="events", **changes): |
| 73 | return object_records.update_collection_record( |
| 74 | collection, record_id, changes, base_dir=data_dir, roots=[]) |
| 75 | |
| 76 | |
| 77 | def rows(data_dir, collection="events"): |
| 78 | return object_records.read_collection_records(collection, base_dir=data_dir, roots=[]) |
| 79 | |
| 80 | |
| 81 | def ids(data_dir, collection="events"): |
| 82 | return [row["id"] for row in rows(data_dir, collection)] |
| 83 | |
| 84 | |
| 85 | @pytest.fixture(params=["classic", "append"]) |
| 86 | def storage(request): |
| 87 | return request.param |
| 88 | |
| 89 | |
| 90 | # --- the declaration ------------------------------------------------------------ |
| 91 | |
| 92 | |
| 93 | def test_the_schema_keeps_a_unique_declaration_in_canonical_form(): |
| 94 | schema = object_schemas.normalize_schema("events", { |
| 95 | "name": "events", "fields": FIELDS, |
| 96 | "unique": [{"fields": ["event_id"], "scope": ["owner_id"]}, |
| 97 | {"fields": ["code"], "ignore_case": True, "message": "Code taken."}]}) |
| 98 | assert schema["unique"] == [ |
| 99 | {"fields": ["event_id"], "scope": ["owner_id"], "ignore_case": False}, |
| 100 | {"fields": ["code"], "scope": [], "ignore_case": True, "message": "Code taken."}, |
| 101 | ] |
| 102 | |
| 103 | |
| 104 | def test_a_schema_without_the_key_has_no_constraints(): |
| 105 | assert "unique" not in object_schemas.normalize_schema( |
| 106 | "events", {"name": "events", "fields": FIELDS}) |
| 107 | |
| 108 | |
| 109 | @pytest.mark.parametrize("unique", [ |
| 110 | {"fields": ["event_id"]}, # not a list of constraints |
| 111 | ["event_id"], # a bare name: one constraint or two? refuse |
| 112 | [["owner_id", "event_id"]], # a bare list, same ambiguity |
| 113 | [{}], # no key |
| 114 | [{"fields": []}], |
| 115 | [{"fields": "event_id"}], |
| 116 | [{"fields": ["event_id"], "scope": "owner_id"}], |
| 117 | [{"fields": ["event_id"], "unknown": True}], # a typo must not be silently ignored |
| 118 | [{"fields": ["event_id"], "ignore_case": "yes"}], |
| 119 | [{"fields": ["event_id"], "message": 7}], |
| 120 | [{"fields": ["id"]}], # id is unique already |
| 121 | [{"fields": ["event_id", "event_id"]}], |
| 122 | [{"fields": ["event_id"], "scope": ["event_id"]}], |
| 123 | [{"fields": ["not a field name"]}], |
| 124 | [{"fields": ["total"]}], # computed: the server writes it |
| 125 | [{"fields": ["tag"]}], # store: extra is not a column |
| 126 | ], ids=lambda value: json.dumps(value)) |
| 127 | def test_a_malformed_unique_declaration_is_refused_not_ignored(unique): |
| 128 | """A constraint the platform cannot enforce must fail the schema, never |
| 129 | load as "no constraint": the collection would look protected and not be.""" |
| 130 | fields = FIELDS + [{"name": "total", "type": "computed", "formula": "quantity * 2"}, |
| 131 | {"name": "tag", "type": "text", "store": "extra"}] |
| 132 | with pytest.raises(ValueError): |
| 133 | object_schemas.normalize_schema( |
| 134 | "events", {"name": "events", "fields": fields, "unique": unique}) |
| 135 | |
| 136 | |
| 137 | # --- create --------------------------------------------------------------------- |
| 138 | |
| 139 | |
| 140 | def test_a_second_record_with_the_same_key_is_refused_and_nothing_is_written(tmp_path, storage): |
| 141 | data_dir = stage(tmp_path, PER_OWNER, storage=storage) |
| 142 | create(data_dir, "e1", owner_id="ann", event_id="evt-1", quantity="10") |
| 143 | |
| 144 | with pytest.raises(object_records.UniqueConstraintError) as refusal: |
| 145 | create(data_dir, "e2", owner_id="ann", event_id="evt-1", quantity="10") |
| 146 | |
| 147 | error = refusal.value |
| 148 | assert isinstance(error, ValueError) |
| 149 | assert (error.collection, error.fields, error.scope) == ("events", ["event_id"], ["owner_id"]) |
| 150 | assert error.existing_id == "e1" |
| 151 | assert "event_id" in str(error) and "owner_id" in str(error) |
| 152 | assert ids(data_dir) == ["e1"] |
| 153 | changes = object_record_changes.list_record_changes("events", base_dir=data_dir)["changes"] |
| 154 | assert [(c["record_id"], c["action"]) for c in changes] == [("e1", "create")] |
| 155 | |
| 156 | |
| 157 | def test_the_scope_narrows_the_constraint(tmp_path, storage): |
| 158 | data_dir = stage(tmp_path, PER_OWNER, storage=storage) |
| 159 | create(data_dir, "e1", owner_id="ann", event_id="evt-1") |
| 160 | create(data_dir, "e2", owner_id="bob", event_id="evt-1") # another owner: fine |
| 161 | create(data_dir, "e3", owner_id="ann", event_id="evt-2") # another key: fine |
| 162 | with pytest.raises(object_records.UniqueConstraintError): |
| 163 | create(data_dir, "e4", owner_id="bob", event_id="evt-1") |
| 164 | assert ids(data_dir) == ["e1", "e2", "e3"] |
| 165 | |
| 166 | |
| 167 | def test_a_blank_key_is_exempt_but_a_blank_scope_is_a_value(tmp_path, storage): |
| 168 | data_dir = stage(tmp_path, PER_OWNER, storage=storage) |
| 169 | # No event id: not a collision, however many there are. |
| 170 | create(data_dir, "e1", owner_id="ann") |
| 171 | create(data_dir, "e2", owner_id="ann", event_id="") |
| 172 | create(data_dir, "e3", owner_id="ann", event_id=" ") |
| 173 | # No owner (an admin-token write is not owner-stamped): the key still |
| 174 | # has to be unique among ownerless rows, or the scope would be a hole. |
| 175 | create(data_dir, "e4", event_id="evt-1") |
| 176 | with pytest.raises(object_records.UniqueConstraintError): |
| 177 | create(data_dir, "e5", event_id="evt-1") |
| 178 | assert ids(data_dir) == ["e1", "e2", "e3", "e4"] |
| 179 | |
| 180 | |
| 181 | def test_values_are_compared_trimmed_and_case_only_when_asked(tmp_path, storage): |
| 182 | data_dir = stage(tmp_path, [{"fields": ["code"], "ignore_case": True}, |
| 183 | {"fields": ["event_id"]}], storage=storage) |
| 184 | create(data_dir, "w1", code="gc-abc", event_id="Evt") |
| 185 | with pytest.raises(object_records.UniqueConstraintError): |
| 186 | create(data_dir, "w2", code=" GC-ABC ") |
| 187 | with pytest.raises(object_records.UniqueConstraintError): |
| 188 | create(data_dir, "w3", event_id=" Evt ") |
| 189 | create(data_dir, "w4", event_id="evt") # case-sensitive unless ignore_case |
| 190 | assert ids(data_dir) == ["w1", "w4"] |
| 191 | |
| 192 | |
| 193 | def test_a_key_of_several_fields_collides_only_when_all_match(tmp_path, storage): |
| 194 | data_dir = stage(tmp_path, [{"fields": ["owner_id", "event_id", "code"]}], storage=storage) |
| 195 | create(data_dir, "e1", owner_id="ann", event_id="x", code="1") |
| 196 | create(data_dir, "e2", owner_id="ann", event_id="x", code="2") |
| 197 | create(data_dir, "e3", owner_id="ann", event_id="x") # a blank part: exempt |
| 198 | create(data_dir, "e4", owner_id="ann", event_id="x") |
| 199 | with pytest.raises(object_records.UniqueConstraintError): |
| 200 | create(data_dir, "e5", owner_id="ann", event_id="x", code="1") |
| 201 | assert ids(data_dir) == ["e1", "e2", "e3", "e4"] |
| 202 | |
| 203 | |
| 204 | def test_every_constraint_is_checked_and_the_error_names_the_one_that_failed(tmp_path): |
| 205 | data_dir = stage(tmp_path, [{"fields": ["event_id"]}, |
| 206 | {"fields": ["code"], "message": "That code is taken."}]) |
| 207 | create(data_dir, "e1", event_id="evt-1", code="A") |
| 208 | with pytest.raises(object_records.UniqueConstraintError) as refusal: |
| 209 | create(data_dir, "e2", event_id="evt-2", code="A") |
| 210 | assert refusal.value.fields == ["code"] |
| 211 | assert str(refusal.value) == "That code is taken." |
| 212 | |
| 213 | |
| 214 | def test_a_collection_without_constraints_builds_no_index(tmp_path, monkeypatch): |
| 215 | data_dir = stage(tmp_path, []) |
| 216 | built = [] |
| 217 | real = object_records._build_unique_map |
| 218 | monkeypatch.setattr(object_records, "_build_unique_map", |
| 219 | lambda *args, **kwargs: built.append(1) or real(*args, **kwargs)) |
| 220 | create(data_dir, "e1", event_id="evt-1") |
| 221 | create(data_dir, "e2", event_id="evt-1") |
| 222 | update(data_dir, "e2", event_id="evt-1") |
| 223 | object_records.delete_collection_record("events", "e1", base_dir=data_dir, roots=[]) |
| 224 | assert built == [] |
| 225 | |
| 226 | |
| 227 | # --- update and delete ------------------------------------------------------------ |
| 228 | |
| 229 | |
| 230 | def test_an_update_cannot_take_a_key_another_record_holds(tmp_path, storage): |
| 231 | data_dir = stage(tmp_path, PER_OWNER, storage=storage) |
| 232 | create(data_dir, "e1", owner_id="ann", event_id="evt-1") |
| 233 | create(data_dir, "e2", owner_id="ann", event_id="evt-2", quantity="5") |
| 234 | |
| 235 | with pytest.raises(object_records.UniqueConstraintError) as refusal: |
| 236 | update(data_dir, "e2", event_id="evt-1") |
| 237 | assert refusal.value.existing_id == "e1" |
| 238 | # ...nor by moving into the scope where the key is taken. |
| 239 | create(data_dir, "e3", owner_id="bob", event_id="evt-1") |
| 240 | with pytest.raises(object_records.UniqueConstraintError): |
| 241 | update(data_dir, "e3", owner_id="ann") |
| 242 | |
| 243 | stored = {row["id"]: row for row in rows(data_dir)} |
| 244 | assert (stored["e2"]["event_id"], stored["e3"]["owner_id"]) == ("evt-2", "bob") |
| 245 | changes = object_record_changes.list_record_changes("events", base_dir=data_dir)["changes"] |
| 246 | assert [c["action"] for c in changes] == ["create", "create", "create"] |
| 247 | |
| 248 | |
| 249 | def test_a_record_may_keep_its_own_key_and_change_everything_else(tmp_path, storage): |
| 250 | data_dir = stage(tmp_path, PER_OWNER, storage=storage) |
| 251 | create(data_dir, "e1", owner_id="ann", event_id="evt-1", quantity="1") |
| 252 | assert update(data_dir, "e1", quantity="2")["quantity"] == "2" |
| 253 | assert update(data_dir, "e1", event_id="evt-1", quantity="3")["quantity"] == "3" |
| 254 | assert update(data_dir, "e1", event_id=" evt-1 ")["event_id"] == " evt-1 " |
| 255 | |
| 256 | |
| 257 | def test_a_key_given_up_by_an_update_or_a_delete_is_free_again(tmp_path, storage): |
| 258 | data_dir = stage(tmp_path, PER_OWNER, storage=storage) |
| 259 | create(data_dir, "e1", owner_id="ann", event_id="evt-1") |
| 260 | update(data_dir, "e1", event_id="evt-9") |
| 261 | create(data_dir, "e2", owner_id="ann", event_id="evt-1") # e1 let go of it |
| 262 | with pytest.raises(object_records.UniqueConstraintError): |
| 263 | create(data_dir, "e3", owner_id="ann", event_id="evt-9") # e1 holds this now |
| 264 | |
| 265 | object_records.delete_collection_record("events", "e1", base_dir=data_dir, roots=[]) |
| 266 | create(data_dir, "e3", owner_id="ann", event_id="evt-9") |
| 267 | with pytest.raises(object_records.UniqueConstraintError): |
| 268 | create(data_dir, "e4", owner_id="ann", event_id="evt-1") # e2 still holds it |
| 269 | assert ids(data_dir) == ["e2", "e3"] |
| 270 | |
| 271 | |
| 272 | # --- data that was already there ------------------------------------------------- |
| 273 | |
| 274 | |
| 275 | def stage_with_legacy_duplicates(tmp_path, storage=None): |
| 276 | """Two rows already share a key: the constraint was declared afterwards.""" |
| 277 | data_dir = stage(tmp_path, [], storage=storage) |
| 278 | create(data_dir, "old1", owner_id="ann", event_id="evt-1", quantity="1") |
| 279 | create(data_dir, "old2", owner_id="ann", event_id="evt-1", quantity="2") |
| 280 | create(data_dir, "old3", owner_id="ann", event_id="evt-2") |
| 281 | return stage(tmp_path, PER_OWNER, storage=storage) |
| 282 | |
| 283 | |
| 284 | def test_declaring_a_constraint_over_existing_duplicates_stops_new_ones_only(tmp_path, storage): |
| 285 | """The platform does not pick a winner among rows it did not write. They |
| 286 | stay, stay editable, and no THIRD holder of the key may arrive.""" |
| 287 | data_dir = stage_with_legacy_duplicates(tmp_path, storage) |
| 288 | |
| 289 | with pytest.raises(object_records.UniqueConstraintError): |
| 290 | create(data_dir, "new1", owner_id="ann", event_id="evt-1") |
| 291 | with pytest.raises(object_records.UniqueConstraintError): |
| 292 | update(data_dir, "old3", event_id="evt-1") |
| 293 | assert update(data_dir, "old2", quantity="20")["quantity"] == "20" # key untouched |
| 294 | |
| 295 | # Deleting one duplicate does not free a key the other still holds. |
| 296 | object_records.delete_collection_record("events", "old1", base_dir=data_dir, roots=[]) |
| 297 | with pytest.raises(object_records.UniqueConstraintError) as refusal: |
| 298 | create(data_dir, "new1", owner_id="ann", event_id="evt-1") |
| 299 | assert refusal.value.existing_id == "old2" |
| 300 | object_records.delete_collection_record("events", "old2", base_dir=data_dir, roots=[]) |
| 301 | create(data_dir, "new1", owner_id="ann", event_id="evt-1") |
| 302 | |
| 303 | |
| 304 | def test_existing_duplicates_can_be_listed_before_or_after_declaring(tmp_path): |
| 305 | data_dir = stage_with_legacy_duplicates(tmp_path) |
| 306 | assert object_records.find_unique_violations("events", base_dir=data_dir, roots=[]) == [ |
| 307 | {"fields": ["event_id"], "scope": ["owner_id"], |
| 308 | "values": {"event_id": "evt-1", "owner_id": "ann"}, "ids": ["old1", "old2"]}, |
| 309 | ] |
| 310 | object_records.delete_collection_record("events", "old2", base_dir=data_dir, roots=[]) |
| 311 | assert object_records.find_unique_violations("events", base_dir=data_dir, roots=[]) == [] |
| 312 | |
| 313 | |
| 314 | # --- the index is kept, not rebuilt ------------------------------------------------ |
| 315 | |
| 316 | |
| 317 | def count_builds(monkeypatch): |
| 318 | built = [] |
| 319 | real = object_records._build_unique_map |
| 320 | monkeypatch.setattr(object_records, "_build_unique_map", |
| 321 | lambda *args, **kwargs: built.append(1) or real(*args, **kwargs)) |
| 322 | return built |
| 323 | |
| 324 | |
| 325 | def test_a_run_of_writes_builds_the_index_once_not_once_per_write(tmp_path, storage, monkeypatch): |
| 326 | """The check must not scan the collection on every write: that turns an |
| 327 | O(1) append into O(n) and a bulk load into O(n^2).""" |
| 328 | data_dir = stage(tmp_path, PER_OWNER, storage=storage) |
| 329 | create(data_dir, "seed", owner_id="ann", event_id="seed") |
| 330 | object_records._UNIQUE_INDEX.clear() |
| 331 | built = count_builds(monkeypatch) |
| 332 | |
| 333 | for n in range(40): |
| 334 | create(data_dir, f"e{n}", owner_id="ann", event_id=f"evt-{n}") |
| 335 | update(data_dir, "e3", event_id="evt-moved") |
| 336 | object_records.delete_collection_record("events", "e4", base_dir=data_dir, roots=[]) |
| 337 | for n in (3, 4): |
| 338 | create(data_dir, f"again{n}", owner_id="ann", event_id=f"evt-{n}") |
| 339 | for n in (5, 6): |
| 340 | with pytest.raises(object_records.UniqueConstraintError): |
| 341 | create(data_dir, f"dup{n}", owner_id="ann", event_id=f"evt-{n}") |
| 342 | |
| 343 | assert built == [1] # one constraint, built once |
| 344 | assert len(ids(data_dir)) == 42 |
| 345 | |
| 346 | |
| 347 | def test_a_write_that_takes_no_key_does_not_build_the_index(tmp_path, storage, monkeypatch): |
| 348 | """A status flip or a rollup recompute on a constrained collection must |
| 349 | not pay for an index it has no question to ask of -- that matters when |
| 350 | several processes take turns writing, since each one's index is stale |
| 351 | after the other's write.""" |
| 352 | data_dir = stage(tmp_path, PER_OWNER, storage=storage) |
| 353 | create(data_dir, "e1", owner_id="ann", event_id="evt-1") |
| 354 | create(data_dir, "e2", owner_id="ann", event_id="evt-2") |
| 355 | object_records._UNIQUE_INDEX.clear() |
| 356 | built = count_builds(monkeypatch) |
| 357 | |
| 358 | update(data_dir, "e1", quantity="7") |
| 359 | create(data_dir, "e3", owner_id="ann") # no key at all |
| 360 | object_records.delete_collection_record("events", "e2", base_dir=data_dir, roots=[]) |
| 361 | assert built == [] |
| 362 | |
| 363 | with pytest.raises(object_records.UniqueConstraintError): |
| 364 | create(data_dir, "e4", owner_id="ann", event_id="evt-1") |
| 365 | create(data_dir, "e5", owner_id="ann", event_id="evt-2") # freed by the delete above |
| 366 | assert built == [1] |
| 367 | |
| 368 | |
| 369 | def test_a_collection_too_large_to_cache_is_still_enforced_without_a_fold_per_write( |
| 370 | tmp_path, monkeypatch): |
| 371 | """Over DBBASIC_RECORDS_CACHE_MAX_ROWS an append collection is never in |
| 372 | the records cache (writes resolve ids through the offset sidecar). The |
| 373 | constraint still holds, and still costs one build, not one per write.""" |
| 374 | monkeypatch.setenv(object_records.RECORDS_CACHE_MAX_ROWS_ENV, "5") |
| 375 | data_dir = stage(tmp_path, PER_OWNER, storage="append") |
| 376 | for n in range(12): |
| 377 | create(data_dir, f"e{n}", owner_id="ann", event_id=f"evt-{n}") |
| 378 | object_records._UNIQUE_INDEX.clear() |
| 379 | object_records._RECORDS_CACHE.clear() |
| 380 | built = count_builds(monkeypatch) |
| 381 | folds = [] |
| 382 | real_parse = object_records._parse_records_file |
| 383 | monkeypatch.setattr(object_records, "_parse_records_file", |
| 384 | lambda *args, **kwargs: folds.append(1) or real_parse(*args, **kwargs)) |
| 385 | |
| 386 | for n in range(12, 30): |
| 387 | create(data_dir, f"e{n}", owner_id="ann", event_id=f"evt-{n}") |
| 388 | with pytest.raises(object_records.UniqueConstraintError): |
| 389 | create(data_dir, "dup", owner_id="ann", event_id="evt-7") |
| 390 | with pytest.raises(object_records.UniqueConstraintError): |
| 391 | create(data_dir, "dup", owner_id="ann", event_id="evt-25") |
| 392 | |
| 393 | assert built == [1] |
| 394 | assert len(folds) == 1 # the one build; no write after it folded the file |
| 395 | assert len(ids(data_dir)) == 30 |
| 396 | |
| 397 | |
| 398 | _OTHER_PROCESS = """\ |
| 399 | import sys |
| 400 | sys.path.insert(0, sys.argv[1]) |
| 401 | import object_records |
| 402 | try: |
| 403 | object_records.create_collection_record( |
| 404 | "events", {"id": sys.argv[3], "owner_id": "ann", "event_id": sys.argv[4]}, |
| 405 | base_dir=sys.argv[2], roots=[]) |
| 406 | print("created") |
| 407 | except object_records.UniqueConstraintError: |
| 408 | print("refused") |
| 409 | """ |
| 410 | |
| 411 | |
| 412 | def in_another_process(tmp_path, data_dir, record_id, event_id): |
| 413 | script = tmp_path / "_other_process.py" |
| 414 | script.write_text(_OTHER_PROCESS) |
| 415 | done = subprocess.run( |
| 416 | [sys.executable, str(script), REPO_ROOT, str(data_dir), record_id, event_id], |
| 417 | capture_output=True, text=True, timeout=60) |
| 418 | assert done.returncode == 0, done.stderr |
| 419 | return done.stdout.strip() |
| 420 | |
| 421 | |
| 422 | def test_a_write_by_another_process_is_seen_by_this_ones_index(tmp_path, storage): |
| 423 | """The worker pool and the daemon write the same files from their own |
| 424 | processes. This process's index is only good for the file it describes.""" |
| 425 | data_dir = stage(tmp_path, PER_OWNER, storage=storage) |
| 426 | create(data_dir, "e1", owner_id="ann", event_id="evt-1") # index is warm here |
| 427 | |
| 428 | assert in_another_process(tmp_path, data_dir, "e2", "evt-2") == "created" |
| 429 | assert in_another_process(tmp_path, data_dir, "e3", "evt-1") == "refused" |
| 430 | |
| 431 | with pytest.raises(object_records.UniqueConstraintError): |
| 432 | create(data_dir, "e4", owner_id="ann", event_id="evt-2") # written over there |
| 433 | create(data_dir, "e5", owner_id="ann", event_id="evt-5") |
| 434 | assert in_another_process(tmp_path, data_dir, "e6", "evt-5") == "refused" |
| 435 | assert ids(data_dir) == ["e1", "e2", "e5"] |
| 436 | |
| 437 | |
| 438 | def test_a_changed_declaration_is_enforced_from_the_next_write(tmp_path): |
| 439 | data_dir = stage(tmp_path, PER_OWNER) |
| 440 | create(data_dir, "e1", owner_id="ann", event_id="evt-1", code="A") |
| 441 | create(data_dir, "e2", owner_id="bob", event_id="evt-1", code="A") # per owner: fine |
| 442 | stage(tmp_path, [{"fields": ["code"]}]) |
| 443 | with pytest.raises(object_records.UniqueConstraintError): |
| 444 | create(data_dir, "e3", owner_id="cat", event_id="evt-3", code="A") |
| 445 | create(data_dir, "e4", owner_id="ann", event_id="evt-1", code="B") # old rule is gone |
| 446 | |
| 447 | |
| 448 | # --- the race this exists for ------------------------------------------------------ |
| 449 | |
| 450 | |
| 451 | def test_threads_racing_real_creates_of_one_key_land_exactly_one(tmp_path, storage): |
| 452 | """Sixteen writers, one key, released together, for several keys in a |
| 453 | row. Without the check inside the lock every one of them would pass a |
| 454 | read-then-write duplicate test.""" |
| 455 | data_dir = stage(tmp_path, PER_OWNER, storage=storage) |
| 456 | writers, rounds = 16, 6 |
| 457 | outcomes = [] |
| 458 | |
| 459 | for round_number in range(rounds): |
| 460 | barrier = threading.Barrier(writers) |
| 461 | |
| 462 | def attempt(n, round_number=round_number, barrier=barrier): |
| 463 | barrier.wait() |
| 464 | try: |
| 465 | create(data_dir, f"r{round_number}-w{n}", owner_id="ann", |
| 466 | event_id=f"evt-{round_number}") |
| 467 | outcomes.append((round_number, "created")) |
| 468 | except object_records.UniqueConstraintError: |
| 469 | outcomes.append((round_number, "refused")) |
| 470 | except Exception as exc: # noqa: BLE001 - reported below |
| 471 | outcomes.append((round_number, f"crashed: {exc!r}")) |
| 472 | |
| 473 | threads = [threading.Thread(target=attempt, args=(n,)) for n in range(writers)] |
| 474 | for thread in threads: |
| 475 | thread.start() |
| 476 | for thread in threads: |
| 477 | thread.join(timeout=60) |
| 478 | |
| 479 | for round_number in range(rounds): |
| 480 | results = sorted(what for r, what in outcomes if r == round_number) |
| 481 | assert results == ["created"] + ["refused"] * (writers - 1), results |
| 482 | stored = rows(data_dir) |
| 483 | assert sorted(row["event_id"] for row in stored) == sorted(f"evt-{n}" for n in range(rounds)) |
| 484 | |
| 485 | |
| 486 | def test_threads_racing_updates_onto_one_key_land_exactly_one(tmp_path, storage): |
| 487 | data_dir = stage(tmp_path, PER_OWNER, storage=storage) |
| 488 | writers = 12 |
| 489 | for n in range(writers): |
| 490 | create(data_dir, f"e{n}", owner_id="ann", event_id=f"own-{n}") |
| 491 | barrier = threading.Barrier(writers) |
| 492 | outcomes = [] |
| 493 | |
| 494 | def attempt(n): |
| 495 | barrier.wait() |
| 496 | try: |
| 497 | update(data_dir, f"e{n}", event_id="contested") |
| 498 | outcomes.append("updated") |
| 499 | except object_records.UniqueConstraintError: |
| 500 | outcomes.append("refused") |
| 501 | |
| 502 | threads = [threading.Thread(target=attempt, args=(n,)) for n in range(writers)] |
| 503 | for thread in threads: |
| 504 | thread.start() |
| 505 | for thread in threads: |
| 506 | thread.join(timeout=60) |
| 507 | |
| 508 | assert sorted(outcomes) == ["refused"] * (writers - 1) + ["updated"] |
| 509 | assert [row["event_id"] for row in rows(data_dir)].count("contested") == 1 |
| 510 | |
| 511 | |
| 512 | _RACER = """\ |
| 513 | import sys, time |
| 514 | from pathlib import Path |
| 515 | sys.path.insert(0, sys.argv[1]) |
| 516 | import object_records |
| 517 | data_dir, who, keys, barrier = sys.argv[2], sys.argv[3], int(sys.argv[4]), Path(sys.argv[5]) |
| 518 | while not barrier.exists(): |
| 519 | time.sleep(0.001) |
| 520 | created = 0 |
| 521 | for n in range(keys): |
| 522 | try: |
| 523 | object_records.create_collection_record( |
| 524 | "events", {"id": f"{who}-{n}", "owner_id": "ann", "event_id": f"evt-{n}"}, |
| 525 | base_dir=data_dir, roots=[]) |
| 526 | created += 1 |
| 527 | except object_records.UniqueConstraintError: |
| 528 | pass |
| 529 | print(created) |
| 530 | """ |
| 531 | |
| 532 | |
| 533 | def test_processes_racing_real_creates_of_the_same_keys_land_each_key_once(tmp_path, storage): |
| 534 | """Separate interpreters, cold caches, nothing shared but the files: |
| 535 | the shape of a worker pool, or of the server and the daemon. Each of |
| 536 | six processes tries to create the same forty keys.""" |
| 537 | data_dir = stage(tmp_path, PER_OWNER, storage=storage) |
| 538 | script = tmp_path / "_racer.py" |
| 539 | script.write_text(_RACER) |
| 540 | barrier = tmp_path / "go" |
| 541 | processes, keys = 6, 40 |
| 542 | running = [ |
| 543 | subprocess.Popen( |
| 544 | [sys.executable, str(script), REPO_ROOT, str(data_dir), f"p{p}", str(keys), str(barrier)], |
| 545 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) |
| 546 | for p in range(processes) |
| 547 | ] |
| 548 | time.sleep(0.5) # let every interpreter reach its wait |
| 549 | barrier.write_text("go") |
| 550 | created = [] |
| 551 | for process in running: |
| 552 | out, err = process.communicate(timeout=120) |
| 553 | assert process.returncode == 0, err |
| 554 | created.append(int(out.strip())) |
| 555 | |
| 556 | object_records._RECORDS_CACHE.clear() |
| 557 | stored = rows(data_dir) |
| 558 | assert sorted(row["event_id"] for row in stored) == sorted(f"evt-{n}" for n in range(keys)) |
| 559 | assert sum(created) == keys, created |
| 560 | assert object_records.find_unique_violations("events", base_dir=data_dir, roots=[]) == [] |
| 561 | |
| 562 | |
| 563 | # --- over HTTP --------------------------------------------------------------------- |
| 564 | |
| 565 | |
| 566 | def http_site(tmp_path, monkeypatch, unique=PER_OWNER): |
| 567 | data_dir = stage(tmp_path, unique) |
| 568 | monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir)) |
| 569 | enable_admin_token(monkeypatch) |
| 570 | return data_dir |
| 571 | |
| 572 | |
| 573 | def post(record): |
| 574 | return request("/collections/events/records", method="POST", |
| 575 | body=json.dumps(record).encode("utf-8"), headers=AUTH) |
| 576 | |
| 577 | |
| 578 | def put(record_id, changes): |
| 579 | return request(f"/collections/events/records/{record_id}", method="PUT", |
| 580 | body=json.dumps(changes).encode("utf-8"), headers=AUTH) |
| 581 | |
| 582 | |
| 583 | def test_a_violation_over_http_is_a_409_that_names_the_fields_and_no_other_record( |
| 584 | tmp_path, monkeypatch): |
| 585 | data_dir = http_site(tmp_path, monkeypatch) |
| 586 | assert post({"id": "secret-row-id", "owner_id": "ann", "event_id": "evt-1"})[0] == 201 |
| 587 | |
| 588 | status, _, payload = post({"id": "e2", "owner_id": "ann", "event_id": "evt-1"}) |
| 589 | |
| 590 | assert status == 409 |
| 591 | assert payload["status"] == "error" |
| 592 | assert payload["code"] == "unique_violation" |
| 593 | assert payload["fields"] == ["event_id"] |
| 594 | assert payload["scope"] == ["owner_id"] |
| 595 | assert "event_id" in payload["error"] |
| 596 | # The caller may not be allowed to read the record that holds the key. |
| 597 | assert "secret-row-id" not in json.dumps(payload) |
| 598 | assert ids(data_dir) == ["secret-row-id"] |
| 599 | |
| 600 | |
| 601 | def test_an_update_violation_over_http_is_the_same_409(tmp_path, monkeypatch): |
| 602 | data_dir = http_site(tmp_path, monkeypatch) |
| 603 | assert post({"id": "e1", "owner_id": "ann", "event_id": "evt-1"})[0] == 201 |
| 604 | assert post({"id": "e2", "owner_id": "ann", "event_id": "evt-2"})[0] == 201 |
| 605 | |
| 606 | status, _, payload = put("e2", {"event_id": "evt-1"}) |
| 607 | |
| 608 | assert (status, payload["code"], payload["fields"]) == (409, "unique_violation", ["event_id"]) |
| 609 | assert [row["event_id"] for row in rows(data_dir)] == ["evt-1", "evt-2"] |
| 610 | assert put("e2", {"quantity": "4"})[0] == 200 |
| 611 | |
| 612 | |
| 613 | def test_two_overlapping_http_creates_of_one_key_land_once(tmp_path, monkeypatch): |
| 614 | """The window the hooks could not close, made deterministic the way |
| 615 | tests/test_findings_money_gates.py does it: request B runs start to |
| 616 | finish after request A has passed every pre-lock gate and before A |
| 617 | persists. B lands; A, arriving at the lock second, is refused.""" |
| 618 | data_dir = http_site(tmp_path, monkeypatch) |
| 619 | real = object_records.create_collection_record |
| 620 | state = {"armed": True, "second": None} |
| 621 | |
| 622 | def create_with_overlap(name, record, *args, **kwargs): |
| 623 | if name == "events" and state["armed"]: |
| 624 | state["armed"] = False |
| 625 | worker = threading.Thread(target=lambda: state.__setitem__( |
| 626 | "second", post({"id": "b", "owner_id": "ann", "event_id": "evt-1"}))) |
| 627 | worker.start() |
| 628 | worker.join(timeout=30) |
| 629 | return real(name, record, *args, **kwargs) |
| 630 | |
| 631 | monkeypatch.setattr(object_records, "create_collection_record", create_with_overlap) |
| 632 | first = post({"id": "a", "owner_id": "ann", "event_id": "evt-1"}) |
| 633 | |
| 634 | assert state["second"] is not None, "request B never ran inside request A" |
| 635 | assert sorted([first[0], state["second"][0]]) == [201, 409] |
| 636 | assert first[2]["code"] == "unique_violation" |
| 637 | assert ids(data_dir) == ["b"] |