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_permission_audit_rotation.py · 13.3 KB · 324 lines
| 1 | """The permission audit log is bounded, and bounding it loses nothing but the oldest segments. |
| 2 | |
| 3 | One line is appended per permission check (one per request, 55 per search), |
| 4 | and the file used to grow for as long as the server ran. It now rotates the |
| 5 | way object logs do: by size, into gzip segments, keeping the newest N. |
| 6 | |
| 7 | What must hold: no entry is lost or duplicated by a rotation (not with |
| 8 | several writers, and not with one that was mid-append when the file was |
| 9 | cut); readers still see the newest entries across the cut; only whole |
| 10 | segments beyond the keep count are ever deleted; and a rotation that cannot |
| 11 | complete never costs the entry being written. |
| 12 | """ |
| 13 | |
| 14 | import gzip |
| 15 | import json |
| 16 | import os |
| 17 | import threading |
| 18 | from pathlib import Path |
| 19 | |
| 20 | import pytest |
| 21 | |
| 22 | import object_permission_audit as audit |
| 23 | |
| 24 | |
| 25 | def entry(n: int, **extra) -> dict: |
| 26 | return {"n": n, "action": "read", "collection": "notes", "decision": {"allowed": n % 2 == 0}, |
| 27 | "pad": "x" * 60, **extra} |
| 28 | |
| 29 | |
| 30 | def append(data_dir: Path, n: int, **extra) -> None: |
| 31 | audit.append_permission_audit(entry(n, **extra), data_dir) |
| 32 | |
| 33 | |
| 34 | def all_numbers(data_dir: Path) -> list[int]: |
| 35 | """Every entry on disk, oldest first: segments in order, then the active file.""" |
| 36 | numbers: list[int] = [] |
| 37 | for segment in audit.list_rotated_audit_files(data_dir): |
| 38 | opener = gzip.open if segment.name.endswith(".gz") else open |
| 39 | with opener(segment, "rt", encoding="utf-8") as handle: |
| 40 | numbers += [json.loads(line)["n"] for line in handle if line.strip()] |
| 41 | active = audit.audit_path(data_dir) |
| 42 | if active.exists(): |
| 43 | numbers += [json.loads(line)["n"] for line in active.read_text().splitlines() if line.strip()] |
| 44 | return numbers |
| 45 | |
| 46 | |
| 47 | @pytest.fixture |
| 48 | def small(monkeypatch): |
| 49 | """Rotate at about ten entries so a test can cross several rotations.""" |
| 50 | monkeypatch.setenv(audit.AUDIT_MAX_BYTES_ENV, "1500") |
| 51 | monkeypatch.delenv(audit.AUDIT_KEEP_ROTATED_ENV, raising=False) |
| 52 | |
| 53 | |
| 54 | def test_nothing_rotates_below_the_default_limit(tmp_path): |
| 55 | data_dir = tmp_path / "data" |
| 56 | for n in range(200): |
| 57 | append(data_dir, n) |
| 58 | assert audit.list_rotated_audit_files(data_dir) == [] |
| 59 | assert audit.DEFAULT_AUDIT_MAX_BYTES == 10 * 1024 * 1024 |
| 60 | assert audit.DEFAULT_AUDIT_KEEP_ROTATED == 32 |
| 61 | assert all_numbers(data_dir) == list(range(200)) |
| 62 | |
| 63 | |
| 64 | def test_the_active_file_stays_near_the_limit_and_no_entry_is_lost_or_repeated(tmp_path, small): |
| 65 | data_dir = tmp_path / "data" |
| 66 | for n in range(300): |
| 67 | append(data_dir, n) |
| 68 | assert audit.audit_path(data_dir).stat().st_size < 1500 + 250 |
| 69 | segments = audit.list_rotated_audit_files(data_dir) |
| 70 | assert len(segments) > 5 |
| 71 | assert all_numbers(data_dir) == list(range(300)) |
| 72 | |
| 73 | |
| 74 | def test_segments_are_compressed_one_rotation_after_they_are_cut(tmp_path, small): |
| 75 | """The newest segment stays plain: an append that was already under way |
| 76 | when the file was cut still lands in it. Everything older is gzip.""" |
| 77 | data_dir = tmp_path / "data" |
| 78 | for n in range(100): |
| 79 | append(data_dir, n) |
| 80 | segments = audit.list_rotated_audit_files(data_dir) |
| 81 | assert [s.name.endswith(".jsonl.gz") for s in segments] == [True] * (len(segments) - 1) + [False] |
| 82 | assert all(s.name.startswith("audit-") for s in segments) |
| 83 | assert sorted(s.name for s in segments) == [s.name for s in segments] |
| 84 | leftovers = [p.name for p in audit.audit_path(data_dir).parent.iterdir() if p.name.endswith(".tmp")] |
| 85 | assert leftovers == [] |
| 86 | |
| 87 | |
| 88 | def test_an_append_under_way_when_the_file_is_cut_is_not_lost(tmp_path, small): |
| 89 | """Appends take no lock. A worker that opened the active file just |
| 90 | before another worker rotated it writes into the renamed segment.""" |
| 91 | data_dir = tmp_path / "data" |
| 92 | for n in range(8): |
| 93 | append(data_dir, n) |
| 94 | slow_writer = audit.audit_path(data_dir).open("a", encoding="utf-8") |
| 95 | n = 8 |
| 96 | try: |
| 97 | while not audit.list_rotated_audit_files(data_dir): |
| 98 | append(data_dir, n) # up to and including the cut of the file it holds |
| 99 | n += 1 |
| 100 | slow_writer.write(json.dumps(entry(1000)) + "\n") |
| 101 | finally: |
| 102 | slow_writer.close() |
| 103 | [segment] = audit.list_rotated_audit_files(data_dir) |
| 104 | assert not segment.name.endswith(".gz"), "the segment just cut stays plain" |
| 105 | while not audit.list_rotated_audit_files(data_dir)[0].name.endswith(".gz"): |
| 106 | append(data_dir, n) # the next cut compresses the segment the slow writer wrote into |
| 107 | n += 1 |
| 108 | numbers = all_numbers(data_dir) |
| 109 | assert sorted(numbers) == sorted([*range(n), 1000]) |
| 110 | assert numbers.count(1000) == 1 |
| 111 | |
| 112 | |
| 113 | def test_an_append_stalled_until_its_segment_is_compressed_is_not_lost(tmp_path, small, monkeypatch): |
| 114 | """The newest segment is compressed only at the next cut, "a whole file |
| 115 | of appends later". That is not a guarantee: a worker descheduled |
| 116 | between opening the active file and writing to it can wake after the |
| 117 | next cut has copied its file and unlinked it. CI lost lines this way on |
| 118 | 3.14t. Here the writer is held at exactly that point (after its open, |
| 119 | before its lock) until the file it opened has been cut AND compressed.""" |
| 120 | data_dir = tmp_path / "data" |
| 121 | for n in range(3): |
| 122 | append(data_dir, n) |
| 123 | opened = threading.Event() |
| 124 | resume = threading.Event() |
| 125 | real_lock = audit._lock |
| 126 | stalled = [] |
| 127 | |
| 128 | def lock(handle, *, shared): |
| 129 | if shared and threading.current_thread().name == "stalled" and not stalled: |
| 130 | stalled.append(os.fstat(handle.fileno()).st_ino) |
| 131 | opened.set() |
| 132 | assert resume.wait(30) |
| 133 | return real_lock(handle, shared=shared) |
| 134 | |
| 135 | monkeypatch.setattr(audit, "_lock", lock) |
| 136 | writer = threading.Thread(target=append, args=(data_dir, 1000), name="stalled") |
| 137 | writer.start() |
| 138 | assert opened.wait(30) |
| 139 | n = 3 |
| 140 | try: |
| 141 | # Append until the inode the writer holds is gone: cut, then compressed. |
| 142 | while any(os.stat(s).st_ino == stalled[0] for s in |
| 143 | [audit.audit_path(data_dir), *audit.list_rotated_audit_files(data_dir)] |
| 144 | if not s.name.endswith(".gz")): |
| 145 | append(data_dir, n) |
| 146 | n += 1 |
| 147 | finally: |
| 148 | resume.set() |
| 149 | writer.join(30) |
| 150 | numbers = all_numbers(data_dir) |
| 151 | assert sorted(numbers) == sorted([*range(n), 1000]) |
| 152 | |
| 153 | |
| 154 | def test_only_whole_segments_beyond_the_keep_count_are_deleted(tmp_path, small, monkeypatch): |
| 155 | monkeypatch.setenv(audit.AUDIT_KEEP_ROTATED_ENV, "3") |
| 156 | data_dir = tmp_path / "data" |
| 157 | for n in range(400): |
| 158 | append(data_dir, n) |
| 159 | segments = audit.list_rotated_audit_files(data_dir) |
| 160 | assert len(segments) == 3 |
| 161 | kept = all_numbers(data_dir) |
| 162 | assert kept == list(range(kept[0], 400)), "what is kept is one unbroken, newest run" |
| 163 | assert 0 < kept[0] < 400 |
| 164 | |
| 165 | |
| 166 | def test_keep_zero_keeps_every_segment(tmp_path, small, monkeypatch): |
| 167 | monkeypatch.setenv(audit.AUDIT_KEEP_ROTATED_ENV, "0") |
| 168 | data_dir = tmp_path / "data" |
| 169 | for n in range(600): |
| 170 | append(data_dir, n) |
| 171 | assert len(audit.list_rotated_audit_files(data_dir)) > 32 |
| 172 | assert all_numbers(data_dir) == list(range(600)) |
| 173 | |
| 174 | |
| 175 | def test_a_limit_of_zero_turns_rotation_off(tmp_path, monkeypatch): |
| 176 | monkeypatch.setenv(audit.AUDIT_MAX_BYTES_ENV, "0") |
| 177 | data_dir = tmp_path / "data" |
| 178 | for n in range(300): |
| 179 | append(data_dir, n) |
| 180 | assert audit.list_rotated_audit_files(data_dir) == [] |
| 181 | assert all_numbers(data_dir) == list(range(300)) |
| 182 | |
| 183 | |
| 184 | def test_an_unreadable_setting_falls_back_to_the_default(tmp_path, monkeypatch): |
| 185 | monkeypatch.setenv(audit.AUDIT_MAX_BYTES_ENV, "plenty") |
| 186 | monkeypatch.setenv(audit.AUDIT_KEEP_ROTATED_ENV, "many") |
| 187 | assert audit._max_bytes() == audit.DEFAULT_AUDIT_MAX_BYTES |
| 188 | assert audit._keep_rotated() == audit.DEFAULT_AUDIT_KEEP_ROTATED |
| 189 | |
| 190 | |
| 191 | def test_readers_see_the_newest_entries_across_a_rotation(tmp_path, small): |
| 192 | """Right after a cut the active file is empty. The newest entries did |
| 193 | not go anywhere, so a reader must still be given them.""" |
| 194 | data_dir = tmp_path / "data" |
| 195 | for n in range(95): |
| 196 | append(data_dir, n) |
| 197 | newest = audit.get_permission_audit(data_dir, limit=20) |
| 198 | assert [e["n"] for e in newest] == list(range(max(0, n - 19), n + 1)), f"after entry {n}" |
| 199 | everything = audit.get_permission_audit(data_dir, limit=1000) |
| 200 | assert [e["n"] for e in everything] == list(range(95)) |
| 201 | |
| 202 | |
| 203 | def test_filters_reach_back_through_the_segments(tmp_path, small): |
| 204 | data_dir = tmp_path / "data" |
| 205 | for n in range(120): |
| 206 | append(data_dir, n, collection="rare" if n in (3, 40, 77) else "notes") |
| 207 | rare = audit.get_permission_audit(data_dir, limit=10, collection="rare") |
| 208 | assert [e["n"] for e in rare] == [3, 40, 77] |
| 209 | denied = audit.get_permission_audit(data_dir, limit=5, allowed=False) |
| 210 | assert [e["n"] for e in denied] == [111, 113, 115, 117, 119] |
| 211 | assert audit.get_permission_audit(data_dir, limit=5, collection="never") == [] |
| 212 | |
| 213 | |
| 214 | def test_reading_before_any_rotation_is_what_it_always_was(tmp_path): |
| 215 | data_dir = tmp_path / "data" |
| 216 | assert audit.get_permission_audit(data_dir) == [] |
| 217 | for n in range(30): |
| 218 | append(data_dir, n) |
| 219 | active = audit.audit_path(data_dir) |
| 220 | with active.open("a") as handle: |
| 221 | handle.write("\n{ not json\n") |
| 222 | append(data_dir, 30) |
| 223 | assert [e["n"] for e in audit.get_permission_audit(data_dir, limit=4)] == [27, 28, 29, 30] |
| 224 | with pytest.raises(ValueError): |
| 225 | audit.get_permission_audit(data_dir, limit=0) |
| 226 | |
| 227 | |
| 228 | def test_a_segment_left_in_both_forms_by_a_crash_is_read_once_and_cleaned_up(tmp_path, small): |
| 229 | """A crash between "compressed copy in place" and "plain copy removed" |
| 230 | leaves the same segment twice. It must not be counted twice, and the |
| 231 | next rotation removes the leftover.""" |
| 232 | data_dir = tmp_path / "data" |
| 233 | for n in range(60): |
| 234 | append(data_dir, n) |
| 235 | plain = [s for s in audit.list_rotated_audit_files(data_dir) if not s.name.endswith(".gz")][0] |
| 236 | with plain.open("rb") as source, gzip.open(str(plain) + ".gz", "wb") as target: |
| 237 | target.write(source.read()) |
| 238 | assert all_numbers(data_dir) == list(range(60)) |
| 239 | assert [e["n"] for e in audit.get_permission_audit(data_dir, limit=1000)] == list(range(60)) |
| 240 | for n in range(60, 100): |
| 241 | append(data_dir, n) |
| 242 | assert not plain.exists() |
| 243 | assert all_numbers(data_dir) == list(range(100)) |
| 244 | |
| 245 | |
| 246 | def test_a_clock_set_back_still_cuts_a_segment_that_sorts_last(tmp_path, small, monkeypatch): |
| 247 | data_dir = tmp_path / "data" |
| 248 | for n in range(40): |
| 249 | append(data_dir, n) |
| 250 | |
| 251 | class Earlier(audit.datetime): |
| 252 | @classmethod |
| 253 | def now(cls, tz=None): |
| 254 | return cls(2001, 1, 1, tzinfo=tz) |
| 255 | |
| 256 | monkeypatch.setattr(audit, "datetime", Earlier) |
| 257 | for n in range(40, 120): |
| 258 | append(data_dir, n) |
| 259 | assert all_numbers(data_dir) == list(range(120)) |
| 260 | assert [e["n"] for e in audit.get_permission_audit(data_dir, limit=1000)] == list(range(120)) |
| 261 | |
| 262 | |
| 263 | def test_a_rotation_that_cannot_complete_still_writes_the_entry(tmp_path, small, monkeypatch): |
| 264 | """Disk full or a permissions problem while rotating must not lose the |
| 265 | decision being recorded, and must not fail the request.""" |
| 266 | data_dir = tmp_path / "data" |
| 267 | for n in range(12): |
| 268 | append(data_dir, n) |
| 269 | |
| 270 | def no_rename(*args, **kwargs): |
| 271 | raise OSError("disk full") |
| 272 | |
| 273 | monkeypatch.setattr(audit.os, "replace", no_rename) |
| 274 | for n in range(12, 40): |
| 275 | append(data_dir, n) |
| 276 | monkeypatch.undo() |
| 277 | monkeypatch.setenv(audit.AUDIT_MAX_BYTES_ENV, "1500") |
| 278 | append(data_dir, 40) |
| 279 | assert all_numbers(data_dir) == list(range(41)) |
| 280 | assert len(audit.list_rotated_audit_files(data_dir)) >= 1 |
| 281 | |
| 282 | |
| 283 | def test_several_threads_appending_through_rotations_lose_and_repeat_nothing(tmp_path, small, monkeypatch): |
| 284 | monkeypatch.setenv(audit.AUDIT_KEEP_ROTATED_ENV, "0") # this is about cuts, not retention |
| 285 | data_dir = tmp_path / "data" |
| 286 | per_thread, threads = 150, 6 |
| 287 | |
| 288 | def writer(t: int) -> None: |
| 289 | for i in range(per_thread): |
| 290 | append(data_dir, t * 1000 + i) |
| 291 | |
| 292 | workers = [threading.Thread(target=writer, args=(t,)) for t in range(threads)] |
| 293 | for worker in workers: |
| 294 | worker.start() |
| 295 | for worker in workers: |
| 296 | worker.join() |
| 297 | numbers = all_numbers(data_dir) |
| 298 | assert sorted(numbers) == sorted(t * 1000 + i for t in range(threads) for i in range(per_thread)) |
| 299 | for t in range(threads): |
| 300 | mine = [n for n in numbers if n // 1000 == t] |
| 301 | assert mine == sorted(mine), "each writer's entries stay in the order it wrote them" |
| 302 | assert len(audit.list_rotated_audit_files(data_dir)) > 10 |
| 303 | |
| 304 | |
| 305 | def test_several_processes_appending_through_rotations_lose_and_repeat_nothing(tmp_path, small, monkeypatch): |
| 306 | """The server runs as several workers, and they rotate the same file.""" |
| 307 | monkeypatch.setenv(audit.AUDIT_KEEP_ROTATED_ENV, "0") # this is about cuts, not retention |
| 308 | import subprocess |
| 309 | import sys |
| 310 | |
| 311 | data_dir = tmp_path / "data" |
| 312 | code = ( |
| 313 | "import sys, object_permission_audit as a\n" |
| 314 | "t = int(sys.argv[2])\n" |
| 315 | "for i in range(120):\n" |
| 316 | " a.append_permission_audit({'n': t * 1000 + i, 'pad': 'x' * 80}, sys.argv[1])\n" |
| 317 | ) |
| 318 | root = str(Path(audit.__file__).resolve().parent) |
| 319 | env = dict(os.environ, PYTHONPATH=root) |
| 320 | procs = [subprocess.Popen([sys.executable, "-c", code, str(data_dir), str(t)], env=env) for t in range(4)] |
| 321 | assert [proc.wait(timeout=120) for proc in procs] == [0, 0, 0, 0] |
| 322 | numbers = all_numbers(data_dir) |
| 323 | assert sorted(numbers) == sorted(t * 1000 + i for t in range(4) for i in range(120)) |
| 324 | assert len(audit.list_rotated_audit_files(data_dir)) > 5 |