python-ddd-framework 0.9.0__py3-none-any.whl → 0.10.1__py3-none-any.whl

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 (93) hide show
  1. python_ddd_framework/__init__.py +17 -1
  2. python_ddd_framework/application/builder.py +38 -32
  3. python_ddd_framework/application/runtime_hooks.py +5 -3
  4. python_ddd_framework/application/state.py +2 -0
  5. python_ddd_framework/auditing/sqlalchemy/mappings.py +29 -0
  6. python_ddd_framework/auditing/sqlalchemy/module.py +1 -2
  7. python_ddd_framework/auditing/sqlalchemy/store.py +23 -15
  8. python_ddd_framework/caching/unit_of_work.py +4 -0
  9. python_ddd_framework/consumer_docs/README.md +91 -0
  10. python_ddd_framework/consumer_docs/architecture.md +264 -0
  11. python_ddd_framework/consumer_docs/development.md +934 -0
  12. python_ddd_framework/developer_kit/templates/basic/{{cookiecutter.module_name}}/README.md +13 -1
  13. python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/README.md +18 -29
  14. python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/sqlalchemy/module.py.jinja +2 -4
  15. python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/AGENTS.md +33 -54
  16. python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/README.md +32 -19
  17. python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/backend/pyproject.toml.jinja +15 -1
  18. python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/docs/architecture.md +22 -151
  19. python_ddd_framework/developer_kit/templates/project/{{cookiecutter.project_name}}/docs/development.md +38 -541
  20. python_ddd_framework/domain/__init__.py +5 -0
  21. python_ddd_framework/domain/aggregates.py +5 -35
  22. python_ddd_framework/domain/auditing.py +11 -0
  23. python_ddd_framework/domain/capabilities.py +39 -0
  24. python_ddd_framework/domain/entities.py +0 -2
  25. python_ddd_framework/entity_caching/__init__.py +5 -0
  26. python_ddd_framework/entity_caching/cache.py +95 -0
  27. python_ddd_framework/entity_caching/contracts.py +22 -0
  28. python_ddd_framework/entity_caching/module.py +9 -0
  29. python_ddd_framework/entity_caching/registration.py +131 -0
  30. python_ddd_framework/events/aggregate.py +6 -13
  31. python_ddd_framework/events/runtime.py +93 -27
  32. python_ddd_framework/extensions/__init__.py +2 -0
  33. python_ddd_framework/extensions/catalog.py +4 -0
  34. python_ddd_framework/extensions/contracts.py +12 -2
  35. python_ddd_framework/identity/application.py +2 -4
  36. python_ddd_framework/identity/domain_rules.py +4 -2
  37. python_ddd_framework/identity/dtos.py +19 -20
  38. python_ddd_framework/identity/management.py +14 -11
  39. python_ddd_framework/identity/models.py +28 -36
  40. python_ddd_framework/identity/seeding.py +2 -2
  41. python_ddd_framework/identity/sqlalchemy/mappings.py +132 -0
  42. python_ddd_framework/identity/sqlalchemy/module.py +1 -11
  43. python_ddd_framework/identity/sqlalchemy/repository.py +147 -178
  44. python_ddd_framework/identity/sqlalchemy/session_security.py +8 -9
  45. python_ddd_framework/identity/sqlalchemy/stores.py +110 -86
  46. python_ddd_framework/identity/stores.py +5 -5
  47. python_ddd_framework/invocation/runtime.py +6 -0
  48. python_ddd_framework/services/__init__.py +2 -1
  49. python_ddd_framework/services/composition.py +8 -0
  50. python_ddd_framework/services/convention.py +28 -1
  51. python_ddd_framework/services/repository.py +31 -29
  52. python_ddd_framework/services/runtime.py +4 -0
  53. python_ddd_framework/settings/sqlalchemy/mappings.py +31 -0
  54. python_ddd_framework/settings/sqlalchemy/module.py +1 -2
  55. python_ddd_framework/settings/sqlalchemy/store.py +66 -45
  56. python_ddd_framework/sqlalchemy/__init__.py +8 -6
  57. python_ddd_framework/sqlalchemy/alembic_runtime/env.py +3 -0
  58. python_ddd_framework/sqlalchemy/auditing.py +112 -30
  59. python_ddd_framework/sqlalchemy/conventions.py +54 -0
  60. python_ddd_framework/sqlalchemy/event_origins.py +163 -0
  61. python_ddd_framework/sqlalchemy/extensions.py +81 -49
  62. python_ddd_framework/sqlalchemy/locking.py +22 -0
  63. python_ddd_framework/sqlalchemy/mapping.py +53 -0
  64. python_ddd_framework/sqlalchemy/metadata.py +27 -47
  65. python_ddd_framework/sqlalchemy/metadata_builder.py +26 -20
  66. python_ddd_framework/sqlalchemy/metadata_fingerprint.py +4 -1
  67. python_ddd_framework/sqlalchemy/metadata_ownership.py +1 -1
  68. python_ddd_framework/sqlalchemy/migration.py +3 -5
  69. python_ddd_framework/sqlalchemy/migration_rendering.py +25 -0
  70. python_ddd_framework/sqlalchemy/module.py +56 -3
  71. python_ddd_framework/sqlalchemy/module_migration.py +4 -4
  72. python_ddd_framework/sqlalchemy/repository.py +139 -64
  73. python_ddd_framework/sqlalchemy/repository_binding.py +152 -0
  74. python_ddd_framework/sqlalchemy/session_provider.py +16 -21
  75. python_ddd_framework/sqlalchemy/tracking.py +231 -0
  76. python_ddd_framework/sqlalchemy/types.py +25 -0
  77. python_ddd_framework/sqlalchemy/unit_of_work.py +110 -6
  78. python_ddd_framework/unit_of_work/contracts.py +13 -6
  79. python_ddd_framework/unit_of_work/lifecycle.py +3 -0
  80. python_ddd_framework/unit_of_work/manager.py +17 -4
  81. python_ddd_framework-0.10.1.dist-info/METADATA +363 -0
  82. {python_ddd_framework-0.9.0.dist-info → python_ddd_framework-0.10.1.dist-info}/RECORD +87 -70
  83. {python_ddd_framework-0.9.0.dist-info → python_ddd_framework-0.10.1.dist-info}/WHEEL +1 -1
  84. python_ddd_framework-0.10.1.dist-info/licenses/LICENSE +21 -0
  85. python_ddd_framework/auditing/sqlalchemy/models.py +0 -31
  86. python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/sqlalchemy/models/base.py.jinja +0 -7
  87. python_ddd_framework/identity/sqlalchemy/models.py +0 -104
  88. python_ddd_framework/settings/sqlalchemy/models.py +0 -36
  89. python_ddd_framework-0.9.0.dist-info/METADATA +0 -619
  90. python_ddd_framework-0.9.0.dist-info/licenses/LICENSE +0 -7
  91. /python_ddd_framework/developer_kit/templates/module/{{cookiecutter.module_name}}/sqlalchemy/{models → mappings}/__init__.py.jinja +0 -0
  92. {python_ddd_framework-0.9.0.dist-info → python_ddd_framework-0.10.1.dist-info}/entry_points.txt +0 -0
  93. {python_ddd_framework-0.9.0.dist-info → python_ddd_framework-0.10.1.dist-info}/licenses/src/python_ddd_framework/background_jobs/pgqueuer/UPSTREAM_LICENSE.txt +0 -0
