@cratis/pi 7.6.2 → 7.6.3

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.
@@ -201,6 +201,17 @@ The default is fire-and-forget. When a caller's correctness depends on all obser
201
201
  7. **No state** — Reactors should be stateless. Inject dependencies via primary constructor, but do not store mutable state on the class.
202
202
  8. **An unattended, irreversible pass reads the log, not the sink — and carries a fuse.** A reactor that deletes, revokes, bills or notifies *because a read model says something is absent* is trusting a materialized sink that is only as current as its observer: a paused partition, a replay in progress or a lagging projection makes "absent" true of the sink and false of the world. Decide from a **`[Passive]`** read model (computed on demand from the events at the moment the reactor runs) or from the events themselves. And the code shape cannot tell an **empty subject set** ("nothing to consider" — fail-safe) from an **empty qualifying set** ("nothing survived the filter" — fail-destructive: every subject is about to be acted on), so an unattended pass states its expected population, refuses when the count is implausible, and caps how many subjects one run may touch — the same discipline as [guards-and-fuses.md](./guards-and-fuses.md), applied to a reactor.
203
203
 
204
+ ## Failure transitions **[convention]**
205
+
206
+ A domain failure must produce a timely, observable workflow outcome rather than
207
+ leave work looking active until a watchdog notices. Assign the transition to a
208
+ reliable consumer: an existing state machine can be sufficient; do not add a
209
+ redundant failure reactor when it already owns the event. Watchdogs cover missing
210
+ signals, not ordinary handling of an already recorded failure. Specify the visible
211
+ transition, repeated delivery, and stale failures from earlier attempts. Keep
212
+ public reasons free of secrets. See **cratis-chronicle-reactor** for the distinction
213
+ between domain failure and an observer's operational failure.
214
+
204
215
  ## Slice Types That Use Reactors
205
216
 
206
217
  | Slice type | Pattern |
@@ -90,6 +90,15 @@ The command carries input from the caller. `Handle()` is defined directly on the
90
90
 
91
91
  **Do not throw for normal business rejection.** A thrown exception (from `Provide()` or `Handle()`) surfaces as an exception/HTTP 500, *not* a validation result. Recoverable, user-facing rejections are validation: `ValidationResult.Error(...)` via a validator or `Result<,>`. (For step-by-step business-rule placement, invoke the **cratis-arc-command-validation** skill.)
92
92
 
93
+ ### Nested commands **[contract]**
94
+
95
+ With Arc + Chronicle, ordinary nested pipeline commands join the outer ambient
96
+ transaction even when the call creates a new DI scope. Child success is enrollment,
97
+ not final persistence. Do not promise partial success for an atomic returned batch.
98
+ Independent outcomes require separate top-level executions outside that transaction;
99
+ operation-capable commands reject nesting entirely. See **cratis-arc-command-execution**
100
+ for the versioned boundary and supported alternatives.
101
+
93
102
  ### Causation — what a command records **[contract]**
94
103
 
95
104
  A command's **property values** are recorded on the causation of every event it appends, alongside the command's name, so an event says not only which command produced it but what that command was asked to do. The causation is written into the event log and stays there for as long as the events do — a value recorded there cannot be taken back out by changing code.
@@ -240,10 +249,28 @@ public record Author(AuthorId Id, AuthorName Name)
240
249
 
241
250
  **[convention] Read-model boundaries & naming.** Read models are shaped for consumers and command policies, not CRUD-style aggregate DTOs. Split one when it starts mixing unrelated lifecycles — the test is coupling (state that changes for different reasons), not size. The event log is already the canonical history/audit trail, so name a model `AuditLog`/`ActivityLog` only when it genuinely is an audit surface; for curated UI projections prefer names like `Timeline`, `WorkSurface`, `Summary`, `Detail`, or `Policy`. (This is "specialization over reuse" applied to read models.)
242
251
 
252
+ **[convention] Keep query cost bounded.** Prefer slim, purpose-built projections
253
+ for frequently read summaries rather than repeatedly joining broad collections.
254
+ This is not a one-collection framework restriction. Embed bounded children; keep
255
+ growing histories in separately paged timeline models. Evaluate variants when
256
+ lifecycle shapes diverge, and preserve reducer admission/ordering guards when
257
+ considering a projection conversion. Narrow observable inputs at the source.
258
+ Ordinary MongoDB `Observe` retains its initial set and applies changes; do not
259
+ claim it always re-queries the whole collection per event. Explicit recompute
260
+ callbacks have a different cost. See the **cratis-chronicle-read-model** skill's
261
+ query reference for versioned behavior and composition trade-offs.
262
+
243
263
  ### Choosing read-model access in command-side code **[convention]**
244
264
 
245
265
  Ladder, first that fits: (1) direct read-model (DCB) injection — only when keyed by the command's own event-source id; (2) a `[Passive]` projection; (3) `IReadModels.GetInstanceById<T>((EventSourceId)key)` for a different/derived key; (4) a materialized projection. A lookup *interface* is justified **only** for a genuine non-key search (e.g. find-by-email) — never to wrap a keyed `GetInstanceById`.
246
266
 
267
+ **[contract] Passive state is not sink state.** `IMongoCollection<T>` cannot
268
+ compute a passive read model; any leftover documents are not maintained state.
269
+ Read through Chronicle by key or supported injection. **[convention]** Never
270
+ materialize secret-bearing state just to make a collection query work: project
271
+ safe metadata separately. Count passive types only as inventory, not as a defect;
272
+ evaluate reconstruction frequency, history length, consistency, and security.
273
+
247
274
  ### Existence checks — what an absent read model actually resolves to **[contract]**
248
275
 
249
276
  `IReadModels.GetInstanceById<T>` is declared `Task<TReadModel>` (non-nullable) yet hands back `default!` when nothing exists, so the compiler gives callers no signal. What "nothing exists" resolves to depends on the **backing** — *not* on whether the model carries `[RemovedWith<T>]`:
@@ -60,7 +60,8 @@ public class <Name>Reactor(ICommandPipeline pipeline) : IReactor
60
60
  ```
61
61
 
62
62
  `Execute(command)` is the scopeless overload: the pipeline creates its own DI
63
- scope for the call. This is the normal case.
63
+ scope for the call. This is the normal case. **A DI scope is not an independent
64
+ transaction boundary**; see the nested-command contract below.
64
65
 
65
66
  ## The overloads
66
67
 
@@ -89,6 +90,42 @@ command failed for any reason, `Response` is `default` — a failed result never
89
90
  carries a response, because the pipeline clears it once the execution scopes
90
91
  have completed.
91
92
 
93
+ ## Nested commands and atomic batches
94
+
95
+ With **Arc's Chronicle integration**, an ordinary nested pipeline command joins
96
+ the outer command's ambient transaction. Only the outer owner commits pending
97
+ returned events. The child's successful result means enrollment, not persistence;
98
+ a commit-time constraint rejection can reject the entire batch. Inspect and
99
+ propagate child failures, and never report per-item persisted success before the
100
+ outer result is known.
101
+
102
+ This remains true with the scopeless overload or a newly created DI scope:
103
+ transaction context follows the async flow, not DI scope identity. Do not invent
104
+ a detached `Execute` overload or use fire-and-forget work to escape the owner.
105
+ Standalone Arc does not supply this Chronicle transaction guarantee. The flat
106
+ operation-capable boundary described above is stricter and rejects nesting.
107
+
108
+ Choose the intended outcome before implementing a bulk action:
109
+
110
+ - **All-or-nothing:** one command owns the returned event batch. Report its final
111
+ result as one atomic outcome, not a list of independently committed children.
112
+ - **Independent outcomes:** orchestrate separate top-level pipeline executions
113
+ outside an enclosing command transaction, awaiting each final result. A durable
114
+ workflow/reactor can own follow-up work and retries. A collection of returned
115
+ reactor commands executes as separate transactions; earlier successes remain
116
+ when a later command fails, so retries must be idempotent.
117
+
118
+ Neither choice makes external service writes atomic. Immediate event appends
119
+ and explicit early commits also do not become rollbackable merely because a
120
+ command later fails; do not use them as an undocumented batch-isolation trick.
121
+
122
+ Checked against **Arc v22.49.0**
123
+ ([transactional commands](https://github.com/Cratis/Arc/blob/v22.49.0/Documentation/backend/csharp/chronicle/commands/transactional-commands.md),
124
+ [transaction scope](https://github.com/Cratis/Arc/blob/v22.49.0/Source/DotNET/Chronicle/Commands/TransactionalCommandScope.cs),
125
+ [ambient context](https://github.com/Cratis/Arc/blob/v22.49.0/Source/DotNET/Chronicle/Commands/CommandTransaction.cs)).
126
+ Specify a later child's rejection and the actual persisted events: none for an
127
+ atomic returned batch, only completed independent items for separate commands.
128
+
92
129
  ## Pre-flight `Validate`
93
130
 
94
131
  `await pipeline.Validate(command)` runs the authorization and validation filters
@@ -55,7 +55,7 @@ return type.
55
55
  | `T`, `T?`, `IEnumerable<T>`, `List<T>`, `T[]` | No | Nothing narrows the result |
56
56
  | `IQueryable<T>` | **Yes** | The query renderer counts, orders, then applies `Skip`/`Take` |
57
57
  | `Task<IQueryable<T>>` | **Yes** | Awaited first, then rendered as the queryable it unwraps to |
58
- | `ISubject<IEnumerable<T>>` | **Yes** | Not by the renderer — the storage `Observe()` helpers read the ambient query context and page at the source, reapplying on every change |
58
+ | `ISubject<IEnumerable<T>>` | **Yes, with a paging-aware storage helper** | Not by the renderer — the helper reads the ambient query context; a custom subject does not page automatically |
59
59
  | `ISubject<IQueryable<T>>` | **No** | No `Observe` overload returns it, and the renderer matches on the outer type |
60
60
 
61
61
  There is exactly one query renderer, and it is for `IQueryable`. Everything else
@@ -82,7 +82,7 @@ For a live paged list, return what `Observe` returns:
82
82
 
83
83
  ```csharp
