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_schema_cache.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, 18 minutes ago History
test_schema_cache.py · 14.9 KB · 352 lines
1"""A cached schema is served only while its file still has the stat it was read under.
2
3get_schema is called 50 times per list and 120-340 times per write. A hit
4used to cost four Path.resolve() calls and three stats; it is now one dict
5lookup and one lstat. What these tests hold is the other side of that trade:
6whoever changes a schema file (the API, the package installer, another
7worker, an operator's editor, a restore), and however little the change
8shows in the file's size or mtime, the very next call returns what is on
9disk. The oracle is a fresh parse of the file.
10"""
11
12import json
13import os
14import random
15import threading
16import time
17from pathlib import Path
18
19import pytest
20
21import object_packages
22import object_records
23import object_schemas
24
25
26def settle() -> None:
27 """Wait until a schema read now may be kept (_SCHEMA_CACHE_RACY_NS)."""
28 time.sleep(object_schemas._SCHEMA_CACHE_RACY_NS / 1e9 + 0.03)
29
30
31def text_for(*names: str, **extra) -> str:
32 return json.dumps({"fields": [{"name": name} for name in names], **extra})
33
34
35def write_schema(data_dir: Path, name: str, text: str) -> Path:
36 path = data_dir / "schemas" / f"{name}.json"
37 path.parent.mkdir(parents=True, exist_ok=True)
38 path.write_text(text)
39 return path
40
41
42def field_names(data_dir, name: str = "invoices") -> list[str]:
43 return [f["name"] for f in object_schemas.get_schema(name, base_dir=data_dir, roots=[])["fields"]]
44
45
46def fresh(data_dir: Path, name: str = "invoices") -> dict:
47 """What an uncached read returns."""
48 payload = json.loads((data_dir / "schemas" / f"{name}.json").read_text())
49 return object_schemas.normalize_schema(name, payload)
50
51
52@pytest.fixture
53def parses(monkeypatch):
54 """Counts schema files actually parsed."""
55 calls = []
56 real = object_schemas._normalize_schema
57
58 def counting(schema, payload, *, source):
59 calls.append(schema)
60 return real(schema, payload, source=source)
61
62 monkeypatch.setattr(object_schemas, "_normalize_schema", counting)
63 return calls
64
65
66@pytest.fixture
67def data_dir(tmp_path):
68 data_dir = tmp_path / "data"
69 write_schema(data_dir, "invoices", text_for("id", "total"))
70 return data_dir
71
72
73def test_a_settled_schema_is_parsed_once_and_a_hit_never_resolves_a_path(data_dir, parses, monkeypatch):
74 """The 71 us were path resolution on an already-validated name. If a
75 hit goes back through _schema_path this fails."""
76 settle()
77 first = object_schemas.get_schema("invoices", base_dir=data_dir, roots=[])
78 assert parses == ["invoices"]
79
80 def no_path_checks(*args, **kwargs):
81 raise AssertionError("a cache hit must not rebuild or resolve the schema path")
82
83 monkeypatch.setattr(object_schemas, "_schema_path", no_path_checks)
84 monkeypatch.setattr(Path, "resolve", no_path_checks)
85 for _ in range(3):
86 assert object_schemas.get_schema("invoices", base_dir=data_dir, roots=[]) is first
87 assert object_schemas.get_schema("invoices", base_dir=str(data_dir), roots=[]) is first
88 assert object_schemas._load_manual_schema("invoices", base_dir=data_dir) is first
89 assert parses == ["invoices"]
90
91
92def test_each_spelling_of_the_data_directory_sees_the_same_change(data_dir, parses):
93 settle()
94 assert field_names(data_dir) == field_names(str(data_dir)) == ["id", "total"]
95 assert field_names(data_dir) == field_names(str(data_dir)) == ["id", "total"]
96 write_schema(data_dir, "invoices", text_for("id", "total", "paid"))
97 assert field_names(data_dir) == field_names(str(data_dir)) == ["id", "total", "paid"]
98
99
100def test_a_same_size_edit_in_the_same_instant_is_seen(data_dir):
101 """The edit an operator makes by hand: one word for another of the same
102 length, written in place, twice in a row. Size never changes, and on a
103 filesystem with coarse timestamps neither does mtime between the two
104 writes, so a schema read inside that window must not be kept."""
105 settle()
106 assert field_names(data_dir) == ["id", "total"]
107 path = data_dir / "schemas" / "invoices.json"
108 path.write_text(text_for("id", "tolls"))
109 assert field_names(data_dir) == ["id", "tolls"]
110 path.write_text(text_for("id", "taxes"))
111 assert field_names(data_dir) == ["id", "taxes"]
112 path.write_text(text_for("id", "total"))
113 assert field_names(data_dir) == ["id", "total"]
114
115
116def test_a_schema_read_moments_after_it_was_written_is_not_kept(data_dir, parses):
117 settle()
118 field_names(data_dir)
119 write_schema(data_dir, "invoices", text_for("id", "total", "paid"))
120 before = len(parses)
121 field_names(data_dir)
122 field_names(data_dir)
123 assert len(parses) == before + 2, "inside the racy window every read parses"
124 settle()
125 field_names(data_dir)
126 field_names(data_dir)
127 assert len(parses) == before + 3, "once the file has settled one parse is kept"
128
129
130def test_an_atomic_replace_that_keeps_size_and_mtime_is_seen(data_dir):
131 """A restore puts a different file in place and sets its mtime to what
132 it was. (mtime, size) says nothing happened; inode and ctime differ.
133 The rollup-parents index is built from these schemas, so it has to
134 follow too."""
135 write_schema(data_dir, "lines", text_for("id", "parent_id"))
136 rollup = {"name": "line_count", "type": "computed",
137 "rollup": {"collection": "lines", "fk_field": "parent_id", "op": "count"}}
138 path = write_schema(data_dir, "invoices", json.dumps({"fields": [{"name": "id"}, rollup]}))
139 settle()
140 before = os.stat(path)
141 assert field_names(data_dir) == ["id", "line_count"]
142 assert [n for n, _ in object_records._rollup_parents_for_source("lines", base_dir=data_dir, roots=[])] == ["invoices"]
143
144 replacement = path.with_name("invoices.json.restored")
145 replacement.write_text(path.read_text().replace('"collection": "lines"', '"collection": "notes"'))
146 os.utime(replacement, ns=(before.st_atime_ns, before.st_mtime_ns))
147 os.replace(replacement, path)
148 after = os.stat(path)
149 assert (after.st_mtime_ns, after.st_size) == (before.st_mtime_ns, before.st_size)
150
151 assert object_schemas.get_schema("invoices", base_dir=data_dir, roots=[]) == fresh(data_dir)
152 assert object_records._rollup_parents_for_source("lines", base_dir=data_dir, roots=[]) == []
153
154
155def test_an_in_place_edit_whose_mtime_is_set_back_is_seen(data_dir):
156 """`touch -r`, or an editor that preserves times: ctime cannot be set."""
157 settle()
158 path = data_dir / "schemas" / "invoices.json"
159 before = os.stat(path)
160 assert field_names(data_dir) == ["id", "total"]
161 path.write_text(text_for("id", "tolls"))
162 os.utime(path, ns=(before.st_atime_ns, before.st_mtime_ns))
163 after = os.stat(path)
164 assert (after.st_mtime_ns, after.st_size) == (before.st_mtime_ns, before.st_size)
165 assert field_names(data_dir) == ["id", "tolls"]
166
167
168def test_a_schema_replaced_through_the_api_is_seen(data_dir):
169 settle()
170 assert field_names(data_dir) == ["id", "total"]
171 object_schemas.replace_schema("invoices", json.loads(text_for("id", "total", "paid")), base_dir=data_dir)
172 assert field_names(data_dir) == ["id", "total", "paid"]
173 assert field_names(str(data_dir)) == ["id", "total", "paid"]
174 object_schemas.replace_schema("invoices", json.loads(text_for("id")), base_dir=str(data_dir))
175 assert field_names(data_dir) == ["id"]
176
177
178def test_a_schema_deleted_and_recreated_is_seen(data_dir):
179 settle()
180 assert field_names(data_dir) == ["id", "total"]
181 path = data_dir / "schemas" / "invoices.json"
182 path.unlink()
183 with pytest.raises(object_schemas.SchemaNotFoundError):
184 object_schemas.get_schema("invoices", base_dir=data_dir, roots=[])
185 write_schema(data_dir, "invoices", text_for("id", "amount"))
186 assert field_names(data_dir) == ["id", "amount"]
187
188
189def test_installing_and_upgrading_a_package_schema_is_seen(tmp_path):
190 data_dir = tmp_path / "data"
191 package_dir = tmp_path / "packages" / "app-pallets"
192 (package_dir / "schemas").mkdir(parents=True)
193
194 def ship(version: str, *names: str) -> None:
195 (package_dir / object_packages.MANIFEST_FILE).write_text(json.dumps({
196 "id": "app-pallets", "name": "Pallets", "version": version,
197 "schemas": [{"collection": "pallets", "path": "schemas/pallets.json"}],
198 }))
199 (package_dir / "schemas" / "pallets.json").write_text(text_for(*names))
200 object_packages.install_package(
201 "app-pallets", root=tmp_path / "packages", base_dir=data_dir,
202 object_roots=[tmp_path / "objects"], allow_replace=True,
203 )
204
205 with pytest.raises(object_schemas.SchemaNotFoundError):
206 object_schemas.get_schema("pallets", base_dir=data_dir, roots=[])
207 ship("0.1.0", "id", "label")
208 assert field_names(data_dir, "pallets") == ["id", "label"]
209 settle()
210 assert field_names(data_dir, "pallets") == ["id", "label"]
211 ship("0.2.0", "id", "label", "weight")
212 assert field_names(data_dir, "pallets") == ["id", "label", "weight"]
213 # the package's schema taken out by hand, as removing the package would
214 (data_dir / "schemas" / "pallets.json").unlink()
215 with pytest.raises(object_schemas.SchemaNotFoundError):
216 object_schemas.get_schema("pallets", base_dir=data_dir, roots=[])
217
218
219def test_a_schema_file_that_stops_parsing_raises_every_time_and_recovers(data_dir):
220 """An error is never remembered, and a good schema is never served
221 once the file under it is no longer that schema."""
222 settle()
223 assert field_names(data_dir) == ["id", "total"]
224 path = data_dir / "schemas" / "invoices.json"
225 path.write_text("{ not json")
226 settle()
227 for _ in range(3):
228 with pytest.raises(ValueError, match="invalid JSON"):
229 object_schemas.get_schema("invoices", base_dir=data_dir, roots=[])
230 path.write_text(json.dumps({"fields": "not a list"}))
231 for _ in range(2):
232 with pytest.raises(ValueError):
233 object_schemas.get_schema("invoices", base_dir=data_dir, roots=[])
234 path.write_text(text_for("id", "total"))
235 assert field_names(data_dir) == ["id", "total"]
236
237
238def test_a_schema_file_replaced_by_a_link_out_of_the_directory_is_refused(data_dir, tmp_path):
239 """The path-safety check the fast path skips must still bite the moment
240 the file stops being a plain file inside the schemas directory."""
241 settle()
242 assert field_names(data_dir) == ["id", "total"]
243 outside = tmp_path / "outside.json"
244 outside.write_text(text_for("id", "secret"))
245 path = data_dir / "schemas" / "invoices.json"
246 path.unlink()
247 os.symlink(outside, path)
248 for _ in range(2):
249 with pytest.raises(object_schemas.InvalidSchemaNameError, match="escapes"):
250 object_schemas.get_schema("invoices", base_dir=data_dir, roots=[])
251
252
253def test_a_linked_schema_file_is_read_every_time(data_dir, parses):
254 """A link's target can change without the link changing, so nothing
255 read through one is kept."""
256 target = data_dir / "schemas" / "shared-definition.data"
257 target.write_text(text_for("id", "one"))
258 os.symlink(target, data_dir / "schemas" / "linked.json")
259 settle()
260 assert field_names(data_dir, "linked") == ["id", "one"]
261 assert field_names(data_dir, "linked") == ["id", "one"]
262 assert parses.count("linked") == 2
263 target.write_text(text_for("id", "two"))
264 assert field_names(data_dir, "linked") == ["id", "two"]
265
266
267def test_a_relative_data_directory_follows_the_working_directory(tmp_path, monkeypatch):
268 """The default base_dir is the relative path "data"."""
269 write_schema(tmp_path / "a" / "data", "invoices", text_for("id", "in_a"))
270 write_schema(tmp_path / "b" / "data", "invoices", text_for("id", "in_b"))
271 settle()
272 monkeypatch.chdir(tmp_path / "a")
273 assert field_names("data") == ["id", "in_a"]
274 assert field_names("data") == ["id", "in_a"]
275 monkeypatch.chdir(tmp_path / "b")
276 assert field_names("data") == ["id", "in_b"]
277
278
279def test_the_listings_follow_a_schema_edited_by_hand(data_dir):
280 settle()
281 assert object_schemas.list_append_storage_collections(base_dir=data_dir) == []
282 assert object_schemas.list_schemas(base_dir=data_dir, roots=[])[0]["field_count"] == 2
283 write_schema(data_dir, "invoices", text_for("id", "total", "paid", storage="append"))
284 assert object_schemas.list_append_storage_collections(base_dir=data_dir) == ["invoices"]
285 assert object_schemas.list_schemas(base_dir=data_dir, roots=[])[0]["field_count"] == 3
286 write_schema(data_dir, "invoices", text_for("id", "total"))
287 assert object_schemas.list_append_storage_collections(base_dir=data_dir) == []
288
289
290def test_names_that_are_not_schema_names_are_still_refused(data_dir):
291 settle()
292 field_names(data_dir)
293 for bad in ("bad!name", "", "../invoices", "a" * 65, None, 7, ["invoices"]):
294 with pytest.raises(object_schemas.InvalidSchemaNameError):
295 object_schemas.get_schema(bad, base_dir=data_dir, roots=[])
296
297
298def test_a_random_run_of_edits_never_disagrees_with_a_fresh_parse(tmp_path):
299 rng = random.Random(20261128)
300 data_dir = tmp_path / "data"
301 words = ["total", "tolls", "taxes", "price", "paid", "note"]
302 path = write_schema(data_dir, "invoices", text_for("id"))
303 for step in range(150):
304 text = text_for("id", *rng.sample(words, rng.randrange(1, 4)))
305 move = rng.random()
306 if move < 0.45:
307 path.write_text(text)
308 elif move < 0.75:
309 object_schemas.replace_schema("invoices", json.loads(text), base_dir=data_dir)
310 elif move < 0.85:
311 stamp = os.stat(path)
312 path.write_text(text)
313 os.utime(path, ns=(stamp.st_atime_ns, stamp.st_mtime_ns))
314 if rng.random() < 0.12:
315 settle()
316 base = data_dir if rng.random() < 0.5 else str(data_dir)
317 assert object_schemas.get_schema("invoices", base_dir=base, roots=[]) == fresh(data_dir), f"step {step}"
318
319
320def test_reading_from_several_threads_while_the_schema_is_replaced(data_dir):
321 """Threaded workers share the cache: every answer must be one of the
322 two schemas that were ever on disk, and the last one the current one."""
323 stop = threading.Event()
324 problems: list[str] = []
325 possible = (["id", "total"], ["id", "total", "paid"])
326
327 def reader() -> None:
328 while not stop.is_set():
329 try:
330 seen = field_names(data_dir)
331 except Exception as exc: # noqa: BLE001
332 problems.append(repr(exc))
333 return
334 if seen not in possible:
335 problems.append(f"impossible schema: {seen}")
336 return
337
338 threads = [threading.Thread(target=reader) for _ in range(4)]
339 for thread in threads:
340 thread.start()
341 for round_ in range(40):
342 object_schemas.replace_schema("invoices", json.loads(text_for("id", "total", "paid")), base_dir=data_dir)
343 if round_ % 4 == 0:
344 time.sleep(0.07)
345 object_schemas.replace_schema("invoices", json.loads(text_for("id", "total")), base_dir=data_dir)
346 stop.set()
347 for thread in threads:
348 thread.join()
349 assert problems == []
350 assert field_names(data_dir) == ["id", "total"]
351 settle()
352 assert field_names(data_dir) == ["id", "total"]