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_package_attention.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, 19 minutes ago History
test_package_attention.py · 17.0 KB · 391 lines
1"""What needs a human ships with the app that knows.
2
3Every gate on this server ends in a pile somebody has to look at, and the
4system has been computing those piles and discarding them for as long as
5it has existed -- `system_scan_processor` returns a key literally named
6`needing_a_human` that no surface has ever read. The `attention` manifest
7section is where a package finally says what its pile MEANS, and these
8are the properties that make saying it safe to do repeatedly.
9
10They are the same properties `nav` holds, for the same reasons: an
11operator's decision outlives an upgrade, a plan that says "unchanged"
12writes nothing, a second package cannot quietly take over a definition,
13and a package still installs when the home-screen app is absent. The one
14addition is the blocking check -- a counter aimed at an object that will
15not exist reads zero forever, and a queue that reads zero forever is
16indistinguishable from a queue that is empty. That silent failure is the
17entire reason this section exists, so it refuses to install.
18"""
19
20import json
21import pathlib
22
23import pytest
24
25import object_packages
26import object_records
27
28REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
29PACKAGES = REPO_ROOT / "packages"
30APP_NAV = PACKAGES / "app-nav"
31SOURCES_SCHEMA = json.loads((APP_NAV / "schemas" / "attention_sources.json").read_text())
32
33MANIFEST = {
34 "id": "app-demo",
35 "name": "Demo",
36 "version": "1.0.0",
37 "objects": [{"id": "system_demo_attention",
38 "path": "objects/system/demo_attention.py"}],
39 "schemas": [{"collection": "attention_sources", "path": "schemas/attention_sources.json"}],
40 "attention": [{"id": "demo_queue", "object_id": "system_demo_attention",
41 "label": "Demo queue", "path": "/demo?status=waiting",
42 "nav_id": "demo", "group": "Work", "severity": "warning"}],
43}
44
45SOURCE = "def COUNT(request):\n return {'count': 2, 'detail': 'both today'}\n"
46
47
48@pytest.fixture
49def package(tmp_path):
50 """A one-provider package that also ships the attention_sources
51 schema, so the registry exists for it to declare into."""
52 root = tmp_path / "packages"
53 pkg = root / "app-demo"
54 (pkg / "objects" / "system").mkdir(parents=True)
55 (pkg / "objects" / "system" / "demo_attention.py").write_text(SOURCE)
56 (pkg / "schemas").mkdir()
57 (pkg / "schemas" / "attention_sources.json").write_text(json.dumps(SOURCES_SCHEMA))
58 (pkg / "dbbasic-package.json").write_text(json.dumps(MANIFEST))
59 objects = tmp_path / "objects"
60 objects.mkdir()
61 data = tmp_path / "data"
62 data.mkdir()
63 return {"root": root, "dir": pkg, "objects": objects, "data": data}
64
65
66def write_manifest(package, **overrides):
67 manifest = {**MANIFEST, **overrides}
68 (package["dir"] / "dbbasic-package.json").write_text(json.dumps(manifest))
69
70
71def install(package, **kwargs):
72 return object_packages.install_package(
73 "app-demo", root=package["root"], base_dir=package["data"],
74 object_roots=[package["objects"]], **kwargs)
75
76
77def plan(package):
78 return object_packages.dry_run_package(
79 "app-demo", root=package["root"], base_dir=package["data"],
80 object_roots=[package["objects"]])
81
82
83def sources(package):
84 try:
85 rows = object_records.read_collection_records(
86 "attention_sources", base_dir=package["data"])
87 except Exception:
88 return {}
89 return {row["id"]: row for row in rows}
90
91
92def set_source(fixture, source_id, **changes):
93 """An operator editing a row by hand -- `fixture` rather than
94 `package` because `package` is itself one of the row's columns."""
95 object_records.update_collection_record(
96 "attention_sources", source_id, changes,
97 base_dir=fixture["data"], actor="operator")
98
99
100# --- declaring ----------------------------------------------------------------
101
102def test_installing_a_package_registers_its_queue(package):
103 result = install(package)
104 assert [entry["status"] for entry in result["attention"]] == ["written"]
105
106 row = sources(package)["demo_queue"]
107 assert row["object_id"] == "system_demo_attention"
108 assert row["label"] == "Demo queue"
109 assert row["path"] == "/demo?status=waiting"
110 assert row["nav_id"] == "demo"
111 assert row["group"] == "Work"
112 assert row["severity"] == "warning"
113 assert row["package"] == "app-demo" # provenance, stamped by install
114 assert row["operator_muted"] == "false"
115
116
117def test_the_plan_says_what_it_would_declare_before_it_does(package):
118 assert plan(package)["attention"] == [{
119 "id": "demo_queue", "object_id": "system_demo_attention",
120 "label": "Demo queue", "path": "/demo?status=waiting", "nav_id": "demo",
121 "group": "Work", "severity": "warning",
122 "exists": False, "action": "create"}]
123 assert plan(package)["package"]["attention_count"] == 1
124 assert sources(package) == {} # a dry run writes nothing
125
126
127def test_a_package_with_no_attention_touches_no_records(package):
128 write_manifest(package, attention=[])
129 result = install(package)
130 assert result["attention"] == []
131 assert sources(package) == {}
132
133
134def test_the_defaults_are_apps_and_normal(package):
135 write_manifest(package, attention=[{
136 "id": "demo_queue", "object_id": "system_demo_attention",
137 "label": "Demo queue", "path": "/demo"}])
138 install(package)
139
140 row = sources(package)["demo_queue"]
141 assert row["group"] == "Apps"
142 assert row["severity"] == "normal"
143 assert row["nav_id"] == "" # a queue may have no door
144
145
146# --- surviving an upgrade -------------------------------------------------------
147
148def test_reinstalling_preserves_the_operators_mute(package):
149 """The package declares what a queue MEANS; the operator decides
150 whether this deployment wants to be told about it. An upgrade that
151 silently un-mutes a counter somebody turned off is the same incident
152 as one that restarts a paused nightly pass."""
153 install(package)
154 set_source(package, "demo_queue", operator_muted="true")
155
156 write_manifest(package, version="1.1.0",
157 attention=[{**MANIFEST["attention"][0], "label": "Renamed"}])
158 install(package, allow_replace=True)
159
160 row = sources(package)["demo_queue"]
161 assert row["operator_muted"] == "true" # untouched
162 assert row["label"] == "Renamed" # but the package's word is restated
163
164
165def test_reinstalling_updates_a_changed_declaration(package):
166 install(package)
167 # nav_id left out (DRON refuses a blank one) clears the door
168 write_manifest(package, version="1.1.0", attention=[{
169 **{k: v for k, v in MANIFEST["attention"][0].items() if k != "nav_id"},
170 "label": "Renamed", "path": "/elsewhere", "group": "System", "severity": "urgent"}])
171 result = install(package, allow_replace=True)
172
173 assert result["attention"][0]["action"] == "update"
174 assert result["attention"][0]["status"] == "updated"
175 row = sources(package)["demo_queue"]
176 assert (row["label"], row["path"], row["nav_id"], row["group"], row["severity"]) == (
177 "Renamed", "/elsewhere", "", "System", "urgent")
178
179
180def test_an_unchanged_entry_reports_unchanged(package):
181 install(package)
182 result = install(package, allow_replace=True)
183 assert result["attention"][0]["status"] == "unchanged"
184 assert result["attention"][0]["action"] == "unchanged"
185
186
187def test_a_plan_that_says_unchanged_writes_nothing_at_all(package):
188 """Every package-owned field is compared, severity and nav_id
189 included: a dry run that under-reports is worse than no dry run."""
190 install(package)
191 before = sources(package)["demo_queue"]
192 install(package, allow_replace=True)
193 assert sources(package)["demo_queue"] == before # byte-for-byte, created_at included
194
195 write_manifest(package, attention=[{**MANIFEST["attention"][0],
196 "severity": "urgent"}])
197 assert plan(package)["attention"][0]["action"] == "update"
198 install(package, allow_replace=True)
199 assert sources(package)["demo_queue"]["severity"] == "urgent"
200
201
202# --- refusing what could not work ------------------------------------------------
203
204def test_two_packages_cannot_own_one_definition(package):
205 """Two packages writing one row is two answers to what needs a human,
206 where whichever installed last silently wins."""
207 install(package)
208 set_source(package, "demo_queue", package="app-other")
209 with pytest.raises(object_packages.PackageInstallError) as exc:
210 install(package, allow_replace=True)
211 assert "app-other" in str(exc.value)
212
213
214def test_a_counter_pointing_at_nothing_blocks_the_install(package):
215 """A provider that will not exist reads zero forever, and a queue that
216 reads zero forever is indistinguishable from an empty one. That silent
217 failure is the reason this whole section exists."""
218 write_manifest(package, attention=[{**MANIFEST["attention"][0],
219 "object_id": "system_not_shipped"}])
220 with pytest.raises(object_packages.PackageInstallError) as exc:
221 install(package)
222 assert "system_not_shipped" in str(exc.value)
223 assert sources(package) == {}
224
225
226def test_a_counter_may_point_at_an_object_already_on_the_server(package):
227 """A package is allowed to count somebody else's queue, as long as the
228 provider is genuinely resolvable when the plan is made."""
229 (package["objects"] / "system_elsewhere.py").write_text(SOURCE)
230 write_manifest(package, attention=[{**MANIFEST["attention"][0],
231 "object_id": "system_elsewhere"}])
232 result = install(package)
233 assert result["attention"][0]["status"] == "written"
234
235
236def test_two_queues_may_point_at_one_list(package):
237 """Deliberately NOT a collision: an orders page is legitimately both
238 'to pick' and 'to invoice', and refusing that would be a false
239 blocker."""
240 write_manifest(package, attention=[
241 MANIFEST["attention"][0],
242 {**MANIFEST["attention"][0], "id": "second_queue", "label": "Also"},
243 ])
244 result = install(package)
245 assert [entry["status"] for entry in result["attention"]] == ["written", "written"]
246
247
248@pytest.mark.parametrize("bad, reason", [
249 ({"id": "two words", "object_id": "system_demo_attention", "label": "X",
250 "path": "/x"}, "attention id"),
251 ({"id": "demo_queue", "object_id": "Not An Id", "label": "X", "path": "/x"},
252 "attention object_id"),
253 ({"id": "demo_queue", "object_id": "system_demo_attention", "label": "X",
254 "path": "x"}, "start with"),
255 ({"id": "demo_queue", "object_id": "system_demo_attention", "label": "X",
256 "path": "/two words"}, "whitespace"),
257 ({"id": "demo_queue", "object_id": "system_demo_attention", "label": "X",
258 "path": "/x\nmore"}, "whitespace"),
259 ({"id": "demo_queue", "object_id": "system_demo_attention", "label": "X",
260 "path": "/x", "severity": "screaming"}, "normal|warning|urgent"),
261 ({"id": "demo_queue", "object_id": "system_demo_attention", "label": "X",
262 "path": "/x", "nav_id": "two words"}, "attention nav_id"),
263 ({"id": "demo_queue", "object_id": "system_demo_attention", "path": "/x"},
264 "requires 'label'"),
265 ({"id": "demo_queue", "object_id": "system_demo_attention", "label": "X"},
266 "requires 'path'"),
267 ({"id": "demo_queue", "label": "X", "path": "/x"}, "requires 'object_id'"),
268])
269def test_a_declaration_that_could_not_work_is_refused_at_install(package, bad, reason):
270 write_manifest(package, attention=[bad])
271 with pytest.raises(object_packages.InvalidPackageManifestError) as exc:
272 install(package)
273 assert reason in str(exc.value)
274 assert sources(package) == {}
275
276
277def test_two_attention_entries_cannot_share_an_id(package):
278 write_manifest(package, attention=[MANIFEST["attention"][0],
279 {**MANIFEST["attention"][0], "path": "/other"}])
280 with pytest.raises(object_packages.InvalidPackageManifestError):
281 install(package)
282
283
284# --- when the home-screen app is not installed -------------------------------------
285
286def test_a_missing_registry_skips_gracefully_instead_of_failing(package):
287 """A package must never fail to install because the home screen is
288 absent. It says so in the result rather than pretending it wrote."""
289 write_manifest(package, schemas=[])
290 result = install(package)
291
292 assert [entry["status"] for entry in result["attention"]] == ["skipped"]
293 assert "attention_sources" in result["attention"][0]["reason"]
294 assert not (package["data"] / "collections" / "attention_sources").exists()
295
296
297def test_a_missing_registry_still_plans_the_entry(package):
298 write_manifest(package, schemas=[])
299 assert plan(package)["attention"][0]["action"] == "create"
300 assert plan(package)["safe_to_install"] is True
301
302
303# --- the real packages --------------------------------------------------------------
304
305def _manifests():
306 return {path.parent.name: json.loads(path.read_text())
307 for path in sorted(PACKAGES.glob("*/dbbasic-package.json"))}
308
309
310def test_shipped_attention_sources_do_not_collide_on_an_id():
311 seen: dict[str, str] = {}
312 for package_id, manifest in _manifests().items():
313 for entry in manifest.get("attention") or []:
314 assert entry["id"] not in seen, (
315 f"{entry['id']} declared by both {seen.get(entry['id'])} "
316 f"and {package_id}")
317 seen[entry["id"]] = package_id
318 assert len(seen) >= 9, "the box's known queues should all be declared"
319
320
321def test_every_shipped_declaration_names_a_provider_its_package_ships():
322 """A counter aimed at an object nobody installs would block its own
323 package's install; this catches it at review time instead."""
324 for package_id, manifest in _manifests().items():
325 shipped = {entry["id"] for entry in manifest.get("objects", [])}
326 schemas = {entry["collection"] for entry in manifest.get("schemas", [])}
327 dependency_schemas = {
328 schema["collection"]
329 for dependency in manifest.get("dependencies", [])
330 for schema in _manifests()[dependency].get("schemas", [])}
331 for entry in manifest.get("attention") or []:
332 if "collection" in entry:
333 # A declared count: the collection is this package's or a
334 # dependency's, so it exists by the time the entry installs.
335 assert entry["collection"] in schemas | dependency_schemas, (
336 f"{package_id} counts {entry['collection']} but neither it "
337 "nor a dependency ships it")
338 continue
339 assert entry["object_id"] in shipped, (
340 f"{package_id} counts {entry['object_id']} but does not ship it")
341 assert entry["object_id"].endswith("_attention"), entry["object_id"]
342
343
344def test_every_shipped_provider_exposes_count_and_nothing_else():
345 """COUNT is the contract with the daemon's rollup pass. A provider
346 that answered on GET or POST instead would read as a permanent zero,
347 which is exactly the silent failure this layer exists to end."""
348 for package_id, manifest in _manifests().items():
349 paths = {entry["id"]: entry["path"] for entry in manifest.get("objects", [])}
350 for entry in manifest.get("attention") or []:
351 if "object_id" not in entry:
352 continue
353 source = (PACKAGES / package_id / paths[entry["object_id"]]).read_text()
354 assert "def COUNT(request):" in source, package_id
355 assert "def POST(request):" not in source, package_id
356
357
358def test_every_shipped_declaration_normalizes_and_uses_the_house_groups():
359 groups = {"Work", "Publishing", "Money", "Commerce", "Warehouse", "System"}
360 nav_ids = {entry["id"]
361 for manifest in _manifests().values()
362 for entry in manifest.get("nav") or []}
363 for package_id in _manifests():
364 package = object_packages.get_package(package_id, root=PACKAGES)
365 for entry in package["attention"]:
366 assert entry["group"] in groups, f"{package_id}: {entry['group']}"
367 assert entry["path"].startswith("/")
368 if entry["nav_id"]:
369 assert entry["nav_id"] in nav_ids, (
370 f"{package_id}: {entry['id']} decorates a door nobody declares")
371
372
373def test_only_a_broken_machine_is_urgent():
374 """Severity is a scale nobody calibrates if everything claims the top
375 of it. `urgent` is reserved for the server reporting that it stopped
376 doing its own work, not for work that is merely late: scheduled passes
377 that failed, and scheduled backups that failed or went stale."""
378 urgent = {entry["id"]
379 for manifest in _manifests().values()
380 for entry in manifest.get("attention") or []
381 if entry.get("severity") == "urgent"}
382 assert urgent == {"scheduler_failures", "backup_problems"}
383
384
385def test_app_nav_owns_the_two_collections_and_declares_no_queue():
386 """The home screen holds the registry and the rollup; it has no
387 domain of its own, so it has nothing that needs a human."""
388 manifest = _manifests()["app-nav"]
389 collections = {entry["collection"] for entry in manifest["schemas"]}
390 assert {"attention_sources", "attention_counts"} <= collections
391 assert not manifest.get("attention")