Expand description
Lazy reactive primitives with dependency tracking and cache invalidation.
§Threading contract
Context is intentionally single-threaded. It owns RefCell graph state
and non-Send callbacks, so sharing a live context across OS threads is
rejected by the type system. Create independent contexts per thread today;
use [ThreadSafeContext] when a single reactive graph must be shared across
threads.
ⓘ
use lazily::Context;
let ctx = Context::new();
let slot = ctx.computed(|_| 1);
std::thread::spawn(move || ctx.get(&slot));§Async contract
[ThreadSafeContext] can be used from async runtimes, but slot and effect
callbacks are still synchronous. Async computations need a separate API
because futures introduce in-flight state, cancellation, stale completion,
and dependency tracking across .await.
ⓘ
use lazily::ThreadSafeContext;
let ctx = ThreadSafeContext::new();
let pending = ctx.computed(|_| async { 1usize });
// The graph does not await async slot callbacks.
let _ = ctx.get(&pending);Re-exports§
pub use reactive_graph::AsyncReactiveGraph;pub use reactive_graph::ReactiveGraph;pub use reactive_graph::SyncReactiveGraph;pub use reactive_graph::Teardown;pub use reactive_graph::ThreadSafeReactiveGraph;pub use statechart::ChartBuilder;pub use statechart::StateBuilder;pub use statechart::TransitionBuilder;pub use statechart::ChartDef;pub use statechart::StateChart;
Modules§
- reactive_
graph - Capability traits over
lazily’s execution models (#lzspecedgeindex). - statechart
- Full Harel/SCXML state charts — native Rust, conforming to
lazily-spec/docs/state-charts.md.
Macros§
- define_
schema - Define a schema marker type for typed lazily contexts.
Structs§
- Alignment
- The alignment of a new block sequence against an old one.
- Awareness
Cell - Reactive typed ephemeral broadcast (cursors / selections): last-writer-per-peer with a TTL.
- Backpressure
Policy - Reactive backpressure limits (analysis §4.4). Every field is a cell, so an
operator or an adaptive controller retunes it live and dependent relays react.
Hysteresis (
high_water≠low_water) prevents flapping. - Barrier
Cell - Reactive wait-for-N gate.
QuorumCellis a barrier withrequired = total / 2 + 1. - Barrier
Core - Wait-for-N gate compute core over distinct arriving peers.
- Block
- A text block, optionally carrying an in-band anchor/id.
- Bulkhead
Cell - Reactive bulkhead: projects
permits_in_useonto aCell. - Bulkhead
Core - Bounded isolation-pool compute core.
- Causal
Receipt - One receipt event for a command/effect causation id.
- Causal
Receipts - Wire body for the externally-tagged
CausalReceiptsenvelope. - Cell
Tree - A node in an ordered, stably-keyed reactive tree (
#lzordtree). - Circuit
Breaker Cell - Reactive circuit breaker: projects the
stateonto aCell. - Circuit
Breaker Core - Circuit-breaker compute core: a sliding window of outcomes trips
Closed → Openatfailure_threshold;Open → HalfOpenat the deadline; a HalfOpen success closes, a failure re-opens. - Compute
- A fortified, non-escapable compute context (
#lzcellkernel). - Computed
- A typed handle to a computed cell within a
Context— a node computed from upstream. Lazy by default;computed().eager()makes it eager (an eager computed cell). - Context
- Container for all reactive nodes. Owns allocations; uses a single
interior-mutability cell (
RefCell) for single-threaded use. - Cron
Cell - Reactive cron source: same reactive contract as
IntervalCell. - Cron
Core - Pattern-periodic compute core: a tick
m ≥ 1fires iffm mod cycle ∈ offsets. Structurally an interval with a match set — a cron expression’s shape. The match count in(cursor, now]is computed arithmetically, so a largenowjump isO(offsets). - Deadline
Cell - Reactive value + deadline: flips
Live(v) → Expired(v)at the deadline, preserving the value; thestatereader invalidates only on the expiry edge. - Deadline
Core - Deadline compute core (bytes-eligible): a
TimerCoreover the deadline. The value lives in the reactive cell (PyObjectPayload). - Debounce
Cell - Reactive debounce over any
Reactive<T>source. - Debounce
Core - Debounce compute core: coalesce inputs (KeepLatest) and emit the latest value
only after
quietticks with no new input — every input resets the deadline. - Discovery
Cell - Reactive service discovery.
- Discovery
Core - Service-discovery core:
service → (endpoint, owner). A peer’s departure (evict) removes its endpoints. - Drain
Exhaustion - Report produced when an effect drain exhausts its iteration budget.
- Effect
- A typed handle to an effect within a
Context. - Ephemeral
Cell - Reactive single-value ephemeral cell.
- Ephemeral
Core - Single-value auto-expiry compute core — “the last value seen in window N”.
- Ephemeral
MapCore - Per-key ephemeral map with TTL eviction — the shared core behind presence and
awareness. Each entry carries an expiry;
tickevicts lapsed entries. - Ephemeral
Value - A newtype witnessing the
Ephemeralmarker (used by the compile-fail doctest and by ephemeral payloads). - Expiry
Policy - TTL / deadline expiry. Drops elements whose age exceeds
ttlagainst a logical clock. Lossy-by-age (explicit); used to shed cold data. - Framed
Transport - A framed transport — models
CrossThread/Ipc/Ws: ops are delivered in bounded frames of at mostframe_size(an MTU / batch boundary). Differentframe_sizes are different framings of the same op stream. - Health
Cell - Reactive health: projects the aggregate onto a
Cellfor/health. - Health
Core - Composed liveness-probe core. Each probe reports
upand whether it iscritical. - InProc
Transport InProc— direct delivery: every buffered op is handed over in one frame.- Inbox
- The transport → app receive side (analysis §4.7). Cannot block the remote directly; backpressure is a credit meter the app replenishes.
- Interval
Cell - Reactive periodic interval: projects
IntervalCore’s fire count onto a cell (invalidates only whencountchanges). - Interval
Core - Periodic compute core: fire boundaries at
period, 2·period, …. A tick counts every boundary in(frontier, now], so a jump past several boundaries counts them all. - Keep
Latest - Keep-latest (right-zero) band:
old ⊕ op = op. Associative and idempotent, not commutative. This is the merge behind a plainCell—Cell ≡ MergeCell<KeepLatest>(analysis §4.0). Positional last-writer-wins; distinct from timestampedLww(which is commutative). - Keyed
Relay - Case 18 — keyed sharding. N independent relays keyed by
K; an op routes to its key’s shard. Merging across shards requires a commutative merge (shards accumulate in parallel, order across keys is not defined). The converged per-key state equals a single relay per key. - Lcg
- A small deterministic LCG (SplitMix64-style) — no external
randdependency, reproducible for the distribution property test. - Leader
Cell - Reactive leadership over a lease from node
me’s perspective. - Lease
Cell - Reactive lease: projects the holder onto a
Cell(invalidates on holder change). - Lease
Core - Single-writer lease authority with a monotone fencing token.
- Lock
Cell - Reactive distributed mutex over a lease + fencing token.
- Manual
Clock - A monotone logical clock a manual runtime (game loop, test) can own to drive
sources.
advanceclamps backwards moves sonowis always non-decreasing. - Max
- Max semilattice:
old ⊕ op = max(old, op). Associative, commutative, and idempotent — the full-CRDT corner for a totally-ordered value. - Membership
Cell - Reactive membership: drives a
MembershipCoreand projects the alive set onto aCellso thePeerSetinvalidates only on a set change. - Membership
Config - Tunables for the failure detector + SWIM state machine.
- Membership
Core - The pure membership compute core: the SWIM state machine over a keyed peer
map, driven by heartbeats and a logical clock. Emits
PeerChangeEvents. - OpId
- A globally-unique, totally-ordered id for one inserted character.
- Outbox
- The app → transport send side (analysis §4.7). Backpressures the local
producer directly via
is_full. - PhiAccrual
- Phi-accrual failure detector over a sliding window of heartbeat
inter-arrival times.
phiis bit-portable across bindings via the Akka-style logistic approximation of the normal CDF. - Presence
Cell - Reactive per-peer presence: heartbeat-kept, membership- and TTL-evicted.
- Priority
Storage - Case 11 — priority egress. A max-priority storage: ingress carries a
priority; egress pops the highest priority first (not FIFO). Reordering,
so sound for a commutative merge downstream (
reorder_adjacent). - Probabilistic
Sample Cell - Reactive probabilistic sampler; owns an injectable
SampleRng. - Probabilistic
Sample Core - Probabilistic (tail) sampling compute core — the plan’s only new algorithm.
A draw in
[0, 1)passes iffdraw < rate. - Queue
Cell - A reactive FIFO queue — SPSC primitive with an MPSC usage rule
(
#lzqueue). - Queue
Reader Handles - Handles to all five reader-kinds of a
QueueCell, for effects that need to subscribe to several reader kinds at once. The four derived reader-kinds are demand-drivenComputeds;closedis aSourcebecause it is a direct input (set byclose), not a derived value. - Rate
Policy - Rate-limited egress (token bucket). A drain is permitted only when a
token is available; ingress backpressures when the bucket is empty. Refilled
refill_per_ticktokens per logical tick, capped atcapacity. - RawFifo
- Raw FIFO append:
old ⊕ op = old ++ op. Associative (concatenation is a free semigroup) but neither commutative nor idempotent — order and multiplicity are meaning (analysis §2,protocol.md§176). ARawFifostream cannot conflate; its only bounded-lossless option is Spill. - Reactive
Map - A keyed reactive collection generic over the entry handle kind
H: a hash map ofK -> Hwith reactive membership and independently-tracked per-entry nodes. - Readiness
Cell - Reactive readiness: projects
readyonto aCellfor/ready. - Readiness
Core - Composed readiness-probe core: ready iff every condition holds.
- Receipt
Projection - Folded receipt projection.
- Relay
Cell - The algebra-typed conflating relay (Phase 2, in-proc core).
- Retry
Policy Cell - Reactive retry policy: projects the current delay onto a
Cell. - Retry
Policy Core - Exponential-backoff compute core:
delay(attempt) = min(cap, base·2^attempt), saturating tocapon shift overflow. - Sample
Cell - Reactive sampler over any
Reactive<T>source. - Sample
Core - Deterministic sampling compute core.
- SemTree
- A memoized semantic derivation over a
CellTree: onememoslot per node, each folding(node value, child derived values) -> D. - Semaphore
Cell - Reactive semaphore: projects
permits_availableonto aCell. - Semaphore
Core - Bounded permit pool compute core.
- Service
Registry - Reactive durable service registry.
- Service
Registry Core - Durable service-registry core: an ordered log (the
DurableOutboxpattern) whose left-fold is the projection, so replay reconstructs it. - Session
Core - Gap-based sessionization compute core.
- Session
Window - Reactive session window (
push(now, v)+flush(now)). - SetUnion
- Set-union (grow-only) semilattice:
old ⊕ op = old ∪ op. Associative, commutative, idempotent. The unordered-at-least-once tier (analysis §2). - Sliding
Core - Count-based sliding window compute core (fold-recompute, correct for any associative merge).
- Sliding
Window - Reactive window over any stream; projects the last emitted aggregate.
- Source
- A typed handle to a source cell within a
Context— a node written from outside, folding accumulated writes under merge policyM(defaultKeepLatest, i.e. last-writer-wins replace).Source<T>is a plain input cell;Source<T, Sum>folds additively; etc. - Spill
Page - One immutable cold page: a coalesced window summary plus its manifest entry.
- Spill
Store - A paged durable tail for a
RelayCell(Phase 3, in-memory reference backend). - State
Machine - A finite state machine backed by a reactive
Context. - Sum
- Additive commutative monoid:
old ⊕ op = old + op. Associative and commutative, not idempotent (re-adding double-counts). The unordered-exactly-once tier (analysis §2): a running counter / sum. - Teardown
Scope - A teardown scope over a
Context: nodes created through it are disposed when it drops. See [Context::child]. - Text
Crdt - A character-granular, mergeable text buffer for concurrent free-text edits.
- TextOp
- One text-CRDT element in a serializable, transport-ready form (#lztextsync).
- Throttle
Cell - Reactive throttle over any
Reactive<T>source. - Throttle
Core - Throttle compute core: at most one emit per
window. - Timeout
Cell - Reactive timeout: projects
is_timed_outonto aCell. - Timeout
Core - Deadline-bounded call compute core.
- Timer
Cell - Reactive single-shot timer: projects
TimerCore’s fire edge onto a cell sohas_fired/valuedependents invalidate only on the fire (idempotent). - Timer
Core - Single-shot compute core:
None → Some(())at the first tick withnow ≥ fire_at; fires exactly once (idempotent thereafter). - Topic
Cell - A broadcast topic: every subscriber receives every published element using
an independent, non-destructive cursor (
#lztopiccell). - Topic
Snapshot - Durable state required to recreate a
TopicCellwithout moving cursors. - Topic
Subscription Snapshot - Public, serializable-in-spirit state for one topic subscription.
- Tumbling
Count Core - Count-based tumbling window compute core.
- Tumbling
Count Window - Reactive window over any stream; projects the last emitted aggregate.
- Tumbling
Time Core - Time-based tumbling window compute core.
- Tumbling
Time Window - Reactive time-tumbling window (
push(now, v)+tick(now)). - Typed
Cell Factory Source - Typed
Cell Handle - A cell handle bound to a typed context schema.
- Typed
Cell Handle Source - Typed
Context - A single-threaded lazily context tagged with a schema/context-family type.
- Typed
Context Ref - Read-only typed context view passed into typed slot computations.
- Typed
Slot Factory Source - Typed
Slot Handle - A slot handle bound to a typed context schema.
- Typed
Slot Handle Source - VecDeque
Storage - The reference
QueueStoragebackend: aVecDeque-backed FIFO, optionally bounded. - Window
Policy - Time-windowed coalescence (debounce/throttle flush groups). Accumulates
ops into the current window; the window flushes when it reaches
window_opsops or on an explicittick(the interval boundary). Because a window is just a flush group, associativity keeps the converged state unchanged. - Work
Queue Cell - A pull-based work queue where N consumers compete for exclusive delivery.
- Work
Queue Dead Letter - A terminal poison-message record.
- Work
Queue Delivery - One exclusive, worker-owned delivery lease.
- Work
Queue Item - A stable queued item.
attemptscounts leases already issued for it. - Work
Queue Reader Handles - Independent reactive reader kinds for queue lifecycle state.
Enums§
- Block
Key - A manufactured identity key for a block: an anchor id, or a content hash of the normalized text.
- Bound
Dim - What a bound measures (analysis §4.4). The Phase-2 core meters
Count; the other dimensions are wired as the metering closure evolves. - Breaker
State - Circuit-breaker state.
- Deadlined
- A value paired with a liveness state:
Liveuntil its deadline, thenExpired— the value is preserved across the flip. - DiffOp
- A single reconciliation operation, keyed by stable id.
- Entry
Kind - Which kind of reactive node a
ReactiveMapentry is — the handle-kind axis the map abstracts over. - Health
- Composed health status (worst component dominates).
- Ingress
Outcome - The outcome of a single
ingressop. - Leader
Role - The local node’s role, derived from lease ownership.
- Match
- How a new block relates to the old sequence.
- Overflow
- The action taken when the hot head crosses
high_water(analysis §4.4). - Peer
Change Event - A diff event over the membership cell.
- Peer
State - Per-peer liveness state (SWIM).
- Queue
PopError - Failure modes for
QueueStorage::try_pop/QueueCell::try_pop. - Queue
Push Error - Failure modes for
QueueStorage::try_push/QueueCell::try_push. - Receipt
Apply Status - Result of applying a receipt to a projection.
- Receipt
Message - Externally-tagged receipt wire message.
- Receipt
Outcome - Generic receipt outcomes.
- Registry
Op - A durable registry op (the ordered log entry).
- Relay
Config Error - Why a construction/merge-swap was rejected (analysis §4.3 flag validation).
- Sample
Mode - Sampling mode for
SampleCore. - Spill
Mode - How spilled windows are laid out on the durable tail (analysis §6).
- Throttle
Edge - Which edge of the window a
ThrottleCoreemits on. - Topic
Durability - Whether a
TopicCellsubscription survives disconnects and participates in the retention frontier. - Topic
Subscribe Outcome - Result of subscribing a stable identity.
- Work
Queue Dead Letter Reason - Why an item exhausted its delivery budget.
Traits§
- Compute
Ops - The compute-time operations subset of the
ContextAPI (#lzcellkernel) — exactly the operations a compute/effect closure may perform (get/set/source/cell/computed/computed_ripple_when/slot/effect/batch/get_rc/read_value/dispose_node), and no more. The rest ofContext— revision control, degree/graph introspection, teardown-scope creation, instrumentation, IPC hooks — is deliberately off this trait. - Durable
- Marker: a value that may be written to the durable outbox.
- Effect
Callback Result - Return value accepted by
Context::effect. - Ephemeral
- Marker: a value on the ephemeral plane. MUST NOT be persisted.
- Graph
Node - A node in a
Context’s reactive graph, addressed by one of its handles. - MapHandle
- The entry-handle axis a
ReactiveMapabstracts over. Implemented bySource(input cells) andComputed(derived slots) only — the two node kinds of the cell model. Sealed: bindings do not add new kinds. - Merge
Policy - The coalescence algebra: an associative fold
⊕ : T × T → T. - Queue
Storage - Pluggable FIFO storage backend for a
QueueCell. - Read
- A handle readable through a context’s
get(#lzcellkernel), generic over the context typeCtx. - Sample
Rng - An injectable RNG so probabilistic sampling is deterministic under a fixed
seed.
next_f64yields a draw in[0, 1). - Timeline
Source - A pure temporal compute core driven by a monotone logical clock.
- Transport
- A pluggable delivery mechanism for relay ops.
deliverenqueues;pollpulls the next transport-defined frame (a batch of ready ops). Framing is the transport’s business; the relay merges whatever each frame delivers. - Typed
Context Family - Extracts the schema marker from a typed context family.
- Typed
Factory Context - Context-like typed views that can memoize decorator-style slot/cell factories.
- Typed
Get - Values that can be read through a
TypedContextwithTypedContext::get. - Typed
GetRef - Values that can be read through a
TypedContextRefwithTypedContextRef::get. - Typed
Set - Values that can be written through a
TypedContextwithTypedContext::set. - Write
- A handle writable through a context’s
set(#lzcellkernel), generic over the context typeCtx.
Functions§
- align
- Align
newagainstold, manufacturing identity. Exact key matches (anchor, then content hash) carry identity directly; remaining new blocks are matched to the most-similar unmatched old block above [EDIT_THRESHOLD] (nearest index breaks ties) and classifiedEdited, elseInserted. Unmatched old blocks areremoved. - apply_
to_ map - Apply a reconcile op set to a live
CellMap, driving it to the new shape with minimal invalidation: stable entries are untouched (their value cells keep their dependents cached), moves useCellMap::move_to(#lzcellmove), and only changed values are written. - apply_
to_ tree - Apply a reconcile op set to one level of a live
CellTree. - assign_
stable_ keys - One stable key per new block, suitable as the
#lzkeyreconkey set. - block_
key - The identity key for a block: its anchor if present, else a content hash.
- parse_
blocks - Re-parse merged text into paragraph
Blocks (split on blank lines). This is the “re-derive the tree from CRDT-merged text” step: feed the result throughassign_stable_keys+reconcileto project the merged text onto the keyed tree. - reconcile
- Reconcile
old→newby stable key, returning the minimal op set. - similarity
- Word-LCS similarity ratio in
[0,1]:2·|LCS| / (|a|+|b|)over whitespace tokens (the difflib/Myers-style ratio). 1.0 = identical token sequence.
Type Aliases§
- CellMap
- A keyed input-cell collection: every entry is a settable
Source<V>. - PeerSet
- The derived reactive alive-peer set — a
Cell<BTreeSet<P>>handle exposed byMembershipCell::peer_set_cell. - SlotMap
- A keyed derived-slot collection: every entry is a
Computed<V>whose value is derived.get_or_insert_withmints a slot on first access (lazy materialization);materialize_allpre-mints the keyset (eager). A slot’s value is derived, soSlotMaphas noset. - Text
Version Vector - A version vector: the greatest
OpIdcounter observed per originating peer — the compact frontier a replica sends so a partner can compute exactly the ops it lacks (#lztextsync). Serde-friendly (integer keys), unlike the raw element map keyed byOpId.
Attribute Macros§
- cell
- Deprecated v1 spelling of
source. Kept as a construction-sugar alias; prefer#[lazily::source]. - computed
- Declare a computed (derived) cell factory. Canonical construction sugar of
the Cell kernel (
#lzcellkernel) — the guarded derived cell. - slot
- Deprecated v1 spelling of
computed. Kept as a construction-sugar alias; prefer#[lazily::computed]. - source
- Declare a source (writable) cell factory. Canonical construction sugar of
the Cell kernel (
#lzcellkernel) — the source cell written from outside.