84
84
  public static ISubject<IEnumerable<<ReadModel>>> AllLive(<Collection> collection) =>
85
- collection.Observe(_ => _.Find(item => !item.<IsArchived>));
85
+ collection.Observe(item => !item.<IsArchived>);
86
86
  ```
87
87
 
88
88
  `ARC0001` is an **error** when a query method's return type is none of the
@@ -91,6 +91,11 @@ query-shaped method on a read model is generic — a generic method is registere
91
91
  and routed but can never be invoked, because there is nothing to close its type
92
92
  parameters with.
93
93
 
94
+ For MongoDB `Observe` cost, distinguish the initial retained result, incremental
95
+ membership updates, and page-refill queries from an application callback that
96
+ explicitly re-runs a query. It does not always fetch the whole collection per
97
+ change. See the read-model skill's [versioned query-cost guidance](../cratis-chronicle-read-model/references/queries.md#cost-and-composition).
98
+
94
99
  ## Page the source, not the answer
95
100
 
96
101
  - Do not `.ToList()` before returning an `IQueryable<T>` — that defeats
@@ -83,6 +83,20 @@ member list. The trap that costs the most time: **`UsingKey`, `UsingParentKey`,
83
83
  `UsingCompositeKey`, and `UsingConstantKey` are not on the projection builder.**
84
84
  They live on the per-event builder that `From<TEvent>` hands to your callback.
85
85
 
86
+ ## Choose a bounded projection shape
87
+
88
+ Project the fields a consumer needs, rather than building a universal entity
89
+ with every detail and historical entry. Children are useful for bounded related
90
+ state, not an invitation to embed an unbounded timeline. Give growing histories
91
+ their own paged read model. A slim summary may combine event facts without
92
+ query-time joins, but there is no framework requirement that a query read only
93
+ one collection. Preserve security/compliance boundaries when choosing the shape.
94
+
95
+ When replacing a reducer, preserve creation/admission and late-event guards;
96
+ an unconditional `[SetValue<T>]` is not equivalent to guarded state transition
97
+ code. See the reducer skill's conversion guidance. Evaluate variants below when
98
+ shapes diverge; do not mandate them for every status field.
99
+
86
100
  ## Joins are on events, never on read models
87
101
 
88
102
  Both `[Join<T>]` and the fluent `Join<TEvent>` take an **event** type. Joining on
@@ -328,6 +328,26 @@ surface it through the operational failure path, and skip the partial side
328
328
  effect. Throwing just to reject it pauses the partition and can quarantine the
329
329
  whole observer.
330
330
 
331
+ ### Domain failures must leave a visible state
332
+
333
+ A recorded failure fact is not complete handling if the user-facing workflow
334
+ still looks running indefinitely. Give each terminal failure a reliable owner
335
+ that transitions the affected attempt/workflow promptly to failed, retryable, or
336
+ another explicit outcome, and project a safe reason for the reader. Keep secrets
337
+ and raw provider payloads out of public failure details.
338
+
339
+ This is an application reliability convention, **not** a requirement for a
340
+ separate failure reactor. An existing reliable state machine that consumes the
341
+ failure event and owns the transition is sufficient; adding another consumer can
342
+ race or duplicate it. Add a reactor only when the transition/effect has no owner.
343
+ Use a watchdog for missing signals or lost work, not as the normal consumer of a
344
+ failure already known. Distinguish domain failure from an observer partition
345
+ failure: the latter also needs operational monitoring and recovery.
346
+
347
+ Specify failure-to-visible-state, repeated delivery, stale failure from an older
348
+ attempt, and recovery/retry behavior. Prove the normal failure transition without
349
+ waiting for the watchdog timeout.
350
+
331
351
  ## Keep the reactor stateless
332
352
 
333
353
  Inject collaborators through the primary constructor; hold no mutable state on
@@ -77,6 +77,21 @@ public record <ReadModelName>(
77
77
  - `Cratis.Chronicle.ReadModels.IndexAttribute` (`[Index]`) marks a property for
78
78
  indexing in the sink.
79
79
 
80
+ ### Shape the model for its consumer
81
+
82
+ Prefer a slim, purpose-built projection over assembling a screen by repeatedly
83
+ joining broad collections at query time. A summary needs summary fields, not
84
+ every detail and historical entry. This is a design convention, **not a
85
+ one-collection framework requirement**: bounded query composition remains valid,
86
+ including when separate security or compliance boundaries must be preserved.
87
+
88
+ Embed children only when their cardinality and payload are bounded by the use
89
+ case. Keep growing activity, message, or attempt histories in separately paged
90
+ timeline models; embedding all history makes every parent read and emission
91
+ larger. Evaluate variants when lifecycle shapes genuinely diverge, not merely
92
+ because a status changes. See the projection skill for children and variants,
93
+ and [query cost and composition](references/queries.md#cost-and-composition).
94
+
80
95
  ## Step 3 — Choose a projection or a reducer
81
96
 
82
97
  | | Projection | Reducer |
@@ -165,6 +180,23 @@ passive: no sink, nothing materialized, and the instance is computed on demand
165
180
  from the events at the moment it is read. Reach for it when a decision needs the
166
181
  model **strongly consistent** rather than eventually consistent.
167
182
 
183
+ **`IMongoCollection<T>` reads only the sink.** It cannot compute passive state:
184
+ a fresh passive model has no maintained collection, and a formerly active one
185
+ may leave stale documents. Use Chronicle's keyed read API above (or supported
186
+ read-model parameter injection) when you need its computed state. Do not remove
187
+ `[Passive]` merely to make a sink query work when the model contains secrets.
188
+ Keep secret-bearing state on the protected access path; project only safe
189
+ metadata into a separate list/search model.
190
+
191
+ The number of passive types is not itself a performance smell. Review event
192
+ history length, invocation frequency, and the consistency/security requirement;
193
+ repeated reconstruction of large histories on a hot path is the concern.
194
+ Passivity does not itself authorize access or encrypt secrets.
195
+
196
+ This access distinction was checked against Chronicle **v19.31.2**
197
+ ([passive projections](https://github.com/Cratis/Chronicle/blob/v19.31.2/Documentation/projections/declarative/passive.mdx),
198
+ [passive reducers](https://github.com/Cratis/Chronicle/blob/v19.31.2/Documentation/reducers/passive-reducers.mdx)).
199
+
168
200
  `[Passive]` on its own does **not** make a read model a projection. It is
169
201
  deliberately excluded from the annotations that do; it changes how an existing
170
202
  projection is registered.
@@ -187,7 +219,9 @@ spans streams.
187
219
  - Query methods are `static` and declare `ISubject<...>` rather than a concrete
188
220
  subject type.
189
221
  - A direct `GetInstanceById` result is checked for absence before use.
190
- - `[Passive]` is present only where a strongly consistent command-side read is
191
- genuinely required.
222
+ - Passive access goes through Chronicle, not a sink collection; consistency,
223
+ access frequency, and non-materialization requirements justify the choice.
224
+ - Summary payloads and embedded children are bounded; growing histories have
225
+ a separate paged surface, and no secret was materialized to fix a query.
192
226
  - The project builds clean and the read-model specifications pass against the
193
227
  verified package versions.
@@ -118,6 +118,43 @@ Two details that catch people out:
118
118
  Also available in the same place: `FindById<T, TId>` and
119
119
  `FindByIdAsync<T, TId>`.
120
120
 
121
+ ## Cost and composition
122
+
123
+ The behavior below was checked against **Arc v22.49.0**
124
+ ([collection observation](https://github.com/Cratis/Arc/blob/v22.49.0/Documentation/backend/csharp/mongodb/observing-collections.md),
125
+ [implementation](https://github.com/Cratis/Arc/blob/v22.49.0/Source/DotNET/MongoDB/MongoCollectionExtensions.cs)).
126
+ Do not generalize it to every provider or custom observable.
127
+
128
+ - Per-collection `Observe` reads an initial filtered set, retains it in memory,
129
+ and applies change-stream updates. It does **not** re-query the entire
130
+ collection for every event. Updates/replacements perform a keyed membership
131
+ lookup; paged removals can query to refill the page.
132
+ - Collection emissions still construct a snapshot of the retained set. In-memory
133
+ joins, sorting, mapping, and serialization downstream can be expensive even
134
+ without a full database re-query. Measure retained rows, payload size, change
135
+ frequency, and concurrent subscriptions separately from database calls.
136
+ - A custom change callback that explicitly runs another query pays that query's
137
+ cost on each invocation. Distinguish this recompute path from ordinary retained
138
+ observation; inspect the actual callback before reporting a full scan.
139
+ - Filter by the requested entity, parent, tenant, or relevant state at the
140
+ observation source; filtering after an unbounded `Observe()` retains too much.
141
+ This narrows initial state and emissions, not necessarily every watched change:
142
+ updates/deletes must still detect documents leaving the set. Test removal and
143
+ filter-exit behavior as well as additions.
144
+ - For counts, do not retain rich documents and entire histories just to count
145
+ them. Consider a slim projected counter or an explicit aggregate query with an
146
+ appropriate refresh policy; preserve the count's actual semantics.
147
+ - Prefer a purpose-built projected summary for frequently recomputed joins.
148
+ Query-time composition is supported, not forbidden. Bound each input and define
149
+ count, paging, missing-related-data, and subscription-disposal behavior.
150
+ In v22.49.0 auxiliary observations can use `ignoreQueryContext: true` so client
151
+ paging/counts belong to the primary source. That option reads **all matching
152
+ auxiliary rows**; it is not a performance limit. Confirm version support before
153
+ using it, and keep an explicit narrow filter.
154
+
155
+ Use the **cratis-arc-query-paging** skill for source-side paging. Paging an
156
+ already materialized list does not bound database reads or retained memory.
157
+
121
158
  ## Custom routes
122
159
 
123
160
  ```csharp
