# Threading contract

Every Ducky store follows the rules below. The same text is in the XML docs (remarks) of `IDispatcher`, so your IDE shows it on that interface.

1. `Dispatch`, `DispatchAsync`, `Restore`, `Select`, `State`, `InitializeAsync` and `WhenIdleAsync` may be called from any thread at any time, including from inside a reducer, a middleware hook, a subscriber or an effect, with two exceptions for `WhenIdleAsync`: from a non-`LongRunning` effect run of the same store it throws `InvalidOperationException` (the run counts itself as running, so the wait could never end; another store's run is an unrelated caller, §6.5), and awaited from a middleware's `InitializeAsync` it waits until `InitTimeout` (idle requires initialization). None of them ever blocks waiting for another thread, except that concurrent first users wait for the one-time construction of effects and middleware (whose constructors must not block).
2. Actions are reduced one at a time, never concurrently, in the order in which they were enqueued, with one exception: user actions dispatched before initialization are replayed after `StoreInitialized`, behind library actions enqueued later (rule 5). Actions from one thread keep their relative order.
3. If no drain is active, the calling thread becomes the drainer and reduces the whole queue inline on its own thread and synchronization context, including actions enqueued by other threads, before its call returns. Otherwise the call enqueues and returns immediately. **A synchronous `Dispatch` gives read-your-writes only when the caller became the drainer.** Use `await DispatchAsync(a)` for read-after-write. It completes after `a` is reduced, not after its effects. Use `WhenIdleAsync()` (or `TestStore.Settled()`) to also wait for effects.
4. `DispatchAsync` never faults or cancels, and never completes inline on the drainer. At run time no member throws for a reducer, middleware or effect failure. The only exceptions are programmer errors, thrown synchronously, before any task exists: `ArgumentNullException` (a null argument); the store's cached `DuckyConfigurationException` (effects or middleware could not be constructed, DUCKY353); `ArgumentOutOfRangeException` from `Restore` with a non-restore origin; `InvalidOperationException` from a constructor that uses the store during materialization; and misuse, `DuckyConfigurationException` DUCKY351 (a `SliceStore` used before the store attached it), `InvalidOperationException` DUCKY352 (`Select` after a component's first render) and `InvalidOperationException` from `WhenIdleAsync` (or `TestStore.Settled`) called inside a non-`LongRunning` effect run (`WhenIdle_FromNonLongRunningEffectRun_ThrowsNotHangs`). **Never block on it** (`.Result`, `.Wait()`, `GetAwaiter().GetResult()`): if the caller is the drainer, that is a self-deadlock. DUCKY010 flags it.
5. Until the store is initialized, user actions are buffered and replayed in order after `StoreInitialized`. Initialization starts automatically on the first dispatch, select, `State` read or idle wait.
6. Reducers, middleware hooks, subscriber callbacks, `Select` `onChange` callbacks and the synchronous part of effects run on the draining thread. On Blazor Server that may be a thread-pool thread. Ducky.Blazor's components marshal to the renderer themselves. Custom callbacks must marshal UI work through `InvokeAsync`.
7. Reducers, `SliceStore` mutators and selector projectors must be pure. Projectors may run concurrently on two threads.
8. A dispatch or restore made while its parent action is being processed (synchronously) is a child with depth + 1, whatever its origin. Chains deeper than `MaxDispatchDepth` (64) are dropped with `ReducerFailed(DispatchLoopException)`. A dispatch made after an effect has really yielded, or while the store is idle, starts a new chain.
9. `State` reads take no lock and always return a complete, immutable snapshot.
10. After disposal begins, dispatches are ignored and complete with `Disposed`, and effect tokens are cancelled.

## Known liveness ceilings

Two limits are known and accepted in 2.0. Each names the change that would lift it.

- the drainer drains other producers' actions with no bound, so on Blazor Server a renderer-thread caller that became the drainer can be held for as long as a hot background producer (a fast poller, a reactive stream) keeps the queue non-empty. "Never blocks" holds; latency does not. Upgrade path: a per-drain action budget that hands the rest to a thread-pool drainer.
- the depth guard bounds linear synchronous loops only. A synchronous fan-out (each action dispatches two children) grows the FIFO queue as 2^depth and exhausts memory long before depth 64. Upgrade path: a per-correlation cap on synchronous-chain actions that drops with `DispatchLoopException`.
