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_append_cache_foreign_writer.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_append_cache_foreign_writer.py · 6.1 KB · 157 lines
1"""An append-mode write after ANOTHER process's append must not poison
2this process's records cache.
3
4Found while racing real processes against a `unique` constraint. A fast
5append does not re-read the file: it derives the new cache entry from the
6PRIOR entry plus its own row (_refresh_records_cache_after_append). That is
7only true if the prior entry described the file as it stood just before the
8append. When another process (a pool worker, the daemon, the CLI) had
9appended in between, the prior entry was already stale -- and the new entry
10was built from it anyway and stamped with the file's CURRENT signature. A
11stale entry fails its signature check and is re-read; this one passed it.
12From then on, in this process:
13
14 * the other process's record did not exist: lists omitted it, a get by id
15 answered "not found";
16 * the duplicate-id check passed for it, so a create with that id was
17 accepted -- and in append mode a second row with an id is an UPDATE, so
18 the other process's record was silently overwritten.
19
20The cache comment in object_records says "a new signature paired with old
21content is structurally impossible". This was the one path where it was not.
22
23Every "other process" here is a real one (subprocess, fresh interpreter):
24the bug is about what a second writer does to the first one's memory.
25"""
26
27import json
28import subprocess
29import sys
30from pathlib import Path
31
32import pytest
33
34import object_records
35
36REPO_ROOT = str(Path(__file__).resolve().parents[1])
37
38_OTHER = """\
39import json, sys
40sys.path.insert(0, sys.argv[1])
41import object_records
42data_dir, action, record_id = sys.argv[2], sys.argv[3], sys.argv[4]
43if action == "create":
44 object_records.create_collection_record(
45 "events", {"id": record_id, "value": "theirs"}, base_dir=data_dir, roots=[])
46elif action == "update":
47 object_records.update_collection_record(
48 "events", record_id, {"value": "theirs"}, base_dir=data_dir, roots=[])
49elif action == "delete":
50 object_records.delete_collection_record("events", record_id, base_dir=data_dir, roots=[])
51"""
52
53
54@pytest.fixture
55def data_dir(tmp_path):
56 data = tmp_path / "data"
57 (data / "schemas").mkdir(parents=True)
58 (data / "schemas" / "events.json").write_text(json.dumps({
59 "name": "events", "storage": "append",
60 "fields": [{"name": "id"}, {"name": "value", "type": "text"}]}))
61 (tmp_path / "_other.py").write_text(_OTHER)
62 return data
63
64
65def elsewhere(data_dir, action, record_id):
66 done = subprocess.run(
67 [sys.executable, str(data_dir.parent / "_other.py"), REPO_ROOT, str(data_dir),
68 action, record_id],
69 capture_output=True, text=True, timeout=60)
70 assert done.returncode == 0, done.stderr
71
72
73def create(data_dir, record_id, value="ours"):
74 return object_records.create_collection_record(
75 "events", {"id": record_id, "value": value}, base_dir=data_dir, roots=[])
76
77
78def stored(data_dir):
79 return {row["id"]: row["value"]
80 for row in object_records.read_collection_records("events", base_dir=data_dir, roots=[])}
81
82
83def on_disk(data_dir):
84 """What a process with no cache at all reads: the file is the truth."""
85 object_records._RECORDS_CACHE.clear()
86 object_records._OIDX_CACHE.clear()
87 return stored(data_dir)
88
89
90def test_a_record_another_process_appended_survives_this_ones_next_append(data_dir):
91 create(data_dir, "e1") # this process's cache is warm
92 elsewhere(data_dir, "create", "e2")
93 create(data_dir, "e3") # a fast append over a stale prior entry
94
95 assert stored(data_dir) == {"e1": "ours", "e2": "theirs", "e3": "ours"}
96 assert object_records.get_collection_record(
97 "events", "e2", base_dir=data_dir, roots=[])["value"] == "theirs"
98
99
100def test_an_id_another_process_created_cannot_be_created_again_here(data_dir):
101 """The consequence that loses data: in append mode a second row for an
102 id folds as an update, so the accepted duplicate overwrote their record."""
103 create(data_dir, "e1")
104 elsewhere(data_dir, "create", "e2")
105 create(data_dir, "e3")
106
107 with pytest.raises(object_records.DuplicateRecordIdError):
108 create(data_dir, "e2", value="ours-overwriting-theirs")
109 assert on_disk(data_dir) == {"e1": "ours", "e2": "theirs", "e3": "ours"}
110
111
112def test_another_processs_update_and_delete_are_seen_after_this_ones_next_append(data_dir):
113 create(data_dir, "e1")
114 create(data_dir, "e2")
115 elsewhere(data_dir, "update", "e1")
116 elsewhere(data_dir, "delete", "e2")
117 create(data_dir, "e3")
118
119 assert stored(data_dir) == {"e1": "theirs", "e3": "ours"}
120 with pytest.raises(object_records.RecordNotFoundError):
121 object_records.get_collection_record("events", "e2", base_dir=data_dir, roots=[])
122 # ...and the id they deleted is free again here, as it is on disk.
123 create(data_dir, "e2")
124 assert on_disk(data_dir) == {"e1": "theirs", "e2": "ours", "e3": "ours"}
125
126
127def test_turn_taking_between_two_processes_never_loses_a_row(data_dir):
128 expected = {}
129 for n in range(6):
130 create(data_dir, f"ours-{n}")
131 expected[f"ours-{n}"] = "ours"
132 elsewhere(data_dir, "create", f"theirs-{n}")
133 expected[f"theirs-{n}"] = "theirs"
134 assert stored(data_dir) == expected
135 assert on_disk(data_dir) == expected
136
137
138def test_this_processs_own_appends_still_never_reparse_the_file(data_dir, monkeypatch):
139 """The guard must not cost the path it guards: with no other writer, a
140 run of appends derives each cache entry from the last and never folds
141 the file again."""
142 create(data_dir, "e0")
143 assert stored(data_dir) == {"e0": "ours"}
144 parses = []
145 real = object_records._parse_records_file
146 monkeypatch.setattr(object_records, "_parse_records_file",
147 lambda *args, **kwargs: parses.append(1) or real(*args, **kwargs))
148 folds_before = object_records._INCREMENTAL_CACHE_FOLDS
149
150 for n in range(1, 40):
151 create(data_dir, f"e{n}")
152 object_records.update_collection_record(
153 "events", f"e{n}", {"value": "edited"}, base_dir=data_dir, roots=[])
154 assert len(stored(data_dir)) == 40
155
156 assert parses == []
157 assert object_records._INCREMENTAL_CACHE_FOLDS == folds_before