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_object_packages.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_object_packages.py · 64.5 KB · 1697 lines
1import json
2from pathlib import Path
3
4import pytest
5
6import object_execution
7import object_namespace
8import object_package_baselines
9import object_packages
10import object_reconciles
11import object_record_changes
12import object_records
13import object_schemas
14import object_state
15import python_object_runtime
16
17
18def write_package(root, package_id, payload, files=()):
19 package_dir = root / package_id
20 package_dir.mkdir(parents=True)
21 (package_dir / object_packages.MANIFEST_FILE).write_text(json.dumps(payload))
22 for relative_path, content in files:
23 path = package_dir / relative_path
24 path.parent.mkdir(parents=True, exist_ok=True)
25 path.write_text(content)
26 return package_dir
27
28
29def update_package(root, package_id, payload, files=()):
30 """Overwrite an already-written package's manifest and files (a "new version")."""
31 package_dir = root / package_id
32 (package_dir / object_packages.MANIFEST_FILE).write_text(json.dumps(payload))
33 for relative_path, content in files:
34 path = package_dir / relative_path
35 path.parent.mkdir(parents=True, exist_ok=True)
36 path.write_text(content)
37 return package_dir
38
39
40def _reconcile_manifest(version):
41 return {
42 "id": "hello-world",
43 "name": "Hello World",
44 "version": version,
45 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
46 "schemas": [{"collection": "contacts", "path": "schemas/contacts.json"}],
47 }
48
49
50def _install_reconcile_fixture(tmp_path, *, edit_object=False, edit_schema=False):
51 """Install hello-world v0.1.0, optionally customize the live object/schema."""
52 packages_root = tmp_path / "packages"
53 data_dir = tmp_path / "data"
54 object_root = tmp_path / "objects"
55 object_root.mkdir()
56
57 write_package(
58 packages_root,
59 "hello-world",
60 _reconcile_manifest("0.1.0"),
61 files=(
62 ("objects/hello/world.py", "def GET(request): return {'v': 1}\n"),
63 (
64 "schemas/contacts.json",
65 json.dumps({"name": "contacts", "fields": [{"name": "id", "type": "text"}]}),
66 ),
67 ),
68 )
69 object_packages.install_package(
70 "hello-world",
71 root=packages_root,
72 base_dir=data_dir,
73 object_roots=[object_root],
74 )
75
76 if edit_object:
77 (object_root / "hello" / "world.py").write_text("def GET(request): return {'v': 'customized'}\n")
78 if edit_schema:
79 # Change "id"'s type (diverging from the shipped base) as well as
80 # adding a new field, so a later package change to "id" is a real
81 # field-level collision rather than a union-mergeable diff.
82 object_schemas.replace_schema(
83 "contacts",
84 {
85 "name": "contacts",
86 "fields": [
87 {"name": "id", "type": "number"},
88 {"name": "x_priority", "type": "text"},
89 ],
90 },
91 base_dir=data_dir,
92 )
93
94 return packages_root, data_dir, object_root
95
96
97def _bump_reconcile_package(packages_root, *, version, object_code=None, schema_fields=None):
98 package_dir = packages_root / "hello-world"
99 files = []
100 if object_code is not None:
101 files.append(("objects/hello/world.py", object_code))
102 if schema_fields is not None:
103 files.append(("schemas/contacts.json", json.dumps({"name": "contacts", "fields": schema_fields})))
104 update_package(packages_root, "hello-world", _reconcile_manifest(version), files=files)
105
106
107def manifest(package_id="crm-starter", **overrides):
108 payload = {
109 "id": package_id,
110 "name": "CRM Starter",
111 "version": "0.1.0",
112 "description": "Contacts and deals",
113 "compatibility": {"object_server": ">=0.0.1"},
114 "dependencies": [{"id": "hello-world", "version": ">=0.1.0"}],
115 "objects": [{"id": "crm_contacts", "path": "objects/crm/contacts.py"}],
116 "schemas": [{"collection": "contacts", "path": "schemas/contacts.json"}],
117 "permissions": [{"path": "permissions/policy.json"}],
118 "seed": [{"collection": "contacts", "path": "seed/contacts.tsv"}],
119 "migrations": [{"id": "001_init", "path": "migrations/001_init.py"}],
120 }
121 payload.update(overrides)
122 return payload
123
124
125def test_list_packages_returns_manifest_summaries(tmp_path):
126 packages_root = tmp_path / "packages"
127 write_package(packages_root, "hello-world", manifest("hello-world"))
128 write_package(packages_root, "crm-starter", manifest("crm-starter"))
129 write_package(packages_root, "Bad.Name", manifest("Bad.Name"))
130
131 packages = object_packages.list_packages(root=packages_root)
132
133 assert [package["id"] for package in packages] == ["crm-starter", "hello-world"]
134 assert packages[0]["status"] == "available"
135 assert packages[0]["object_count"] == 1
136 assert packages[0]["schema_count"] == 1
137 assert packages[0]["dependency_count"] == 1
138
139
140def test_get_package_normalizes_manifest(tmp_path):
141 packages_root = tmp_path / "packages"
142 write_package(packages_root, "crm-starter", manifest())
143
144 package = object_packages.get_package("crm-starter", root=packages_root)
145
146 assert package["id"] == "crm-starter"
147 assert package["objects"] == [{"id": "crm_contacts", "path": "objects/crm/contacts.py"}]
148 assert package["schemas"] == [{"collection": "contacts", "path": "schemas/contacts.json"}]
149 assert package["dependencies"] == [{"id": "hello-world", "version": ">=0.1.0"}]
150
151
152def test_dry_run_reports_create_replace_merge_apply_and_missing_files(tmp_path):
153 packages_root = tmp_path / "packages"
154 data_dir = tmp_path / "data"
155 object_root = tmp_path / "objects"
156 (object_root / "crm").mkdir(parents=True)
157 (object_root / "crm" / "contacts.py").write_text("def GET(request): return {}\n")
158 (data_dir / "schemas").mkdir(parents=True)
159 (data_dir / "schemas" / "contacts.json").write_text('{"fields":[]}\n')
160 (data_dir / "collections" / "contacts").mkdir(parents=True)
161 (data_dir / "collections" / "contacts" / "records.tsv").write_text("id\tname\nc1\tAlice\n")
162 (data_dir / object_packages.PACKAGE_MIGRATIONS_DIR / "crm-starter").mkdir(parents=True)
163 (data_dir / object_packages.PACKAGE_MIGRATIONS_DIR / "crm-starter" / "001_init.json").write_text("{}\n")
164
165 write_package(
166 packages_root,
167 "crm-starter",
168 manifest(),
169 files=(
170 ("objects/crm/contacts.py", "def GET(request): return {}\n"),
171 ("schemas/contacts.json", '{"fields":[]}\n'),
172 ("permissions/policy.json", '{"rules": []}\n'),
173 ("seed/contacts.tsv", "id\tname\nc2\tBob\n"),
174 ),
175 )
176
177 plan = object_packages.dry_run_package(
178 "crm-starter",
179 root=packages_root,
180 base_dir=data_dir,
181 object_roots=[object_root],
182 )
183
184 assert plan["mode"] == "dry_run"
185 assert plan["install_enabled"] is False
186 assert plan["safe_to_install"] is False
187 assert plan["objects"][0]["action"] == "replace"
188 assert plan["schemas"][0]["action"] == "replace"
189 assert plan["permissions"][0]["action"] == "merge"
190 assert plan["seed"][0]["action"] == "skip"
191 assert plan["migrations"][0]["action"] == "skip"
192 assert plan["warnings"] == ["Missing package migration file: migrations/001_init.py"]
193
194
195def test_dry_run_is_safe_when_declared_files_exist(tmp_path):
196 packages_root = tmp_path / "packages"
197 write_package(
198 packages_root,
199 "hello-world",
200 {
201 "id": "hello-world",
202 "name": "Hello World",
203 "version": "0.1.0",
204 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
205 },
206 files=(("objects/hello/world.py", "def GET(request): return {}\n"),),
207 )
208
209 plan = object_packages.dry_run_package("hello-world", root=packages_root)
210
211 assert plan["safe_to_install"] is True
212 assert plan["warnings"] == []
213 assert plan["objects"][0]["action"] == "create"
214
215
216def test_repository_system_dashboard_package_installs_and_executes(tmp_path):
217 packages_root = Path("packages")
218 data_dir = tmp_path / "data"
219 object_root = tmp_path / "objects"
220
221 package = object_packages.get_package("system-dashboard", root=packages_root)
222 plan = object_packages.dry_run_package(
223 "system-dashboard",
224 root=packages_root,
225 base_dir=data_dir,
226 object_roots=[object_root],
227 )
228
229 # 0.6.0 added the scheduler board alongside the dashboard page.
230 assert package["objects"] == [
231 {"id": "system_dashboard", "path": "objects/system/dashboard.py"},
232 {"id": "system_scheduler", "path": "objects/system/scheduler.py"},
233 # 0.8.0: failed scheduled runs, the one `urgent` attention
234 # provider on this server.
235 {"id": "system_scheduler_attention",
236 "path": "objects/system/scheduler_attention.py"},
237 # 0.9.0: the scheduled-backup page and its urgent provider.
238 {"id": "system_backups", "path": "objects/system/backups.py"},
239 {"id": "system_backup_attention",
240 "path": "objects/system/backup_attention.py"},
241 ]
242 assert plan["safe_to_install"] is True
243 assert plan["objects"][0]["action"] == "create"
244
245 install = object_packages.install_package(
246 "system-dashboard",
247 root=packages_root,
248 base_dir=data_dir,
249 object_roots=[object_root],
250 )
251
252 assert install["objects"][0]["destination"] == "system/dashboard.py"
253 assert (object_root / "system" / "dashboard.py").is_file()
254
255 runtime = python_object_runtime.PythonObjectRuntime(base_dir=data_dir)
256 result = object_execution.execute_object(
257 runtime,
258 object_execution.ObjectExecutionRequest("system_dashboard"),
259 roots=[object_root],
260 )
261
262 assert result.ok is True
263 assert result.result["content_type"] == "text/html; charset=utf-8"
264 assert "DBBASIC Dashboard" in result.result["body"]
265 assert "sign in</a> for live metrics" in result.result["body"]
266 assert object_state.get_object_state("system_dashboard", base_dir=data_dir)["served"] == 1
267
268
269def test_repository_admin_write_probe_package_installs_and_writes_records(tmp_path):
270 packages_root = Path("packages")
271 data_dir = tmp_path / "data"
272 object_root = tmp_path / "objects"
273
274 package = object_packages.get_package("admin-write-probe", root=packages_root)
275 plan = object_packages.dry_run_package(
276 "admin-write-probe",
277 root=packages_root,
278 base_dir=data_dir,
279 object_roots=[object_root],
280 )
281
282 assert package["objects"] == [
283 {"id": "system_write_probe", "path": "objects/system/write_probe.py"}
284 ]
285 assert package["schemas"] == [
286 {"collection": "dbbasic_probe", "path": "schemas/dbbasic_probe.json"}
287 ]
288 assert package["seed"] == [
289 {"collection": "dbbasic_probe", "path": "seed/dbbasic_probe.tsv"}
290 ]
291 assert plan["safe_to_install"] is True
292 assert plan["objects"][0]["action"] == "create"
293 assert plan["schemas"][0]["action"] == "create"
294 assert plan["seed"][0]["action"] == "create"
295
296 install = object_packages.install_package(
297 "admin-write-probe",
298 root=packages_root,
299 base_dir=data_dir,
300 object_roots=[object_root],
301 )
302
303 assert install["objects"][0]["destination"] == "system/write_probe.py"
304 assert install["schemas"][0]["destination"] == "schemas/dbbasic_probe.json"
305 assert install["seed"][0]["destination"] == "collections/dbbasic_probe/records.tsv"
306 assert (object_root / "system" / "write_probe.py").is_file()
307
308 runtime = python_object_runtime.PythonObjectRuntime(base_dir=data_dir)
309 result = object_execution.execute_object(
310 runtime,
311 object_execution.ObjectExecutionRequest("system_write_probe"),
312 roots=[object_root],
313 )
314
315 assert result.ok is True
316 assert result.result["content_type"] == "text/html; charset=utf-8"
317 assert "DBBASIC Write Probe" in result.result["body"]
318 assert "packages/admin-write-probe" in result.result["body"]
319 assert object_state.get_object_state("system_write_probe", base_dir=data_dir)["served"] == 1
320
321 record = object_records.create_collection_record(
322 "dbbasic_probe",
323 {
324 "id": "probe_test",
325 "note": "created by package test",
326 "status": "created",
327 "updated_at": "2026-07-01T00:00:00+00:00",
328 },
329 base_dir=data_dir,
330 )
331 assert record["status"] == "created"
332
333 updated = object_records.update_collection_record(
334 "dbbasic_probe",
335 "probe_test",
336 {
337 "note": "updated by package test",
338 "status": "updated",
339 },
340 base_dir=data_dir,
341 )
342 assert updated["note"] == "updated by package test"
343 assert updated["status"] == "updated"
344
345 deleted = object_records.delete_collection_record(
346 "dbbasic_probe",
347 "probe_test",
348 base_dir=data_dir,
349 )
350 assert deleted["id"] == "probe_test"
351 assert object_records.read_collection_records("dbbasic_probe", base_dir=data_dir) == []
352
353
354def test_install_package_creates_objects_schemas_and_seed(tmp_path):
355 packages_root = tmp_path / "packages"
356 data_dir = tmp_path / "data"
357 object_root = tmp_path / "objects"
358 write_package(
359 packages_root,
360 "hello-world",
361 {
362 "id": "hello-world",
363 "name": "Hello World",
364 "version": "0.1.0",
365 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
366 "schemas": [{"collection": "contacts", "path": "schemas/contacts.json"}],
367 "permissions": [],
368 "seed": [{"collection": "contacts", "path": "seed/contacts.tsv"}],
369 "migrations": [],
370 },
371 files=(
372 ("objects/hello/world.py", "def GET(request): return {'status': 'ok'}\n"),
373 ("schemas/contacts.json", '{"name":"contacts","fields":[{"name":"id","type":"text"}]}\n'),
374 ("seed/contacts.tsv", "id\tname\nc1\tAlice\n"),
375 ),
376 )
377
378 result = object_packages.install_package(
379 "hello-world",
380 root=packages_root,
381 base_dir=data_dir,
382 object_roots=[object_root],
383 )
384
385 assert result["mode"] == "install"
386 assert result["install_enabled"] is True
387 assert result["objects"][0]["destination"] == "hello/world.py"
388 assert (object_root / "hello" / "world.py").read_text() == "def GET(request): return {'status': 'ok'}\n"
389 schema = json.loads((data_dir / "schemas" / "contacts.json").read_text())
390 assert schema["name"] == "contacts"
391 assert schema["field_count"] == 1
392 assert (data_dir / "collections" / "contacts" / "records.tsv").read_text() == "id\tname\nc1\tAlice\n"
393
394
395def test_install_package_attributes_seed_records(tmp_path):
396 """Seed writes bypass object_records.create_collection_record (the whole
397
398 records.tsv lands as one atomic byte copy), so unlike a normal record
399 write nothing emits a change automatically -- universal attribution
400 still requires one, attributed to the installing package.
401 """
402 packages_root = tmp_path / "packages"
403 data_dir = tmp_path / "data"
404 object_root = tmp_path / "objects"
405 write_package(
406 packages_root,
407 "hello-world",
408 {
409 "id": "hello-world",
410 "name": "Hello World",
411 "version": "0.1.0",
412 "objects": [],
413 "schemas": [{"collection": "contacts", "path": "schemas/contacts.json"}],
414 "permissions": [],
415 "seed": [{"collection": "contacts", "path": "seed/contacts.tsv"}],
416 "migrations": [],
417 },
418 files=(
419 ("schemas/contacts.json", '{"name":"contacts","fields":[{"name":"id","type":"text"}]}\n'),
420 ("seed/contacts.tsv", "id\tname\nc1\tAlice\nc2\tBob\n"),
421 ),
422 )
423
424 object_packages.install_package(
425 "hello-world",
426 root=packages_root,
427 base_dir=data_dir,
428 object_roots=[object_root],
429 )
430
431 changes = object_record_changes.list_record_changes("contacts", base_dir=data_dir)["changes"]
432 assert {change["record_id"] for change in changes} == {"c1", "c2"}
433 assert all(change["action"] == "create" for change in changes)
434 assert all(change["actor"] == "package-install:hello-world" for change in changes)
435
436
437def test_install_package_refuses_existing_objects_without_replace(tmp_path):
438 packages_root = tmp_path / "packages"
439 object_root = tmp_path / "objects"
440 (object_root / "hello").mkdir(parents=True)
441 (object_root / "hello" / "world.py").write_text("def GET(request): return {'old': True}\n")
442 write_package(
443 packages_root,
444 "hello-world",
445 {
446 "id": "hello-world",
447 "name": "Hello World",
448 "version": "0.1.0",
449 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
450 },
451 files=(("objects/hello/world.py", "def GET(request): return {'new': True}\n"),),
452 )
453
454 with pytest.raises(object_packages.PackageInstallError, match="allow_replace=true"):
455 object_packages.install_package(
456 "hello-world",
457 root=packages_root,
458 object_roots=[object_root],
459 )
460
461 assert (object_root / "hello" / "world.py").read_text() == "def GET(request): return {'old': True}\n"
462
463
464def test_install_package_replaces_objects_when_allowed(tmp_path):
465 # The pre-existing file here was never installed by this package (no
466 # baseline recorded for it), so the reconcile engine has no basis to call
467 # it "pristine" and would park it as a conflict rather than guess. This
468 # is the "replaces when allowed" path re-armed under Phase 2: allow_replace
469 # clears the create/replace blocker, and force is the explicit "discard
470 # whatever is there" signal (see docs/upgrade-and-customization.md Rule 1).
471 packages_root = tmp_path / "packages"
472 object_root = tmp_path / "objects"
473 (object_root / "hello").mkdir(parents=True)
474 (object_root / "hello" / "world.py").write_text("def GET(request): return {'old': True}\n")
475 write_package(
476 packages_root,
477 "hello-world",
478 {
479 "id": "hello-world",
480 "name": "Hello World",
481 "version": "0.1.0",
482 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
483 },
484 files=(("objects/hello/world.py", "def GET(request): return {'new': True}\n"),),
485 )
486
487 result = object_packages.install_package(
488 "hello-world",
489 root=packages_root,
490 base_dir=tmp_path / "data",
491 object_roots=[object_root],
492 allow_replace=True,
493 force=True,
494 )
495
496 assert result["objects"][0]["action"] == "replace"
497 assert result["objects"][0]["status"] == "forced"
498 assert (object_root / "hello" / "world.py").read_text() == "def GET(request): return {'new': True}\n"
499
500
501def test_install_package_parks_conflict_when_replace_has_no_baseline(tmp_path):
502 # Same setup as above, but WITHOUT force: an untracked existing file plus
503 # differing shipped content is a conflict, not a blind overwrite. The
504 # install still succeeds; the live file is left untouched and a
505 # pending-reconcile record is created instead.
506 packages_root = tmp_path / "packages"
507 object_root = tmp_path / "objects"
508 (object_root / "hello").mkdir(parents=True)
509 (object_root / "hello" / "world.py").write_text("def GET(request): return {'old': True}\n")
510 write_package(
511 packages_root,
512 "hello-world",
513 {
514 "id": "hello-world",
515 "name": "Hello World",
516 "version": "0.1.0",
517 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
518 },
519 files=(("objects/hello/world.py", "def GET(request): return {'new': True}\n"),),
520 )
521
522 result = object_packages.install_package(
523 "hello-world",
524 root=packages_root,
525 base_dir=tmp_path / "data",
526 object_roots=[object_root],
527 allow_replace=True,
528 )
529
530 assert result["objects"][0]["action"] == "replace"
531 assert result["objects"][0]["status"] == "conflict"
532 assert "reconcile_id" in result["objects"][0]
533 assert result["reconciles"] == [result["objects"][0]["reconcile_id"]]
534 assert (object_root / "hello" / "world.py").read_text() == "def GET(request): return {'old': True}\n"
535
536
537def test_install_package_runs_before_write_hook_after_validation(tmp_path):
538 packages_root = tmp_path / "packages"
539 object_root = tmp_path / "objects"
540 write_package(
541 packages_root,
542 "hello-world",
543 {
544 "id": "hello-world",
545 "name": "Hello World",
546 "version": "0.1.0",
547 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
548 },
549 files=(("objects/hello/world.py", "def GET(request): return {'new': True}\n"),),
550 )
551 calls = []
552
553 def before_write(plan):
554 calls.append(plan["package"]["id"])
555 assert not (object_root / "hello" / "world.py").exists()
556 return {"path": "restore-point.tar.gz"}
557
558 result = object_packages.install_package(
559 "hello-world",
560 root=packages_root,
561 object_roots=[object_root],
562 before_write=before_write,
563 )
564
565 assert calls == ["hello-world"]
566 assert result["restore_point"] == {"path": "restore-point.tar.gz"}
567 assert (object_root / "hello" / "world.py").is_file()
568
569
570def test_install_package_does_not_run_before_write_hook_when_blocked(tmp_path):
571 packages_root = tmp_path / "packages"
572 object_root = tmp_path / "objects"
573 (object_root / "hello").mkdir(parents=True)
574 (object_root / "hello" / "world.py").write_text("def GET(request): return {'old': True}\n")
575 write_package(
576 packages_root,
577 "hello-world",
578 {
579 "id": "hello-world",
580 "name": "Hello World",
581 "version": "0.1.0",
582 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
583 },
584 files=(("objects/hello/world.py", "def GET(request): return {'new': True}\n"),),
585 )
586 calls = []
587
588 with pytest.raises(object_packages.PackageInstallError):
589 object_packages.install_package(
590 "hello-world",
591 root=packages_root,
592 object_roots=[object_root],
593 before_write=lambda plan: calls.append(plan["package"]["id"]),
594 )
595
596 assert calls == []
597 assert (object_root / "hello" / "world.py").read_text() == "def GET(request): return {'old': True}\n"
598
599
600def test_install_package_rejects_unsupported_permission_and_migration_writes(tmp_path):
601 packages_root = tmp_path / "packages"
602 write_package(
603 packages_root,
604 "crm-starter",
605 manifest(),
606 files=(
607 ("objects/crm/contacts.py", "def GET(request): return {}\n"),
608 ("schemas/contacts.json", '{"fields":[]}\n'),
609 ("permissions/policy.json", '{"rules": []}\n'),
610 ("seed/contacts.tsv", "id\tname\nc2\tBob\n"),
611 ("migrations/001_init.py", "def run(): pass\n"),
612 ),
613 )
614
615 with pytest.raises(object_packages.PackageInstallError) as exc:
616 object_packages.install_package("crm-starter", root=packages_root)
617
618 assert "migration execution" in str(exc.value)
619
620
621def test_install_package_merges_permission_rules_with_provenance(tmp_path):
622 import object_permission_store
623
624 packages_root = tmp_path / "packages"
625 data_dir = tmp_path / "data"
626 object_root = tmp_path / "objects"
627 object_root.mkdir()
628 fragment = json.dumps(
629 {
630 "rules": [
631 {
632 "effect": "allow",
633 "principal": "public",
634 "actions": ["execute"],
635 "object_id": "crm_contacts",
636 "reason": "public contacts page",
637 },
638 {
639 "effect": "allow",
640 "principal": "registered",
641 "actions": ["read", "create"],
642 "collection": "contacts",
643 },
644 ]
645 }
646 )
647 payload = manifest(dependencies=[], migrations=[], seed=[])
648 write_package(
649 packages_root,
650 "crm-starter",
651 payload,
652 files=(
653 ("objects/crm/contacts.py", "def GET(request): return {}\n"),
654 ("schemas/contacts.json", '{"fields":[]}\n'),
655 ("permissions/policy.json", fragment),
656 ),
657 )
658
659 plan = object_packages.dry_run_package(
660 "crm-starter", root=packages_root, base_dir=data_dir, object_roots=[object_root]
661 )
662 install = object_packages.install_package(
663 "crm-starter", root=packages_root, base_dir=data_dir, object_roots=[object_root]
664 )
665 policy = object_permission_store.load_policy(data_dir)
666
667 assert plan["permissions"][0] == {
668 "path": "permissions/policy.json",
669 "action": "merge",
670 "exists": True,
671 "rules": 2,
672 "new_rules": 2,
673 }
674 assert install["permissions"][0]["status"] == "merged"
675 assert install["permissions"][0]["new_rules"] == 2
676 assert len(policy.rules) == 2
677 assert all(rule.package == "crm-starter" for rule in policy.rules)
678 assert policy.rules[0].object_id == "crm_contacts"
679
680 reinstall = object_packages.install_package(
681 "crm-starter",
682 root=packages_root,
683 base_dir=data_dir,
684 object_roots=[object_root],
685 allow_replace=True,
686 )
687 policy_after = object_permission_store.load_policy(data_dir)
688
689 assert reinstall["permissions"][0]["new_rules"] == 0
690 assert len(policy_after.rules) == 2
691
692
693def test_install_package_rejects_invalid_permission_fragment(tmp_path):
694 packages_root = tmp_path / "packages"
695 object_root = tmp_path / "objects"
696 object_root.mkdir()
697 payload = manifest(dependencies=[], migrations=[], schemas=[], seed=[])
698 write_package(
699 packages_root,
700 "crm-starter",
701 payload,
702 files=(
703 ("objects/crm/contacts.py", "def GET(request): return {}\n"),
704 ("permissions/policy.json", '{"rules": [{"effect": "allow"}]}\n'),
705 ),
706 )
707
708 with pytest.raises(object_packages.PackageInstallError) as exc:
709 object_packages.install_package(
710 "crm-starter",
711 root=packages_root,
712 base_dir=tmp_path / "data",
713 object_roots=[object_root],
714 )
715
716 assert "permission rule is invalid" in str(exc.value)
717
718
719def test_install_package_merges_seed_by_id_preserving_existing(tmp_path):
720 # Seeding a collection that already holds records MERGES by id: existing
721 # rows survive untouched, and seed rows whose id isn't present are added.
722 # This is what lets several packages each seed a shared collection
723 # (views/site_routes) and lets a new package version ship new default rows,
724 # while never clobbering live data ("upgrade the app, keep the data").
725 packages_root = tmp_path / "packages"
726 data_dir = tmp_path / "data"
727 (data_dir / "collections" / "contacts").mkdir(parents=True)
728 (data_dir / "collections" / "contacts" / "records.tsv").write_text("id\tname\nc1\tAlice\n")
729 write_package(
730 packages_root,
731 "seeded",
732 {
733 "id": "seeded",
734 "name": "Seeded",
735 "version": "0.1.0",
736 "seed": [{"collection": "contacts", "path": "seed/contacts.tsv"}],
737 },
738 files=(("seed/contacts.tsv", "id\tname\nc2\tBob\n"),),
739 )
740
741 result = object_packages.install_package(
742 "seeded", root=packages_root, base_dir=data_dir, allow_replace=True
743 )
744
745 seed_entry = result["seed"][0]
746 assert seed_entry["status"] == "merged"
747 assert seed_entry["installed"] is True
748 assert seed_entry["added"] == 1
749 # Existing row (Alice) preserved AND the new seed row (Bob) merged in by id.
750 records = object_records.read_collection_records("contacts", base_dir=data_dir)
751 assert {r["name"] for r in records} == {"Alice", "Bob"}
752 # Re-installing adds nothing (ids already present).
753 again = object_packages.install_package(
754 "seeded", root=packages_root, base_dir=data_dir, allow_replace=True
755 )
756 assert again["seed"][0]["status"] == "skipped" and again["seed"][0]["added"] == 0
757
758
759def test_a_seed_row_the_collection_refuses_is_named_in_the_install_result(tmp_path):
760 """A merged seed row that breaks a schema `unique` constraint (or any
761 other rule the collection enforces) was swallowed by a bare except:
762 the install said "merged 1 new row(s)" and the row that did not land
763 was nowhere. It still does not fail the install -- one bad default row
764 is not worth a half-installed package -- but the result names it, with
765 the refusal, so whoever installed the package can see what is missing."""
766 packages_root = tmp_path / "packages"
767 data_dir = tmp_path / "data"
768 schema = {"name": "contacts", "fields": [{"name": "id"}, {"name": "email"},
769 {"name": "age", "type": "integer"}],
770 "unique": [{"fields": ["email"], "message": "That email is taken."}]}
771 manifest_v1 = {"id": "uniq-seed", "name": "Uniq Seed", "version": "0.1.0",
772 "schemas": [{"collection": "contacts", "path": "schemas/contacts.json"}],
773 "seed": [{"collection": "contacts", "path": "seed/contacts.tsv"}]}
774 write_package(
775 packages_root, "uniq-seed", manifest_v1,
776 files=(("schemas/contacts.json", json.dumps(schema)),
777 ("seed/contacts.tsv", "id\temail\tage\nc2\tann@example.com\t\n")),
778 )
779 object_packages.install_package("uniq-seed", root=packages_root, base_dir=data_dir)
780 # Live data takes an email; the next version seeds that email again,
781 # and a row whose age is not a number.
782 object_records.create_collection_record(
783 "contacts", {"id": "live", "email": "bob@example.com"}, base_dir=data_dir)
784 update_package(
785 packages_root, "uniq-seed", {**manifest_v1, "version": "0.2.0"},
786 files=(("seed/contacts.tsv",
787 "id\temail\tage\nc2\tann@example.com\t\nc3\tbob@example.com\t\n"
788 "c4\tcy@example.com\tnot-a-number\n"),),
789 )
790
791 result = object_packages.install_package(
792 "uniq-seed", root=packages_root, base_dir=data_dir, allow_replace=True)
793
794 entry = result["seed"][0]
795 assert entry["added"] == 0
796 assert entry["status"] == "skipped"
797 rejected = {row["id"]: row for row in entry["rejected"]}
798 assert set(rejected) == {"c3", "c4"}
799 assert rejected["c3"]["code"] == "unique_violation"
800 assert "That email is taken." in rejected["c3"]["error"]
801 assert "2 seed row(s) refused" in entry["reason"]
802 assert any("c3 (unique_violation)" in warning and "c4 (invalid_record)" in warning
803 for warning in result["warnings"]), result["warnings"]
804 ids = {r["id"] for r in object_records.read_collection_records("contacts", base_dir=data_dir)}
805 assert ids == {"c2", "live"}
806
807
808def test_a_fresh_seed_with_two_rows_on_one_unique_key_is_reported(tmp_path):
809 """A first install writes the seed file into the fresh collection byte
810 for byte, so two seed rows on one `unique` key both landed and the
811 install said "written" with nothing more. The file is still written
812 (the trusted package-author path; shipped seeds are checked in CI by
813 tests/test_package_schema_rules.py), but the duplicates are named."""
814 packages_root = tmp_path / "packages"
815 data_dir = tmp_path / "data"
816 schema = {"name": "contacts", "fields": [{"name": "id"}, {"name": "email"}],
817 "unique": [{"fields": ["email"], "ignore_case": True,
818 "message": "That email is taken."}]}
819 manifest = {"id": "dup-seed", "name": "Dup Seed", "version": "0.1.0",
820 "schemas": [{"collection": "contacts", "path": "schemas/contacts.json"}],
821 "seed": [{"collection": "contacts", "path": "seed/contacts.tsv"}]}
822 write_package(
823 packages_root, "dup-seed", manifest,
824 files=(("schemas/contacts.json", json.dumps(schema)),
825 ("seed/contacts.tsv",
826 "id\temail\nc1\tann@example.com\nc2\tAnn@example.com\nc3\tbo@example.com\n")),
827 )
828 result = object_packages.install_package("dup-seed", root=packages_root, base_dir=data_dir)
829 entry = result["seed"][0]
830 assert entry["status"] == "written"
831 assert [v["ids"] for v in entry["unique_violations"]] == [["c1", "c2"]]
832 assert any("email on c1, c2" in w for w in result["warnings"]), result["warnings"]
833
834
835def test_a_clean_fresh_seed_reports_no_unique_violations(tmp_path):
836 packages_root = tmp_path / "packages"
837 data_dir = tmp_path / "data"
838 schema = {"name": "contacts", "fields": [{"name": "id"}, {"name": "email"}],
839 "unique": [{"fields": ["email"], "message": "That email is taken."}]}
840 manifest = {"id": "ok-seed", "name": "Ok Seed", "version": "0.1.0",
841 "schemas": [{"collection": "contacts", "path": "schemas/contacts.json"}],
842 "seed": [{"collection": "contacts", "path": "seed/contacts.tsv"}]}
843 write_package(
844 packages_root, "ok-seed", manifest,
845 files=(("schemas/contacts.json", json.dumps(schema)),
846 ("seed/contacts.tsv", "id\temail\nc1\tann@example.com\n")),
847 )
848 result = object_packages.install_package("ok-seed", root=packages_root, base_dir=data_dir)
849 assert "unique_violations" not in result["seed"][0]
850 assert not any("unique" in w for w in result.get("warnings", []))
851
852
853def test_install_package_validates_schema_before_writing_objects(tmp_path):
854 packages_root = tmp_path / "packages"
855 data_dir = tmp_path / "data"
856 object_root = tmp_path / "objects"
857 write_package(
858 packages_root,
859 "bad-schema",
860 {
861 "id": "bad-schema",
862 "name": "Bad Schema",
863 "version": "0.1.0",
864 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
865 "schemas": [{"collection": "contacts", "path": "schemas/contacts.json"}],
866 },
867 files=(
868 ("objects/hello/world.py", "def GET(request): return {'status': 'ok'}\n"),
869 ("schemas/contacts.json", '{"name":"other","fields":[]}\n'),
870 ),
871 )
872
873 with pytest.raises(object_packages.PackageInstallError, match="schema is invalid"):
874 object_packages.install_package(
875 "bad-schema",
876 root=packages_root,
877 base_dir=data_dir,
878 object_roots=[object_root],
879 )
880
881 assert not (object_root / "hello" / "world.py").exists()
882
883
884def test_package_manifest_rejects_unsafe_paths_and_ids(tmp_path):
885 packages_root = tmp_path / "packages"
886 write_package(
887 packages_root,
888 "bad-package",
889 manifest("bad-package", objects=[{"id": "bad/id", "path": "../secret.py"}]),
890 )
891
892 with pytest.raises(object_packages.InvalidPackageManifestError):
893 object_packages.get_package("bad-package", root=packages_root)
894
895 with pytest.raises(object_packages.InvalidPackageIdError):
896 object_packages.get_package("../bad", root=packages_root)
897
898
899def test_missing_package_raises(tmp_path):
900 with pytest.raises(object_packages.PackageNotFoundError):
901 object_packages.get_package("missing", root=tmp_path / "packages")
902
903
904# --- Phase 2: reconcile-on-upgrade decision table ---------------------------
905#
906# See docs/upgrade-and-customization.md (Rule 1). Each test below exercises
907# one row of the three-way-compare table for objects (and, at the end,
908# schemas): pristine vs customized, shipped unchanged vs shipped changed.
909
910
911def test_reconcile_fresh_install_status_written(tmp_path):
912 packages_root = tmp_path / "packages"
913 data_dir = tmp_path / "data"
914 object_root = tmp_path / "objects"
915 object_root.mkdir()
916 write_package(
917 packages_root,
918 "hello-world",
919 _reconcile_manifest("0.1.0"),
920 files=(
921 ("objects/hello/world.py", "def GET(request): return {'v': 1}\n"),
922 (
923 "schemas/contacts.json",
924 json.dumps({"name": "contacts", "fields": [{"name": "id", "type": "text"}]}),
925 ),
926 ),
927 )
928
929 result = object_packages.install_package(
930 "hello-world",
931 root=packages_root,
932 base_dir=data_dir,
933 object_roots=[object_root],
934 )
935
936 assert result["objects"][0]["status"] == "written"
937 assert result["schemas"][0]["status"] == "written"
938 assert result["reconciles"] == []
939
940
941def test_reconcile_unchanged_reinstall_is_noop(tmp_path):
942 packages_root, data_dir, object_root = _install_reconcile_fixture(tmp_path)
943
944 result = object_packages.install_package(
945 "hello-world",
946 root=packages_root,
947 base_dir=data_dir,
948 object_roots=[object_root],
949 allow_replace=True,
950 )
951
952 assert result["objects"][0]["status"] == "unchanged"
953 assert result["schemas"][0]["status"] == "unchanged"
954 assert result["reconciles"] == []
955 assert (object_root / "hello" / "world.py").read_text() == "def GET(request): return {'v': 1}\n"
956
957
958def test_reconcile_pristine_fast_forwards_on_upgrade(tmp_path):
959 packages_root, data_dir, object_root = _install_reconcile_fixture(tmp_path, edit_object=False)
960 _bump_reconcile_package(
961 packages_root,
962 version="0.2.0",
963 object_code="def GET(request): return {'v': 2}\n",
964 )
965
966 result = object_packages.install_package(
967 "hello-world",
968 root=packages_root,
969 base_dir=data_dir,
970 object_roots=[object_root],
971 allow_replace=True,
972 )
973
974 assert result["objects"][0]["status"] == "updated"
975 assert result["reconciles"] == []
976 assert (object_root / "hello" / "world.py").read_text() == "def GET(request): return {'v': 2}\n"
977
978 baseline = object_package_baselines.load_baseline("hello-world", base_dir=data_dir)
979 assert baseline["version"] == "0.2.0"
980 assert baseline["objects"]["hello_world"] == object_package_baselines.sha256_text(
981 "def GET(request): return {'v': 2}\n"
982 )
983
984
985def test_reconcile_customized_and_shipped_unchanged_keeps_customization(tmp_path):
986 packages_root, data_dir, object_root = _install_reconcile_fixture(tmp_path, edit_object=True)
987
988 result = object_packages.install_package(
989 "hello-world",
990 root=packages_root,
991 base_dir=data_dir,
992 object_roots=[object_root],
993 allow_replace=True,
994 )
995
996 assert result["objects"][0]["status"] == "kept"
997 assert result["reconciles"] == []
998 assert (
999 object_root / "hello" / "world.py"
1000 ).read_text() == "def GET(request): return {'v': 'customized'}\n"
1001
1002
1003def test_reconcile_customized_and_shipped_changed_parks_conflict(tmp_path):
1004 packages_root, data_dir, object_root = _install_reconcile_fixture(tmp_path, edit_object=True)
1005 _bump_reconcile_package(
1006 packages_root,
1007 version="0.2.0",
1008 object_code="def GET(request): return {'v': 2}\n",
1009 )
1010
1011 result = object_packages.install_package(
1012 "hello-world",
1013 root=packages_root,
1014 base_dir=data_dir,
1015 object_roots=[object_root],
1016 allow_replace=True,
1017 )
1018
1019 assert result["objects"][0]["status"] == "conflict"
1020 assert "reconcile_id" in result["objects"][0]
1021 assert result["reconciles"] == [result["objects"][0]["reconcile_id"]]
1022 # The install itself never raises: the conflict is parked, not blocking.
1023 assert (
1024 object_root / "hello" / "world.py"
1025 ).read_text() == "def GET(request): return {'v': 'customized'}\n"
1026
1027 reconcile = object_reconciles.get_reconcile(result["objects"][0]["reconcile_id"], base_dir=data_dir)
1028 assert reconcile["status"] == "pending"
1029 assert reconcile["package"] == "hello-world"
1030 assert reconcile["target_version"] == "0.2.0"
1031 assert reconcile["baseline_version"] == "0.1.0"
1032 assert reconcile["artifact"] == {"kind": "object", "id": "hello_world"}
1033 assert reconcile["mine"] == "def GET(request): return {'v': 'customized'}\n"
1034 assert reconcile["theirs"] == "def GET(request): return {'v': 2}\n"
1035
1036
1037def test_reconcile_force_overwrites_conflict(tmp_path):
1038 packages_root, data_dir, object_root = _install_reconcile_fixture(tmp_path, edit_object=True)
1039 _bump_reconcile_package(
1040 packages_root,
1041 version="0.2.0",
1042 object_code="def GET(request): return {'v': 2}\n",
1043 )
1044
1045 result = object_packages.install_package(
1046 "hello-world",
1047 root=packages_root,
1048 base_dir=data_dir,
1049 object_roots=[object_root],
1050 allow_replace=True,
1051 force=True,
1052 )
1053
1054 assert result["objects"][0]["status"] == "forced"
1055 assert result["reconciles"] == []
1056 assert (object_root / "hello" / "world.py").read_text() == "def GET(request): return {'v': 2}\n"
1057
1058 baseline = object_package_baselines.load_baseline("hello-world", base_dir=data_dir)
1059 assert baseline["objects"]["hello_world"] == object_package_baselines.sha256_text(
1060 "def GET(request): return {'v': 2}\n"
1061 )
1062
1063
1064def test_reconcile_resolve_take_theirs_writes_live_and_baseline(tmp_path):
1065 packages_root, data_dir, object_root = _install_reconcile_fixture(tmp_path, edit_object=True)
1066 _bump_reconcile_package(
1067 packages_root,
1068 version="0.2.0",
1069 object_code="def GET(request): return {'v': 2}\n",
1070 )
1071 result = object_packages.install_package(
1072 "hello-world",
1073 root=packages_root,
1074 base_dir=data_dir,
1075 object_roots=[object_root],
1076 allow_replace=True,
1077 )
1078 reconcile_id = result["objects"][0]["reconcile_id"]
1079
1080 resolved = object_reconciles.resolve_reconcile(
1081 reconcile_id,
1082 "take_theirs",
1083 base_dir=data_dir,
1084 object_roots=[object_root],
1085 resolved_at="2026-07-08T00:00:00Z",
1086 )
1087
1088 assert resolved["status"] == "resolved"
1089 assert resolved["resolution"] == {"choice": "take_theirs", "resolved_at": "2026-07-08T00:00:00Z"}
1090 assert (object_root / "hello" / "world.py").read_text() == "def GET(request): return {'v': 2}\n"
1091
1092 status = object_packages.package_status(
1093 "hello-world", root=packages_root, base_dir=data_dir, object_roots=[object_root]
1094 )
1095 assert status["pending_reconciles"] == 0
1096 object_artifact = next(a for a in status["artifacts"] if a["kind"] == "object")
1097 assert object_artifact["state"] == "pristine"
1098
1099
1100def test_reconcile_resolve_keep_mine_preserves_live_and_updates_baseline(tmp_path):
1101 packages_root, data_dir, object_root = _install_reconcile_fixture(tmp_path, edit_object=True)
1102 _bump_reconcile_package(
1103 packages_root,
1104 version="0.2.0",
1105 object_code="def GET(request): return {'v': 2}\n",
1106 )
1107 result = object_packages.install_package(
1108 "hello-world",
1109 root=packages_root,
1110 base_dir=data_dir,
1111 object_roots=[object_root],
1112 allow_replace=True,
1113 )
1114 reconcile_id = result["objects"][0]["reconcile_id"]
1115
1116 resolved = object_reconciles.resolve_reconcile(
1117 reconcile_id,
1118 "keep_mine",
1119 base_dir=data_dir,
1120 object_roots=[object_root],
1121 resolved_at="2026-07-08T00:00:00Z",
1122 )
1123
1124 assert resolved["status"] == "resolved"
1125 assert resolved["resolution"]["choice"] == "keep_mine"
1126 # Live content is untouched — the operator's customization survives.
1127 assert (
1128 object_root / "hello" / "world.py"
1129 ).read_text() == "def GET(request): return {'v': 'customized'}\n"
1130
1131 status = object_packages.package_status(
1132 "hello-world", root=packages_root, base_dir=data_dir, object_roots=[object_root]
1133 )
1134 assert status["pending_reconciles"] == 0
1135 # Baseline now reads sha_theirs, so live (still "mine") reads customized
1136 # against the new upstream baseline — the operator's choice is durable.
1137 object_artifact = next(a for a in status["artifacts"] if a["kind"] == "object")
1138 assert object_artifact["state"] == "customized"
1139
1140
1141def test_reconcile_schema_conflict_and_resolve(tmp_path):
1142 # Base ships id:text. The operator changes id's type to "number" *and*
1143 # the upgrade changes id's type to "boolean": the same field diverged on
1144 # both sides, so field-union merge cannot resolve it and it must still
1145 # park as a conflict (the "email" addition alone would have merged).
1146 packages_root, data_dir, object_root = _install_reconcile_fixture(tmp_path, edit_schema=True)
1147 _bump_reconcile_package(
1148 packages_root,
1149 version="0.2.0",
1150 schema_fields=[
1151 {"name": "id", "type": "boolean"},
1152 {"name": "email", "type": "text"},
1153 ],
1154 )
1155
1156 result = object_packages.install_package(
1157 "hello-world",
1158 root=packages_root,
1159 base_dir=data_dir,
1160 object_roots=[object_root],
1161 allow_replace=True,
1162 )
1163
1164 assert result["schemas"][0]["status"] == "conflict"
1165 assert result["schemas"][0]["collisions"] == ["id"]
1166 reconcile_id = result["schemas"][0]["reconcile_id"]
1167 assert result["reconciles"] == [reconcile_id]
1168
1169 live_before = object_schemas.get_schema("contacts", base_dir=data_dir, roots=[object_root])
1170 assert live_before["field_count"] == 2
1171 assert {f["name"] for f in live_before["fields"]} == {"id", "x_priority"}
1172
1173 reconcile_record = object_reconciles.get_reconcile(reconcile_id, base_dir=data_dir)
1174 assert reconcile_record["collisions"] == ["id"]
1175
1176 resolved = object_reconciles.resolve_reconcile(
1177 reconcile_id,
1178 "take_theirs",
1179 base_dir=data_dir,
1180 object_roots=[object_root],
1181 resolved_at="2026-07-08T00:00:00Z",
1182 )
1183 assert resolved["status"] == "resolved"
1184
1185 live_after = object_schemas.get_schema("contacts", base_dir=data_dir, roots=[object_root])
1186 assert {f["name"] for f in live_after["fields"]} == {"id", "email"}
1187
1188 baseline_after = object_package_baselines.load_baseline("hello-world", base_dir=data_dir)
1189 assert {f["name"] for f in baseline_after["schema_bodies"]["contacts"]["fields"]} == {"id", "email"}
1190
1191 status = object_packages.package_status(
1192 "hello-world", root=packages_root, base_dir=data_dir, object_roots=[object_root]
1193 )
1194 schema_artifact = next(a for a in status["artifacts"] if a["kind"] == "schema")
1195 assert schema_artifact["state"] == "pristine"
1196 assert status["pending_reconciles"] == 0
1197
1198
1199def test_reconcile_schema_merges_additive_changes_without_conflict(tmp_path):
1200 # Phase 4a / Rule 3: schemas are additive, so an operator-added field and
1201 # a package-added field on the same base should both survive an upgrade
1202 # via field-union merge, with no reconcile parked.
1203 packages_root = tmp_path / "packages"
1204 data_dir = tmp_path / "data"
1205 object_root = tmp_path / "objects"
1206 object_root.mkdir()
1207
1208 write_package(
1209 packages_root,
1210 "hello-world",
1211 _reconcile_manifest("0.1.0"),
1212 files=(
1213 ("objects/hello/world.py", "def GET(request): return {'v': 1}\n"),
1214 (
1215 "schemas/contacts.json",
1216 json.dumps(
1217 {
1218 "name": "contacts",
1219 "fields": [
1220 {"name": "id", "type": "text"},
1221 {"name": "name", "type": "text"},
1222 ],
1223 }
1224 ),
1225 ),
1226 ),
1227 )
1228 object_packages.install_package(
1229 "hello-world", root=packages_root, base_dir=data_dir, object_roots=[object_root]
1230 )
1231
1232 # Operator adds a local field directly to the live schema.
1233 object_schemas.replace_schema(
1234 "contacts",
1235 {
1236 "name": "contacts",
1237 "fields": [
1238 {"name": "id", "type": "text"},
1239 {"name": "name", "type": "text"},
1240 {"name": "x_priority", "type": "text"},
1241 ],
1242 },
1243 base_dir=data_dir,
1244 )
1245
1246 # Upgrade ships its own new field, on the same base.
1247 _bump_reconcile_package(
1248 packages_root,
1249 version="0.2.0",
1250 schema_fields=[
1251 {"name": "id", "type": "text"},
1252 {"name": "name", "type": "text"},
1253 {"name": "status", "type": "text"},
1254 ],
1255 )
1256
1257 result = object_packages.install_package(
1258 "hello-world",
1259 root=packages_root,
1260 base_dir=data_dir,
1261 object_roots=[object_root],
1262 allow_replace=True,
1263 )
1264
1265 assert result["schemas"][0]["status"] == "merged"
1266 assert "reconcile_id" not in result["schemas"][0]
1267 assert result["reconciles"] == []
1268
1269 live = object_schemas.get_schema("contacts", base_dir=data_dir, roots=[object_root])
1270 assert {f["name"] for f in live["fields"]} == {"id", "name", "x_priority", "status"}
1271
1272 baseline = object_package_baselines.load_baseline("hello-world", base_dir=data_dir)
1273 assert {f["name"] for f in baseline["schema_bodies"]["contacts"]["fields"]} == {"id", "name", "status"}
1274
1275
1276def test_reconcile_schema_without_baseline_body_falls_back_to_conflict(tmp_path):
1277 # Backward-compat: a baseline recorded before this feature existed has no
1278 # "schema_bodies" entry. A both-changed schema must still fall back to
1279 # the old park-a-conflict behavior instead of crashing.
1280 packages_root, data_dir, object_root = _install_reconcile_fixture(tmp_path, edit_schema=True)
1281
1282 baseline_file = object_package_baselines.baseline_path("hello-world", base_dir=data_dir)
1283 baseline = json.loads(baseline_file.read_text())
1284 del baseline["schema_bodies"]
1285 baseline_file.write_text(json.dumps(baseline))
1286
1287 _bump_reconcile_package(
1288 packages_root,
1289 version="0.2.0",
1290 schema_fields=[
1291 {"name": "id", "type": "text"},
1292 {"name": "email", "type": "text"},
1293 ],
1294 )
1295
1296 result = object_packages.install_package(
1297 "hello-world",
1298 root=packages_root,
1299 base_dir=data_dir,
1300 object_roots=[object_root],
1301 allow_replace=True,
1302 )
1303
1304 assert result["schemas"][0]["status"] == "conflict"
1305 assert "reconcile_id" in result["schemas"][0]
1306 live = object_schemas.get_schema("contacts", base_dir=data_dir, roots=[object_root])
1307 assert {f["name"] for f in live["fields"]} == {"id", "x_priority"}
1308
1309
1310def test_reconcile_schema_resolve_keep_mine_updates_baseline_schema_body(tmp_path):
1311 packages_root, data_dir, object_root = _install_reconcile_fixture(tmp_path, edit_schema=True)
1312 _bump_reconcile_package(
1313 packages_root,
1314 version="0.2.0",
1315 schema_fields=[
1316 {"name": "id", "type": "boolean"},
1317 {"name": "email", "type": "text"},
1318 ],
1319 )
1320
1321 result = object_packages.install_package(
1322 "hello-world",
1323 root=packages_root,
1324 base_dir=data_dir,
1325 object_roots=[object_root],
1326 allow_replace=True,
1327 )
1328 reconcile_id = result["schemas"][0]["reconcile_id"]
1329
1330 resolved = object_reconciles.resolve_reconcile(
1331 reconcile_id,
1332 "keep_mine",
1333 base_dir=data_dir,
1334 object_roots=[object_root],
1335 )
1336 assert resolved["status"] == "resolved"
1337
1338 # Live keeps the operator's version...
1339 live = object_schemas.get_schema("contacts", base_dir=data_dir, roots=[object_root])
1340 assert {f["name"] for f in live["fields"]} == {"id", "x_priority"}
1341
1342 # ...but the baseline body advances to the new upstream shape, so a
1343 # future upgrade diffs against what was actually shipped.
1344 baseline = object_package_baselines.load_baseline("hello-world", base_dir=data_dir)
1345 assert {f["name"] for f in baseline["schema_bodies"]["contacts"]["fields"]} == {"id", "email"}
1346
1347
1348def test_reconcile_package_status_counts_pending_reconciles(tmp_path):
1349 packages_root, data_dir, object_root = _install_reconcile_fixture(tmp_path, edit_object=True)
1350 _bump_reconcile_package(
1351 packages_root,
1352 version="0.2.0",
1353 object_code="def GET(request): return {'v': 2}\n",
1354 )
1355
1356 object_packages.install_package(
1357 "hello-world",
1358 root=packages_root,
1359 base_dir=data_dir,
1360 object_roots=[object_root],
1361 allow_replace=True,
1362 )
1363
1364 status = object_packages.package_status(
1365 "hello-world", root=packages_root, base_dir=data_dir, object_roots=[object_root]
1366 )
1367 assert status["pending_reconciles"] == 1
1368
1369
1370# --- Phase 3: override objects (conflict-free customization, Rule 2) --------
1371#
1372# See docs/upgrade-and-customization.md (Rule 2). An override shadows a
1373# package object by id without touching the package copy, so install/
1374# reconcile logic (which always targets get_base_object_roots()) never sees
1375# a conflict for an overridden object, and the package copy stays
1376# upgradeable.
1377
1378
1379def test_package_status_reports_overridden_flag(tmp_path, monkeypatch):
1380 packages_root = tmp_path / "packages"
1381 data_dir = tmp_path / "data"
1382 object_root = tmp_path / "objects"
1383 object_root.mkdir()
1384 override_root = tmp_path / "overrides"
1385 monkeypatch.delenv("DBBASIC_OVERRIDES_DIR", raising=False)
1386 write_package(
1387 packages_root,
1388 "hello-world",
1389 _reconcile_manifest("0.1.0"),
1390 files=(
1391 ("objects/hello/world.py", "def GET(request): return {'v': 1}\n"),
1392 (
1393 "schemas/contacts.json",
1394 json.dumps({"name": "contacts", "fields": [{"name": "id", "type": "text"}]}),
1395 ),
1396 ),
1397 )
1398 object_packages.install_package(
1399 "hello-world", root=packages_root, base_dir=data_dir, object_roots=[object_root]
1400 )
1401
1402 status_before = object_packages.package_status(
1403 "hello-world", root=packages_root, base_dir=data_dir, object_roots=[object_root]
1404 )
1405 object_artifact = next(a for a in status_before["artifacts"] if a["kind"] == "object")
1406 assert object_artifact["overridden"] is False
1407
1408 monkeypatch.setenv("DBBASIC_OVERRIDES_DIR", str(override_root))
1409 override_file = override_root / "hello" / "world.py"
1410 override_file.parent.mkdir(parents=True)
1411 override_file.write_text("def GET(request): return {'v': 'overridden'}\n")
1412
1413 status_after = object_packages.package_status(
1414 "hello-world", root=packages_root, base_dir=data_dir, object_roots=[object_root]
1415 )
1416 object_artifact_after = next(a for a in status_after["artifacts"] if a["kind"] == "object")
1417 assert object_artifact_after["overridden"] is True
1418 # pristine/customized state is computed from the base-root copy only —
1419 # the override never influences it.
1420 assert object_artifact_after["state"] == "pristine"
1421
1422
1423def test_upgrade_fast_forwards_base_copy_without_conflict_when_overridden(tmp_path, monkeypatch):
1424 packages_root = tmp_path / "packages"
1425 data_dir = tmp_path / "data"
1426 object_root = tmp_path / "objects"
1427 override_root = tmp_path / "overrides"
1428 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(object_root))
1429 monkeypatch.delenv("DBBASIC_OVERRIDES_DIR", raising=False)
1430
1431 write_package(
1432 packages_root,
1433 "hello-world",
1434 _reconcile_manifest("0.1.0"),
1435 files=(
1436 ("objects/hello/world.py", "def GET(request): return {'v': 1}\n"),
1437 (
1438 "schemas/contacts.json",
1439 json.dumps({"name": "contacts", "fields": [{"name": "id", "type": "text"}]}),
1440 ),
1441 ),
1442 )
1443
1444 object_packages.install_package(
1445 "hello-world",
1446 root=packages_root,
1447 base_dir=data_dir,
1448 object_roots=object_namespace.get_base_object_roots(),
1449 )
1450
1451 # Enable overrides and customize hello_world via an override. The
1452 # package copy under object_root is never touched by this.
1453 monkeypatch.setenv("DBBASIC_OVERRIDES_DIR", str(override_root))
1454 override_file = object_namespace.override_path("hello_world")
1455 override_file.parent.mkdir(parents=True)
1456 override_file.write_text("def GET(request): return {'v': 'overridden'}\n")
1457 assert object_namespace.resolve_object_id("hello_world") == override_file
1458
1459 # Ship an upgrade with different shipped object content.
1460 _bump_reconcile_package(
1461 packages_root,
1462 version="0.2.0",
1463 object_code="def GET(request): return {'v': 2}\n",
1464 )
1465
1466 result = object_packages.install_package(
1467 "hello-world",
1468 root=packages_root,
1469 base_dir=data_dir,
1470 object_roots=object_namespace.get_base_object_roots(),
1471 allow_replace=True,
1472 )
1473
1474 # The base/package copy fast-forwards cleanly: no conflict, because the
1475 # base copy (not the override) was pristine going into the upgrade.
1476 assert result["objects"][0]["status"] == "updated"
1477 assert result["reconciles"] == []
1478 assert (object_root / "hello" / "world.py").read_text() == "def GET(request): return {'v': 2}\n"
1479
1480 # The override is completely untouched by the upgrade.
1481 assert override_file.read_text() == "def GET(request): return {'v': 'overridden'}\n"
1482
1483 status = object_packages.package_status(
1484 "hello-world",
1485 root=packages_root,
1486 base_dir=data_dir,
1487 object_roots=object_namespace.get_base_object_roots(),
1488 )
1489 object_artifact = next(a for a in status["artifacts"] if a["kind"] == "object")
1490 assert object_artifact["state"] == "pristine"
1491 assert object_artifact["overridden"] is True
1492
1493
1494# --- where an install actually writes -----------------------------------------
1495#
1496# The bug this guards was not a crash. install_package defaulted base_dir to
1497# the literal "data" and ignored DBBASIC_DATA_DIR, so an install run with the
1498# environment set to somewhere else reported "status": "written" for every
1499# schema and seed -- into a freshly created ./data beside the checkout that
1500# nothing reads. Nothing failed, nothing warned, and the package was simply
1501# absent from the running server. Hit twice in one afternoon on a box whose
1502# layout was well understood, which is why the default changed rather than
1503# somebody remembering harder.
1504
1505def test_an_install_writes_where_the_environment_says(tmp_path, monkeypatch):
1506 packages_root = tmp_path / "packages"
1507 object_root = tmp_path / "objects"
1508 live = tmp_path / "live-data"
1509 decoy = tmp_path / "cwd"
1510 decoy.mkdir()
1511
1512 write_package(
1513 packages_root,
1514 "hello-world",
1515 {
1516 "id": "hello-world",
1517 "name": "Hello World",
1518 "version": "0.1.0",
1519 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
1520 "schemas": [{"collection": "widgets", "path": "schemas/widgets.json"}],
1521 },
1522 files=(
1523 ("objects/hello/world.py", "def GET(request): return {'ok': True}\n"),
1524 ("schemas/widgets.json",
1525 '{"name": "widgets", "fields": [{"name": "id"}, {"name": "title"}]}\n'),
1526 ),
1527 )
1528
1529 monkeypatch.chdir(decoy)
1530 monkeypatch.setenv("DBBASIC_DATA_DIR", str(live))
1531
1532 result = object_packages.install_package(
1533 "hello-world", root=packages_root, object_roots=[object_root])
1534
1535 assert (live / "schemas" / "widgets.json").is_file()
1536 # And nothing was created in the working directory, which is where the
1537 # old default would have put it.
1538 assert not (decoy / "data").exists()
1539
1540 # The result says WHERE, so "written" is a claim a caller can check.
1541 assert result["data_dir"] == str(live.resolve())
1542
1543
1544def test_an_explicit_base_dir_still_wins_over_the_environment(tmp_path, monkeypatch):
1545 """Every real caller passes one -- the server always does -- and the
1546 environment must not quietly override somebody who was specific."""
1547 packages_root = tmp_path / "packages"
1548 object_root = tmp_path / "objects"
1549 chosen = tmp_path / "chosen"
1550
1551 write_package(
1552 packages_root,
1553 "hello-world",
1554 {
1555 "id": "hello-world",
1556 "name": "Hello World",
1557 "version": "0.1.0",
1558 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
1559 "schemas": [{"collection": "widgets", "path": "schemas/widgets.json"}],
1560 },
1561 files=(
1562 ("objects/hello/world.py", "def GET(request): return {'ok': True}\n"),
1563 ("schemas/widgets.json",
1564 '{"name": "widgets", "fields": [{"name": "id"}, {"name": "title"}]}\n'),
1565 ),
1566 )
1567
1568 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "ignored"))
1569 result = object_packages.install_package(
1570 "hello-world", root=packages_root, base_dir=chosen,
1571 object_roots=[object_root])
1572
1573 assert (chosen / "schemas" / "widgets.json").is_file()
1574 assert not (tmp_path / "ignored").exists()
1575 assert result["data_dir"] == str(chosen.resolve())
1576
1577
1578def test_resolve_base_dir_prefers_explicit_then_environment_then_data(monkeypatch):
1579 monkeypatch.delenv("DBBASIC_DATA_DIR", raising=False)
1580 assert object_packages.resolve_base_dir() == Path("data")
1581 assert object_packages.resolve_base_dir("/tmp/x") == Path("/tmp/x")
1582
1583 monkeypatch.setenv("DBBASIC_DATA_DIR", "/srv/live")
1584 assert object_packages.resolve_base_dir() == Path("/srv/live")
1585 assert object_packages.resolve_base_dir("/tmp/x") == Path("/tmp/x")
1586
1587
1588def test_a_dry_run_reports_the_same_data_dir_it_would_install_into(tmp_path,
1589 monkeypatch):
1590 """A plan that does not say where it would write is a plan nobody can
1591 check before running it."""
1592 packages_root = tmp_path / "packages"
1593 object_root = tmp_path / "objects"
1594 live = tmp_path / "live-data"
1595
1596 write_package(
1597 packages_root,
1598 "hello-world",
1599 {
1600 "id": "hello-world",
1601 "name": "Hello World",
1602 "version": "0.1.0",
1603 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
1604 },
1605 files=(("objects/hello/world.py", "def GET(request): return {'ok': True}\n"),),
1606 )
1607
1608 monkeypatch.setenv("DBBASIC_DATA_DIR", str(live))
1609 plan = object_packages.dry_run_package(
1610 "hello-world", root=packages_root, object_roots=[object_root])
1611 assert plan["data_dir"] == str(live.resolve())
1612
1613
1614def test_a_new_package_object_installs_into_the_base_root_not_overrides(tmp_path):
1615 """A package install that lands in the override root is a silent no-run.
1616
1617 get_object_roots() returns [override, base] in LOOKUP order, so the
1618 override root is roots[0] -- and installing new objects there
1619 contradicted object_namespace.get_base_object_roots's own stated
1620 contract ("the root packages install into and reconcile against ...
1621 the pristine, upgradeable copy").
1622
1623 The consequence was not cosmetic, which is why this test exists at
1624 the level of `kind` rather than just the path: iter_object_sources
1625 labels anything under the override root kind="override", and
1626 object_handlers.build_index indexes ONLY kind=="system" (Decision 2,
1627 user-authored handlers deferred). So a package object declaring
1628 HANDLES installed cleanly, reported "written", and then never
1629 received a single event. Caught in production on system_wallet_books,
1630 not by a test.
1631 """
1632 packages_root = tmp_path / "packages"
1633 base_root = tmp_path / "objects"
1634 override_root = tmp_path / "overrides"
1635 base_root.mkdir()
1636 override_root.mkdir()
1637
1638 handler_source = 'HANDLES = ["widgets.record.created"]\n\n\ndef EVENT(request):\n return {"ok": True}\n'
1639 write_package(
1640 packages_root, "handler-pkg",
1641 {"id": "handler-pkg", "name": "Handler", "version": "0.1.0",
1642 "objects": [{"id": "system_widget_books", "path": "objects/system/widget_books.py"}]},
1643 files=[("objects/system/widget_books.py", handler_source)],
1644 )
1645
1646 # Roots in real lookup order: override first, base last.
1647 roots = [override_root, base_root]
1648 result = object_packages.install_package(
1649 "handler-pkg", root=packages_root, base_dir=tmp_path / "data",
1650 object_roots=roots)
1651 assert result["objects"][0]["status"] == "written"
1652
1653 assert (base_root / "system" / "widget_books.py").is_file()
1654 assert not (override_root / "system" / "widget_books.py").exists()
1655
1656 sources = {s.object_id: s for s in object_namespace.iter_object_sources(roots)}
1657 assert sources["system_widget_books"].kind == "system"
1658
1659 import object_handlers
1660 index = object_handlers.build_index(roots)
1661 assert index.get("widgets.record.created") == ["system_widget_books"]
1662
1663
1664def test_an_overridden_object_stays_in_the_override_root_on_upgrade(tmp_path):
1665 """The other half: a customized object must not be yanked out of the
1666 override root by an upgrade -- that is what overrides are FOR."""
1667 packages_root = tmp_path / "packages"
1668 base_root = tmp_path / "objects"
1669 override_root = tmp_path / "overrides"
1670 base_root.mkdir()
1671 override_root.mkdir()
1672 roots = [override_root, base_root]
1673
1674 write_package(
1675 packages_root, "widget-pkg",
1676 {"id": "widget-pkg", "name": "Widget", "version": "0.1.0",
1677 "objects": [{"id": "system_widget", "path": "objects/system/widget.py"}]},
1678 files=[("objects/system/widget.py", "def GET(request):\n return {}\n")],
1679 )
1680 object_packages.install_package("widget-pkg", root=packages_root,
1681 base_dir=tmp_path / "data", object_roots=roots)
1682
1683 # An operator customizes it: the object now also lives in overrides.
1684 customized = override_root / "system" / "widget.py"
1685 customized.parent.mkdir(parents=True, exist_ok=True)
1686 customized.write_text("def GET(request):\n return {'mine': True}\n")
1687
1688 update_package(
1689 packages_root, "widget-pkg",
1690 {"id": "widget-pkg", "name": "Widget", "version": "0.2.0",
1691 "objects": [{"id": "system_widget", "path": "objects/system/widget.py"}]},
1692 files=[("objects/system/widget.py", "def GET(request):\n return {'v2': True}\n")],
1693 )
1694 object_packages.install_package("widget-pkg", root=packages_root,
1695 base_dir=tmp_path / "data", object_roots=roots,
1696 allow_replace=True)
1697 assert customized.is_file()