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_platform_differential.py · 18.6 KB · 376 lines
| 1 | """The platform answers every request the way a baseline commit answered it. |
| 2 | |
| 3 | Run deliberately (it installs every package twice and takes a few minutes): |
| 4 | |
| 5 | pytest -m conformance tests/test_platform_differential.py |
| 6 | |
| 7 | `tests/differential_driver.py` plays one long scripted session through the |
| 8 | real ASGI app: the requests the request profiler issues, the error paths, and |
| 9 | then a run of changes to what is on disk (schemas, the policy, object files, |
| 10 | records files, a package), each made the instant after the requests that |
| 11 | would warm a cache, through the API and by hand, with the same probe requests |
| 12 | repeated after every change. This test plays that session twice, against the |
| 13 | root modules of a baseline commit (extracted with `git archive`) and against |
| 14 | the working tree, with the current `packages/` in both, and compares status, |
| 15 | headers and body of every response. |
| 16 | |
| 17 | It exists for changes that are meant to change no behaviour, the caches added |
| 18 | after `scripts/bench/experiments/profile_requests_results.md` being the first. |
| 19 | The baseline re-read everything on every request, so it is the oracle for |
| 20 | "this cache is never stale". A change that is MEANT to alter a response makes |
| 21 | this fail by design: move the baseline with DBBASIC_DIFFERENTIAL_BASELINE (any |
| 22 | commit-ish) to the last commit before the change under test -- or, when the |
| 23 | baseline must stay where it is (it is the oracle for the caches), state that |
| 24 | response's exact old and new answer in INTENDED below, and nothing else. |
| 25 | |
| 26 | What is not compared, and why: the wall-clock time of the run. That is every |
| 27 | instant in a response (INSTANT), the `_rev` content hash of a row that itself |
| 28 | holds an instant (_volatile_revs; the `_rev` of every other row is compared), |
| 29 | and the byte size of the compressed backup a package install takes, whose |
| 30 | contents hold instants (BACKUP_BYTES). Nothing else is masked, and that list |
| 31 | was measured, not guessed: it is exactly what differs when the baseline is |
| 32 | recorded twice (3 kinds of difference in 46 of 2,145 responses). Generated ids ARE |
| 33 | compared: the driver makes os.urandom deterministic, one stream per request |
| 34 | (keyed by its label), so both runs mint the same ids for the same request |
| 35 | even when an earlier request was answered differently. |
| 36 | """ |
| 37 | |
| 38 | from __future__ import annotations |
| 39 | |
| 40 | import io |
| 41 | import json |
| 42 | import os |
| 43 | import re |
| 44 | import subprocess |
| 45 | import sys |
| 46 | import tarfile |
| 47 | from pathlib import Path |
| 48 | |
| 49 | import pytest |
| 50 | |
| 51 | pytestmark = pytest.mark.conformance |
| 52 | |
| 53 | ROOT = Path(__file__).resolve().parents[1] |
| 54 | DRIVER = Path(__file__).resolve().parent / "differential_driver.py" |
| 55 | BASELINE_ENV = "DBBASIC_DIFFERENTIAL_BASELINE" |
| 56 | # Was c145348 (before the caches), which proved every cache against a tree that |
| 57 | # re-read everything; it passed against that baseline up to ba041f3. From |
| 58 | # 504814f, package manifests may declare attention counts (collection + where), |
| 59 | # which c145348's package loader refuses, so the session cannot install there. |
| 60 | # 504814f is the first tree that loads today's packages. From the commit after |
| 61 | # 143d5c1, app-shipping reads its stuck-parcel threshold from a setting |
| 62 | # (older_than_days {"setting", "default"}) and app-mail-sync's detail is a |
| 63 | # fixed sentence, both of which 504814f's loader refuses; 143d5c1 added them, |
| 64 | # and against 504814f it differed in none of its 2,290 responses. |
| 65 | # Moved to 3cc9672 after three intended behaviour changes landed together: |
| 66 | # a create without owner_id is now stamped with the caller (was 403), and |
| 67 | # installing app-nav registers nav entries / attention sources of packages |
| 68 | # installed before it (25 responses changed, all from those two; recorded in |
| 69 | # the commit messages of db9b96c and 4992704). 143d5c1 passed up to 9f84876. |
| 70 | # Moved to 21ae8b6 (on the public main branch) after the permission-enforcement |
| 71 | # series. Against 3cc9672 the session differed in 102 of 2,276 responses, every |
| 72 | # one from a change whose commit message says it was meant (CHANGELOG: "A server |
| 73 | # asked to enforce permissions could quietly stop enforcing them", 2026-12-02): |
| 74 | # - 66: /permissions/status and /identity gained fields (permissions.mode, |
| 75 | # ae847aa; identity_source_configured / identity_source_refused, 31c2b9c; |
| 76 | # the unready-override warning now says it does nothing, c7a7372; the |
| 77 | # readiness blockers when the policy file is gone, 0b75c1c); |
| 78 | # - 6: a record asked for by id that the caller may not read answers 404 |
| 79 | # like a missing one, was 403 (193e698); |
| 80 | # - 27: while the policy file is invalid, everyone but the admin token gets |
| 81 | # 503 permission_policy_unavailable (was 500, 67849ee), and the admin |
| 82 | # token's own requests answer or report the problem instead of crashing |
| 83 | # (1faa042; its audit rows now carry the admin decision); |
| 84 | # - 2: a policy file that is removed denies non-admins (was: served every |
| 85 | # record), 0b75c1c; |
| 86 | # - 1: search over a broken schema file answers 503 (was an uncaught |
| 87 | # ValueError), 41d01ff. |
| 88 | DEFAULT_BASELINE = "21ae8b6" |
| 89 | |
| 90 | # An instant: ISO-8601 with or without fraction and zone, or the compact |
| 91 | # form backup file names use (20261129T040600910545Z). Each thing masked is a |
| 92 | # place a real difference could hide, so this stays as short as two runs of |
| 93 | # the SAME tree allow. |
| 94 | INSTANT = re.compile( |
| 95 | r"\d{4}-\d\d-\d\d[T ]\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:?\d\d)?|\b\d{8}T\d{6,}Z\b" |
| 96 | ) |
| 97 | REV = re.compile(r"[0-9a-f]{64}") |
| 98 | BACKUP_BYTES = re.compile(r'("format_version": \d+, "created_at": "[^"]*", "files": \d+, "bytes": )\d+') |
| 99 | |
| 100 | |
| 101 | def _git(*args: str) -> subprocess.CompletedProcess: |
| 102 | return subprocess.run(["git", *args], cwd=ROOT, capture_output=True) |
| 103 | |
| 104 | |
| 105 | def _extract_baseline(ref: str, dest: Path) -> None: |
| 106 | listing = _git("ls-tree", "--name-only", ref) |
| 107 | if listing.returncode != 0: |
| 108 | pytest.skip(f"baseline {ref!r} is not in this checkout ({BASELINE_ENV} selects another)") |
| 109 | names = [name for name in listing.stdout.decode().split("\n") if name.endswith(".py")] |
| 110 | archive = _git("archive", "--format=tar", ref, "--", *names) |
| 111 | assert archive.returncode == 0, archive.stderr.decode() |
| 112 | dest.mkdir(parents=True) |
| 113 | with tarfile.open(fileobj=io.BytesIO(archive.stdout)) as tar: |
| 114 | tar.extractall(dest, filter="data") |
| 115 | # Both runs install TODAY's packages, and a package may import a root |
| 116 | # module the baseline commit did not have yet (object_corrections, which |
| 117 | # app-orders' and app-invoices' line checks import). Without it the |
| 118 | # baseline answers every such write 503 "check could not be loaded" and |
| 119 | # the whole session diverges from there. A module the baseline lacks |
| 120 | # cannot be the code under comparison, so it is supplied as it is today; |
| 121 | # every module the baseline DID have is still the baseline's own. |
| 122 | for module in sorted(ROOT.glob("*.py")): |
| 123 | if not (dest / module.name).exists(): |
| 124 | (dest / module.name).write_bytes(module.read_bytes()) |
| 125 | |
| 126 | |
| 127 | def _record(tree: Path, work: Path, out: Path) -> list[list]: |
| 128 | """One session against `tree`. `work` is the same path for both runs so |
| 129 | a path that reaches a response is the same text in both.""" |
| 130 | env = dict(os.environ, PYTHONHASHSEED="0") |
| 131 | env.pop("PYTHONPATH", None) |
| 132 | result = subprocess.run( |
| 133 | [sys.executable, str(DRIVER), "--tree", str(tree), "--packages", str(ROOT / "packages"), |
| 134 | "--work", str(work), "--out", str(out), "--set", "full"], |
| 135 | cwd=work.parent, env=env, capture_output=True, text=True, |
| 136 | ) |
| 137 | assert result.returncode == 0, result.stdout[-2000:] + result.stderr[-6000:] |
| 138 | return json.loads(out.read_text()) |
| 139 | |
| 140 | |
| 141 | def _volatile_revs(body: str) -> set[str]: |
| 142 | """Every `_rev` in this response. A rev a client is given is a keyed |
| 143 | hash under a secret each box makes for itself (so it cannot be used to |
| 144 | test guesses of a hidden field), which means the two trees can never |
| 145 | agree on one: the comparison is of everything else. That a rev moves |
| 146 | when its row does, and only then, is held by tests/test_rev_oracle.py |
| 147 | and the If-Match steps of this session, which send back the rev each |
| 148 | tree handed out.""" |
| 149 | try: |
| 150 | payload = json.loads(body) |
| 151 | except ValueError: |
| 152 | return set() |
| 153 | if not isinstance(payload, dict): |
| 154 | return set() |
| 155 | found: set[str] = set() |
| 156 | rev = payload.get("_rev") |
| 157 | if isinstance(rev, str) and REV.fullmatch(rev): |
| 158 | found.add(rev) |
| 159 | revs = payload.get("revs") |
| 160 | if isinstance(revs, dict): |
| 161 | found.update(v for v in revs.values() if isinstance(v, str) and REV.fullmatch(v)) |
| 162 | return found |
| 163 | |
| 164 | |
| 165 | def _normalise(text: str, tree: Path) -> str: |
| 166 | for rev in _volatile_revs(text): |
| 167 | text = text.replace(rev, "<rev: keyed per box>") |
| 168 | text = BACKUP_BYTES.sub(r"\1<size of a compressed archive>", text) |
| 169 | return INSTANT.sub("<instant>", text.replace(str(tree), "<tree>")) |
| 170 | |
| 171 | |
| 172 | def _comparable(entry: list, tree: Path) -> tuple: |
| 173 | label, status, headers, body = entry |
| 174 | return ( |
| 175 | label, |
| 176 | status, |
| 177 | tuple((name, _normalise(value, tree)) for name, value in headers), |
| 178 | _normalise(body, tree), |
| 179 | ) |
| 180 | |
| 181 | |
| 182 | # Responses this tree answers differently from the baseline ON PURPOSE, each |
| 183 | # stated exactly: (status before, status after, body before, body after), |
| 184 | # compared after _normalise. A response listed here may also match the |
| 185 | # baseline unchanged (a baseline moved past the change); any other difference |
| 186 | # in it, or in any response not listed, still fails. |
| 187 | # |
| 188 | # m06 (a schema file that is not JSON sits in <data>/schemas/): a write to a |
| 189 | # collection another schema could roll up used to land and then be answered |
| 190 | # 400 with the broken file's error, because the post-write lookup of rollup |
| 191 | # parents raised it. It is now answered as written, and the order's rollup is |
| 192 | # refreshed by the write instead of staying stale until m07's line. The probe |
| 193 | # note that is now created also gets its update and delete (INTENDED_EXTRA). |
| 194 | # |
| 195 | # m31b (a second user files a note under the first user's project before it |
| 196 | # is shared with them): notes.project_id now declares relation.requires read |
| 197 | # (docs/permissions-model.md, "Pointing at a record you may not act on"), so |
| 198 | # u2 may not file a note under a project u2 cannot see. It is answered |
| 199 | # exactly like a missing project, and so it is absent from u2's list after |
| 200 | # the share; the note filed AFTER the share still lands. |
| 201 | _M06 = "m06 schema file broken/" |
| 202 | _M31B = "m31b other user " |
| 203 | _M31B_PROJECT = "6cd67bd8-0bc8-4a13-ac29-893061a5361b" |
| 204 | _M31B_NOTE = "e60e1fe2-e969-44b1-b504-929e5a718bb2" |
| 205 | _SCHEMA_ERROR = '{"status": "error", "error": "Schema file contains invalid JSON: scratch_things"}' |
| 206 | INTENDED: dict[str, tuple[int, int, str, str]] = { |
| 207 | _M06 + "create :: POST /collections/notes/records": ( |
| 208 | 400, 201, _SCHEMA_ERROR, |
| 209 | '{"status": "ok", "collection": "notes", "record": {"id": "5a446b0a-2b2f-49ea-8030-b2001a6b8c8a", ' |
| 210 | '"content": "probe m06 schema file broken", "project_id": "p1_0", "is_public": "false", ' |
| 211 | '"owner_id": "u1", "created_at": "<instant>", "zz": "", "diff_flag": "", "diff_flug": ""}}'), |
| 212 | _M06 + "orderline-create :: POST /collections/order_lines/records": ( |
| 213 | 400, 201, _SCHEMA_ERROR, |
| 214 | '{"status": "ok", "collection": "order_lines", "record": {"id": "efdcf2ac-f1e5-4585-b72f-b00badb7b4d1", ' |
| 215 | '"order_id": "o1_0", "product_id": "", "description": "m06 schema file broken", "quantity": "2", ' |
| 216 | '"unit_price_cents": "500", "line_note": "", "modifier_cents": "0", "backordered": "false", ' |
| 217 | '"discount_bps": "", "line_discount_cents": "", "line_total_cents": "0", "tax_rate_bps": "", ' |
| 218 | '"line_tax_cents": "0", "owner_id": "u1", "created_at": "<instant>"}}'), |
| 219 | _M31B + "note in the new project :: POST /collections/notes/records": ( |
| 220 | 201, 400, |
| 221 | '{"status": "ok", "collection": "notes", "record": {"id": "' + _M31B_NOTE + '", ' |
| 222 | '"content": "not mine", "project_id": "' + _M31B_PROJECT + '", "is_public": "false", ' |
| 223 | '"owner_id": "u2", "created_at": "<instant>", "zz": "", "diff_flag": "", "diff_flug": ""}}', |
| 224 | '{"status": "error", "error": "Record field \'project_id\' references a missing record: ' |
| 225 | 'projects/' + _M31B_PROJECT + '"}'), |
| 226 | } |
| 227 | # Same status; the body differs only by these replacements (old -> new, and |
| 228 | # optionally how many times old occurs; default exactly once). |
| 229 | # |
| 230 | # m28 (a package install takes a restore-point backup): the archive now also |
| 231 | # carries permissions/policy.json and identity/users.tsv + accounts.tsv |
| 232 | # (docs/http-api-contract.md "Backups"), so the restore point holds three |
| 233 | # more files. Stated as "three more", not as two absolute counts: the |
| 234 | # archive also holds every shipped package's files, so the absolute number |
| 235 | # moves whenever a package is added (435 when this was written, 468 once |
| 236 | # app-exchange and app-bills shipped), and pinning it made the replay fail on |
| 237 | # a change it was never about. |
| 238 | BACKUP_FILES = re.compile(r'"files": (\d+),') |
| 239 | |
| 240 | |
| 241 | def _three_more_backup_files(body: str) -> str | None: |
| 242 | """The baseline body with each backup file count raised by three, or |
| 243 | None unless the count appears exactly three times (once per place the |
| 244 | answer names the backup).""" |
| 245 | if len(BACKUP_FILES.findall(body)) != 3: |
| 246 | return None |
| 247 | return BACKUP_FILES.sub(lambda m: f'"files": {int(m.group(1)) + 3},', body) |
| 248 | |
| 249 | |
| 250 | INTENDED_EDITS: dict[str, list[tuple]] = { |
| 251 | "m28 install package :: POST /packages/hello-world/install": [ |
| 252 | (_three_more_backup_files,), # the backup, named three times in the answer |
| 253 | ], |
| 254 | _M06 + "order-after :: GET /collections/orders/records/o1_0": [ |
| 255 | ('"subtotal_cents": "10000"', '"subtotal_cents": "11000"'), |
| 256 | ('"total_cents": "10000"', '"total_cents": "11000"'), |
| 257 | ], # its _rev moves too; the row holds an instant, so the rev is masked |
| 258 | _M31B + "list after the share :: GET /collections/notes/records?limit=500": [ |
| 259 | ('{"id": "' + _M31B_NOTE + '", "content": "not mine", "project_id": "' + _M31B_PROJECT + '", ' |
| 260 | '"is_public": "false", "owner_id": "u2", "created_at": "<instant>", "zz": "", ' |
| 261 | '"diff_flag": "", "diff_flug": ""}, ', ''), |
| 262 | ('"count": 36, "total": 36', '"count": 35, "total": 35'), |
| 263 | (', "' + _M31B_NOTE + '": "<rev: keyed per box>"', ''), |
| 264 | ], |
| 265 | } |
| 266 | COLLECTIONS_COUNT_AT_END = re.compile(r'\}\], "count": (\d+)\}$') |
| 267 | |
| 268 | |
| 269 | def _collections_gain_user_objects(body: str) -> str | None: |
| 270 | """The baseline /collections body with the per-owner summary of user |
| 271 | objects added after `count`; this session has no user objects, so the |
| 272 | list is empty. None unless the body ends with the collection count.""" |
| 273 | if COLLECTIONS_COUNT_AT_END.search(body) is None: |
| 274 | return None |
| 275 | return COLLECTIONS_COUNT_AT_END.sub( |
| 276 | lambda m: '}], "count": ' + m.group(1) + ', "user_objects": []}', body) |
| 277 | |
| 278 | |
| 279 | # The same edit at every step that issues the request (label suffix). |
| 280 | INTENDED_EDITS_EVERY_STEP: dict[str, list[tuple]] = { |
| 281 | # GET /collections summarises user objects (u_<id>_<name>) per owner |
| 282 | # under "user_objects" instead of counting them inside the collection |
| 283 | # their name spells (docs/http-api-contract.md "Collections"). |
| 284 | "/collections :: GET /collections": [ |
| 285 | (_collections_gain_user_objects,), |
| 286 | ], |
| 287 | # /permissions/status lists the stored policy's mistakes; this session's |
| 288 | # policies have none (the policy-strict-save change). |
| 289 | "/permissions-status :: GET /permissions/status": [ |
| 290 | ('"temporary_rules": 0}', '"temporary_rules": 0, "findings": []}'), |
| 291 | ], |
| 292 | } |
| 293 | # Requests only this tree's session issues (the driver follows a 201 probe |
| 294 | # create with an update and a delete), and the status each must have. |
| 295 | _PROBE_NOTE = "/collections/notes/records/5a446b0a-2b2f-49ea-8030-b2001a6b8c8a" |
| 296 | INTENDED_EXTRA: dict[str, int] = { |
| 297 | _M06 + "update :: PUT " + _PROBE_NOTE: 200, |
| 298 | _M06 + "delete :: DELETE " + _PROBE_NOTE: 200, |
| 299 | } |
| 300 | |
| 301 | |
| 302 | def _intended(a: tuple, b: tuple) -> bool: |
| 303 | """Whether the difference between comparable entries a (baseline) and b |
| 304 | is exactly one stated above.""" |
| 305 | label = a[0] |
| 306 | if a[2] != b[2]: |
| 307 | return False |
| 308 | if label in INTENDED: |
| 309 | return (a[1], b[1], a[3], b[3]) == INTENDED[label] |
| 310 | edits = INTENDED_EDITS.get(label) |
| 311 | if edits is None: |
| 312 | edits = next((e for suffix, e in INTENDED_EDITS_EVERY_STEP.items() if label.endswith(suffix)), None) |
| 313 | if edits is not None: |
| 314 | body = a[3] |
| 315 | for edit in edits: |
| 316 | if callable(edit[0]): |
| 317 | body = edit[0](body) |
| 318 | if body is None: |
| 319 | return False |
| 320 | continue |
| 321 | old_text, new_text, *times = edit |
| 322 | if body.count(old_text) != (times[0] if times else 1): |
| 323 | return False |
| 324 | body = body.replace(old_text, new_text) |
| 325 | return a[1] == b[1] and body == b[3] |
| 326 | return False |
| 327 | |
| 328 | |
| 329 | def compare(old: list[list], new: list[list], old_tree: Path, new_tree: Path) -> list[str]: |
| 330 | """Human-readable differences between two recordings, [] when none.""" |
| 331 | problems: list[str] = [] |
| 332 | old_labels = {e[0] for e in old} |
| 333 | extra = [e for e in new if e[0] in INTENDED_EXTRA and e[0] not in old_labels] |
| 334 | for entry in extra: |
| 335 | if entry[1] != INTENDED_EXTRA[entry[0]]: |
| 336 | problems.append(f"{entry[0]}: status {entry[1]}, expected {INTENDED_EXTRA[entry[0]]}") |
| 337 | new = [e for e in new if e not in extra] |
| 338 | if [e[0] for e in old] != [e[0] for e in new]: |
| 339 | problems.append(f"the two sessions issued different requests ({len(old)} vs {len(new)})") |
| 340 | for before, after in zip(old, new): |
| 341 | a, b = _comparable(before, old_tree), _comparable(after, new_tree) |
| 342 | if a == b or _intended(a, b): |
| 343 | continue |
| 344 | what = [] |
| 345 | if a[1] != b[1]: |
| 346 | what.append(f"status {a[1]} -> {b[1]}") |
| 347 | if a[2] != b[2]: |
| 348 | what.append(f"headers {sorted(set(a[2]) ^ set(b[2]))}") |
| 349 | if a[3] != b[3]: |
| 350 | at = next((i for i, (x, y) in enumerate(zip(a[3], b[3])) if x != y), min(len(a[3]), len(b[3]))) |
| 351 | what.append(f"body at {at}: {a[3][max(0, at - 60):at + 100]!r} -> {b[3][max(0, at - 60):at + 100]!r}") |
| 352 | problems.append(f"{a[0]}: " + "; ".join(what)) |
| 353 | return problems |
| 354 | |
| 355 | |
| 356 | def test_every_response_matches_the_baseline_tree(tmp_path): |
| 357 | """Byte-identical status, headers and body for ~2,400 requests, across |
| 358 | every on-disk change a cache could miss. A difference is either a stale |
| 359 | cache or an unintended behaviour change; both are bugs here.""" |
| 360 | ref = os.environ.get(BASELINE_ENV, DEFAULT_BASELINE) |
| 361 | baseline_tree = tmp_path / "baseline" |
| 362 | _extract_baseline(ref, baseline_tree) |
| 363 | work = tmp_path / "work" |
| 364 | |
| 365 | old = _record(baseline_tree, work, tmp_path / "old.json") |
| 366 | import shutil |
| 367 | |
| 368 | shutil.rmtree(work) |
| 369 | new = _record(ROOT, work, tmp_path / "new.json") |
| 370 | |
| 371 | assert len(old) > 2000, "the session did not run to the end" |
| 372 | statuses = {entry[1] for entry in old} |
| 373 | assert {200, 201, 400, 401, 403, 404, 500} <= statuses, statuses |
| 374 | |
| 375 | problems = compare(old, new, baseline_tree, ROOT) |
| 376 | assert not problems, f"{len(problems)} of {len(old)} responses differ from {ref}:\n" + "\n".join(problems[:25]) |