Skip to main content

Crate lazily

Crate lazily 

Source
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.
AwarenessCell
Reactive typed ephemeral broadcast (cursors / selections): last-writer-per-peer with a TTL.
BackpressurePolicy
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_waterlow_water) prevents flapping.
BarrierCell
Reactive wait-for-N gate. QuorumCell is a barrier with required = total / 2 + 1.
BarrierCore
Wait-for-N gate compute core over distinct arriving peers.
Block
A text block, optionally carrying an in-band anchor/id.
BulkheadCell
Reactive bulkhead: projects permits_in_use onto a Cell.
BulkheadCore
Bounded isolation-pool compute core.
CausalReceipt
One receipt event for a command/effect causation id.
CausalReceipts
Wire body for the externally-tagged CausalReceipts envelope.
CellTree
A node in an ordered, stably-keyed reactive tree (#lzordtree).
CircuitBreakerCell
Reactive circuit breaker: projects the state onto a Cell.
CircuitBreakerCore
Circuit-breaker compute core: a sliding window of outcomes trips Closed → Open at failure_threshold; Open → HalfOpen at 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.
CronCell
Reactive cron source: same reactive contract as IntervalCell.
CronCore
Pattern-periodic compute core: a tick m ≥ 1 fires iff m 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 large now jump is O(offsets).
DeadlineCell
Reactive value + deadline: flips Live(v) → Expired(v) at the deadline, preserving the value; the state reader invalidates only on the expiry edge.
DeadlineCore
Deadline compute core (bytes-eligible): a TimerCore over the deadline. The value lives in the reactive cell (PyObjectPayload).
DebounceCell
Reactive debounce over any Reactive<T> source.
DebounceCore
Debounce compute core: coalesce inputs (KeepLatest) and emit the latest value only after quiet ticks with no new input — every input resets the deadline.
DiscoveryCell
Reactive service discovery.
DiscoveryCore
Service-discovery core: service → (endpoint, owner). A peer’s departure (evict) removes its endpoints.
DrainExhaustion
Report produced when an effect drain exhausts its iteration budget.
Effect
A typed handle to an effect within a Context.
EphemeralCell
Reactive single-value ephemeral cell.
EphemeralCore
Single-value auto-expiry compute core — “the last value seen in window N”.
EphemeralMapCore
Per-key ephemeral map with TTL eviction — the shared core behind presence and awareness. Each entry carries an expiry; tick evicts lapsed entries.
EphemeralValue
A newtype witnessing the Ephemeral marker (used by the compile-fail doctest and by ephemeral payloads).
ExpiryPolicy
TTL / deadline expiry. Drops elements whose age exceeds ttl against a logical clock. Lossy-by-age (explicit); used to shed cold data.
FramedTransport
A framed transport — models CrossThread/Ipc/Ws: ops are delivered in bounded frames of at most frame_size (an MTU / batch boundary). Different frame_sizes are different framings of the same op stream.
HealthCell
Reactive health: projects the aggregate onto a Cell for /health.
HealthCore
Composed liveness-probe core. Each probe reports up and whether it is critical.
InProcTransport
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.
IntervalCell
Reactive periodic interval: projects IntervalCore’s fire count onto a cell (invalidates only when count changes).
IntervalCore
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.
KeepLatest
Keep-latest (right-zero) band: old ⊕ op = op. Associative and idempotent, not commutative. This is the merge behind a plain CellCell ≡ MergeCell<KeepLatest> (analysis §4.0). Positional last-writer-wins; distinct from timestamped Lww (which is commutative).
KeyedRelay
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 rand dependency, reproducible for the distribution property test.
LeaderCell
Reactive leadership over a lease from node me’s perspective.
LeaseCell
Reactive lease: projects the holder onto a Cell (invalidates on holder change).
LeaseCore
Single-writer lease authority with a monotone fencing token.
LockCell
Reactive distributed mutex over a lease + fencing token.
ManualClock
A monotone logical clock a manual runtime (game loop, test) can own to drive sources. advance clamps backwards moves so now is always non-decreasing.
Max
Max semilattice: old ⊕ op = max(old, op). Associative, commutative, and idempotent — the full-CRDT corner for a totally-ordered value.
MembershipCell
Reactive membership: drives a MembershipCore and projects the alive set onto a Cell so the PeerSet invalidates only on a set change.
MembershipConfig
Tunables for the failure detector + SWIM state machine.
MembershipCore
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. phi is bit-portable across bindings via the Akka-style logistic approximation of the normal CDF.
PresenceCell
Reactive per-peer presence: heartbeat-kept, membership- and TTL-evicted.
PriorityStorage
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).
ProbabilisticSampleCell
Reactive probabilistic sampler; owns an injectable SampleRng.
ProbabilisticSampleCore
Probabilistic (tail) sampling compute core — the plan’s only new algorithm. A draw in [0, 1) passes iff draw < rate.
QueueCell
A reactive FIFO queue — SPSC primitive with an MPSC usage rule (#lzqueue).
QueueReaderHandles
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-driven Computeds; closed is a Source because it is a direct input (set by close), not a derived value.
RatePolicy
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_tick tokens per logical tick, capped at capacity.
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). A RawFifo stream cannot conflate; its only bounded-lossless option is Spill.
ReactiveMap
A keyed reactive collection generic over the entry handle kind H: a hash map of K -> H with reactive membership and independently-tracked per-entry nodes.
ReadinessCell
Reactive readiness: projects ready onto a Cell for /ready.
ReadinessCore
Composed readiness-probe core: ready iff every condition holds.
ReceiptProjection
Folded receipt projection.
RelayCell
The algebra-typed conflating relay (Phase 2, in-proc core).
RetryPolicyCell
Reactive retry policy: projects the current delay onto a Cell.
RetryPolicyCore
Exponential-backoff compute core: delay(attempt) = min(cap, base·2^attempt), saturating to cap on shift overflow.
SampleCell
Reactive sampler over any Reactive<T> source.
SampleCore
Deterministic sampling compute core.
SemTree
A memoized semantic derivation over a CellTree: one memo slot per node, each folding (node value, child derived values) -> D.
SemaphoreCell
Reactive semaphore: projects permits_available onto a Cell.
SemaphoreCore
Bounded permit pool compute core.
ServiceRegistry
Reactive durable service registry.
ServiceRegistryCore
Durable service-registry core: an ordered log (the DurableOutbox pattern) whose left-fold is the projection, so replay reconstructs it.
SessionCore
Gap-based sessionization compute core.
SessionWindow
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).
SlidingCore
Count-based sliding window compute core (fold-recompute, correct for any associative merge).
SlidingWindow
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 policy M (default KeepLatest, i.e. last-writer-wins replace). Source<T> is a plain input cell; Source<T, Sum> folds additively; etc.
SpillPage
One immutable cold page: a coalesced window summary plus its manifest entry.
SpillStore
A paged durable tail for a RelayCell (Phase 3, in-memory reference backend).
StateMachine
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.
TeardownScope
A teardown scope over a Context: nodes created through it are disposed when it drops. See [Context::child].
TextCrdt
A character-granular, mergeable text buffer for concurrent free-text edits.
TextOp
One text-CRDT element in a serializable, transport-ready form (#lztextsync).
ThrottleCell
Reactive throttle over any Reactive<T> source.
ThrottleCore
Throttle compute core: at most one emit per window.
TimeoutCell
Reactive timeout: projects is_timed_out onto a Cell.
TimeoutCore
Deadline-bounded call compute core.
TimerCell
Reactive single-shot timer: projects TimerCore’s fire edge onto a cell so has_fired/value dependents invalidate only on the fire (idempotent).
TimerCore
Single-shot compute core: None → Some(()) at the first tick with now ≥ fire_at; fires exactly once (idempotent thereafter).
TopicCell
A broadcast topic: every subscriber receives every published element using an independent, non-destructive cursor (#lztopiccell).
TopicSnapshot
Durable state required to recreate a TopicCell without moving cursors.
TopicSubscriptionSnapshot
Public, serializable-in-spirit state for one topic subscription.
TumblingCountCore
Count-based tumbling window compute core.
TumblingCountWindow
Reactive window over any stream; projects the last emitted aggregate.
TumblingTimeCore
Time-based tumbling window compute core.
TumblingTimeWindow
Reactive time-tumbling window (push(now, v) + tick(now)).
TypedCellFactorySource
TypedCellHandle
A cell handle bound to a typed context schema.
TypedCellHandleSource
TypedContext
A single-threaded lazily context tagged with a schema/context-family type.
TypedContextRef
Read-only typed context view passed into typed slot computations.
TypedSlotFactorySource
TypedSlotHandle
A slot handle bound to a typed context schema.
TypedSlotHandleSource
VecDequeStorage
The reference QueueStorage backend: a VecDeque-backed FIFO, optionally bounded.
WindowPolicy
Time-windowed coalescence (debounce/throttle flush groups). Accumulates ops into the current window; the window flushes when it reaches window_ops ops or on an explicit tick (the interval boundary). Because a window is just a flush group, associativity keeps the converged state unchanged.
WorkQueueCell
A pull-based work queue where N consumers compete for exclusive delivery.
WorkQueueDeadLetter
A terminal poison-message record.
WorkQueueDelivery
One exclusive, worker-owned delivery lease.
WorkQueueItem
A stable queued item. attempts counts leases already issued for it.
WorkQueueReaderHandles
Independent reactive reader kinds for queue lifecycle state.

Enums§

BlockKey
A manufactured identity key for a block: an anchor id, or a content hash of the normalized text.
BoundDim
What a bound measures (analysis §4.4). The Phase-2 core meters Count; the other dimensions are wired as the metering closure evolves.
BreakerState
Circuit-breaker state.
Deadlined
A value paired with a liveness state: Live until its deadline, then Expired — the value is preserved across the flip.
DiffOp
A single reconciliation operation, keyed by stable id.
EntryKind
Which kind of reactive node a ReactiveMap entry is — the handle-kind axis the map abstracts over.
Health
Composed health status (worst component dominates).
IngressOutcome
The outcome of a single ingress op.
LeaderRole
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).
PeerChangeEvent
A diff event over the membership cell.
PeerState
Per-peer liveness state (SWIM).
QueuePopError
Failure modes for QueueStorage::try_pop / QueueCell::try_pop.
QueuePushError
Failure modes for QueueStorage::try_push / QueueCell::try_push.
ReceiptApplyStatus
Result of applying a receipt to a projection.
ReceiptMessage
Externally-tagged receipt wire message.
ReceiptOutcome
Generic receipt outcomes.
RegistryOp
A durable registry op (the ordered log entry).
RelayConfigError
Why a construction/merge-swap was rejected (analysis §4.3 flag validation).
SampleMode
Sampling mode for SampleCore.
SpillMode
How spilled windows are laid out on the durable tail (analysis §6).
ThrottleEdge
Which edge of the window a ThrottleCore emits on.
TopicDurability
Whether a TopicCell subscription survives disconnects and participates in the retention frontier.
TopicSubscribeOutcome
Result of subscribing a stable identity.
WorkQueueDeadLetterReason
Why an item exhausted its delivery budget.

Traits§

ComputeOps
The compute-time operations subset of the Context API (#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 of Context — 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.
EffectCallbackResult
Return value accepted by Context::effect.
Ephemeral
Marker: a value on the ephemeral plane. MUST NOT be persisted.
GraphNode
A node in a Context’s reactive graph, addressed by one of its handles.
MapHandle
The entry-handle axis a ReactiveMap abstracts over. Implemented by Source (input cells) and Computed (derived slots) only — the two node kinds of the cell model. Sealed: bindings do not add new kinds.
MergePolicy
The coalescence algebra: an associative fold ⊕ : T × T → T.
QueueStorage
Pluggable FIFO storage backend for a QueueCell.
Read
A handle readable through a context’s get (#lzcellkernel), generic over the context type Ctx.
SampleRng
An injectable RNG so probabilistic sampling is deterministic under a fixed seed. next_f64 yields a draw in [0, 1).
TimelineSource
A pure temporal compute core driven by a monotone logical clock.
Transport
A pluggable delivery mechanism for relay ops. deliver enqueues; poll pulls the next transport-defined frame (a batch of ready ops). Framing is the transport’s business; the relay merges whatever each frame delivers.
TypedContextFamily
Extracts the schema marker from a typed context family.
TypedFactoryContext
Context-like typed views that can memoize decorator-style slot/cell factories.
TypedGet
Values that can be read through a TypedContext with TypedContext::get.
TypedGetRef
Values that can be read through a TypedContextRef with TypedContextRef::get.
TypedSet
Values that can be written through a TypedContext with TypedContext::set.
Write
A handle writable through a context’s set (#lzcellkernel), generic over the context type Ctx.

Functions§

align
Align new against old, 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 classified Edited, else Inserted. Unmatched old blocks are removed.
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 use CellMap::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 #lzkeyrecon key 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 through assign_stable_keys + reconcile to project the merged text onto the keyed tree.
reconcile
Reconcile oldnew by 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 by MembershipCell::peer_set_cell.
SlotMap
A keyed derived-slot collection: every entry is a Computed<V> whose value is derived. get_or_insert_with mints a slot on first access (lazy materialization); materialize_all pre-mints the keyset (eager). A slot’s value is derived, so SlotMap has no set.
TextVersionVector
A version vector: the greatest OpId counter 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 by OpId.

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.