@@ -0,0 +1,934 @@
1
+ # Framework development guide
2
+
3
+ Use this guide with the installed [capability index](README.md#capabilities) and [framework contracts](architecture.md). Read the application's own AGENTS, architecture and affected module README for its actual requirements and decisions. This file belongs to the installed framework version; example business types are illustrative, not generated business requirements.
4
+
5
+ [CLI operations](#cli-operations) · [Plan a business change](#plan-a-business-change) · [Design checks](#design-and-delivery-checks) · [Choose a capability](#choose-a-framework-capability) · [Installed version](#match-the-installed-framework) · [Add a module](#add-a-module) · [HTTP generators](#http-generators-and-continuous-access) · [Verification](#verification)
6
+
7
+ <a id="cli-operations"></a>
8
+
9
+ ## CLI operations
10
+
11
+ Use the installed `pddd` CLI for operations it provides. Project commands dispatch into the owning backend environment; do not bypass them with handwritten module generation or direct migration/seed calls. Use each subcommand's `--help` as the parameter authority.
12
+
13
+ | Operation | Entry point |
14
+ | --- | --- |
15
+ | Create a project | `pddd new <name> --python <major.minor[.patch]>`; `--dry-run` previews, `--no-sync` skips environment setup, and `--framework-wheel <path>` selects a local artifact for validation. |
16
+ | Add a module | `pddd add module <name> --template basic` or `--template ddd`; inspect `--dry-run` before adapting generated examples. |
17
+ | Run development | `pddd dev`; inspect `pddd dev --help` for bind options. |
18
+ | Prepare local infrastructure | `pddd dev-init --environment development`; review the configuration first. |
19
+ | Migrate or seed | `pddd db <revision\|upgrade\|status\|seed> --module <alias> --environment <environment>`; follow the [database procedure](#initialize-the-database). |
20
+ | Inspect composition | `pddd inspect --environment <environment>`; this builds and closes an Application without starting its resources. |
21
+
22
+ The CLI has no build/test command: use native `uv build --no-sources` and pytest from `backend/`, within the approved verification scope. Availability of a command does not authorize dependency, data, or infrastructure changes.
23
+
24
+ <a id="implementation-workflow"></a>
25
+
26
+ <a id="plan-a-business-change"></a>
27
+
28
+ ## Plan a business change
29
+
30
+ Start with the affected module README and confirmed requirements. For an existing behavior, reuse its model and record only the decisions that change. For a new domain use case, answer these questions before choosing files:
31
+
32
+ | Decision | Questions to resolve |
33
+ | --- | --- |
34
+ | Language and use case | What do the business terms mean here? Who sends the command or query, and what outcome do they expect? Which facts distinguish success, rejection, and a pending operation? |
35
+ | Business boundary | Which module owns each rule and fact? Where do terms or policies change meaning across contexts? Which public contract allows collaboration with another owner? |
36
+ | Aggregate and values | Which entity controls the state change? Which related values must remain consistent together? Which rules belong on that aggregate, and which need a domain service because they depend on another input or policy? |
37
+ | Consistency and failure | What must commit atomically? What happens with a stale version, duplicate request, cancellation, or a failure after commit? Which work may finish later, and does it need durable execution? |
38
+ | Acceptance | Which concrete examples prove the rule and its failure paths? Which existing checks cover them, and which require approved new tests or real infrastructure? |
39
+
40
+ Choose boundaries from business language, invariants, and consistency needs. A database table or a generated layer Module does not establish a bounded context or aggregate boundary. Keep entity transitions and value constraints in Domain, orchestration and caller policy in Application, and storage/transport in their existing owners. Use a domain service for a rule that needs collaborators; retain rules that an aggregate can enforce itself on the aggregate.
41
+
42
+ An ordinary in-process service can use the [basic template](#add-a-module). A capability that needs domain, persistence, and HTTP structure can use `ddd`; business implementations and capability declarations are added when required. Record the chosen model, reasons, and unresolved business questions in the module README. The generated DDD README provides a responsibility record and first-use-case checklist; it contains no preset domain model. Names such as Order in the recipes below are illustrative types to implement only when required, not existing generated files.
43
+
44
+ <a id="check-a-domain-change"></a>
45
+
46
+ ### Check a domain change
47
+
48
+ Use the [mandatory DDD rules](architecture.md#mandatory-ddd-rules) as the review boundary. Before considering the change complete:
49
+
50
+ 1. Trace the public command through Application to the aggregate's business operation. For example, approval calls `order.approve()` through the domain policy; an application assignment to `order._status` fails review. Retain permission and expected-version checks at their existing owners.
51
+ 2. If the aggregate has children, trace additions, removals, and edits through the root. A returned list that lets a caller append an invalid child fails the same check. Inspect repository reconstitution separately from business creation and mutation.
52
+ 3. Check repository signatures and imports: domain-facing inputs/results express the aggregate contract, while ORM and driver conversion stay in persistence. Do not infer a new repository boundary from a new table.
53
+ 4. For writes touching multiple aggregates or later side effects, compare the implementation with the module's recorded atomicity, concurrency, failure, and duplicate-handling decisions. A transaction, local event, or job enqueue alone does not prove all of these guarantees.
54
+ 5. Update the module's rule record with the owner, operation, rejection example, and the smallest relevant verification. Reuse existing checks where applicable; request approval for additional tests when the task requires it. Report missing evidence rather than marking the rule verified.
55
+
56
+ These are review criteria, not a generated automated architecture-test suite. Use the actual checks listed under [verification](#verification).
57
+
58
+ <a id="design-and-delivery-checks"></a>
59
+
60
+ ### Design and delivery checks
61
+
62
+ For code and architecture changes, follow **requirements and rules -> owner -> layer and directory -> framework capability -> implementation -> verification**. Scale the record to the impact: reuse a module README, accepted decision, or approved plan; a local correction can cite an existing conclusion in the task notes. Do not create a new plan or design file just to satisfy this workflow.
63
+
64
+ Before implementation:
65
+
66
+ 1. Read affected requirements, decisions, module guidance, [layer boundaries](architecture.md#business-module-boundaries), and [directory rules](#module-layout-and-coding-rules). Identify the use case, public contract, mutable state, lifecycle owner, and external I/O boundary.
67
+ 2. Record **Owner -> layer -> target directory -> verified framework API**, with responsibility evidence and a matching installed API/example location. Mark framework lookup as not applicable if the change needs none. Check public imports, Module/provider activation, and direct callers before editing.
68
+ 3. For an abstraction or dependency change, identify the real contract, variation point, or reuse need and apply the [seven principles](architecture.md#mandatory-design-principles). Pause affected work if requirements, ownership, contracts, or the approved plan conflict; present the evidence and obtain an explicit ruling. Do not rewrite a rule to authorize an implementation after the fact.
69
+
70
+ Before delivery:
71
+
72
+ 1. Review the stable diff against each applicable principle, imports, Module dependencies, public contracts, state mutation paths, and resource ownership. Domain changes also require the [aggregate and consistency checks](#check-a-domain-change).
73
+ 2. Check inputs, results, errors, cancellation, idempotency, and cleanup against the actual contract when replacing an implementation. Confirm that new abstractions reuse existing framework capabilities and do not duplicate policy or merely forward calls.
74
+ 3. Run the smallest relevant existing checks and authorized build; record commands, outcomes, and coverage limits. Fix confirmed violations within scope or report the blocking decision. A passing build or unrelated tests do not establish correct ownership. Additional dependencies, tests, gates, and infrastructure still require task authorization.
75
+ 4. Update the affected owner documents and report changes, evidence, unverified behavior, and material risks. For documentation-only changes, check contracts, links, anchors, fences, examples, and the diff; do not claim that this proves runtime behavior.
76
+
77
+ These mandatory reviews are distinct from automated checks. Only claim gates actually provided by the project under [verification](#verification). If future architecture gates are approved, discover boundaries from live source and Module declarations instead of maintaining a second module inventory.
78
+
79
+ <a id="choose-a-framework-capability"></a>
80
+
81
+ ## Choose a framework capability
82
+
83
+ Read the complete [capability index](README.md#capabilities), then the linked contract and usage chapter together. Check the affected public API and Module/provider declarations in this installation. Installing a dependency does not activate a capability. Record the chosen owner, API, activation requirements and verification in the application's module README when that decision changes.
84
+
85
+ If no existing capability or native extension point meets the requirement, identify the exact missing behavior and the installed source checked before proposing new infrastructure. Missing documentation is not proof that an API is absent. An additional dependency or copied third-party code requires the task's explicit approval.
86
+
87
+ <a id="match-the-installed-framework"></a>
88
+
89
+ ## Match the installed framework
90
+
91
+ The application's development guide owns the platform-specific lookup command. Use its backend environment and Python isolated mode; do not inspect a global CLI or another virtual environment. Compare the installed version and source with the application's pyproject.toml and uv.lock. The installation's package resources are the authority for available APIs. Reading guidance does not authorize environment repair, dependency upgrades or an Application build.
92
+
93
+ If the user supplies a framework checkout, inspect its HEAD, dirty scope and applicable contributor instructions before using it as a read-only reference. Matching version strings alone do not prove identical source or artifacts. Do not embed personal paths in project guidance or add source overrides merely because a checkout is available. Report contract/source disagreements before affected implementation.
94
+
95
+ Read the [upgrade reference](README.md#migration-notes) before upgrading. A package upgrade does not rewrite project documentation or business code.
96
+
97
+ <a id="add-a-module"></a>
98
+
99
+ ## Add a module
100
+
101
+ From the application root:
102
+
103
+ ```sh
104
+ pddd add module orders --dry-run
105
+ pddd add module orders --template ddd
106
+ pddd add module conversions --template basic
107
+ ```
108
+
109
+ The CLI generates `backend/src/modules/orders/`, registers its application/persistence/HTTP modules in the Host, updates standard package metadata, and synchronizes dependencies. It also creates the module's README. Existing module directories are not overwritten. Repeat with another valid lowercase name when a separate business owner is needed.
110
+
111
+ The default is `ddd`. `basic` instead wires one ordinary Module and its alias, with a synchronous `ConversionService` Protocol and `DefaultConversionService(ConversionService, TransientDependency)`. Each REQUEST resolution creates an instance. Its only files are package markers, `module.py`, the contract, implementation, and README; no providers, Domain, database, migration, seed, HTTP, or background resources are generated. A consuming Module declares a dependency and injects the interface. The basic README shows formal replacement through `post_configure`. Invalid template names are rejected before writes; both templates support dry-run and refuse overwrite.
112
+
113
+ Read the generated module README before implementing your domain. Recipes below illustrate an `orders` capability; its business types are not generated. Define the needed types from confirmed requirements and substitute your actual names. The application remains usable as a pure Host before adding a module.
114
+
115
+ <a id="module-layout-and-coding-rules"></a>
116
+
117
+ ## Module layout and coding rules
118
+
119
+ For `basic`, keep public interfaces in `contracts/` and implementations in `services/`, with the Module in `module.py`. All seven lifecycle hooks remain explicit; empty hooks use `pass`. Its synchronous conversion is unmarked, without automatic interception or HTTP. For `ddd`, read the module README and choose the owning layer and directory below, and inspect direct callers. Propose a standards change before adding a responsibility category or reversing a dependency.
120
+
121
+ | Layer | Required responsibility directories |
122
+ | --- | --- |
123
+ | `domain_shared` | `constants`, `enums`, `errors`, `permissions`, `messages`, `value_objects` |
124
+ | `domain` | `entities`, `value_objects`, `services`, `repositories`, `events`, `settings`, `seeding` |
125
+ | `application_contracts` | `services`, `integration_services`, `inputs`, `views` |
126
+ | `application` | `services`, `integration_services`, `background_jobs`, `background_workers`, `hosted_services`, `event_handlers`, `interceptors`, `caching`, `options` |
127
+ | `sqlalchemy` | `mappings`, `repositories`, `migrations` |
128
+ | `http_api` | `routers`, `filters`, `websockets`, `models` |
129
+
130
+ - Use specific `snake_case` file names such as `order_query_service.py` or `order_changed_handler.py`. Do not combine unrelated responsibilities into `orders.py` or `tasks.py`.
131
+ - Give each independent service, handler, task, and lifecycle owner its own file. Group parts of one capability, such as `background_jobs/order_approval/payload.py` and `handler.py`, in a capability directory. Closely related small immutable values, enums, and exceptions may share a file; line count and class count are not splitting rules.
132
+ - `module.py` declares dependencies, registrations, and lifecycle hooks. `__init__.py` marks a package; it owns no business code, metadata state, or compatibility re-exports. Native mapping functions live in `sqlalchemy/mappings/`; the framework creates their registry and MetaData for each Application.
133
+ - User query, management, approval, and item operations belong in separate `services`. Internal reporting contracts and implementations go in their respective `integration_services`. Thread/SDK lifecycle owners go in `hosted_services`. Inputs and output projections go in `inputs` and `views`; transport-only models go in `http_api/models`.
134
+ - Shared immutable values such as `Money` belong in `domain_shared/value_objects`; domain-only values such as `OrderTitle` belong in `domain/value_objects`. Both public DTOs and domain objects may reuse a shared value without Contracts depending on Domain. Keep a single definition owner. These illustrative names do not require monetary fields in your HTTP contract.
135
+ - Preserve framework typing and native extension points. Use classes for identity, state, lifecycle, or real variation; keep stateless algorithms private to their capability. Avoid `common`, `utils`, `helpers`, aggregate facades, speculative interfaces, and old-path aliases. Explain key invariants and failure paths with concise Chinese source comments.
136
+
137
+ The `ddd` template retains all responsibility directories and package markers, six Module classes, native mapping discovery, migration registration, and the module README. It generates no business implementation, placeholder service, table, revision, or test case. Add capability dependencies and declarations as the implementation needs them. The full-directory exception is limited to CLI templates and generated projects; it does not authorize speculative framework layers.
138
+
139
+ All Host and six-layer Modules explicitly define seven hooks with framework context types. `pre_configure` contributes PreOptions, `configure` registers services and Options, and `post_configure` completes Options or overrides existing registrations. The async `pre_initialize`, `initialize`, and `post_initialize` hooks prepare, initialize, and finish resources. Async `shutdown` waits for cleanup. Empty phases use `pass`; configuration phases do not start I/O, threads, or tasks. Do not manually start framework-managed background components in these hooks.
140
+
141
+ The skeleton declares no workers, hosted services, schedules, settings, permissions, or jobs. Introduce each capability at its owning Module when required. Hosted services and schedules require explicit declarations; a discovered Job handler alone does not enable periodic enqueue. Choose provider and execution placement in Host configuration.
142
+
143
+ When splitting services, update Python contracts/imports directly and retain existing HTTP paths, verbs, status codes, response shapes, permissions, and operation IDs using `ApplicationServiceRouteOverride`. Preserve commit-before-event handling, cache removal before notification, transactional enqueue, idempotent Job handling, and awaited resource cleanup.
144
+
145
+ <a id="services-and-permissions"></a>
146
+
147
+ ## Services and permissions
148
+
149
+ 1. Define shared business values and permission names in `domain_shared/`.
150
+ 2. Put aggregate invariants and repository contracts in `domain/`.
151
+ 3. Define Pydantic DTOs and an `ApplicationServiceContract, Protocol` in `application_contracts/`.
152
+ 4. Implement the contract with `ApplicationService` in `application/`. Keep permission and HTTP method policies on the final implementation.
153
+ 5. Keep `scan_packages` scoped to the owning package. The generated application module already scans its package; the HTTP module explicitly exposes its contracts.
154
+
155
+ After defining the illustrated business types, a method inside an ApplicationService can implement a managed write as follows:
156
+
157
+ ```python
158
+ from uuid import uuid4
159
+
160
+ from python_ddd_framework.authorization import authorize
161
+ from python_ddd_framework.fastapi import http
162
+
163
+ from ...application_contracts.inputs.create_order import CreateOrder
164
+ from ...application_contracts.views.order_view import OrderView
165
+ from ...domain.entities.order import Order
166
+ from ...domain.value_objects.order_title import OrderTitle
167
+ from ...domain_shared.permissions.order_permissions import ORDERS_WRITE
168
+
169
+ # Method inside your ApplicationService implementation:
170
+ @authorize(ORDERS_WRITE)
171
+ @http.post(status_code=201)
172
+ async def create(self, command: CreateOrder) -> OrderView:
173
+ order = Order.create(uuid4(), OrderTitle(value=command.title))
174
+ await self._repository.insert(order, auto_save=True)
175
+ return OrderView.model_validate(order)
176
+ ```
177
+
178
+ `auto_save=True` flushes the owning Unit of Work so generated version and audit values are available to the returned DTO. It does not commit the enclosing transaction; the invocation's Unit of Work owns completion.
179
+
180
+ Reuse the existing permission definition provider when adding a permission. A new permission definition does not replace the application's grant policy. Do not grant end-user permissions to background components to repair an incorrectly chosen service boundary.
181
+
182
+ In DI-managed code, inject the public contract and call `await service.method(...)`. Outside DI, use `await invoke(application, ServiceContract.method, ...)`; it is anonymous by default. Trusted Host/test callers can supply a validated identity through `invoke_as`. Import `invoke`, `invoke_as`, `call`, and `call_as` from `python_ddd_framework`. Use `call(application, function, ...)` for ordinary async callables that need DI. Do not resolve or instantiate the private service implementation yourself.
183
+
184
+ For ordinary services, use the module's existing registration methods or native Dishka providers. Repository, application-service, and hosted-service scopes are fixed by the framework. Do not add a wrapper or custom container around those roles.
185
+
186
+ Ordinary DI services can use `@unit_of_work`, `@authorize`, or inherit `ValidationEnabled` without becoming ApplicationServices. The owning Module must depend directly or transitively on UnitOfWorkModule, AuthorizationModule, or InvocationModule respectively. Preserve native scope/cache registration. Marked methods must be async instance methods; a class-wide declaration cannot cover synchronous, static, class, or async-generator methods. Unmarked synchronous members keep their original signatures and results. Call injected services directly; use `call` / `call_as` to inject them for an external caller. Manual construction and self-calls do not re-enter interception.
187
+
188
+ A Domain service can explicitly enable validation while retaining its transient lifetime; its caller still owns saving and transaction completion. Interceptor match functions receive the shared `ServiceMethod`; plain services and ApplicationServices share the same invocation stages, while ApplicationServices retain their REQUEST-to-ACTION proxy and explicit HTTP exposure rules.
189
+
190
+ <a id="extend-reusable-modules"></a>
191
+
192
+ ## Extend reusable modules
193
+
194
+ Use the existing `post_configure` override registration with a reason and a direct dependency on the target owner. Identity offers `DefaultAuthenticationApplicationService` and `DefaultIdentityManagementApplicationService` for specialization. Keep the public contract signature and policies on the final method; calling `super` does not re-enter interception.
195
+
196
+ For Identity fields, define an `ExtensionProperties` Pydantic class in `application_contracts/inputs` or `views`, then contribute `ModelExtensions((ModelExtension(IDENTITY_USER_EXTENSION, YourProperties),))` from a Module depending on `IdentityModule` and `ExtensionsModule`. Defaults, validators, and types belong to that class. HTTP input/output remains `extra_properties: {...}`; undeclared fields are rejected. Read typed values with `view.extra_properties.read(YourProperties)`. Nested DTOs and native generic containers share the effective schema. Property types, including aliases, must be closed; nested models and dataclasses must reject unknown fields.
197
+
198
+ Optional independent columns belong in the consumer persistence Module: contribute `SqlAlchemyModelExtension` instead of `ModelExtension`, and pass `ExtensionColumn(YourProperties.model_fields["field_name"], lambda: Column(...))` for each mapped field. Import these SQL types from `python_ddd_framework.sqlalchemy`; do not import a provider into DTO code. Add `SqlAlchemyExtensionMigrations` with your local migrations package, branch, and exact base revision dependencies. Register the Module's CLI alias in `backend/pyproject.toml`. Upgrade the base owner first, generate and review your extension revision, then upgrade that alias. Identity's JSON container is introduced by `identity_0003`. Required properties on existing data need explicit backfill migrations.
199
+
200
+ For a confirmed employee extension, the following shows the declaration and physical-column registration. Put the properties in the consumer's contracts and import them into its persistence Module; retain the other generated lifecycle hooks. The namespace and migration branch are illustrative application-owned names:
201
+
202
+ ```python
203
+ from pydantic import Field
204
+ from sqlalchemy import Column, String
205
+ from python_ddd_framework import AppModule, ExtensionProperties, ModelExtensions
206
+ from python_ddd_framework.identity import IDENTITY_USER_EXTENSION, IdentityModule
207
+ from python_ddd_framework.identity.sqlalchemy import SqlAlchemyIdentityModule
208
+ from python_ddd_framework.sqlalchemy import (
209
+ ExtensionColumn, SqlAlchemyExtensionMigrations, SqlAlchemyModelExtension,
210
+ )
211
+
212
+ class EmployeeProperties(ExtensionProperties):
213
+ employee_number: str | None = Field(default=None, max_length=40)
214
+ department: str = "Engineering"
215
+
216
+ class CustomerPersistenceModule(AppModule):
217
+ dependencies = (IdentityModule, SqlAlchemyIdentityModule)
218
+ extensions = ModelExtensions((SqlAlchemyModelExtension(
219
+ IDENTITY_USER_EXTENSION, EmployeeProperties,
220
+ columns=(ExtensionColumn(
221
+ EmployeeProperties.model_fields["employee_number"],
222
+ lambda: Column(String(40), nullable=True, index=True),
223
+ ),),
224
+ ),))
225
+ migrations = SqlAlchemyExtensionMigrations(
226
+ "modules.customer.sqlalchemy.migrations", "employee", ("identity_0003",)
227
+ )
228
+ ```
229
+
230
+ Provide that real migrations package and its standard CLI alias, select CustomerPersistenceModule in the Host, then follow the base-before-extension revision/upgrade procedure above. Verify both effective DTO schema and real persistence/migration behavior when those changes are authorized. A declaration alone does not prove backfill safety.
231
+
232
+ <a id="identity-management"></a>
233
+
234
+ ## Identity management
235
+
236
+ Inject `IdentityManagementApplicationService` from `python_ddd_framework.identity`. User and role queries take `PagedResultRequestDto` and return `PagedResult` with `items` and `total_count`. The standard HTTP lists are `GET /api/identity/users` and `GET /api/identity/roles`, with `skip_count` and `max_result_count` query parameters. The configured API prefix applies normally; use OpenAPI for the current routes and DTOs.
237
+
238
+ Read the owner's `version` and send it as `expected_version` in edits, activation, deletion, password commands, and whole-set relationship changes. Relationship updates return the resulting version. A 409 requires rereading and resolving the conflicting edit. Do not substitute a newer version automatically. `permission_version` is internal authorization cache state. User edits preserve extension values by sending `extra_properties`; creation, editing, and paged output use the same extension declaration.
239
+
240
+ `PUT /api/auth/password` requires a real signed-in user, `old_password`, `new_password`, and the version returned by `/api/auth/me`. Administrators use `PUT /api/identity/users/{user_id}/password` with `new_password` and the user's version. Deactivation uses `/active`; user roles and role permissions use `/roles` and `/permissions` for GET/PUT. DELETE takes a JSON body containing `expected_version`. Password changes, deactivation, and deletion invalidate the user's existing sessions after commit. Sign in again after changing a password.
241
+
242
+ Apply `pddd db upgrade --module identity` before running code that needs `identity_0004` (user/role edit versions). Do not change published revisions or author migrations in the framework installation. This does not transfer ownership of your extension columns or indexes to Identity.
243
+
244
+ The Host can set `authorization.always_allow: true` to bypass login/permission authorization on managed service calls, including nested calls. It does not create a user identity or accept an invalid token. Input validation, transactions, password checks, and authenticated realtime connections remain active. Keep the permission declarations; setting the option back to false restores authorization. `IdentityOptions` owns access/refresh lifetimes and lockout controls in the `identity` section; duration values accept Pydantic duration strings such as `PT15M`.
245
+
246
+ For example, call the injected public contract from an appropriately authorized managed use case. This illustrates version-preserving updates, not a generated application operation:
247
+
248
+ ```python
249
+ from python_ddd_framework import PagedResultRequestDto
250
+ from python_ddd_framework.identity import IdentityManagementApplicationService, UpdateUserCommand
251
+
252
+ async def rename_first(service: IdentityManagementApplicationService) -> None:
253
+ page = await service.get_users(PagedResultRequestDto(max_result_count=1))
254
+ if page.items:
255
+ user = page.items[0]
256
+ await service.update_user(user.user_id, UpdateUserCommand(
257
+ username="Operator", expected_version=user.version,
258
+ extra_properties=user.extra_properties,
259
+ ))
260
+ ```
261
+
262
+ <a id="options-and-settings"></a>
263
+
264
+ ## Options and settings
265
+
266
+ Startup configuration belongs in a `BaseOptions` type and is bound by the owning module:
267
+
268
+ ```python
269
+ from python_ddd_framework import BaseOptions, Options
270
+
271
+ class OrdersOptions(BaseOptions):
272
+ allow_background_approval: bool = True
273
+
274
+ # In the module's configure(context) method:
275
+ # context.configure(OrdersOptions, section="orders")
276
+
277
+ class ApprovalPolicy:
278
+ def __init__(self, options: Options[OrdersOptions]) -> None:
279
+ self._options = options
280
+
281
+ def background_approval_allowed(self) -> bool:
282
+ return self._options.value.allow_background_approval
283
+ ```
284
+
285
+ This illustrates Options declaration and injection; no `OrdersOptions` is generated. Define it only for an authorized requirement and reuse one owner rather than duplicating the type. Register the ordinary service in its module and configure this illustrative option in `backend/app.development.yaml`:
286
+
287
+ ```yaml
288
+ orders:
289
+ allow_background_approval: false
290
+ ```
291
+
292
+ The corresponding environment key is `PDDD_ORDERS__ALLOW_BACKGROUND_APPROVAL`. `PDDD_HTTP__API_PREFIX` changes the business API prefix. `PYTHON_DDD_FRAMEWORK_ENVIRONMENT` selects the Host environment and is separate from business configuration. Values that affect composition require the framework's pre-configuration phase; do not read unbound Options during construction.
293
+
294
+ <a id="global-settings"></a>
295
+
296
+ ### Global settings
297
+
298
+ Settings defines, reads, writes, and clears global runtime overrides. The following is an illustrative recipe, not a generated business feature. Add a definition and its provider under the owning module's `domain/settings/worker_settings.py` only when the setting is required:
299
+
300
+ ```python
301
+ from python_ddd_framework.settings import (
302
+ SettingDefinition,
303
+ SettingDefinitionContext,
304
+ SettingDefinitionProvider,
305
+ )
306
+
307
+ WORKER_LIMIT = SettingDefinition("worker.limit", int, default=10)
308
+
309
+
310
+ class WorkerSettingDefinitionProvider(SettingDefinitionProvider):
311
+ def define(self, context: SettingDefinitionContext) -> None:
312
+ context.add(WORKER_LIMIT)
313
+ ```
314
+
315
+ Add `SettingsModule` from `python_ddd_framework` to the existing Domain Module's dependencies, and include its package in `scan_packages`; retain the other dependencies and lifecycle hooks. Import this same definition in callers instead of constructing another object with the same name. Store credentials in Host configuration, not Settings.
316
+
317
+ By default, values resolve from runtime override, Host configuration, then definition default. An optional Host value in `backend/app.development.yaml` looks like this:
318
+
319
+ ```yaml
320
+ settings:
321
+ worker:
322
+ limit: 12
323
+ ```
324
+
325
+ The default environment key is `PDDD_SETTINGS__WORKER__LIMIT`. Without an override the value is 12, or 10 if that configuration is absent. Writing 20 makes it the override; reset resumes the configured 12. Configuration is frozen at startup: restart the Host after changing YAML/environment inputs. Reset does not reload files, and writing the default value still creates an override.
326
+
327
+ Inject `SettingProvider` for reads and `SettingManager` into an authorized service for writes. In an existing async service method, with `reader` and `manager` already injected:
328
+
329
+ ```python
330
+ limit = await reader.get(WORKER_LIMIT)
331
+ current = await reader.snapshot(WORKER_LIMIT)
332
+ saved = await manager.update(WORKER_LIMIT, 20, expected_version=current.version)
333
+ # saved is SettingSnapshot[int]: name, value, source, version.
334
+ reset = await manager.reset(WORKER_LIMIT, expected_version=saved.version)
335
+ ```
336
+
337
+ This demonstrates an immediate write/reset sequence. Interactive editing must retain the version the operator actually read, rather than fetch a fresh token just before saving. A conflict requires re-reading and a caller decision, not an automatic retry. Application services can also use `self.setting_provider` during managed invocation, not construction. Storage errors propagate; if no allowed source has a value, `snapshot` reports UNSET and `get` fails.
338
+
339
+ The generated Host selects `SqlAlchemyRuntimeSettingsModule` and `SettingsManagementHttpApiModule`. A custom Host must select them when it needs persistent overrides and management HTTP. Configure its database and run `pddd db upgrade --module settings` as part of database setup; startup does not migrate. Without a store binding, reads can use configuration/defaults but Manager is not registered.
340
+
341
+ With the default API prefix, use these operations after authenticating and granting the management permissions:
342
+
343
+ | Operation | Request |
344
+ | --- | --- |
345
+ | List visible settings | `GET /api/settings` |
346
+ | Read a setting and its version | `GET /api/settings/worker.limit` |
347
+ | Save an override | `PUT /api/settings/worker.limit`, body `{"value": 20, "expected_version": "<version from read>"}` |
348
+ | Clear an override | `POST /api/settings/worker.limit/reset`, body `{"expected_version": "<latest version>"}` |
349
+
350
+ Pass JSON null for `expected_version` only when the read returned null. Reads and writes return `name`, `value`, `source`, and `version`; reset retains a new version token. HTTP 409 means a version conflict. Writes commit independently of the caller's business transaction, and a successful response confirms persistence only.
351
+
352
+ Definitions may restrict `allowed_sources` without changing their fixed order. Excluding CONFIGURATION rejects matching Host inputs, so remove the YAML/environment setting too. `management_access` defaults to READ_WRITE; READ_ONLY rejects generic writes/reset, while HIDDEN omits the setting from lists and returns not found for individual management operations. Reads require `settings.read`; writes/reset require both `settings.read` and `settings.write`. Optional `read_permission`/`write_permission` values add per-setting requirements: declare those permissions under `domain_shared/permissions`, scan their PermissionDefinitionProvider, and depend on AuthorizationModule. Declaring a permission does not grant it. Internal services own their authorization; Manager still enforces ownership, sources, types, and versions.
353
+
354
+ Business code decides when to read and apply values. Settings provides no component refresh, change notification, reconciliation, retry, or application status. Generic Notifications and HostedService remain independent capabilities.
355
+
356
+ For a setting with restricted sources and management permissions, replace the earlier illustrative definition instead of registering the same name twice:
357
+
358
+ ```python
359
+ from python_ddd_framework.authorization import (
360
+ PermissionDefinition, PermissionDefinitionContext, PermissionDefinitionProvider, PermissionName,
361
+ )
362
+ from python_ddd_framework.settings import (
363
+ SettingDefinition, SettingManagementAccess, SettingValueSource,
364
+ )
365
+
366
+ WORKER_READ = PermissionName("worker.settings.read")
367
+ WORKER_WRITE = PermissionName("worker.settings.write")
368
+ WORKER_LIMIT = SettingDefinition(
369
+ "worker.limit", int, default=10,
370
+ allowed_sources=frozenset({SettingValueSource.RUNTIME, SettingValueSource.DEFINITION}),
371
+ management_access=SettingManagementAccess.READ_WRITE,
372
+ read_permission=WORKER_READ,
373
+ write_permission=WORKER_WRITE,
374
+ )
375
+
376
+ class WorkerPermissionDefinitionProvider(PermissionDefinitionProvider):
377
+ def define(self, context: PermissionDefinitionContext) -> None:
378
+ context.add(PermissionDefinition(WORKER_READ, "Read worker settings"))
379
+ context.add(PermissionDefinition(WORKER_WRITE, "Write worker settings"))
380
+ ```
381
+
382
+ The existing setting-definition provider still contributes WORKER_LIMIT. Put both providers in the owner's declared discovery scope, depend on SettingsModule and AuthorizationModule, and use the actual application's grant policy. Defining a permission is not granting it. Host configuration for this example's disallowed configuration source fails composition; do not silently ignore it. Verify permission denial, stale versions and reset through the actual management boundary when applicable.
383
+
384
+ <a id="inspect-configuration"></a>
385
+
386
+ ### Inspect configuration
387
+
388
+ Inspect configuration sources and service registrations with:
389
+
390
+ ```sh
391
+ pddd inspect --environment development
392
+ ```
393
+
394
+ This composes and closes a new Application without starting it. Output contains redacted configuration inputs, not running-process state or the final Options values after defaults and module contributions. Mark secrets through the framework's existing secret types/metadata; do not log configuration objects or credentials.
395
+
396
+ <a id="unit-of-work"></a>
397
+
398
+ <a id="persistence-and-migrations"></a>
399
+
400
+ ## Persistence and migrations
401
+
402
+ Use `find` for optional entities and `get` for required entities. Standard list/count/page operations share one native SQLAlchemy query and stable primary-key tie breaking; pass explicit loader options for details. `auto_save=True` flushes, while the owning UoW controls commit. Use full Session.flush(); passing objects other than None, including an empty list, raises ValueError before writing and leaves the active UoW usable.
403
+
404
+ Inject the provider-neutral `Repository[Entity, Id]` for ordinary CRUD. Defaults apply to non-abstract mapped aggregate roots with one primary key and a closed identity type matching the mapper. Ordinary entities and composite keys need explicit bindings. For an existing mapped Order, constructor injection needs no empty repository Protocol or CRUD forwarding class:
405
+
406
+ ```python
407
+ from uuid import UUID
408
+
409
+ from python_ddd_framework import DomainService, Repository
410
+ from modules.orders.domain.entities.order import Order
411
+
412
+ class OrderPolicy(DomainService):
413
+ def __init__(self, orders: Repository[Order, UUID]) -> None:
414
+ self._orders = orders
415
+ ```
416
+
417
+ This shows dependency declaration only; implement domain methods from actual business rules.
418
+
419
+ | Need | Repository choice |
420
+ | --- | --- |
421
+ | Standard CRUD, counts and pages | Inject `Repository[Order, UUID]`; the framework supplies a default only when no effective custom binding exists. |
422
+ | Custom sorting, base query or detail loading, without new business methods | Keep the necessary `SqlAlchemyRepository` subclass and bind it with `@service(provides=Repository[Order, UUID], scope=Scope.REQUEST)`; no empty Protocol is required. |
423
+ | Actual business query methods | Extend `Repository[Order, UUID]` and `Protocol`; the concrete SQLAlchemy implementation supplies those methods, and the generic key aliases the same cached REQUEST instance. |
424
+
425
+ Import `service` from `python_ddd_framework` and `Scope` from `dishka`. Repository implementations belong under `sqlalchemy/repositories/`; keep Sessions and ORM types there. Defaults respect final arbitration and do not hide invalid overrides, conflicting creators or invalid lifetimes.
426
+
427
+ Keep the entity in Domain and place native Table/mapper functions in `sqlalchemy/mappings/`. Mark each function with `@sqlalchemy_mapping`; it receives the current application's registry and MetaData. Use registry.map_imperatively, relationship and TypeDecorator directly. Register `SqlAlchemyModelRegistration(mappings_package=..., migrations_package=..., branch_label=...)`; new mapping files need no import list. Keep migrations in the separate `sqlalchemy/migrations/` package.
428
+
429
+ Use `Repository[Entity, Id]` for insert/update/delete and queries. Tracked changes save without an explicit update; detached updates return the managed entity and cannot recreate a deleted aggregate. `AggregateRoot` provides explicit version and local-event capabilities, and `configure_by_convention` fills their mapping. Explicit version columns use version_id_generator=False. Declare aggregate members through relationship info={"aggregate_member": True}, independently of delete cascade; track both roots before a member transfer. Unified flush owns validation, version/audit updates and event transfer. Domain creation and transitions remain domain methods. Flush or use auto_save=True before producing generated-value DTO snapshots with ConfigDict(from_attributes=True) and model_validate(entity). Do not create Row copies or blindly assign command fields.
430
+
431
+ For your own extensible entity, its owner declares `HasExtraProperties`, an `ExtensionTarget` pointing to the entity and DTOs, and the native mapper. Field contributors supply `ExtensionProperties` through `ModelExtension`; use `SqlAlchemyModelExtension` only for explicit physical columns. The framework derives the entity binding from the existing target and mapper, so no second mapping list is needed. A mapped capability entity without a formal target fails construction; a DTO-only target does not create an entity or table.
432
+
433
+ Built-in Identity already supplies its entity, mapper and `IDENTITY_USER_EXTENSION`; consumers reuse that target and contribute fields. Preserve JSON/JSONB, explicit columns/indexes and migration ownership. Replace the complete validated `extra_properties` value when editing; nested in-place mutation is not a persistence contract.
434
+
435
+ One process runs one Host Application. Complete shutdown before rebuilding mappings of its domain classes. Failed construction releases the current native registry; loading an aggregate restores transient event state without rerunning business construction.
436
+
437
+ After adding actual models and preparing the providers using the [database procedure](#initialize-the-database) and the application's README, generate a revision. An empty skeleton is rejected before database I/O:
438
+
439
+ ```sh
440
+ pddd db revision --module orders
441
+ ```
442
+
443
+ Review the revision, especially renames, data backfills, external revision dependencies, and destructive operations. Autogeneration does not decide whole-table deletion or another owner's migration for you. Then run:
444
+
445
+ ```sh
446
+ pddd db upgrade --module orders
447
+ pddd db status --module orders
448
+ pddd db seed --module orders
449
+ ```
450
+
451
+ Upgrade prerequisites explicitly. Do not modify already applied revisions or write migrations into the installed framework package. Domain Modules with `DataSeedContributor` depend on `DataSeedingModule`; contributors are ordinary DI classes and do not use `@application_service`. Seed contributors run in independent transactions and should be idempotent; seeding a business module does not seed identity on its behalf.
452
+
453
+ Managed application-service calls provide the normal unit-of-work boundary. Open an explicit short unit of work only when the operation requires it, inside a managed invocation, and complete it explicitly. Never hold it across a device call, long-running task, external network wait, or streamed response. A child task or thread cannot reuse the parent's Session.
454
+
455
+ For shared databases, configure installation-specific Alembic version table locations, queue schema/object prefixes, and Redis prefixes through their existing Options. A queue schema has one migration owner; it cannot contain the Alembic version table. Changing installation identity after data exists requires an explicit data and migration-record plan.
456
+
457
+ <a id="entity-caching"></a>
458
+
459
+ ## Entity caching
460
+
461
+ Use the existing entity and DTO from the owning business module. Register the cache in that module's configure hook; the Host still supplies persistence and cache providers:
462
+
463
+ ```python
464
+ from uuid import UUID
465
+ from python_ddd_framework import AppModule, ConfigureContext
466
+ from python_ddd_framework.entity_caching import EntityCache, EntityCachingModule, add_entity_cache
467
+
468
+ # Order, OrderCacheItem and OrdersDomainModule are the application's existing types.
469
+ class OrdersApplicationModule(AppModule):
470
+ dependencies = (OrdersDomainModule, EntityCachingModule)
471
+
472
+ def configure(self, context: ConfigureContext) -> None:
473
+ add_entity_cache(context, Order, OrderCacheItem, UUID)
474
+
475
+ async def read_order(cache: EntityCache[OrderCacheItem, UUID], identity: UUID) -> OrderCacheItem:
476
+ return await cache.get(identity)
477
+ ```
478
+
479
+ Pass exactly `uuid.UUID`, `str`, or `int` as the key type. Unsupported key classes fail during registration; use the registered type for both query IDs and entity IDs.
480
+
481
+ The default mapper uses Pydantic attribute validation. Supply `mapper=to_cache_item` for an application-owned synchronous conversion; it runs only on misses. Supply `options=DistributedCacheEntryOptions(...)` to replace the default two-minute relative absolute expiration. For direct entity caching, pass the entity class as both entity and cache item; it must already support typed JSON round trips. There is no automatic serializer for ORM state.
482
+
483
+ Use `find` for optional results, `get` for required results, and the list/dictionary methods described in the [contract](architecture.md#entity-caching) for batches. Registering entity caching also subscribes to existing CRUD entity events; remove equivalent handwritten query/fill/invalidation code. Keep permissions and business notifications at their existing owners. Do not read write-transaction managed entities from this cache or assume related entity changes will invalidate a parent.
484
+
485
+ Replace `EntityCache[Item, Key]` through a native Provider contributed in the consuming Module's `post_configure`: set `provider.provide(..., provides=EntityCache[Item, Key], scope=Scope.REQUEST, override=True)` and contribute it with `RegistrationKind.OVERRIDE` and a nonempty `reason`. Declare a direct dependency on the module that registered the target; the existing arbitration rejects missing or ambiguous targets. Prefer `mapper` when only conversion differs.
486
+
487
+ <a id="events-and-background-work"></a>
488
+
489
+ ## Events and background work
490
+
491
+ Raise domain events on the aggregate using frozen records and stable nested values. Capture the needed IDs and values at publication; use tuples/frozensets or frozen records for collections and follow the [event value rules](architecture.md#calls-scopes-and-transactions). Put typed handlers in a scanned package and select the required `LocalEventPhase` with `@local_event_handler`. Use DOMAIN for transactional rules and AFTER_COMMIT for work such as the sample's online notifications. Entity caching owns its CRUD invalidation separately. Post-commit failures cannot undo a committed order; local events are not a durable message bus.
492
+
493
+ Inject `DistributedCache[OrderStatisticsCacheItem]` and call `get`, `set`, `remove`, or their batch variants with keys directly. Ordinary cache item classes in `application/caching/` own stable `@cache_name` metadata. Omitted entry options use global defaults (20-minute sliding expiration); an explicit `DistributedCacheEntryOptions` replaces the entire object. `get_or_add` uses an async factory; cache access error hiding does not hide factory/type errors or cancellation. Development configuration explicitly disables `caching.hide_errors`. Use `consider_uow=True` when a cache mutation must wait for successful UoW completion; handle post-commit failure as committed database work.
494
+
495
+ Jobs inherit `BackgroundJobHandler[Payload]`, declare their durable name/version/current/timeout on the class, and are discovered by module scanning. The following fragment assumes an application-defined `ApprovalJob` and `ApprovalPayload`; these types are not generated. Enqueue by type from a managed invocation, using the same configured database connection for transactional enqueue:
496
+
497
+ ```python
498
+ from uuid import UUID
499
+
500
+ from python_ddd_framework.background_jobs import BackgroundJobEnqueuer
501
+
502
+ from modules.orders.application.background_jobs.order_approval.handler import ApprovalJob
503
+ from modules.orders.application.background_jobs.order_approval.payload import ApprovalPayload
504
+
505
+ async def queue_approval(jobs: BackgroundJobEnqueuer, order_id: UUID) -> str:
506
+ return await jobs.enqueue(ApprovalJob, ApprovalPayload(order_id=order_id))
507
+ ```
508
+
509
+ Keep persisted payload versions until their queued jobs are drained or explicitly migrated. A job's external side effects must tolerate repeat execution. A schedule takes a Job type (or a registered function's definition), a typed payload and cron: `BackgroundJobSchedule(name="orders.statistics", cron="0 * * * *", job=OrderStatisticsJob, payload=StatisticsPayload())`. These names illustrate application-defined types; no schedule is generated. Register it explicitly with `BackgroundSchedules`; task identity and serialization come from the Application's Job catalog, while PgQueuer owns scheduling.
510
+
511
+ Workers implement `BackgroundWorker.run_iteration` and are registered with `background_workers = BackgroundWorkers((WorkerType,))`; their period, timeout, and enabled state live on the class. The skeleton contains no worker classes. Change a worker's code declaration deliberately before expecting it to run; configuration and management endpoints cannot enable a code-disabled worker.
512
+
513
+ Background execution Options use catalog names to select `host`, `shared`, or `exclusive` placement. Only worker configuration accepts `enabled`; job configuration does not. Management start/stop is asynchronous: query status after a request. Stopping a job processor preserves its queued data.
514
+
515
+ Use the existing `DistributedLock` provider for explicit business leases. `locks.acquire(key, wait_timeout=timedelta(0))` tries without waiting; omit the argument or pass `None` for configured waiting, or pass a positive timedelta for this acquisition only. If acquisition returns false, skip or report the operation as appropriate. Preserve cancellation and cleanup on lease loss. Use database concurrency and idempotency for their separate guarantees.
516
+
517
+ A `HostedService` starts its SDK/thread in `start(context)`, initiates business cleanup and waits for callbacks in optional `stopping(context, reason)`, then releases resources and joins threads in `stop(reason)`. Register it with `hosted_services = HostedServices((ServiceType,))`; the skeleton registers none. Use `context.call` for an independent managed call and `context.submit_call(...).result()` for a callback from an external thread. Each call creates its own scope; never pass a Session or scope to the thread or hold a transaction while waiting for the SDK.
518
+
519
+ The stopping context is separate from the startup context, which stays closed to new work. Its permission ends when the hook returns, fails, or receives a timeout cancellation request; accepted work still drains before resource stop. Only successfully started services receive `stopping`, while every touched service must tolerate `stop` after partial startup. Each hook uses `hosted_service.shutdown_timeout`, requests cancellation on expiry, and waits for actual cleanup; it is not a total shutdown deadline. HTTP/WebSocket use native transport shutdown.
520
+
521
+ <a id="http-files-and-real-time-communication"></a>
522
+
523
+ ## HTTP, files, and real-time communication
524
+
525
+ The Host passes `http.api_prefix` to `FastApiAdapter`, defaulting to `/api`. The generated HTTP module exposes its application contracts; `exposes_application_services` also contributes their formal Module dependency. Conventional methods are exposed automatically, `remote_service(is_enabled=False)` excludes methods, and overrides retain deliberate route identities. A plain Pydantic GET query DTO binds through native FastAPI Query metadata; explicit Query/Body/Header/Depends takes precedence. Declare Body explicitly for a GET body, and use native explicit input design for complex shapes. Check `/docs` after route changes. Keep method paths relative to their service; module overrides do not repeat the global prefix.
526
+
527
+ For explicit business routes, use `HttpRouter(use_api_prefix=True, ...)` and inject public service contracts. Independent endpoints such as WebSocket and health routes retain separate paths. Native FastAPI parameter and response types remain supported.
528
+
529
+ Use `UploadFile`, `File`, and `Form` for uploads and native response types for downloads/streams. Keep byte limits enforced while reading. For generator endpoints, preparation dependencies, and resource cleanup, use the [complete streaming example](#http-generators-and-continuous-access).
530
+
531
+ No WebSocket route or message type is generated. When the business requires realtime communication, typed messages under `domain_shared/messages/` own their versioned `message_type` values and Pydantic payload schemas. Send an instance through `publisher.send_to_user(user_id, message)` or `connection.send(message)`; explicitly map domain events and query results to that schema. The envelope retains its ID, UTC time and correlation, and reports only local queue acceptance. Invocations recheck identity and permissions. Non-loopback deployments require WSS; query-token authentication requires an explicit Origin policy. Native realtime delivery stays within the Host process and do not promise replay or delivery acknowledgment.
532
+
533
+ `SettingManager.update(definition, value, expected_version=version)` pairs `SettingDefinition[T]` with `value: T`; read the version before update/reset. Reset follows current defaults while retaining a new version token; business code owns when values are read and applied. A business error may carry `BusinessError(DEFINITION, data=PublicData(...))`, where PublicData is a Pydantic model of intentionally public fields. HTTP omits data when absent; do not put raw exception text, SQL or secrets in the public DTO.
534
+
535
+ Use `logging.getLogger(__name__)` for application logs. Configure logging in the Host's YAML, keep credentials and payloads out of messages, and enable existing tracing export only when its destination is configured. Avoid process-global logging/tracing setup in a business module.
536
+
537
+ <a id="http-generators-and-continuous-access"></a>
538
+
539
+ ## HTTP generators and continuous access
540
+
541
+ `HttpRouter` supports sync and async generators. Put authorization, input checks, and business work that must finish before sending in preparation dependencies or Filters. Native `Depends` functions use Dishka `@inject` / `FromDishka`; endpoint parameters can use the framework's type inference. Preparation does not read the first item. ApplicationService methods keep ordinary return contracts and may return a native `StreamingResponse`; do not convert them into generator methods.
542
+
543
+ The following standalone `backend/stream_example.py` needs only the installed framework and its existing dependencies. It demonstrates a short service call and a finite subscription using AnyIO's native memory stream, without database or Redis providers. Production subscriptions use the owning SDK's resource API and the same request-scoped dependency boundary. This is a usage example, not a business requirement or an additional generated module.
544
+
545
+ ```python
546
+ from collections.abc import AsyncIterator, Iterator
547
+ from pathlib import Path
548
+ from typing import Annotated
549
+
550
+ from anyio import CancelScope, create_memory_object_stream
551
+ from anyio.streams.memory import MemoryObjectReceiveStream
552
+ from dishka.integrations.fastapi import FromDishka, inject
553
+ from fastapi import Depends, FastAPI
554
+ from fastapi.responses import StreamingResponse
555
+ from fastapi.sse import EventSourceResponse, ServerSentEvent
556
+ from pydantic import BaseModel
557
+
558
+ from python_ddd_framework import ApplicationBuilder, ApplicationService, AppModule
559
+ from python_ddd_framework.fastapi import FastApiAdapter, FastApiModule, HttpRouter, contributes_routers
560
+
561
+
562
+ class Reading(BaseModel):
563
+ value: int
564
+
565
+
566
+ class ReadingApplicationService(ApplicationService):
567
+ async def get(self) -> Reading:
568
+ # Real queries belong in this short call; return detached values.
569
+ return Reading(value=1)
570
+
571
+
572
+ @inject
573
+ async def prepare(service: FromDishka[ReadingApplicationService]) -> Reading:
574
+ return await service.get()
575
+
576
+
577
+ async def subscribe(
578
+ initial: Annotated[Reading, Depends(prepare)],
579
+ ) -> AsyncIterator[MemoryObjectReceiveStream[Reading]]:
580
+ reading_stream = create_memory_object_stream[Reading]
581
+ send, receive = reading_stream(1)
582
+ try:
583
+ await send.send(initial)
584
+ await send.aclose()
585
+ yield receive
586
+ finally:
587
+ # Request cleanup also runs when the response generator never starts.
588
+ with CancelScope(shield=True):
589
+ await receive.aclose()
590
+ await send.aclose()
591
+
592
+
593
+ router = HttpRouter()
594
+ Subscription = Annotated[MemoryObjectReceiveStream[Reading], Depends(subscribe, scope="request")]
595
+
596
+
597
+ @router.get("/events", response_class=EventSourceResponse)
598
+ async def events(source: Subscription) -> AsyncIterator[ServerSentEvent]:
599
+ async for item in source:
600
+ yield ServerSentEvent(data=item, event="reading")
601
+
602
+
603
+ @router.get("/jsonl")
604
+ async def jsonl(source: Subscription) -> AsyncIterator[Reading]:
605
+ async for item in source:
606
+ yield item
607
+
608
+
609
+ @router.get("/bytes", response_class=StreamingResponse)
610
+ def download(initial: Annotated[Reading, Depends(prepare)]) -> Iterator[bytes]:
611
+ # Native thread-pool next() must return; shutdown does not abandon it.
612
+ yield str(initial.value).encode()
613
+
614
+
615
+ @contributes_routers(router)
616
+ class StreamingModule(AppModule):
617
+ dependencies = (FastApiModule,)
618
+ scan_packages = (__name__,)
619
+
620
+
621
+ def create_app() -> FastAPI:
622
+ application = ApplicationBuilder(
623
+ StreamingModule, environment="development", base_path=Path(__file__).parent,
624
+ env_prefix="STREAM_",
625
+ ).build()
626
+ adapter = FastApiAdapter(application)
627
+ web = FastAPI(lifespan=adapter.lifespan)
628
+ adapter.install(web)
629
+ return web
630
+ ```
631
+
632
+ From `backend/`, run the standalone factory; use a second terminal for the requests:
633
+
634
+ ```sh
635
+ uv run python -c 'from python_ddd_framework.fastapi.server import run_host; run_host("stream_example:create_app", host="127.0.0.1", port=8000)'
636
+ curl -N http://127.0.0.1:8000/events
637
+ curl -N http://127.0.0.1:8000/jsonl
638
+ curl -N http://127.0.0.1:8000/bytes
639
+ ```
640
+
641
+ Expect an SSE `reading` event containing `{"value":1}`, a JSONL record with that value, and the byte `1`, respectively. [Native SSE](https://fastapi.tiangolo.com/tutorial/server-sent-events/), [JSONL](https://fastapi.tiangolo.com/tutorial/stream-json-lines/), and [yield dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/) supply protocol and dependency behavior; framework scope and authorization boundaries are defined in [architecture](architecture.md#http-streaming-and-continuous-access).
642
+
643
+ For database access during async iteration, call the injected service proxy or use `async with manager.begin() as work`, complete the work with `await work.complete()`, and exit before yielding detached data. Never retain the preparation Session or transaction across `yield`. Preparation-only yield dependencies may use native `Depends(..., scope="function")`; subscriptions needed for transmission use `scope="request"` as above. If a generator itself acquires resources, shield awaited cleanup locally inside its `finally`. Do not keep a `CancelScope` open across `yield`. Unstarted generators cannot clean up subscriptions acquired during preparation; repeated cancellation does not make resource release optional.
644
+
645
+ The example declares no authorization. For a protected route, apply the existing `@authorize(...)` declaration with the application's permission definition and Host-selected Identity provider. Continuous checks then use independent short REQUEST scopes, including while idle or sending to a slow client. Custom HTTP authenticators/checkers may inject native `Request` and use short managed calls/UoWs; never retain their scope or transaction between checks. The [architecture rules](architecture.md#http-streaming-and-continuous-access) cover anonymous routes, `always_allow`, identity snapshots, authentication-cycle protection, and errors before/after `http.response.start`. Configuration and shutdown operations are in the [upgrade reference](README.md#migration-notes).
646
+
647
+ <a id="in-process-messages"></a>
648
+
649
+ ## In-process messages
650
+
651
+ For a business requirement that needs replaceable observations, define the message value in
652
+ `domain_shared/messages/` and its `MessageHandler[OrderObservation]` in
653
+ `application/hosted_services/`. The handler implements async `handle(message)` and owns the
654
+ actual processing; these types are not generated. In the owning `application/module.py`, import
655
+ the message, handler, and business-owned `observation_identity`, add `MessagingModule` to
656
+ `dependencies`, then declare the channel and binding:
657
+
658
+ ```python
659
+ from python_ddd_framework import MessageChannelDefinition, MessagingModule
660
+
661
+ # On the Application Module class:
662
+ observations = MessageChannelDefinition(
663
+ OrderObservation, OrderObservationHandler, capacity=16, snapshot_key=observation_identity
664
+ )
665
+ # In configure(context), using the existing Scope import:
666
+ context.services.add_scoped(OrderObservationHandler, scope=Scope.ACTION)
667
+ ```
668
+
669
+ Inject `MessageChannel[OrderObservation]` into the producer. `await channel.send(value)` returns
670
+ `MessageReceipt`; `await receipt.wait()` returns `MessageOutcome` with a `MessageState`.
671
+
672
+ ```python
673
+ from python_ddd_framework import MessageChannel, MessageState
674
+
675
+ async def observe(channel: MessageChannel[OrderObservation]) -> None:
676
+ receipt = await channel.send(OrderObservation(source="inventory", count=3))
677
+ outcome = await receipt.wait()
678
+ if outcome.state is not MessageState.COMPLETED:
679
+ raise RuntimeError(f"Observation ended as {outcome.state.value}")
680
+ ```
681
+
682
+ COMPLETED includes handler and scope cleanup, SUPERSEDED marks a replaced pending snapshot,
683
+ ABORTED means never executed, and CANCELLED does not imply rollback. FAILED retains the
684
+ exception and cleanup chain. Receipt completion does not claim commit or external acknowledgement.
685
+ Cancelling a receipt wait does not retract accepted work.
686
+
687
+ Capacity covers queued and executing messages. Async send rejects immediately when full and
688
+ creates no waiting tasks. An external SDK thread can use `channel.submit(value)` with at most
689
+ another capacity pending bridge submissions; its Future returns the acceptance receipt.
690
+ Future cancellation can race with acceptance. Handle `MessageRejectedError` for full/closed/failed
691
+ channels and `HostedServiceInvocationRejectedError` for bridge rejection. Never pass Session,
692
+ UoW, scope or concurrently mutable payloads between tasks/threads. Host configuration
693
+ `messaging.shutdown_timeout` requests cancellation after the deadline; shutdown still waits for
694
+ resource exit and reports timeout. Restart requires a new Application. Commands, results and
695
+ events requiring individual processing must not declare a coalescing key.
696
+
697
+ To accept SDK messages during a hosted service's stopping hook, declare
698
+ `MessageChannelDefinition(T, Handler, stopping_owners=(ServiceType,))` and make the channel
699
+ Module depend on the service's owner Module. Send with `await channel.send(value, stopping=context)`
700
+ or `channel.submit(value, stopping=context)` using that hook's current context. The default empty
701
+ tuple keeps input closed. Ordinary, expired, undeclared-owner and foreign-Application contexts
702
+ are rejected. Already accepted messages still drain before resource stop; the permission changes
703
+ neither capacity nor handler validation, authorization, scope/UoW or receipt semantics.
704
+
705
+ <a id="verification"></a>
706
+
707
+ ## Verification
708
+
709
+ Run native uv/test/build commands from `backend/`. Installed `pddd` commands locate the backend from the application root or any descendant, including nested foreign Python projects. Read fixtures first: Host tests use disposable PostgreSQL and Redis containers, so Docker must be available.
710
+
711
+ ```sh
712
+ # After implementing and authorizing domain tests; the skeleton has no test cases.
713
+ uv run pytest src/modules/orders/tests
714
+
715
+ # Full application tests include real Host infrastructure.
716
+ uv run pytest
717
+
718
+ # Check the application distribution without local source overrides.
719
+ uv build --no-sources
720
+ ```
721
+
722
+ For custom service tests, use `TestApplication(ApplicationBuilder(...))`, its async context manager, and typed `invoke`/`invoke_as`. The wrapper uses normal composition and cleanup; choose only the modules and providers required by the behavior being tested. Preserve identity and transaction boundaries in integration tests.
723
+
724
+ The development group includes mypy and this project owns its strict configuration and Pydantic plugin settings. Run `uv run python -m mypy` from backend/. Typed factories returning Protocols let mypy verify members and signatures; Dishka owns dependency graph and scope validation. Ruff and an architecture-test suite are not generated. Do not describe a static check or a mock as live database, HTTP, or deployment verification.
725
+
726
+ <a id="maintain-the-application"></a>
727
+
728
+ ## Maintain the application
729
+
730
+ Update a module README for changed business rules, contracts, persistence, or background behavior. Keep architecture and usage instructions in their respective documents. Record a new architectural decision only when there is an actual decision to preserve; do not pre-generate empty plans or status logs.
731
+
732
+ Framework upgrades update dependencies, not application source or documentation. Follow the target release's README and capability guides and update these documents deliberately. Add application dependencies with `uv add <package>` from `backend/`; preserve their source overrides and version choices when changing the framework dependency.
733
+
734
+ <a id="modules-and-lifecycle"></a>
735
+
736
+ ## Modules and lifecycle
737
+
738
+ Use the generated Module classes and explicit dependencies. A capability declaration belongs to its actual owner: ApplicationServicesModule for application services, UnitOfWorkModule for transaction policies, AuthorizationModule for permissions, InvocationModule for managed validation/calls, and the relevant cache/job/message/notification capability when used. The Host selects concrete providers. Do not add capabilities merely because the package is installed.
739
+
740
+ Configuration follows dependency-first global barriers: pre_configure, configure, post_configure, then finalized binding/validation. Runtime uses pre_initialize, initialize, post_initialize before selected runtime participants start, and shutdown after their cleanup. Put synchronous assembly in configuration hooks and awaited resource work in runtime hooks. Preserve all seven hooks in generated modules, including explicit empty hooks.
741
+
742
+ For example, a module can bind one immutable Options type without creating another configuration system:
743
+
744
+ ```python
745
+ from python_ddd_framework import AppModule, BaseOptions, ConfigureContext
746
+
747
+ class SalesOptions(BaseOptions):
748
+ currency: str = "JPY"
749
+
750
+ class SalesModule(AppModule):
751
+ def configure(self, context: ConfigureContext) -> None:
752
+ context.configure(SalesOptions, section="sales")
753
+ ```
754
+
755
+ This focused example shows the configure hook; keep the remaining generated lifecycle hooks. Add SalesModule to the actual composition, inject `Options[SalesOptions]`, and configure `sales.currency` in the application's environment YAML or `PDDD_SALES__CURRENCY`. Values needed to construct composition use the existing pre-configuration phase, not an early read of unbound Options. Use `configure(T, values=...)` only for the formal contribution/precedence rules. Configuration precedence and lifecycle contracts are in [architecture](architecture.md#configuration-and-lifecycle).
756
+
757
+ For a reusable capability with real resource ownership, use the native framework `ServiceComposition` and `RuntimeParticipant` extension points. A participant's optional `drain` waits for work already accepted, including before start; it must not start new resources. Do not move provider details or mutable state into the composition root. Verify composition with `pddd inspect` only when an Application build is authorized; verify actual resource start/stop separately.
758
+
759
+ <a id="dependency-injection"></a>
760
+
761
+ ## Dependency injection
762
+
763
+ Use `context.services.add_singleton`, `add_scoped` or `add_transient` in configure for ordinary services, or contribute native Dishka providers for resource factories. Use native components and multi-bindings only when the caller actually needs multiple implementations. The [installed contribution API](../services/contribution.py) owns the signatures, scope and arbitration rules; do not add a second container or service locator.
764
+
765
+ The generated basic module already contains a concrete synchronous contract/implementation example. A consuming Module declares a dependency on that owner and injects its public Protocol. Each transient resolution is independent. To replace a service, declare a dependency on its owner and perform the existing override registration in post_configure with a reason. Keep the original contract and lifetime valid; do not create a second lookup alias or forwarding facade.
766
+
767
+ For application services, repositories and hosted services, use their framework-owned role scopes rather than manually registering another lifetime. For ordinary async services that require policies, follow [services and permissions](#services-and-permissions). Check the effective registration through inspect and exercise the actual public caller; static Protocol checks alone do not prove lifecycle behavior.
768
+
769
+ <a id="validation-and-errors"></a>
770
+
771
+ ## Validation and errors
772
+
773
+ Define public DTOs with native Pydantic types and explicit validation. Define aggregate changes as domain operations. Managed calls validate inputs; ordinary DI services can explicitly use ValidationEnabled with the InvocationModule dependency. Neither raw construction nor a self-call creates a managed pipeline. Keep domain output conversion explicit with model_validate/from_attributes; it is not a business update operation.
774
+
775
+ A safe business error can carry a declared DTO:
776
+
777
+ ```python
778
+ from pydantic import BaseModel
779
+ from python_ddd_framework import BusinessError, BusinessErrorDefinition
780
+
781
+ class AvailableCapacity(BaseModel):
782
+ available: int
783
+
784
+ INSUFFICIENT_CAPACITY = BusinessErrorDefinition("orders.capacity", "Insufficient capacity")
785
+
786
+ def require_capacity(available: int) -> None:
787
+ if available < 1:
788
+ raise BusinessError(INSUFFICIENT_CAPACITY, data=AvailableCapacity(available=available))
789
+ ```
790
+
791
+ Put the definition and public data under the actual business owner. Choose fields that are safe to publish; arbitrary dictionaries, exceptions and SQL are not the public data contract. Exercise the declared rejection through the public service and HTTP boundary as relevant, checking that internal details are absent. The [error contract](architecture.md#validation-and-errors) owns the guarantees.
792
+
793
+ <a id="realtime-and-notifications"></a>
794
+
795
+ ## Realtime and notifications
796
+
797
+ Choose realtime APIs for currently connected clients, typed Notifications for the selected Pub/Sub transport, local events for transaction-related domain reactions, and durable Jobs for work requiring persistence. These are different delivery contracts.
798
+
799
+ For realtime, the Host selects FastAPI realtime support and the business HTTP Module declares its socket/router. Define a typed message in the owning shared layer, then inject `RealtimePublisher` into an authorized application service or event handler:
800
+
801
+ ```python
802
+ from uuid import UUID
803
+ from python_ddd_framework import RealtimeMessage, RealtimePublisher
804
+
805
+ class OrderChangedMessage(RealtimeMessage):
806
+ message_type = "orders.changed.v1"
807
+ id: UUID
808
+ status: str
809
+
810
+ async def notify(publisher: RealtimePublisher, user_id: UUID, order_id: UUID) -> None:
811
+ await publisher.send_to_user(user_id, OrderChangedMessage(id=order_id, status="approved"))
812
+ ```
813
+
814
+ Call this through the normal managed caller with real business values; map the event explicitly and choose the correct post-commit phase. Queue acceptance is not client acknowledgment. Verify actual authorized connections, disconnects and delivery separately from this helper's return.
815
+
816
+ For transport notifications, declare the definition and its capability in the business Module; the Host selects `RedisNotificationsModule` from `python_ddd_framework.redis.notifications` and supplies Redis configuration:
817
+
818
+ ```python
819
+ from python_ddd_framework import AppModule
820
+ from python_ddd_framework.notifications import NotificationDefinition, NotificationDefinitions
821
+ from python_ddd_framework.notifications.module import NotificationsModule
822
+
823
+ CHANGED = NotificationDefinition("orders.changed", str)
824
+
825
+ class OrderNotificationsModule(AppModule):
826
+ dependencies = (NotificationsModule,)
827
+ notification_definitions = NotificationDefinitions((CHANGED,))
828
+ ```
829
+
830
+ The example defines only the capability contribution; retain the other generated hooks. Inject `Notifications` into the real publisher and subscriber owner. A long-lived subscriber belongs to an explicitly registered HostedService or equivalent lifecycle owner:
831
+
832
+ ```python
833
+ from collections.abc import Awaitable, Callable
834
+ from python_ddd_framework.notifications import Notifications, NotificationPublishStatus
835
+
836
+ async def publish_while_subscribed(
837
+ bus: Notifications, handler: Callable[[str], Awaitable[None]], order_id: str
838
+ ) -> NotificationPublishStatus:
839
+ async with bus.subscribe(CHANGED, handler):
840
+ return await bus.publish(CHANGED, order_id)
841
+ ```
842
+
843
+ This demonstrates subscription cleanup and publication status only; it does not wait for a subscriber acknowledgment. A real subscriber keeps its context open for its declared lifetime. Handle the returned status according to business requirements and test the actual transport if delivery matters. Do not add a Settings refresh/retry coordinator: Notifications does not own that behavior.
844
+
845
+ <a id="hosted-services"></a>
846
+
847
+ ## Hosted services
848
+
849
+ Use the [hosted service public contract](../hosted_services/__init__.py) to own an SDK, thread or process-local resource. Declare HostedServicesModule and `hosted_services = HostedServices((YourService,))` in its owner. The Host selects whether an additional background-process instance is appropriate; opt in explicitly when needed.
850
+
851
+ Follow the start/stopping/stop and managed callback recipe under [background work](#events-and-background-work). Keep startup and temporary stopping contexts distinct. `submit_call(...).result()` is for external threads, while an asynchronous owner awaits `call`; neither transfers a Session to the SDK. Inspect registration, then verify partial-startup cleanup, callback admission and actual thread/resource exit using the existing relevant behavior tests. Successful composition alone does not prove shutdown.
852
+
853
+ <a id="distributed-locks"></a>
854
+
855
+ ## Distributed locks
856
+
857
+ Inject the provider-neutral `DistributedLock` contract into the business service; it has no separate Module declaration to invent. The consuming Host selects `RedisDistributedLockModule` from `python_ddd_framework.redis`, which supplies the provider and its connection dependency. Use its existing `distributed_lock` Options section and the Host's Redis prefix; do not add another connection or duplicate environment prefixes in business keys.
858
+
859
+ ```python
860
+ from collections.abc import Awaitable, Callable
861
+ from datetime import timedelta
862
+ from python_ddd_framework import DistributedLock
863
+
864
+ async def with_business_lease(locks: DistributedLock, operation: Callable[[], Awaitable[None]]) -> bool:
865
+ async with locks.acquire("orders.reconcile", wait_timeout=timedelta(0)) as acquired:
866
+ if not acquired:
867
+ return False
868
+ await operation()
869
+ return True
870
+ ```
871
+
872
+ This is an illustrative business operation, not a framework wrapper to add to every application. Invoke it through the normal DI-managed caller. False means no work was authorized by the lease. Preserve cancellation and required shielded cleanup on loss; never unconditionally delete a Redis key to release a lock. Verify actual competing acquisition, lease loss and cleanup against Redis when that behavior is in scope. Database transactions and external-effect idempotency remain separate requirements; read the [lease contract](architecture.md#distributed-locks).
873
+
874
+ <a id="auditing-and-observability"></a>
875
+
876
+ ## Auditing and observability
877
+
878
+ Use AuditingModule at the consuming capability boundary and the Host-selected audit provider/sink. Declare `audited`, `disable_auditing` or existing AuditingOptions only where the public policy requires it. Entity creation/update auditing uses explicit domain capabilities plus native SQLAlchemy convention mapping; never infer support from a similarly named field. Repository deletion is physical deletion, with no default soft-delete filter or restore operation. Invocation/request auditing records operations independently of entity audit fields. Verify public operations and persisted audit effects with the required infrastructure when applicable.
879
+
880
+ The Host selects `StructuredLoggingModule` from `python_ddd_framework.observability.logging` and `TracingModule` from `python_ddd_framework.observability.tracing`. Their Options types belong to `python_ddd_framework.observability`. Logging code uses the standard library:
881
+
882
+ ```python
883
+ import logging
884
+
885
+ logger = logging.getLogger(__name__)
886
+
887
+ def record_completion() -> None:
888
+ logger.info("Reconciliation completed")
889
+ ```
890
+
891
+ Keep secrets and arbitrary DTOs out of message strings and extras. Configure `logging` and `tracing` in the Host's environment YAML using the installed Options definitions, preserving logger-name case and dots. Trace export is opt-in; use the native injected OpenTelemetry provider and official HTTPX instrumentation rather than a global provider. Verify configured output/export and cleanup separately from source checks. For composition diagnostics use [inspect](#inspect-configuration), respecting that it reports inputs and a newly built graph, not live health.
892
+
893
+ <a id="testing"></a>
894
+
895
+ ## Testing
896
+
897
+ Use the normal builder and only the Modules/providers required by the test. This complete lifecycle example needs no database or network:
898
+
899
+ ```python
900
+ from pathlib import Path
901
+ from python_ddd_framework import AppModule, ApplicationBuilder, InvocationModule
902
+ from python_ddd_framework.testing import TestApplication
903
+
904
+ class ExampleModule(AppModule):
905
+ dependencies = (InvocationModule,)
906
+
907
+ async def answer() -> int:
908
+ return 42
909
+
910
+ async def exercise(base_path: Path) -> int:
911
+ builder = ApplicationBuilder(
912
+ ExampleModule, environment="test", base_path=base_path, env_prefix="EXAMPLE_"
913
+ )
914
+ async with TestApplication(builder) as test:
915
+ return await test.call(answer)
916
+ ```
917
+
918
+ Provide an existing empty configuration directory as base_path and await exercise from the existing async test environment. The tiny Module is a test graph role, not a generated business module. For application-service behavior use typed `invoke` or `invoke_as` with the actual contract and appropriate validated user. Use real selected providers for claims about their behavior; no test-only resolver or private container access is needed. Each TestApplication builds once and owns cleanup. Adding tests still requires authorization; this recipe does not generate test cases.
919
+
920
+ <a id="initialize-the-database"></a>
921
+
922
+ ## Initialize the database
923
+
924
+ Follow the application's README to configure connections and prepare authorized local infrastructure. `pddd dev-init --environment development` writes/refreshes local Compose inputs but does not start the Application, migrate or seed. Start the reviewed Compose services using the application's actual deployment files.
925
+
926
+ Upgrade prerequisite framework owners explicitly with `pddd db upgrade --module <alias> --environment <environment>`, then review/generate and apply the business module's revisions using the [persistence procedure](#persistence-and-migrations). The alias comes from actual entry points; do not maintain a second dependency list. Run seed only for the requested owner using `pddd db seed --module <alias>`. Host startup does not perform these operations. Credentials and production data changes require the application's authorization and operational process.
927
+
928
+ <a id="deployment"></a>
929
+
930
+ ## Deployment
931
+
932
+ The generated project owns `backend/Dockerfile`, Compose files and production configuration. Build and inspect its application wheel with native uv, then use the project's Docker procedure. Production installs the runtime package; developer-kit is for generation, not runtime. The image starts the existing `python -m host.main` entry point without development reload. Keep provider choices and secrets in Host/deployment configuration, and verify actual readiness, external access and shutdown rather than equating image build with a successful deployment.
933
+
934
+ Upgrade through the application's native dependency workflow after reading the target release's [upgrade procedure](README.md#migration-notes). Preserve application dependencies, source overrides, source code, migrations and Markdown. A global CLI upgrade does not upgrade the project environment.