@@ -59,6 +59,22 @@ public class <ReadModelName>Reducer : IReducerFor<<ReadModelName>>
59
59
  `IReducerFor<TReadModel>` is a marker with no members, constrained to
60
60
  `where TReadModel : class`.
61
61
 
62
+ ## Preserve admission and ordering when converting
63
+
64
+ A handler that ends with `current with { Status = ... }` is not necessarily a
65
+ plain setter. First inspect guards: does it require a creation event, ignore an
66
+ older attempt, preserve a terminal state, or compare prior values? Replacing it
67
+ with unconditional `[SetValue<T>]` can create state too early or resurrect a
68
+ finished entity. Keep the reducer when the projection APIs cannot express those
69
+ semantics; the admission test is about behavior, not handler length.
70
+
71
+ Evaluate variants for mutually exclusive lifecycle shapes (see the projection
72
+ skill). Their non-entering events are update-only, but that does not replace
73
+ arbitrary guards on attempt identity, ordering, or prior state. Before conversion,
74
+ keep specifications for update-before-create, late events after completion,
75
+ repeated events, and each guarded branch, as applicable. Assert the same outcomes
76
+ with the replacement, not only the happy-path final status.
77
+
62
78
  ## Method signatures — exactly what is accepted
63
79
 
64
80
  Dispatch is by the **first parameter's type**, never by the method name. Name the
