@cratis/pi 7.53.0 → 7.54.0

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.
@@ -35,6 +35,8 @@ One precise line per load-bearing term, so the same word means the same thing ev
35
35
  - **Command** — a `[Command]` record expressing an imperative **intent**; its public `Handle()` produces event(s) (or a response).
36
36
  - **Provide()** — the command method that fetches/computes data after validation/authorization and before `Handle()`; may short-circuit with a `ValidationResult`.
37
37
  - **Causation chain** — the ordered links saying how an append came about (root process → command → …), each carrying properties. A command records its **name and its property values** there, so an event says what the command was asked to do; the chain lives in the event log and is as permanent as the events.
38
+ - **Observation command** — a command whose input comes from outside the model's own decisions (webhook, poll, sweep, retry, classifier). It compares with current state and appends nothing when nothing changed; looking is not a fact.
39
+ - **Signal event** — an event appended only to make a reactor do something (`…Requested`, `…Started`, `…Skipped`). Not a domain fact; use a job, state machine, command operation or `ICommandPipeline`.
38
40
  - **Constraint** — `IConstraint`; an **append-time** invariant (uniqueness / concurrency) enforced at the event-store level.
39
41
  - **DCB (Dynamic Consistency Boundary)** — enforcing a state-dependent rule under concurrency over explicitly enrolled event-state reads: stream decisions/exact scopes or protected, admitted projection decision reads. Plain injected models and `Result<TEvent, ValidationResult>` alone are advisory, not a guard.
40
42
  - **Consistency boundary** — the scope within which an invariant holds atomically (an event source, a routed stream, or the event state enrolled by an admitted protected decision read).
@@ -226,7 +226,8 @@ findings). Each reactor class should have a focused purpose. Multiple handler me
226
226
  5. **Failure behavior** — If a reactor throws, *or* a returned side-effect event fails to append (constraint violation, concurrency violation, or error), the failing event-source partition pauses until the issue is resolved. Repeated failures can **quarantine** the observer: once `QuarantineOnFailedPartitionCount`/`QuarantineOnFailedPartitionPercentage` (under `Observers`) is crossed, the observer enters the `Quarantined` state — reminders cancelled, retries stopped, automatic recovery suppressed. **A quarantine ends when an operator clears it (`ClearObserverQuarantine()`), or when the observer is subscribed again** — for an application observer that is when the client connects again, for example after a redeploy; Kernel-owned observers are subscribed again when the Kernel starts. A periodic watchdog (default 60s, `WatchdogInterval`) re-routes stuck/dead observers but does not rescue quarantined ones. Design for resilience.
227
227
  6. **Don't throw to validate malformed inbound events** — reactors are not data-quality validators; invalid payloads must be rejected at the command/append site. When a malformed cross-service fact reaches a consumer, throwing just to reject it pauses the partition and can quarantine the whole observer. Instead append a clear failure/dead-letter event (e.g. `ProvisioningFailed`) or surface it via the operational failure path, and skip partial side effects.
228
228
  7. **No state** — Reactors should be stateless. Inject dependencies via primary constructor, but do not store mutable state on the class.
229
- 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.instructions.md), applied to a reactor.
229
+ 8. **A new side-effect reactor must not act on history.** A reactor that is new in a release (or has a new id) catches up from the start of the event log when it first registers, and `[OnceOnly]` does not cover that first catch-up because it is not a replay. If its handlers cause side effects (jobs, AI calls, external calls, notifications), start the observer at the tail on first registration or make the handler ignore facts that predate its registration, and specify that history causes nothing.
230
+ 9. **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.instructions.md), applied to a reactor. A sweep that decides from a read model also refuses while that model's observer is replaying or behind, because a rebuilding model reads as "nothing was ever processed"; specify the replaying case.
230
231
 
231
232
  ## Failure transitions **[convention]**
232
233
 
@@ -320,6 +320,18 @@ evaluate reconstruction frequency, history length, consistency, and security.
320
320
 
321
321
  **Injected-parameter nullability is the required/optional switch:** a nullable `TReadModel?` parameter (on a validator, `Provide()`, or `Handle()`) gets `null` injected for a never-created/removed instance — check `is null`. A **non-nullable** `TReadModel` whose instance does not exist is **rejected, not crashed**: Arc raises `ReadModelDoesNotExistForCommand`, which surfaces as a validation failure (HTTP 400) with reason `DependencyUnavailable` (non-nullable = "required, must exist"). The server-fault path (`CannotResolveCommandDependency` / `CannotResolveValidatorDependency`, HTTP 500) is reached only when the dependency is *not* a registered read model or no usable key was resolved — the exact contract is in the **cratis-arc-command** skill's `read-model-injection` reference. ⚠️ Both switches ride on the same resolution, so on a **`[Passive]` projection** neither fires for a never-created instance: the nullable parameter receives a default-valued object and the `is null` guard never runs, and the non-nullable one resolves happily. Check the existence flag there, not nullability. Type by-id accessors you write yourself as `Task<T?>` so callers get the compiler signal Chronicle's own signature withholds.
322
322
 
323
+ ### Observation commands append only changes **[convention]**
324
+
325
+ A command fed by a webhook, poll, sweep, retry or classifier is an *observation*, and looking is not a fact.
326
+
327
+ - Compare with current state and append **nothing** when nothing changed; `Handle()` takes the thing it would change and compares each fact on its own.
328
+ - Compare against something that cannot lag: a `[Passive]` read model read by key, or the stream's own events, never a materialized read model (it trails the log and is bypassed exactly while rebuilding).
329
+ - Never append a tick, a heartbeat, a trigger event for a reactor, a "last looked" timestamp, telemetry or a non-answer ("pending", "could not decide"); use a job, state machine, command operation or `ICommandPipeline`.
330
+ - An event named `…Changed` records a real change; split a broad `…DetailsChanged` into per-fact events.
331
+ - Specify two behaviors per observation command: the same observation twice appends nothing, and a changed observation appends exactly the change.
332
+
333
+ See the **cratis-chronicle-event-modeling** skill (`references/event-log-hygiene.md`).
334
+
323
335
  ## Projections **[contract]**
324
336
 
325
337
  Projections build read models from **events** (never from other read models). Use the ladder — for adding one to an existing model, invoke the **cratis-chronicle-projection** skill:
@@ -335,6 +347,7 @@ For self models, keep `[ReadModel]`, static `Reduce` methods and queries on one
335
347
  - ⚠️ **AutoMap runs per *event* across every event the projection references — it does not defer to your explicit setters.** A property sourced with `[SetFrom<A>]` can still be silently overwritten when some *other* referenced event `B` happens to carry an identically named property (AutoMap wires `B`'s value on top). Fence the property with property-level **`[NoAutoMap]`** (which pairs with the `[SetFrom]`, not replaces it) so only your explicit setter writes it. `[SetFrom]` does **not** imply this — leaving AutoMap on is what allows the common create-then-rename pattern (a later event updating a property by name-match). No colliding event property name means no `[NoAutoMap]` needed. (An event subscribed only via an aggregate like `[Count]` doesn't auto-map its other properties, so it can't collide.) The analyzer **`CHR0025`** surfaces this collision as an *informational* heads-up (not a warning, because either resolution — add `[NoAutoMap]`, or accept the update — can be correct).
336
348
  - **[contract] `[Nested]`** projects a single nullable child object; place `[FromEvent<T>]` on the nested type (or property-level `[SetFrom<T>]` when the parent shares the event — declaring class-level `[FromEvent<T>]` on both parent and nested type for the same event is a duplicate-registration startup crash).
337
349
  - **[contract] Event-sequence source attributes:** class-level `[EventSequence("name")]`, `[EventLog]`, or `[EventStore("name")]` select where the projection reads from (a named sequence, the explicit default log, or another Chronicle event store / inbox). ⚠️ `[FromEventSequence]` is **removed** — use `[EventSequence("name")]`.
350
+ - **[convention] Counters and aggregates (`[Increment]`, `[Decrement]`, `[Count]`) need clean lifecycle transitions.** They see the event, not the item's previous state, so a close for an already closed item drifts the counter permanently and replay reproduces it. The command that appends the lifecycle event refuses a non-transition and appends nothing; fold the log per event source with the proposed mapping and compare it with the state it summarizes before shipping.
338
351
 
339
352
  ## Constraints **[contract]**
340
353
 
@@ -34,6 +34,8 @@ One precise line per load-bearing term, so the same word means the same thing ev
34
34
  - **Command** — a `[Command]` record expressing an imperative **intent**; its public `Handle()` produces event(s) (or a response).
35
35
  - **Provide()** — the command method that fetches/computes data after validation/authorization and before `Handle()`; may short-circuit with a `ValidationResult`.
36
36
  - **Causation chain** — the ordered links saying how an append came about (root process → command → …), each carrying properties. A command records its **name and its property values** there, so an event says what the command was asked to do; the chain lives in the event log and is as permanent as the events.
37
+ - **Observation command** — a command whose input comes from outside the model's own decisions (webhook, poll, sweep, retry, classifier). It compares with current state and appends nothing when nothing changed; looking is not a fact.
38
+ - **Signal event** — an event appended only to make a reactor do something (`…Requested`, `…Started`, `…Skipped`). Not a domain fact; use a job, state machine, command operation or `ICommandPipeline`.
37
39
  - **Constraint** — `IConstraint`; an **append-time** invariant (uniqueness / concurrency) enforced at the event-store level.
38
40
  - **DCB (Dynamic Consistency Boundary)** — enforcing a state-dependent rule under concurrency over explicitly enrolled event-state reads: stream decisions/exact scopes or protected, admitted projection decision reads. Plain injected models and `Result<TEvent, ValidationResult>` alone are advisory, not a guard.
39
41
  - **Consistency boundary** — the scope within which an invariant holds atomically (an event source, a routed stream, or the event state enrolled by an admitted protected decision read).
@@ -225,7 +225,8 @@ findings). Each reactor class should have a focused purpose. Multiple handler me
225
225
  5. **Failure behavior** — If a reactor throws, *or* a returned side-effect event fails to append (constraint violation, concurrency violation, or error), the failing event-source partition pauses until the issue is resolved. Repeated failures can **quarantine** the observer: once `QuarantineOnFailedPartitionCount`/`QuarantineOnFailedPartitionPercentage` (under `Observers`) is crossed, the observer enters the `Quarantined` state — reminders cancelled, retries stopped, automatic recovery suppressed. **A quarantine ends when an operator clears it (`ClearObserverQuarantine()`), or when the observer is subscribed again** — for an application observer that is when the client connects again, for example after a redeploy; Kernel-owned observers are subscribed again when the Kernel starts. A periodic watchdog (default 60s, `WatchdogInterval`) re-routes stuck/dead observers but does not rescue quarantined ones. Design for resilience.
226
226
  6. **Don't throw to validate malformed inbound events** — reactors are not data-quality validators; invalid payloads must be rejected at the command/append site. When a malformed cross-service fact reaches a consumer, throwing just to reject it pauses the partition and can quarantine the whole observer. Instead append a clear failure/dead-letter event (e.g. `ProvisioningFailed`) or surface it via the operational failure path, and skip partial side effects.
227
227
  7. **No state** — Reactors should be stateless. Inject dependencies via primary constructor, but do not store mutable state on the class.
228
- 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.
228
+ 8. **A new side-effect reactor must not act on history.** A reactor that is new in a release (or has a new id) catches up from the start of the event log when it first registers, and `[OnceOnly]` does not cover that first catch-up because it is not a replay. If its handlers cause side effects (jobs, AI calls, external calls, notifications), start the observer at the tail on first registration or make the handler ignore facts that predate its registration, and specify that history causes nothing.
229
+ 9. **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. A sweep that decides from a read model also refuses while that model's observer is replaying or behind, because a rebuilding model reads as "nothing was ever processed"; specify the replaying case.
229
230
 
230
231
  ## Failure transitions **[convention]**
231
232
 
@@ -319,6 +319,18 @@ evaluate reconstruction frequency, history length, consistency, and security.
319
319
 
320
320
  **Injected-parameter nullability is the required/optional switch:** a nullable `TReadModel?` parameter (on a validator, `Provide()`, or `Handle()`) gets `null` injected for a never-created/removed instance — check `is null`. A **non-nullable** `TReadModel` whose instance does not exist is **rejected, not crashed**: Arc raises `ReadModelDoesNotExistForCommand`, which surfaces as a validation failure (HTTP 400) with reason `DependencyUnavailable` (non-nullable = "required, must exist"). The server-fault path (`CannotResolveCommandDependency` / `CannotResolveValidatorDependency`, HTTP 500) is reached only when the dependency is *not* a registered read model or no usable key was resolved — the exact contract is in the **cratis-arc-command** skill's `read-model-injection` reference. ⚠️ Both switches ride on the same resolution, so on a **`[Passive]` projection** neither fires for a never-created instance: the nullable parameter receives a default-valued object and the `is null` guard never runs, and the non-nullable one resolves happily. Check the existence flag there, not nullability. Type by-id accessors you write yourself as `Task<T?>` so callers get the compiler signal Chronicle's own signature withholds.
321
321
 
322
+ ### Observation commands append only changes **[convention]**
323
+
324
+ A command fed by a webhook, poll, sweep, retry or classifier is an *observation*, and looking is not a fact.
325
+
326
+ - Compare with current state and append **nothing** when nothing changed; `Handle()` takes the thing it would change and compares each fact on its own.
327
+ - Compare against something that cannot lag: a `[Passive]` read model read by key, or the stream's own events, never a materialized read model (it trails the log and is bypassed exactly while rebuilding).
328
+ - Never append a tick, a heartbeat, a trigger event for a reactor, a "last looked" timestamp, telemetry or a non-answer ("pending", "could not decide"); use a job, state machine, command operation or `ICommandPipeline`.
329
+ - An event named `…Changed` records a real change; split a broad `…DetailsChanged` into per-fact events.
330
+ - Specify two behaviors per observation command: the same observation twice appends nothing, and a changed observation appends exactly the change.
331
+
332
+ See the **cratis-chronicle-event-modeling** skill (`references/event-log-hygiene.md`).
333
+
322
334
  ## Projections **[contract]**
323
335
 
324
336
  Projections build read models from **events** (never from other read models). Use the ladder — for adding one to an existing model, invoke the **cratis-chronicle-projection** skill:
@@ -334,6 +346,7 @@ For self models, keep `[ReadModel]`, static `Reduce` methods and queries on one
334
346
  - ⚠️ **AutoMap runs per *event* across every event the projection references — it does not defer to your explicit setters.** A property sourced with `[SetFrom<A>]` can still be silently overwritten when some *other* referenced event `B` happens to carry an identically named property (AutoMap wires `B`'s value on top). Fence the property with property-level **`[NoAutoMap]`** (which pairs with the `[SetFrom]`, not replaces it) so only your explicit setter writes it. `[SetFrom]` does **not** imply this — leaving AutoMap on is what allows the common create-then-rename pattern (a later event updating a property by name-match). No colliding event property name means no `[NoAutoMap]` needed. (An event subscribed only via an aggregate like `[Count]` doesn't auto-map its other properties, so it can't collide.) The analyzer **`CHR0025`** surfaces this collision as an *informational* heads-up (not a warning, because either resolution — add `[NoAutoMap]`, or accept the update — can be correct).
335
347
  - **[contract] `[Nested]`** projects a single nullable child object; place `[FromEvent<T>]` on the nested type (or property-level `[SetFrom<T>]` when the parent shares the event — declaring class-level `[FromEvent<T>]` on both parent and nested type for the same event is a duplicate-registration startup crash).
336
348
  - **[contract] Event-sequence source attributes:** class-level `[EventSequence("name")]`, `[EventLog]`, or `[EventStore("name")]` select where the projection reads from (a named sequence, the explicit default log, or another Chronicle event store / inbox). ⚠️ `[FromEventSequence]` is **removed** — use `[EventSequence("name")]`.
349
+ - **[convention] Counters and aggregates (`[Increment]`, `[Decrement]`, `[Count]`) need clean lifecycle transitions.** They see the event, not the item's previous state, so a close for an already closed item drifts the counter permanently and replay reproduces it. The command that appends the lifecycle event refuses a non-transition and appends nothing; fold the log per event source with the proposed mapping and compare it with the state it summarizes before shipping.
337
350
 
338
351
  ## Constraints **[contract]**
339
352
 
@@ -104,6 +104,20 @@ Do not append an event for derived or aggregate state. Project it from the sourc
104
104
  events instead; an event that records a total is a fact that can disagree with
105
105
  its own inputs.
106
106
 
107
+ ## Only domain facts, never repeats
108
+
109
+ Append only real domain facts. A tick, a heartbeat, a `…Requested`/`…Started`/`…Skipped`/`…Undecided`
110
+ event whose only job is to wake a reactor, a "last looked" timestamp, usage or cost telemetry and a
111
+ non-answer such as "could not decide" are not facts; orchestrate with a durable job, a state machine,
112
+ a reminder, a command operation or `ICommandPipeline` instead. An observation command (webhook, poll,
113
+ sweep, retry, classifier) compares with current state and appends nothing when nothing changed.
114
+ `…Changed` must be a real change, and a counter built from `[Increment]`/`[Decrement]` needs commands
115
+ that refuse non-transitions. Read [references/event-log-hygiene.md](references/event-log-hygiene.md)
116
+ when modeling an event vocabulary, an observation command or a counter, or measuring a log that grows
117
+ faster than the product's activity. Read
118
+ [references/event-log-cleanup-rollout.md](references/event-log-cleanup-rollout.md) when a release removes
119
+ or reshapes many event types and the stored data must be repaired.
120
+
107
121
  ## Public facts and streams that end
108
122
 
109
123
  Declare source vocabulary with `IEventSource`, `[EventSource]` and `[EventStream]`;
@@ -0,0 +1,53 @@
1
+ <!-- Copyright (c) Cratis. All rights reserved. -->
2
+ <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
3
+
4
+ # Rolling out a cleanup that removes or reshapes many event types
5
+
6
+ Read this when a release deletes or reshapes many event types in place (no generations) and the
7
+ stored data must be repaired to match. The mechanics of repair are repository-specific; these are
8
+ the traps that apply to any store.
9
+
10
+ ## Contents
11
+
12
+ - Procedure
13
+ - Traps in the new code
14
+ - Traps in the repair
15
+
16
+ ## Procedure
17
+
18
+ 1. Scale every registrant of the store to zero so nothing appends or registers while data changes.
19
+ 2. Back up every collection the repair writes, before the first write.
20
+ 3. Run a **dry run** and review each count. Give every step a **fuse** (the most documents it may
21
+ touch, sized from the reviewed dry run) so a step over its fuse stops before writing; see
22
+ [guards-and-fuses.md](../../../rules/guards-and-fuses.md). Make the repair idempotent: a re-run skips work already done.
23
+ 4. Apply, then restart the kernel if it caches the event type registry, then scale the application
24
+ back up.
25
+ 5. **Wipe the whole schema registry** for the store rather than a hand-picked subset; the application
26
+ registers every current type again on start. A hand-picked list misses stale registrations and the
27
+ application crash-loops against them.
28
+ 6. Verify the pages that read each reshaped model, then re-run the dry run: every step reports zero.
29
+
30
+ ## Traps in the new code
31
+
32
+ - **A reactor added by the release catches up the whole history on first registration, and
33
+ `[OnceOnly]` does not cover that**: a first catch-up is not a replay. A side-effect reactor (jobs,
34
+ AI calls, external calls) therefore starts at the tail of the log, or its handlers ignore facts
35
+ that predate its registration. Specify that a new side-effect reactor does nothing for history.
36
+ - **Reconciliation sweeps must not decide from read models that are replaying.** A rebuilding model
37
+ looks like "nothing was ever processed" and the sweep starts the work again for everything. Decide
38
+ from the events or a `[Passive]` model, or refuse to run while the model's observer is replaying or
39
+ behind; specify the replaying case. See **cratis-chronicle-reactor**.
40
+ - **Re-recorded facts retrigger downstream consumers.** Recording facts again in a new shape (for
41
+ example a synchronizer re-emitting per-fact events once the broad event was removed) looks like new
42
+ evidence to gates and evaluations and supersedes concluded work. Make consumers follow what the
43
+ evidence says, not that an event arrived, and prefer rewriting the stored events over re-recording.
44
+
45
+ ## Traps in the repair
46
+
47
+ - **Numbers written by `mongosh` are BSON doubles** and break `int64` event schemas. Write integers
48
+ with `NumberLong`.
49
+ - **Every observer whose read model is reset must actually replay.** After a reset, check each
50
+ observer's state and position: a projection left at position 0 without a running replay job leaves
51
+ its read model empty (counter projections were missed this way). Request the replay again and verify.
52
+ - **A dry run is evidence only for the data it saw.** Wait out the quiet period, run it again just
53
+ before applying, and investigate any count that grew before raising a fuse.
@@ -0,0 +1,92 @@
1
+ <!-- Copyright (c) Cratis. All rights reserved. -->
2
+ <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
3
+
4
+ # Event log hygiene
5
+
6
+ An event log that fills with ticks, triggers and repeats makes every projection replay noise
7
+ forever, grows the database without the product doing more, and hides real changes among
8
+ restatements. The log holds domain facts only.
9
+
10
+ ## Contents
11
+
12
+ - What is not an event
13
+ - Orchestration without events
14
+ - Zero repeats in observation commands
15
+ - Event names
16
+ - Counters need clean transitions
17
+ - Measure the log
18
+
19
+ ## What is not an event
20
+
21
+ A fact is something that happened in the domain and that the domain would still care about
22
+ after the process that noticed it is gone. These are not facts:
23
+
24
+ - **Ticks and heartbeats**: "still alive", "checked again", "retried", anything recorded because
25
+ time passed or a loop came round.
26
+ - **Signals**: an event appended so a reactor does something. `…Requested`, `…Started`,
27
+ `…Skipped`, `…Deferred`, `…Undecided`, `…Concluded` and `…Passed` used as triggers describe work
28
+ being asked for or the act of looking, not the world.
29
+ - **"When did we last look"**: a freshness timestamp belongs in a read model, a metric or job
30
+ state. Do not derive it from the time of the last recorded event; that makes it mean "the last
31
+ time anything was recorded".
32
+ - **Telemetry**: usage, token counts, cost, latency. Use metrics or an operational store unless
33
+ the figure is itself a business fact (a billable amount).
34
+ - **Non-answers**: `Pending`, `Computing`, "could not decide", "nothing was judged". The previous
35
+ fact stays; the process logs the non-answer and a later attempt answers.
36
+ - **Retry policy**: how often something was tried and when to try again lives in the retrying
37
+ process.
38
+
39
+ ## Orchestration without events
40
+
41
+ Pick the mechanism that owns the progress, so progress is state of that mechanism, not events:
42
+
43
+ - a **durable job** (Cratis.Orleans jobs, see **cratis-orleans-jobs**) for work with steps, retries and pacing;
44
+ - an **event-sourced state machine** when the lifecycle is itself a domain fact sequence;
45
+ - an **Orleans reminder** to wake up later;
46
+ - a **command operation** (**cratis-arc-command-operation**) for inline work with compensation;
47
+ - **`ICommandPipeline`** (**cratis-arc-command-execution**) when a reactor or job must run a command.
48
+
49
+ ## Zero repeats in observation commands
50
+
51
+ An *observation command* takes input from outside the model's own decisions: a webhook, a poll,
52
+ a sweep, a retry, a classifier result. The same fact is never recorded twice in a row on one stream.
53
+
54
+ - `Handle()` takes the thing it would change and returns no events when they agree. A bare
55
+ `=> new SomethingChanged(...)` is a defect for any command fed by polling, webhooks, retries or
56
+ classifiers.
57
+ - Compare **each fact on its own**, so a change in one does not re-record the others.
58
+ - Compare against something that **cannot lag**: a `[Passive]` read model read by key, or the
59
+ stream's own events. A materialized read model trails the log, so a guard reading it is bypassed
60
+ exactly while it is rebuilding or behind. A stale comparison may cost one extra event; it must
61
+ never drop a change. A poller may instead compare with the last-look store it writes itself.
62
+ - A passive model proves existence only through a flag set by the first event; read
63
+ [vertical-slices.md](../../../rules/vertical-slices.md) "Existence checks" first.
64
+ - Specify two behaviors per observation command: the **same observation twice appends nothing**,
65
+ and a **changed observation appends exactly the changed fact**. A command that can judge
66
+ nothing also gets a specification that "nothing judged" appends nothing.
67
+
68
+ ## Event names
69
+
70
+ `…Changed` is a promise that something changed. An event of that name that can be appended with
71
+ nothing changed is wrong; so is `…Observed` appended on every sighting. Split a broad
72
+ `…DetailsChanged` into one event per fact (`…BodyChanged`, `…LabelsChanged`) so a change in one
73
+ field records one event and consumers subscribe to the facts they care about.
74
+
75
+ ## Counters need clean transitions
76
+
77
+ `[Increment]`/`[Decrement]` projections know the event, not the item's previous state. A close for
78
+ an already closed item, or an add for one already present, drifts the counter permanently, and
79
+ replay reproduces the drift (a "failing builds" counter went deeply negative this way). The command that
80
+ appends a lifecycle event refuses a non-transition and appends nothing. Before shipping a counter,
81
+ fold the log per event source with the proposed mapping and compare the result with the state it
82
+ summarizes; any difference means the events are not clean transitions.
83
+
84
+ ## Measure the log
85
+
86
+ - Set an **event volume budget** from the product's real activity (events per entity lifecycle and
87
+ per day) and alarm on a sustained rate far above it. A rate above budget is a defect to find.
88
+ - Count events per type and per day, then find `(event type, event source)` pairs with **identical
89
+ consecutive events** (same payload, ignoring sequence number and occurred time). Those are repeats a
90
+ missing comparison produced; each pair names the command to fix.
91
+ - Per entity, compare the measured events per lifecycle with the modeled ones; the difference is
92
+ almost always non-facts.
@@ -74,6 +74,12 @@ targets. Two things there are worth knowing before you write anything:
74
74
  `[FromEvent<T>]` is an **object-initializer property**, never a constructor
75
75
  argument: `[Count<TEvent>(ConstantKey = "<key>")]`.
76
76
 
77
+ A counter or aggregate (`[Increment<T>]`, `[Decrement<T>]`, `[Count<T>]`) sees the
78
+ event, not the item's previous state. Its commands must refuse non-transitions
79
+ (a close for an already closed item) or the counter drifts permanently and replay
80
+ reproduces the drift; see **cratis-chronicle-event-modeling**
81
+ (`references/event-log-hygiene.md`).
82
+
77
83
  ## Fluent projections — structured mappings
78
84
 
79
85
  Use `Cratis.Chronicle.Projections.IProjectionFor<TReadModel>` when the mapping
@@ -135,6 +135,14 @@ re-delivers the event as an ordinary observation, and a `[OnceOnly]` handler run
135
135
  again. Catch-up and crash redelivery are not replay either; every ordinary
136
136
  matching event can run, even on the same source. Keep effects idempotent.
137
137
 
138
+ **A reactor new to a store catches up the whole history on first registration, and
139
+ `[OnceOnly]` does not cover that.** For a side-effect reactor (jobs, AI or external
140
+ calls), start the observer at the tail or have the handler ignore facts that
141
+ predate its registration, and specify that history causes nothing. A
142
+ reconciliation sweep that decides from a read model must not run while that model's
143
+ observer is replaying or behind: a rebuilding model looks like "never processed".
144
+ Decide from the events or a `[Passive]` model, and specify the replaying case.
145
+
138
146
  Analyzer **CHR0022** (warning) requires `[OnceOnly]` on a handler that returns
139
147
  event side effects, because a replay would otherwise append duplicates.
140
148
 
@@ -78,8 +78,8 @@ language tabs. Never hand-edit a generated proxy or a synchronized docs copy.
78
78
  ## Version constraints belong in the page; the test log does not
79
79
 
80
80
  A reader needs the versions that change what they install or write. Published
81
- prose can say that a feature needs a minimum release ("Variants need Chronicle
82
- 19.1.0 or later"), pin packages and images in the commands a reader runs, and
81
+ prose can say that a feature needs a minimum release ("This needs Chronicle
82
+ <version> or later"), pin packages and images in the commands a reader runs, and
83
83
  name the one release where behavior changed.
84
84
 
85
85
  Keep the author's verification record out of the page. Exact SDK builds, image
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.53.0",
3
+ "version": "7.54.0",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [