django-compose 0.1.0.dev5__tar.gz → 0.1.0.dev6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/CHANGELOG.md +9 -0
  2. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/PKG-INFO +1 -1
  3. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/docs/README.md +1 -0
  4. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/docs/SPEC.md +38 -5
  5. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/docs/dependencies.md +1 -1
  6. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/docs/migrations.md +65 -0
  7. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/docs/packaging.md +4 -4
  8. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/pyproject.toml +1 -1
  9. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/management/commands/makemigrations.py +104 -4
  10. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/migrations.py +98 -27
  11. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/snapshot.py +14 -7
  12. django_compose-0.1.0.dev6/tests/test_initial_history.py +752 -0
  13. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_migrations.py +26 -0
  14. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_snapshot.py +48 -1
  15. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/uv.lock +1 -1
  16. django_compose-0.1.0.dev5/tests/test_initial_history.py +0 -171
  17. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/.gitignore +0 -0
  18. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/AGENTS.md +0 -0
  19. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/CONTRIBUTING.md +0 -0
  20. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/COPYING +0 -0
  21. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/LICENSE +0 -0
  22. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/Makefile +0 -0
  23. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/NOTICE +0 -0
  24. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/README.md +0 -0
  25. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/docs/ROADMAP.md +0 -0
  26. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/docs/components.md +0 -0
  27. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/docs/configuration.md +0 -0
  28. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/docs/extensions.md +0 -0
  29. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/docs/models.md +0 -0
  30. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/docs/proposals/0001-native-url-collisions.md +0 -0
  31. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/docs/proposals/0002-supplied-distribution-metadata.md +0 -0
  32. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/docs/proposals/README.md +0 -0
  33. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/docs/provisioning.md +0 -0
  34. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/docs/quickstart.md +0 -0
  35. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/.gitignore +0 -0
  36. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/README.md +0 -0
  37. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/catalog/__init__.py +0 -0
  38. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/catalog/apps.py +0 -0
  39. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/catalog/autoconfig.py +0 -0
  40. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/catalog/integrations.py +0 -0
  41. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/catalog/management/__init__.py +0 -0
  42. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/catalog/management/commands/__init__.py +0 -0
  43. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/catalog/management/commands/verify_context.py +0 -0
  44. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/catalog/models.py +0 -0
  45. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/catalog/pyproject.toml +0 -0
  46. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/catalog/schema.py +0 -0
  47. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/catalog/transport.py +0 -0
  48. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/catalog/urls.py +0 -0
  49. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/contexts.py +0 -0
  50. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/manage.py +0 -0
  51. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/reviews/__init__.py +0 -0
  52. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/reviews/apps.py +0 -0
  53. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/reviews/autoconfig.py +0 -0
  54. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/reviews/models.py +0 -0
  55. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/reviews/pyproject.toml +0 -0
  56. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/settings.py +0 -0
  57. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/urls.py +0 -0
  58. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/examples/shop/verify.py +0 -0
  59. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/scripts/check_distribution.py +0 -0
  60. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/__init__.py +0 -0
  61. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/__main__.py +0 -0
  62. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/apps.py +0 -0
  63. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/artifacts.py +0 -0
  64. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/asgi.py +0 -0
  65. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/autoreload.py +0 -0
  66. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/build.py +0 -0
  67. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/checks.py +0 -0
  68. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/cli.py +0 -0
  69. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/components.py +0 -0
  70. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/conf.py +0 -0
  71. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/declarations.py +0 -0
  72. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/history.py +0 -0
  73. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/management/__init__.py +0 -0
  74. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/management/commands/__init__.py +0 -0
  75. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/management/commands/check_migrations.py +0 -0
  76. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/management/commands/compose.py +0 -0
  77. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/management/commands/migrate.py +0 -0
  78. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/management/commands/provision.py +0 -0
  79. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/management/commands/reset_migration_history.py +0 -0
  80. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/management/commands/retire_history.py +0 -0
  81. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/migration_imports.py +0 -0
  82. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/model_composition.py +0 -0
  83. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/models.py +0 -0
  84. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/provision.py +0 -0
  85. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/py.typed +0 -0
  86. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/rendering.py +0 -0
  87. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/serving.py +0 -0
  88. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/sources.py +0 -0
  89. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/typing.py +0 -0
  90. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/src/django_compose/urls.py +0 -0
  91. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/core_fixtures/__init__.py +0 -0
  92. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_artifacts.py +0 -0
  93. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_asgi.py +0 -0
  94. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_autoreload.py +0 -0
  95. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_bootstrap.py +0 -0
  96. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_boundaries.py +0 -0
  97. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_command_context.py +0 -0
  98. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_components.py +0 -0
  99. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_conf.py +0 -0
  100. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_history.py +0 -0
  101. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_integrations.py +0 -0
  102. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_launcher.py +0 -0
  103. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_migration_imports.py +0 -0
  104. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_migration_scaffold.py +0 -0
  105. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_migrations_guards.py +0 -0
  106. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_migrations_postgres.py +0 -0
  107. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_models.py +0 -0
  108. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_provision.py +0 -0
  109. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_provision_postgres.py +0 -0
  110. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_sources.py +0 -0
  111. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_startup.py +0 -0
  112. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_typing.py +0 -0
  113. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/test_urls.py +0 -0
  114. {django_compose-0.1.0.dev5 → django_compose-0.1.0.dev6}/tests/typing_fixtures/__init__.py +0 -0
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.0.dev6
4
+
5
+ - Allow transition owners to declare an adoption-safe initial baseline through
6
+ `initial_baseline: "satisfied"`, preserving true-guard data work and immutable
7
+ source hashes. Roll back initial schema, bindings and reconciliation together
8
+ when migration authoring raises.
9
+ - Expose the existing transition discovery owner as `discover_transitions` so
10
+ settings adapters can annotate addon-owned records without copying discovery.
11
+
3
12
  ## 0.1.0.dev5