@@ -68,7 +68,20 @@ behavior this file does not already state.
68
68
  - No N+1: one query returns what the caller needs.
69
69
  - A count is a count. Hydrating the collection to measure its length is the
70
70
  same finding as an unpaged list, wearing different clothes.
71
- - A read model does not embed a large nested collection nothing fully iterates.
71
+ - Prefer slim projection-backed summaries over repeatedly assembling broad
72
+ collections. Query composition is supported; one collection per query is not
73
+ a framework requirement. Bound each input and measure recomputation.
74
+ - Embed bounded related state, not growing histories; page timelines separately.
75
+ Evaluate variants for divergent lifecycle shapes, not every status field.
76
+ - Preserve reducer admission and ordering guards when proposing a projection
77
+ conversion; an unconditional setter may resurrect or prematurely create state.
78
+ - Count passive models as inventory, not a smell. Assess history length and read
79
+ frequency against consistency/security needs. `IMongoCollection<T>` cannot
80
+ read passive computed state; never materialize secrets to make that query work.
81
+ - Distinguish retained `Observe` state and in-memory emissions from explicit
82
+ recompute queries. Narrow source filters and inspect page-refill/membership
83
+ lookups; do not claim every change re-queries the entire collection. See the
84
+ **cratis-chronicle-read-model** query reference for versioned behavior.
72
85
 
73
86
  ## Step 3 — Commands and queries
74
87
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.6.2",
3
+ "version": "7.6.3",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [