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_rollup_parents_cache.py · 13.7 KB · 328 lines
| 1 | """The rollup-parents index is kept only while the schema files prove it current. |
| 2 | |
| 3 | Every write asks "which schemas roll up this collection", and answering |
| 4 | meant loading every schema (about 8 ms with 102 of them). The answer is now |
| 5 | built once per state of the schemas directory. A stale answer here is silent |
| 6 | and wrong in the worst way: a parent's total stops moving, or keeps being |
| 7 | recomputed from a rollup that was removed. So every test changes the disk the |
| 8 | way some other writer would (the API, the installer, an editor) and checks |
| 9 | the very next call, against the uncached scan and against real writes. |
| 10 | """ |
| 11 | |
| 12 | import json |
| 13 | import os |
| 14 | import random |
| 15 | import threading |
| 16 | import time |
| 17 | from pathlib import Path |
| 18 | |
| 19 | import pytest |
| 20 | |
| 21 | import object_packages |
| 22 | import object_records |
| 23 | import object_schemas |
| 24 | |
| 25 | |
| 26 | def settle() -> None: |
| 27 | """Wait until an index built now may be kept (_ROLLUP_PARENTS_RACY_NS).""" |
| 28 | time.sleep(object_records._ROLLUP_PARENTS_RACY_NS / 1e9 + 0.03) |
| 29 | |
| 30 | |
| 31 | def rollup(name: str, source: str, fk: str = "parent_id") -> dict: |
| 32 | return {"name": name, "type": "computed", "rollup": {"collection": source, "fk_field": fk, "op": "count"}} |
| 33 | |
| 34 | |
| 35 | def schema_text(*extra_fields: dict) -> str: |
| 36 | return json.dumps({"fields": [{"name": "id"}, {"name": "title"}, {"name": "parent_id"}, *extra_fields]}) |
| 37 | |
| 38 | |
| 39 | def write_schema(data_dir: Path, name: str, *extra_fields: dict) -> Path: |
| 40 | path = data_dir / "schemas" / f"{name}.json" |
| 41 | path.parent.mkdir(parents=True, exist_ok=True) |
| 42 | path.write_text(schema_text(*extra_fields)) |
| 43 | return path |
| 44 | |
| 45 | |
| 46 | def parents(data_dir: Path, source: str): |
| 47 | return object_records._rollup_parents_for_source(source, base_dir=data_dir, roots=[]) |
| 48 | |
| 49 | |
| 50 | def scanned(data_dir: Path, source: str): |
| 51 | return object_records._scan_rollup_parents_for_source(source, base_dir=data_dir, roots=[]) |
| 52 | |
| 53 | |
| 54 | def parent_names(data_dir: Path, source: str) -> list[str]: |
| 55 | return [name for name, _specs in parents(data_dir, source)] |
| 56 | |
| 57 | |
| 58 | @pytest.fixture |
| 59 | def builds(monkeypatch): |
| 60 | """Counts index builds, to tell a kept index from a rebuilt one.""" |
| 61 | calls = [] |
| 62 | real = object_records._build_rollup_parent_index |
| 63 | |
| 64 | def counting(base_dir, roots): |
| 65 | calls.append(1) |
| 66 | return real(base_dir, roots) |
| 67 | |
| 68 | monkeypatch.setattr(object_records, "_build_rollup_parent_index", counting) |
| 69 | return calls |
| 70 | |
| 71 | |
| 72 | @pytest.fixture |
| 73 | def data_dir(tmp_path): |
| 74 | data_dir = tmp_path / "data" |
| 75 | write_schema(data_dir, "lines") |
| 76 | write_schema(data_dir, "orders", rollup("line_count", "lines"), rollup("note_count", "notes")) |
| 77 | write_schema(data_dir, "batches", rollup("line_count", "lines")) |
| 78 | write_schema(data_dir, "notes", rollup("reply_count", "notes")) # rolls up itself: never a parent of itself |
| 79 | write_schema(data_dir, "plain") |
| 80 | return data_dir |
| 81 | |
| 82 | |
| 83 | def test_the_index_answers_what_the_scan_answers_for_every_collection(data_dir): |
| 84 | settle() |
| 85 | for source in ("lines", "notes", "orders", "batches", "plain", "no_such_collection"): |
| 86 | assert parents(data_dir, source) == scanned(data_dir, source), source |
| 87 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 88 | assert parent_names(data_dir, "notes") == ["orders"], "a collection is never its own rollup parent" |
| 89 | assert parent_names(data_dir, "plain") == [] |
| 90 | |
| 91 | |
| 92 | def test_a_settled_schemas_directory_is_indexed_once(data_dir, builds): |
| 93 | settle() |
| 94 | first = parents(data_dir, "lines") |
| 95 | assert len(builds) == 1 |
| 96 | for source in ("lines", "notes", "orders", "plain"): |
| 97 | parents(data_dir, source) |
| 98 | assert len(builds) == 1, "unchanged schema files must not be loaded again" |
| 99 | # Callers own what they get: emptying it must not empty the next answer. |
| 100 | first[0][1].clear() |
| 101 | first.clear() |
| 102 | assert parents(data_dir, "lines") == scanned(data_dir, "lines") |
| 103 | assert len(builds) == 1 |
| 104 | |
| 105 | |
| 106 | def test_a_rollup_added_through_the_schema_api_is_seen_by_the_next_call(data_dir): |
| 107 | settle() |
| 108 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 109 | object_schemas.replace_schema( |
| 110 | "plain", json.loads(schema_text(rollup("line_count", "lines"))), base_dir=data_dir |
| 111 | ) |
| 112 | assert parent_names(data_dir, "lines") == ["batches", "orders", "plain"] |
| 113 | object_schemas.replace_schema("plain", json.loads(schema_text()), base_dir=data_dir) |
| 114 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 115 | |
| 116 | |
| 117 | def test_a_schema_edited_by_hand_in_place_is_seen_by_the_next_call(data_dir): |
| 118 | """An editor that writes in place does not touch the directory, and |
| 119 | this edit keeps the file the same size: only the file's own times can |
| 120 | give it away.""" |
| 121 | settle() |
| 122 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 123 | path = data_dir / "schemas" / "batches.json" |
| 124 | text = path.read_text() |
| 125 | edited = text.replace('"collection": "lines"', '"collection": "notes"') |
| 126 | assert len(edited) == len(text) |
| 127 | path.write_text(edited) |
| 128 | assert parent_names(data_dir, "lines") == ["orders"] |
| 129 | assert parent_names(data_dir, "notes") == ["batches", "orders"] |
| 130 | settle() |
| 131 | assert parent_names(data_dir, "notes") == ["batches", "orders"] |
| 132 | path.write_text(text) |
| 133 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 134 | |
| 135 | |
| 136 | def test_a_schema_file_created_or_deleted_is_seen_by_the_next_call(data_dir): |
| 137 | settle() |
| 138 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 139 | path = write_schema(data_dir, "shipments", rollup("line_count", "lines")) |
| 140 | assert parent_names(data_dir, "lines") == ["batches", "orders", "shipments"] |
| 141 | settle() |
| 142 | assert parent_names(data_dir, "lines") == ["batches", "orders", "shipments"] |
| 143 | path.unlink() |
| 144 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 145 | (data_dir / "schemas" / "batches.json").unlink() |
| 146 | assert parent_names(data_dir, "lines") == ["orders"] |
| 147 | |
| 148 | |
| 149 | def test_installing_a_package_that_declares_a_rollup_is_seen_by_the_next_call(data_dir, tmp_path): |
| 150 | settle() |
| 151 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 152 | package_dir = tmp_path / "packages" / "app-pallets" |
| 153 | (package_dir / "schemas").mkdir(parents=True) |
| 154 | (package_dir / object_packages.MANIFEST_FILE).write_text(json.dumps({ |
| 155 | "id": "app-pallets", "name": "Pallets", "version": "0.1.0", |
| 156 | "schemas": [{"collection": "pallets", "path": "schemas/pallets.json"}], |
| 157 | })) |
| 158 | (package_dir / "schemas" / "pallets.json").write_text(schema_text(rollup("line_count", "lines"))) |
| 159 | object_packages.install_package( |
| 160 | "app-pallets", root=tmp_path / "packages", base_dir=data_dir, object_roots=[tmp_path / "objects"] |
| 161 | ) |
| 162 | assert parent_names(data_dir, "lines") == ["batches", "orders", "pallets"] |
| 163 | # Taking the package's schema out again, as an operator removing it would. |
| 164 | (data_dir / "schemas" / "pallets.json").unlink() |
| 165 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 166 | |
| 167 | |
| 168 | def test_a_write_updates_a_parent_whose_rollup_was_declared_a_moment_ago(data_dir): |
| 169 | """End to end, through the write path: the first child write after the |
| 170 | schema changes must move the new parent's count, and the first one after |
| 171 | the rollup is removed must not.""" |
| 172 | create = object_records.create_collection_record |
| 173 | get = object_records.get_collection_record |
| 174 | create("plain", {"id": "p1", "title": "parent"}, base_dir=data_dir, roots=[]) |
| 175 | settle() |
| 176 | create("lines", {"id": "l1", "title": "one", "parent_id": "p1"}, base_dir=data_dir, roots=[]) |
| 177 | assert "line_count" not in get("plain", "p1", base_dir=data_dir, roots=[]) |
| 178 | |
| 179 | object_schemas.replace_schema( |
| 180 | "plain", json.loads(schema_text(rollup("line_count", "lines"))), base_dir=data_dir |
| 181 | ) |
| 182 | create("lines", {"id": "l2", "title": "two", "parent_id": "p1"}, base_dir=data_dir, roots=[]) |
| 183 | assert get("plain", "p1", base_dir=data_dir, roots=[])["line_count"] == "2" |
| 184 | |
| 185 | (data_dir / "schemas" / "plain.json").write_text(schema_text({"name": "line_count"})) |
| 186 | create("lines", {"id": "l3", "title": "three", "parent_id": "p1"}, base_dir=data_dir, roots=[]) |
| 187 | assert get("plain", "p1", base_dir=data_dir, roots=[])["line_count"] == "2", ( |
| 188 | "the rollup was removed from the schema: the stored number must stop moving" |
| 189 | ) |
| 190 | |
| 191 | |
| 192 | def test_two_schema_changes_in_the_same_instant_are_both_seen(data_dir, builds): |
| 193 | settle() |
| 194 | parents(data_dir, "lines") |
| 195 | write_schema(data_dir, "plain", rollup("line_count", "lines")) |
| 196 | before = len(builds) |
| 197 | assert parent_names(data_dir, "lines") == ["batches", "orders", "plain"] |
| 198 | assert parent_names(data_dir, "lines") == ["batches", "orders", "plain"] |
| 199 | assert len(builds) == before, "nothing may be indexed while a schema file is this fresh" |
| 200 | write_schema(data_dir, "plain") |
| 201 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 202 | settle() |
| 203 | parents(data_dir, "lines") |
| 204 | parents(data_dir, "lines") |
| 205 | assert len(builds) == before + 1, "once the files have settled the index is kept again" |
| 206 | |
| 207 | |
| 208 | def test_a_schema_that_does_not_load_is_skipped_and_never_cached(data_dir, builds): |
| 209 | """The lookup runs after the write has landed, so a schema file that |
| 210 | does not load is skipped rather than raised (it used to fail every write |
| 211 | to any other collection after the row was written; see |
| 212 | test_rollup_broken_schema.py). Its own rollups are unknowable while it is |
| 213 | broken. Nothing about the broken state may be remembered past the file |
| 214 | being fixed.""" |
| 215 | settle() |
| 216 | path = data_dir / "schemas" / "batches.json" |
| 217 | good = path.read_text() |
| 218 | path.write_text("{ not json") |
| 219 | settle() |
| 220 | before = len(builds) |
| 221 | for _ in range(2): |
| 222 | assert parent_names(data_dir, "lines") == ["orders"] |
| 223 | assert [name for name, _ in scanned(data_dir, "lines")] == ["orders"] |
| 224 | assert len(builds) == before + 2, "an index with a schema that does not load is never kept" |
| 225 | assert parents(data_dir, "batches") == scanned(data_dir, "batches") == [] |
| 226 | path.write_text(good) |
| 227 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 228 | |
| 229 | (data_dir / "schemas" / "bad-name.json").write_text(schema_text(rollup("line_count", "lines"))) |
| 230 | settle() |
| 231 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 232 | assert [name for name, _ in scanned(data_dir, "lines")] == ["batches", "orders"] |
| 233 | (data_dir / "schemas" / "bad-name.json").unlink() |
| 234 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 235 | |
| 236 | |
| 237 | def test_a_symlinked_schema_file_is_never_indexed(data_dir, builds, tmp_path): |
| 238 | """A link's target can be rewritten without the link, or the schemas |
| 239 | directory, changing at all.""" |
| 240 | target = data_dir / "schemas" / "shared-definition.data" |
| 241 | target.write_text(schema_text(rollup("line_count", "lines"))) |
| 242 | os.symlink(target, data_dir / "schemas" / "linked.json") |
| 243 | settle() |
| 244 | assert parent_names(data_dir, "lines") == ["batches", "linked", "orders"] |
| 245 | target.write_text(schema_text()) |
| 246 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 247 | assert builds == [], "an index over a symlink must never be built, let alone kept" |
| 248 | |
| 249 | |
| 250 | def test_no_schemas_directory_then_one_appearing(tmp_path): |
| 251 | data_dir = tmp_path / "data" |
| 252 | assert parents(data_dir, "lines") == [] |
| 253 | settle() |
| 254 | assert parents(data_dir, "lines") == [] |
| 255 | write_schema(data_dir, "orders", rollup("line_count", "lines")) |
| 256 | assert parent_names(data_dir, "lines") == ["orders"] |
| 257 | |
| 258 | |
| 259 | def test_the_schemas_directory_removed_leaves_no_parents(data_dir): |
| 260 | import shutil |
| 261 | |
| 262 | settle() |
| 263 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 264 | shutil.rmtree(data_dir / "schemas") |
| 265 | assert parents(data_dir, "lines") == scanned(data_dir, "lines") == [] |
| 266 | settle() |
| 267 | assert parents(data_dir, "lines") == [] |
| 268 | |
| 269 | |
| 270 | def test_a_random_run_of_schema_changes_never_disagrees_with_the_scan(tmp_path): |
| 271 | rng = random.Random(20261128) |
| 272 | data_dir = tmp_path / "data" |
| 273 | names = ["alpha", "beta", "gamma", "delta", "epsilon"] |
| 274 | sources = ["lines", "notes", "alpha", "beta"] |
| 275 | write_schema(data_dir, "alpha") |
| 276 | for step in range(100): |
| 277 | name = rng.choice(names) |
| 278 | path = data_dir / "schemas" / f"{name}.json" |
| 279 | move = rng.random() |
| 280 | if move < 0.55: |
| 281 | fields = [rollup(f"c{i}", rng.choice(sources)) for i in range(rng.randrange(3))] |
| 282 | if rng.random() < 0.5: |
| 283 | write_schema(data_dir, name, *fields) |
| 284 | else: |
| 285 | object_schemas.replace_schema(name, json.loads(schema_text(*fields)), base_dir=data_dir) |
| 286 | elif move < 0.75: |
| 287 | path.unlink(missing_ok=True) |
| 288 | if rng.random() < 0.15: |
| 289 | settle() |
| 290 | for source in sources: |
| 291 | assert parents(data_dir, source) == scanned(data_dir, source), f"step {step}, {source}" |
| 292 | |
| 293 | |
| 294 | def test_asking_from_several_threads_while_schemas_change(data_dir): |
| 295 | """Threaded workers share the index. Every answer must be one the |
| 296 | schema files could have given at some moment, and the last one right.""" |
| 297 | stop = threading.Event() |
| 298 | problems: list[str] = [] |
| 299 | possible = {("batches", "orders"), ("batches", "orders", "plain")} |
| 300 | |
| 301 | def reader() -> None: |
| 302 | while not stop.is_set(): |
| 303 | try: |
| 304 | seen = tuple(parent_names(data_dir, "lines")) |
| 305 | except Exception as exc: # noqa: BLE001 |
| 306 | problems.append(repr(exc)) |
| 307 | return |
| 308 | if seen not in possible: |
| 309 | problems.append(f"impossible answer: {seen}") |
| 310 | return |
| 311 | |
| 312 | threads = [threading.Thread(target=reader) for _ in range(4)] |
| 313 | for thread in threads: |
| 314 | thread.start() |
| 315 | for round_ in range(30): |
| 316 | object_schemas.replace_schema( |
| 317 | "plain", json.loads(schema_text(rollup("line_count", "lines"))), base_dir=data_dir |
| 318 | ) |
| 319 | if round_ % 4 == 0: |
| 320 | time.sleep(0.07) |
| 321 | object_schemas.replace_schema("plain", json.loads(schema_text()), base_dir=data_dir) |
| 322 | stop.set() |
| 323 | for thread in threads: |
| 324 | thread.join() |
| 325 | assert problems == [] |
| 326 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |
| 327 | settle() |
| 328 | assert parent_names(data_dir, "lines") == ["batches", "orders"] |