4
13
 
5
14
  - Respect Django's swapped-model storage semantics when guarding migrations, so
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: django-compose
3
- Version: 0.1.0.dev5
3
+ Version: 0.1.0.dev6
4
4
  Summary: Compose reusable Django apps into a runnable project.
5
5
  Project-URL: Source, https://github.com/ang-ee/django-compose
6
6
  Project-URL: Documentation, https://github.com/ang-ee/django-compose/tree/main/docs
@@ -52,6 +52,7 @@ validation and lifecycle rules live in the [API reference](SPEC.md).
52
52
  | `components.index_components(distributions, *, group)` | Apply the same indexing rules to supplied native `Distribution` objects |
53
53
  | `components.active_requirements(requirements)` | Return native `Requirement` values active on this platform with `extra=""` |
54
54
  | `conf.apply_app_settings(namespace, closure)` | Apply app settings to a project using ordinary authored concrete models |
55
+ | `snapshot.discover_transitions(entries)` | Read default transition records from resolved app identities for an integration to annotate without importing migration code |
55
56
  | `provision.require_provisioned(using="default", timeout=0)` | Require recorded database readiness for the verified build |
56
57
  | `serving.artifact_path(relative)` | Locate and verify a generated artifact |
57
58
  | `serving.receipt_lease()` / `verified_receipt()` | Hold a shared build-record lease / read the startup-verified record |
@@ -286,10 +286,23 @@ setup. Snapshot and serving do not import the model compiler or execute integrat
286
286
 
287
287
  Without `COMPOSE_TRANSITION_SOURCE`, each selected app contributes sorted
288
288
  `compose_migrations/<label>/<name>.py` files in app order, including numeric
289
- migration names. An explicit source replaces that discovery. Records have exactly
290
- `declaring_app`, `name`, `app_label` and `module` keys. Modules relative to the
291
- declaring app are normalized once. Duplicate `<declaring_app>:<name>` origins
292
- fail. `Snapshot.transition_records` retains the frozen normalized records;
289
+ migration names. The public owner is
290
+ `snapshot.discover_transitions(entries: Iterable[Entry]) -> tuple[Mapping[str, str], ...]`.
291
+ It accepts resolved identities such as `Closure.app_entries`, preserves their
292
+ order, reports watched paths and returns immutable normalized records without
293
+ importing apps or migration modules. Default snapshot discovery calls this same
294
+ function. A settings adapter can use the already resolved `COMPOSE_CLOSURE` during
295
+ an app's `settings(namespace)` callback, annotate copies using owner-declared
296
+ facts, and return concrete `COMPOSE_TRANSITION_SOURCE` records before the snapshot.
297
+ Preserve other records and any explicitly authored replacement source; selecting
298
+ apps again or reading lazy Django settings during configuration is unnecessary.
299
+ An explicit source replaces discovery. Records require
300
+ `declaring_app`, `name`, `app_label` and `module` string keys, and optionally
301
+ `initial_baseline: "satisfied"`; other keys or baseline values are invalid.
302
+ Omission retains strict guard handling. The explicit transition-owner provider
303
+ supplies this assertion; default discovery does not infer it from source modules.
304
+ Modules relative to the declaring app are normalized once. Duplicate
305
+ `<declaring_app>:<name>` origins fail. `Snapshot.transition_records` retains the frozen normalized records;
293
306
  `Snapshot.transitions` stores their origin/sha256 pairs. Build and native history
294
307
  use the same records.
295
308
 
@@ -466,11 +479,31 @@ expansion. Initial `--check` retains Django's exit status 1 for missing history;
466
479
  are refused before initial schema authoring. If native expansion requires changes
467
480
  to an app with existing history, the command refuses before writes and asks the
468
481
  caller to author that app's transitions first; existing history bytes remain intact.
482
+ Initial authoring, binding and final reconciliation share an exception rollback
483
+ boundary: restore affected pre-call migration bytes and permissions, remove exact
484
+ newly authored files and invalidate migration imports, without recorder writes.
485
+ A failed attempt can retry from the same disk history. This is exception safety,
486
+ not crash-atomic publication of multiple files.
469
487
 
470
488
  `TransitionBinding` uses frozen snapshot records by default, or explicit
471
489
  `declarations=`. It binds native migration origins `<declaring_app>:<name>` to
472
490
  the project's actual graph leaves. Each source provides a native `Migration`
473
- and a pure `applies(ProjectState) -> bool` guard; a pending false guard is refused.
491
+ and a pure `applies(ProjectState) -> bool` guard. A pending false guard is refused
492
+ unless its owner declares `initial_baseline: "satisfied"` and the label acquired
493
+ its first native disk nodes in this successful command's initial-authoring phase,
494
+ including native prerequisite expansion. The assertion means the final-schema
495
+ initial baseline satisfies this transition on every database adopting it,
496
+ including existing rows adopted through native `migrate --fake-initial`. It does
497
+ not assert that the original operations executed. Existing initial-looking
498
+ files, reset-created initials and global read-only checks supply no exemption.
499
+ True guards always retain their operations, including bootstrap and backfill
500
+ work. A false-guard baseline binding substitutes Django's native empty migration
501
+ before downstream graph state calculation. Its materialization footer seals a
502
+ native zero-operation Migration subclass and `compose_initial_baseline =
503
+ "satisfied"`, omitting any source-class state or database lifecycle overrides. This
504
+ durable origin must be retained like any other native history node after its
505
+ source declaration is removed. Its source bytes and source SHA remain unchanged;
506
+ adding the optional declaration does not rewrite or invalidate existing origins.
474
507
  Immutable source/body digests, dependencies, `run_before`, `replaces` and complete
475
508
  squash chains are preserved. Materialized history remains executable after its
476
509
  source declaration is removed. Changed immutable sources, duplicate origins,
@@ -50,7 +50,7 @@ The `typing` extra is unnecessary for building or running a project. Install it
50
50
  in the project's environment when you want composed-model analysis:
51
51
 
52
52
  ```sh
53
- python -m pip install 'django-compose[typing]==0.1.0.dev5'
53
+ python -m pip install 'django-compose[typing]==0.1.0.dev6'
54
54
  ```
55
55
 
56
56
  The extra installs published Angee forks of mypy and django-stubs, keeping their
@@ -156,6 +156,71 @@ helpers still need their providers. A guard that sees a final schema cannot prov
156
156
  that a data operation already ran. Native dependencies, replacements and complete
157
157
  squash chains retain that execution history.
158
158
 
159
+ A transition owner can explicitly assert that a final-schema initial baseline
160
+ satisfies a transition by adding `initial_baseline: "satisfied"` to its existing
161
+ explicit declaration provider, without editing its immutable migration source:
162
+
163
+ ```python
164
+ # inventory/transitions.py; safe to call before Django setup.
165
+ def declarations():
166
+ return [{
167
+ "declaring_app": "inventory",
168
+ "name": "rename_legacy",
169
+ "app_label": "inventory",
170
+ "module": "inventory.compose_migrations.inventory.rename_legacy",
171
+ "initial_baseline": "satisfied",
172
+ }]
173
+ ```
174
+
175
+ Wire that provider through `COMPOSE_TRANSITION_SOURCE =
176
+ "inventory.transitions.declarations"`. The explicit provider replaces default
177
+ filename discovery, so include every required transition record. Omission is
178
+ strict; no other baseline value is accepted. The frozen declaration participates
179
+ in the snapshot digest while migration source bytes and hashes stay unchanged.
180
+
181
+ Integrations that annotate discovered transitions can reuse the public discovery
182
+ owner instead of maintaining another list or directory scanner:
183
+
184
+ ```python
185
+ # Inside an integration's autoconfig.settings(namespace) callback:
186
+ from django_compose.snapshot import discover_transitions
187
+
188
+ records = discover_transitions(namespace["COMPOSE_CLOSURE"].app_entries)
189
+ ```
190
+
191
+ One shared adapter can consult each selected app's own declarations, copy the
192
+ matching records with `dict(record, initial_baseline="satisfied")`, and return
193
+ the resulting ordered sequence as `COMPOSE_TRANSITION_SOURCE`. Keep all other
194
+ records unchanged and respect any explicit project-authored replacement. The
195
+ snapshot then freezes the result; no migration module is imported by discovery.
196
+ The package defines no extra addon metadata format for these policy facts.
197
+
198
+ This is a strong assertion: no original operation is needed on **any** database
199
+ adopting the final-schema baseline, including existing tables and rows adopted
200
+ with native `migrate --fake-initial`. If those rows need conversion or backfill,
201
+ keep that work in a separate native transition whose guard is true on the final
202
+ schema and whose operations handle both empty and preexisting tables. True guards
203
+ always run their original operations, even when the declaration has this option.
204
+
205
+ Only a declared false guard targeting a label actually initialized by this
206
+ command's native initial-authoring phase becomes a sealed zero-operation origin.
207
+ Native prerequisite expansion contributes its exact newly initialized labels.
208
+ Existing initial-looking files do not qualify, and ordinary planning/checks and
209
+ history reset stay strict. The sealed `compose_initial_baseline = "satisfied"`
210
+ metadata identifies satisfaction by the baseline, rather than execution of the
211
+ original operations. Planning and sealed history use a native empty migration,
212
+ so source-class state and database lifecycle overrides are omitted too. Keep that
213
+ native origin node after removing the declaration; it preserves source/body digests, imports and resolved graph edges and remains
214
+ executable without the original source module. Imported helpers still need their
215
+ providers.
216
+
217
+ If initial generation, binding or final reconciliation raises, authoring restores
218
+ affected pre-call migration bytes and permissions and removes its exact new
219
+ files. It invalidates migration imports and never writes the migration recorder;
220
+ a retry starts from the same disk history. This exception rollback does not
221
+ promise crash-atomic multi-file filesystem publication. Django owns subsequent
222
+ application and database retry behavior.
223
+
159
224
  New bindings use `compose_*` metadata. Existing `angee_origin` and
160
225
  `angee_source_sha256` metadata remain readable for historical compatibility;
161
226
  there is no need to rewrite old migration files. Check and dry-run paths do not
@@ -1,6 +1,6 @@
1
1
  # Installation and deployment
2
2
 
3
- The current version is the development preview `0.1.0.dev5`, including component
3
+ The current version is the development preview `0.1.0.dev6`, including component
4
4
  selection, isolated inspection and native provisioning.
5
5
  Python 3.14 is the verified environment. The declared constraints are Python
6
6
  `>=3.14` and Django `>=6.1.2,<6.2`; see [dependencies](dependencies.md) and
@@ -9,10 +9,10 @@ Python 3.14 is the verified environment. The declared constraints are Python
9
9
  ## Install from PyPI
10
10
 
11
11
  ```sh
12
- python -m pip install django-compose==0.1.0.dev5
12
+ python -m pip install django-compose==0.1.0.dev6
13
13
  ```
14
14
 
15
- Use `django-compose[typing]==0.1.0.dev5` for the optional composition plugin and
15
+ Use `django-compose[typing]==0.1.0.dev6` for the optional composition plugin and
16
16
  its published typing dependencies; see [advanced typing](dependencies.md#advanced-typing).
17
17
 
18
18
  ## Install locally
@@ -36,7 +36,7 @@ environment:
36
36
  # In the django-compose checkout, with uv installed:
37
37
  uv build --wheel
38
38
  # In the project environment, using the actual archive path:
39
- python -m pip install /path/to/django-compose/dist/django_compose-0.1.0.dev5-py3-none-any.whl
39
+ python -m pip install /path/to/django-compose/dist/django_compose-0.1.0.dev6-py3-none-any.whl
40
40
  ```
41
41
 
42
42
  The base installation includes Django, packaging and django-yamlconf. Optional extras are described in
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "django-compose"
7
- version = "0.1.0.dev5"
7
+ version = "0.1.0.dev6"
8
8
  description = "Compose reusable Django apps into a runnable project."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.14"
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import importlib
6
+ import stat
6
7
  from pathlib import Path
7
8
  from typing import Any
8
9
 
@@ -16,15 +17,21 @@ from django.db.migrations.loader import MigrationLoader
16
17
  from django.db.migrations.writer import MigrationWriter
17
18
  from django.utils.module_loading import module_dir
18
19
 
20
+ from django_compose.artifacts import atomic_write
19
21
  from django_compose.management import require_serving_mode
20
22
  from django_compose.migrations import (
21
23
  DropGuardAutodetector,
22
24
  TransitionBinding,
25
+ _forget_history,
23
26
  _metadata,
24
27
  )
25
28
  from django_compose.serving import read_receipt
26
29
 
27
30
 
31
+ def _file_state(path: Path) -> tuple[bytes, int] | None:
32
+ return (path.read_bytes(), stat.S_IMODE(path.stat().st_mode)) if path.exists() else None
33
+
34
+
28
35
  def history_labels() -> tuple[str, ...]:
29
36
  """Read the compiler receipt without invoking composition."""
30
37
  receipt = read_receipt(Path(settings.COMPOSE_OUTPUT_DIR))
@@ -39,7 +46,77 @@ class Command(NativeCommand):
39
46
  autodetector = DropGuardAutodetector
40
47
  _initial_history: frozenset[str] | None = None
41
48
 
49
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
50
+ super().__init__(*args, **kwargs)
51
+ self._originals: dict[Path, tuple[bytes, int] | None] = {}
52
+ self._bound_files: list[Path] = []
53
+ self._changed_labels: set[str] = set()
54
+ self._migration_packages: dict[str, Path] = {}
55
+
42
56
  def handle(self, *app_labels: str, **options: Any) -> str | None:
57
+ self._originals.clear()
58
+ self._bound_files.clear()
59
+ self._changed_labels.clear()
60
+ self._migration_packages.clear()
61
+ try:
62
+ return self._author(*app_labels, **options)
63
+ except BaseException:
64
+ for path in self._bound_files:
65
+ path.unlink(missing_ok=True)
66
+ for path, original in self._originals.items():
67
+ if original is None:
68
+ path.unlink(missing_ok=True)
69
+ else:
70
+ content, mode = original
71
+ atomic_write(path, content, mode=mode)
72
+ _forget_history(self._changed_labels, packages=self._migration_packages)
73
+ raise
74
+
75
+ def _remember(self, path: Path) -> None:
76
+ path = path.resolve()
77
+ if path not in self._originals:
78
+ self._originals[path] = _file_state(path)
79
+
80
+ def _record_native_directory(self, writer: MigrationWriter, package: str) -> Path:
81
+ """Observe package writes; Django alone chooses and creates the directory.
82
+
83
+ basedir has no write hook. Snapshot initializer candidates below every
84
+ native imported ancestor, including AppConfig.path's direct-submodule
85
+ case, then journal only files changed by the native call. Do not select
86
+ a destination from these candidates or substitute a source pathfinder.
87
+ """
88
+ parts = package.split(".")
89
+ candidates: list[tuple[str, Path, list[str]]] = []
90
+ config = apps.get_app_config(writer.migration.app_label)
91
+ if package.rpartition(".")[0] == config.name:
92
+ candidates.append((config.name, Path(config.path), parts[-1:]))
93
+ for length in range(1, len(parts) + 1):
94
+ prefix = ".".join(parts[:length])
95
+ try:
96
+ directory = Path(module_dir(importlib.import_module(prefix)))
97
+ except ImportError, ValueError:
98
+ continue
99
+ candidates.append((prefix, directory, parts[length:]))
100
+ initializers: dict[Path, tuple[str, tuple[bytes, int] | None]] = {}
101
+ for prefix, directory, suffix in candidates:
102
+ for part in ("", *suffix):
103
+ if part:
104
+ prefix += "." + part
105
+ directory /= part
106
+ path = (directory / "__init__.py").resolve()
107
+ initializers.setdefault(path, (prefix, _file_state(path)))
108
+ try:
109
+ directory = Path(writer.basedir).resolve()
110
+ finally:
111
+ for path, (prefix, original) in initializers.items():
112
+ if _file_state(path) != original:
113
+ self._originals.setdefault(path, original)
114
+ self._migration_packages[prefix] = path.parent
115
+ importlib.invalidate_caches()
116
+ self._migration_packages[package] = directory
117
+ return directory
118
+
119
+ def _author(self, *app_labels: str, **options: Any) -> str | None:
43
120
  require_serving_mode()
44
121
  name = options.get("name")
45
122
  if name and not name.isidentifier():
@@ -61,6 +138,7 @@ class Command(NativeCommand):
61
138
  and any(apps.get_app_config(label).get_models())
62
139
  }
63
140
  selected = set(app_labels) if app_labels else None
141
+ new_labels = frozenset[str]()
64
142
  if initial:
65
143
  for flag in ("merge", "empty", "update"):
66
144
  if options.get(flag):
@@ -72,10 +150,15 @@ class Command(NativeCommand):
72
150
  self._initial_history = None
73
151
  if options.get("dry_run") or options.get("check_changes"):
74
152
  return None
153
+ # Native writer may have imported a missing initializer as a
154
+ # namespace before writing it (including a same-process retry).
155
+ _forget_history(self._changed_labels, packages=self._migration_packages)
156
+ # Only actual disk nodes created by this native initial phase prove
157
+ # first authoring, including native prerequisite expansion.
158
+ current = MigrationLoader(None, ignore_no_migrations=True)
159
+ new_labels = frozenset(label for label, _ in current.disk_migrations if label not in initialized)
75
160
  if selected is not None:
76
- # Native dependency expansion can initialize other fresh apps.
77
- current = MigrationLoader(None, ignore_no_migrations=True)
78
- selected.update(label for label, _ in current.disk_migrations if label not in initialized)
161
+ selected.update(new_labels)
79
162
  if options.get("merge"):
80
163
  return super().handle(*app_labels, **options)
81
164
  authored = TransitionBinding(labels=labels)
@@ -83,7 +166,17 @@ class Command(NativeCommand):
83
166
  if options.get("dry_run") or options.get("check_changes"):
84
167
  authored.check(app_labels=selected)
85
168
  else:
86
- authored.materialize(apps, app_labels=selected)
169
+ authored.materialize(
170
+ apps,
171
+ app_labels=selected,
172
+ initial_baselines=new_labels,
173
+ written_files=self._bound_files,
174
+ )
175
+ self._changed_labels.update(
176
+ declaration["app_label"]
177
+ for declaration in authored.declarations
178
+ if MigrationLoader.migrations_module(declaration["app_label"])[0] is not None
179
+ )
87
180
  except (RuntimeError, ImproperlyConfigured) as error:
88
181
  raise CommandError(str(error)) from error
89
182
  return super().handle(*app_labels, **options)
@@ -113,6 +206,13 @@ class Command(NativeCommand):
113
206
  if package is None:
114
207
  raise CommandError(f"Migrations are disabled for app {label!r}")
115
208
  writer = MigrationWriter(migration, self.include_header)
209
+ if not self.dry_run:
210
+ directory = self._record_native_directory(writer, package)
211
+ self._changed_labels.add(label)
212
+ self._remember(directory / writer.filename)
213
+ self._remember(directory / "__init__.py")
214
+ if update_previous_migration_paths:
215
+ self._remember(Path(update_previous_migration_paths[label]))
116
216
  key = package, writer.filename
117
217
  if key in destinations:
118
218
  raise CommandError(f"Multiple migrations target {key!r}")
@@ -13,7 +13,7 @@ import importlib.util
13
13
  import stat
14
14
  import sys
15
15
  from collections.abc import Callable, Iterable, Iterator, Mapping
16
- from dataclasses import dataclass
16
+ from dataclasses import dataclass, replace
17
17
  from pathlib import Path
18
18
  from typing import Any, cast
19
19
 
@@ -103,7 +103,7 @@ def _directory(label: str, *, missing: bool = False) -> Path:
103
103
  module = importlib.import_module(package)
104
104
  if not hasattr(module, "__path__"):
105
105
  raise ValueError("Migrations must be a Python package")
106
- return Path(module_dir(module))
106
+ return Path(module_dir(module)).resolve()
107
107
  except ModuleNotFoundError as error:
108
108
  if (
109
109
  not missing
@@ -114,12 +114,12 @@ def _directory(label: str, *, missing: bool = False) -> Path:
114
114
  parent, _, name = package.rpartition(".")
115
115
  config = global_apps.get_app_config(label)
116
116
  if parent == config.name:
117
- return Path(config.path) / name
117
+ return (Path(config.path) / name).resolve()
118
118
  try:
119
119
  parent_module = importlib.import_module(parent)
120
120
  if not hasattr(parent_module, "__path__"):
121
121
  raise ValueError("Migration parent must be a Python package")
122
- return Path(module_dir(parent_module)) / name
122
+ return (Path(module_dir(parent_module)) / name).resolve()
123
123
  except (ImportError, ValueError) as parent_error:
124
124
  raise ImproperlyConfigured(
125
125
  f"Initialize importable migration parent package {parent!r}"
@@ -153,6 +153,7 @@ class TransitionPlan:
153
153
  dependencies: tuple[Node, ...]
154
154
  run_before: tuple[Node, ...]
155
155
  source_package: str
156
+ initial_baseline: bool = False
156
157
 
157
158
 
158
159
  @dataclass(frozen=True)
@@ -164,6 +165,7 @@ class _Source:
164
165
  text: str
165
166
  digest: str
166
167
  package: str
168
+ initial_baseline: bool
167
169
 
168
170
 
169
171
  class _BindingLoader(MigrationLoader):
@@ -208,8 +210,9 @@ class TransitionBinding:
208
210
  """Bind declared migrations to host leaves without connecting to a database.
209
211
 
210
212
  Origins and snapshots are immutable, including after declaration removal.
211
- A false guard never establishes that a data operation has run. Completed
212
- transitions must remain in native history, including native squash chains.
213
+ A false guard never establishes that a data operation has run. Only an
214
+ explicit declaration can assert satisfaction by a newly authored initial
215
+ baseline. Completed transitions remain in native history and squash chains.
213
216
  """
214
217
 
215
218
  def __init__(
@@ -309,7 +312,16 @@ class TransitionBinding:
309
312
  if len(leaves) == 1 and leaves[0] not in migration.dependencies:
310
313
  cast(list[Node], migration.dependencies).append(leaves[0])
311
314
  package = (module.__spec__.parent if module.__spec__ else None) or module_name.rpartition(".")[0]
312
- pending[key] = _Source(origin, migration, guard, path, data.decode("utf-8"), digest, package)
315
+ pending[key] = _Source(
316
+ origin,
317
+ migration,
318
+ guard,
319
+ path,
320
+ data.decode("utf-8"),
321
+ digest,
322
+ package,
323
+ declaration.get("initial_baseline") == "satisfied",
324
+ )
313
325
  return pending
314
326
 
315
327
  def plan(
@@ -319,6 +331,7 @@ class TransitionBinding:
319
331
  defer_drop_check: bool = False,
320
332
  app_labels: Iterable[str] | None = None,
321
333
  allow_missing_packages: bool = False,
334
+ initial_baselines: frozenset[str] = frozenset(),
322
335
  ) -> tuple[TransitionPlan, ...]:
323
336
  """Validate the complete graph and selected prerequisite closure, without writes."""
324
337
  existing = MigrationLoader(None, ignore_no_migrations=True)
@@ -354,7 +367,17 @@ class TransitionBinding:
354
367
  raise RuntimeError(f"{source.origin}: applies(project_state) failed") from error
355
368
  if not isinstance(applies, bool):
356
369
  raise RuntimeError(f"{source.origin}: applies must return bool")
357
- if not applies:
370
+ baseline = not applies and source.initial_baseline and key[0] in initial_baselines
371
+ if baseline:
372
+ # A native empty migration also omits source-class lifecycle
373
+ # overrides. Replace the graph owner before downstream state.
374
+ migration = Migration(key[1], key[0])
375
+ cast(list[Node], migration.dependencies).extend(source.migration.dependencies)
376
+ cast(list[Node], migration.run_before).extend(source.migration.run_before)
377
+ pending[key] = source = replace(source, migration=migration)
378
+ loader.disk_migrations[key] = migration
379
+ loader.graph.nodes[key] = migration
380
+ elif not applies:
358
381
  raise RuntimeError(
359
382
  f"{source.origin}: false guard cannot prove a data transition completed; "
360
383
  "retain native history or a complete replacement baseline"
@@ -379,6 +402,7 @@ class TransitionBinding:
379
402
  tuple(source.migration.dependencies),
380
403
  tuple(source.migration.run_before),
381
404
  source.package,
405
+ baseline,
382
406
  )
383
407
  )
384
408
  if apps is not None and not defer_drop_check:
@@ -456,30 +480,69 @@ class TransitionBinding:
456
480
  body.decode()
457
481
  + MATERIALIZED_FOOTER
458
482
  + "\n"
483
+ + (
484
+ "from django.db.migrations import Migration as _ComposeInitialBaselineMigration\n"
485
+ "class Migration(_ComposeInitialBaselineMigration):\n"
486
+ " operations = []\n"
487
+ if plan.initial_baseline
488
+ else ""
489
+ )
459
490
  + f"Migration.dependencies = {list(plan.dependencies)!r}\n"
460
491
  + f"Migration.run_before = {list(plan.run_before)!r}\n"
461
492
  + f"Migration.compose_origin = {plan.origin!r}\n"
462
493
  + f"Migration.compose_source_sha256 = {plan.source_sha256!r}\n"
463
494
  + f"Migration.compose_body_sha256 = {body_digest!r}\n"
495
+ + ("Migration.compose_initial_baseline = 'satisfied'\n" if plan.initial_baseline else "")
464
496
  ).encode()
465
497
  return payload + _SEAL_PREFIX + repr(hashlib.sha256(payload).hexdigest()).encode() + b"\n"
466
498
 
467
- def materialize(self, apps: Apps, app_labels: Iterable[str] | None = None) -> tuple[Path, ...]:
468
- """Snapshot all validated sources at the explicit native authoring boundary."""
469
- plans = self.plan(apps=apps, app_labels=app_labels, allow_missing_packages=True)
499
+ def materialize(
500
+ self,
501
+ apps: Apps,
502
+ app_labels: Iterable[str] | None = None,
503
+ *,
504
+ initial_baselines: frozenset[str] = frozenset(),
505
+ written_files: list[Path] | None = None,
506
+ ) -> tuple[Path, ...]:
507
+ """Snapshot sources, optionally satisfying declared first-authoring baselines.
508
+
509
+ initial_baselines is the command's exact newly initialized disk-label
510
+ delta, never inferred from initial-looking files or database contents.
511
+ written_files tracks exclusive destinations for an enclosing native
512
+ authoring rollback, including a write that raises after publication.
513
+ """
514
+ plans = self.plan(
515
+ apps=apps,
516
+ app_labels=app_labels,
517
+ allow_missing_packages=True,
518
+ initial_baselines=initial_baselines,
519
+ )
470
520
  rendered = [(plan, self._render(plan)) for plan in plans]
471
- for label in dict.fromkeys(plan.app_label for plan in plans):
472
- directory = Path(MigrationWriter(Migration("_package", label)).basedir)
473
- directory.mkdir(parents=True, exist_ok=True)
474
- if not (directory / "__init__.py").exists():
475
- atomic_write(directory / "__init__.py", b"", exclusive=True)
476
- written = []
521
+ packages = [
522
+ directory / "__init__.py"
523
+ for label in dict.fromkeys(plan.app_label for plan in plans)
524
+ for directory in (_directory(label, missing=True),)
525
+ if not (directory / "__init__.py").exists()
526
+ ]
527
+ written: list[Path] = []
477
528
  try:
478
- for plan, content in rendered:
479
- if plan.output_path.exists():
480
- raise RuntimeError(f"Migration destination appeared during authoring: {plan.output_path}")
481
- atomic_write(plan.output_path, content, exclusive=True)
482
- written.append(plan.output_path)
529
+ for path, content in [
530
+ *((path, b"") for path in packages),
531
+ *((plan.output_path, content) for plan, content in rendered),
532
+ ]:
533
+ if path.exists():
534
+ raise RuntimeError(f"Migration destination appeared during authoring: {path}")
535
+ written.append(path)
536
+ if written_files is not None:
537
+ written_files.append(path)
538
+ try:
539
+ atomic_write(path, content, exclusive=True)
540
+ except FileExistsError:
541
+ # Exclusive publication lost a race; that file is not ours.
542
+ written.pop()
543
+ if written_files is not None:
544
+ written_files.pop()
545
+ raise
483
546
  importlib.invalidate_caches()
484
547
  self.plan(apps=apps, app_labels=app_labels)
485
548
  except BaseException:
@@ -487,7 +550,7 @@ class TransitionBinding:
487
550
  path.unlink(missing_ok=True)
488
551
  _forget_history({plan.app_label for plan in plans})
489
552
  raise
490
- return tuple(written)
553
+ return tuple(plan.output_path for plan in plans)
491
554
 
492
555
 
493
556
  def _storage_identifier(connection: BaseDatabaseWrapper, identifier: str) -> tuple[str, str]:
@@ -794,13 +857,21 @@ class DropGuardAutodetector(MigrationAutodetector):
794
857
  )
795
858
 
796
859
 
797
- def _forget_history(labels: Iterable[str]) -> None:
798
- prefixes = [MigrationLoader.migrations_module(label)[0] for label in labels]
860
+ def _forget_history(labels: Iterable[str], *, packages: Mapping[str, Path] | None = None) -> None:
861
+ # Native writer observation can retain paths even when restored package
862
+ # initializers no longer import successfully. Do not execute them to clean
863
+ # their import caches, or leave newly authored ancestor packages cached.
864
+ directories = dict(packages or {})
865
+ for label in labels:
866
+ package = MigrationLoader.migrations_module(label)[0]
867
+ if package is not None and package not in directories:
868
+ directories[package] = _directory(label, missing=True)
869
+ prefixes = tuple(directories)
799
870
  for name in tuple(sys.modules):
800
871
  if any(prefix and (name == prefix or name.startswith(prefix + ".")) for prefix in prefixes):
801
872
  sys.modules.pop(name, None)
802
- for label in labels:
803
- for bytecode in (_directory(label) / "__pycache__").glob("*.pyc"):
873
+ for directory in set(directories.values()):
874
+ for bytecode in (directory / "__pycache__").glob("*.pyc"):
804
875
  bytecode.unlink()
805
876
  importlib.invalidate_caches()
806
877