8000 GitHub - lazily-hub/lazily-dart: Lazy reactive primitives for Dart — Slots, Cells, and Signals with automatic dependency tracking and cache invalidation, plus the lazily-spec wire protocol. Flutter + web + native. · GitHub
[go: up one dir, main page]

Skip to content

About

Lazy reactive primitives for Dart — Slots, Cells, and Signals with automatic dependency tracking and cache invalidation, plus the lazily-spec wire protocol. Flutter + web + native.

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

lazily (Dart)

Lazy reactive primitives for Dart — the Cell kernel (Source, Computed, Effect) with automatic dependency tracking and cache invalidation. Pure Dart: Flutter, web, and native.

A port of the lazily reactive family (lazily-rs, lazily-py, lazily-js, lazily-zig).

The Cell kernel (v2)

Cell is the value-bearing node concept — a reactive that holds a readable value. It is not a type: there is no Cell<T, K> genus. The two concrete cell handles are what a caller holds (#lzcellkernel):

  • Source<T> — a value written from outside (get / set / merge); the writable kind. Construct with source(ctx, v) or Source<T>(ctx, v). A MergeCell is a Source whose write folds under a policy (Source ≡ MergeCell(KeepLatest)). Cell is retained as a compatibility spelling of Source.
  • Computed<T> — a value computed from upstream (get, .eager(), .lazy(), isEager). Construct with computed(ctx, f); guarded, always — an equal recompute (==) suppresses the downstream cascade (TC39 Signal.Computed). Lazy by default; make it eager with computed(ctx, f).eager(), which re-materializes immediately on every upstream change.
  • Effect — a value-less sink, outside the cell hierarchy; nothing can depend on it.

Slot is retained as the lower-level storage/computation position and the unguarded callable lazy computed — reach for it when a value is not ==-comparable or the guard is unwanted. There is no separate memo kind: the equality guard folded into Computed. Dart has no compile-time read/write split: the kind is convention — a Source has set / merge, a Computed does not.

Values are lazy by default. When you need eager push-style semantics, call computed(ctx, f).eager(). There is no Signal compatibility constructor.

Usage

import 'package:lazily/lazily.dart';

final ctx = Context();
final a = Cell<int>(ctx, 2);
final b = Cell<int>(ctx, 3);

// Lazy: computes on first read, caches, recomputes only when a or b changes.
final sum = Slot<int>(ctx, (_) => a.value + b.value);
print(sum()); // 5

a.value = 10;
print(sum()); // 13

// A guarded, lazy derived value.
final label = computed(ctx, (_) => 'sum=${sum()}');
print(label.value); // sum=13

// Eager: `.eager()` re-materializes immediately when a dependency changes.
final parity = computed(ctx, (_) => a.value.isEven ? 'even' : 'odd').eager();
print(parity.value); // even
a.value = 11;
print(parity.value); // odd (already updated before the read)

Side effects — the hook for Flutter ValueNotifier bridges and setState wrappers — are declared as an Effect. A Cell has no listener registry: an effect observes through a real dependency edge, so it batches and stays glitch-free with the rest of the graph.

final count = Cell<int>(ctx, 0);
final effect = Effect(ctx, (_) {
  print('now ${count.value}');
  return null;
}); // prints "now 0"
count.value = 1; // prints "now 1"
effect.dispose();

When a consumer genuinely needs a stream of every transition rather than the settled value, publish to a Topic — that is the stream primitive, and it survives batching by design.

Competing-consumer work queue

WorkQueueCell<T> provides exclusive FIFO claims, visibility deadlines, worker-scoped acknowledgements, tail retries, and bounded dead-letter handling. Item ids remain stable across retries; each claim gets a fresh delivery id.

final work = WorkQueueCell<String>(
  ctx,
  visibilityTimeout: 10,
  maxDeliveries: 3,
);
work.push('job');
final delivery = work.claim('worker-a', 100)!;
assert(work.ack('worker-a', delivery.deliveryId));

Latest durable projection

LatestDurableProjectionCore<K, T> is the graph-independent command authority for a latest-value durable sink. Each key retains the newest desired epoch, allows at most one claimed envelope, advances durableThrough only when that exact envelope succeeds, and returns failures to retryable pending state unless a newer desired epoch already superseded them. reconnect advances a generation fence, requeues abandoned in-flight work, and makes acknowledgements from the old actor inert.

final saves = LatestDurableProjection<String, String>(ctx, 1);
saves.upsertDesired('document', 1, markdown);
final envelope = saves.claim('document', 1).envelope;
if (envelope != null) {
  await storage.write(envelope.value);
  saves.ackApplied(envelope.key, envelope.generation, envelope.epoch);
}

LatestDurableProjection, ThreadSafeLatestDurableProjection, and AsyncLatestDurableProjection expose matching entryHandle, generationHandle, and snapshotHandle readers while keeping transitions synchronous. All four surfaces replay lazily-spec v0.38.0's canonical egress/latest_durable_projection.json fixture and correspond to LazilyFormal.LatestDurableProjectionCore in lazily-formal v0.38.1.

Replay-equivalence proof

A durable-execution host — a Temporal.io workflow replay, an event-sourced aggregate, a deterministic simulation — re-runs your code from an ordered event log and expects the same decisions. ReplayHarness makes that provable rather than assumed (#l 8000 zreplaydart, lazily-spec/docs/replay-equivalence.md):

final log = ReplayLog.fromRecords([('add', 1), ('add', 2), ('add', 3)]);
final harness = ReplayHarness(() => Accumulator());

final fingerprint = harness.record(log); // pin it, or commit `toWire()`
harness.verify(log, fingerprint); // throws at the FIRST diverging checkpoint
harness.prove(log); // record + re-replay, no pinned artifact needed

Three obligations, and each is a distinct exception type so a driver routes on the type rather than on a message:

  • The fingerprint is bound to its log. ReplayLog carries a digest over its canonical bytes and verify revalidates that binding before comparing any observed value, throwing ReplayLogMismatchError. Two different logs can settle to the same final values — [+1,+2,+3] and [+3,+2,+1] both sum to 6 — so a value-only comparison would pass and certify nothing. check, the non-raising reporting form, refuses a stale fingerprint too.
  • Divergence is localized. Every event is checkpointed by default, and ReplayDivergenceError.first names the first diverging checkpoint's seq and the label of the cell that differed. A coarser stride is available for long logs and is itself part of the fingerprint, so a fingerprint sampled at one stride is refused against a harness sampling at another (ReplayStrideMismatchError).
  • The observation encoding is canonical, or it fails. canonicalBytes is type-tagged and length-framed — {a:1, b:2} equals {b:2, a:1}, [1,2] does not equal [2,1], and ['a','bc'] does not equal ['ab','c'] — and a value with no defined encoding throws ReplayEncodingError rather than falling back on toString(), which renders every instance of a class alike and would fold two different observations into one value.

Digests are the base64 of the exact canonical bytes, not a hash: the spec leaves both the hash and the byte layout binding-chosen because fingerprints are pinned next to a test and never exchanged between bindings, and package:lazily keeps its zero runtime dependencies rather than buying package:crypto for collision resistance that identity already has.

Context

All reactives that react to each other must share a Context. The context holds an identity-keyed cache and the computation stack used for automatic dependency tracking. One context per reactive graph is the contract.

State machine

StateMachine is a finite state machine backed by a Cell, so any slot or signal that reads state is invalidated on transition:

final m = StateMachine<String, String>(
  ctx, 'Red',
  (s, e) => e == 'advance'
      ? const {'Red': 'Green', 'Green': 'Yellow', 'Yellow': 'Red'}[s]
      : null,
);
m.send('advance'); // true -> 'Green'

State chart

StateChart is a full Harel/SCXML hierarchical state machine — the native counterpart of lazily-formal's LazilyFormal.StateChart and lazily-rs's / lazily-kt's state charts. It is compute, not protocol: it is never serialized as a distinct wire kind. The active configuration lives in a Cell, so any slot or signal reading configuration, activeLeaves, or matches is invalidated on a real transition; a no-op (configuration unchanged) is suppressed by the cell's structural-equality guard.

send is deterministic by construction — a total function of (chart, configuration, history, guards, event), mirroring the Lean StateChart.send. A chart is built from the declarative JSON form (lazily-spec/docs/state-charts.md) via ChartDef.fromJson.

Implemented subset (per the spec's implementation-status note): compound (hierarchical) states with default initial descent, orthogonal (parallel) regions, shallow and deep history (record-on-exit / restore-on-enter), entry/exit/transition actions (exit innermost-first → transition → entry outermost-first), named guards resolved at send time (fail-closed), and external + internal transitions. run actions and {"expr": …} context guards are rejected explicitly. final states are accepted as leaves without raising completion (done) events, matching lazily-py and lazily-kt.

import 'package:lazily/lazily.dart';

final def = ChartDef.fromJson({
  'initial': 'on',
  'states': {
    'root': {'initial': 'on'},
    'on': {
      'parent': 'root', 'initial': 'playing',
      'on': {'toggle': 'off'},           // handled by 'on', bubbles from a child
    },
    'playing': {'parent': 'on', 'on': {'pause': 'paused'}},
    'paused':  {'parent': 'on', 'on': {'play': 'playing'}},
    'off':     {'parent': 'root', 'on': {'toggle': 'on'}},  // re-enters -> 'playing'
  },
});
final chart = StateChart(ctx, def);

chart.activeLeaves();            // ['playing']
chart.send('toggle');            // true; off -> on -> playing (initial)
chart.matches('on');             // true
chart.lastActions();             // exit → transition → entry actions

Conformance

lazily-dart replays the shared lazily-spec conformance fixtures:

CI and release qualification use immutable lazily-spec v0.43.0 (4b34879b); local development may use another explicit sibling checkout.

  • State-chart fixtures mirrored into test/conformance/statechart/ are replayed by test/statechart_conformance_test.dart, asserting accepted, active, matches, and actions identically to every other binding (lazily-rs / lazily-kt / lazily-py / lazily-zig / lazily-js). When the sibling lazily-spec checkout is present on disk, the canonical fixtures are preferred, so this harness also guards against cross-family drift.
  • The reactive-source families — temporal (#lztime), rate-shaping (#lzrateshape), membership + phi-accrual (#lzmemb), coordination (#lzcoord), presence (#lzpresence), windowing (#lzwindow), resilience (#lzresilience), and the embedded-service plane (#lzservice) — mirror test/conformance/{temporal,rateshape,membership,coordination,presence,windowing,resilience,service}/ and are replayed by the matching test/*_conformance_test.dart, asserting op returns, the projected reader value, and per-step reader invalidation (invalidates) — a reader recomputes only when its projected value actually changes.
  • The replay-equivalence fixtures (replay/fingerprint_log_binding.json, replay/divergence_localization.json, replay/canonical_encoding_equality.json) are replayed by test/replay_conformance_test.dart against ReplayHarness. They assert the log binding is revalidated before any value compare, that a divergence is reported at its first checkpoint with the diverging cell's label, and the encoding's equality classes — never a hex digest, so each binding's choice of hash stays free.
  • SimConsumerTestkit applies one generated history to a deterministic in-memory consumer and explicitly selected Postgres, NATS, or external-process adapters. Its narrow SimConsumerWorldEvidence seam proves execution without prescribing a scheduler; the canonical runner covers all five simulation/consumer_testkit.json scenarios, including localized observation, history-prefix, and simulation-bypass failures.

Core qualification report

scripts/core-conformance.json declares the core-v1 report command. The command replays the 16 Core reactive-graph fixtures against Context, ThreadSafeContext, and AsyncContext, writes fresh assertion-consumption evidence beneath $LAZILY_CORE_REPORTS_ROOT/dart, and emits the report at $LAZILY_CORE_REPORT_PATH. The divergent feedback-drain fixture remains an explicit whole-fixture skip until the scheduler exposes bounded-drain exhaustion. Dart does not currently claim c_abi_ffi_boundary: lib/src/ffi.dart is an in-language protocol mirror, not an exported native artifact.

The generator resolves its Dart SDK by probing each distinct dart on PATH with a bounded dart --version and using the first that prints an SDK banner; DART=/path/to/dart pins one instead. Every replay runs in its own process group, capped by the verifier's remaining LAZILY_CORE_COMMAND_TIMEOUT_MS budget, and a timeout or SIGTERM kills that group and removes the build/ scratch directory. make core-conformance-report-self-test pins this with fake dart executables.

Formal model (lazily-formal)

dart test also builds the lazily-formal Lean 4 model — the executable reference behind the state-chart fixtures and the deterministic send lazily-dart inherits. tool/formal_check.dart runs lake build over the sibling lazily-formal checkout (located via the LAZILY_FORMAL_PATH env var, then the src/lazily-dart ↔ src/lazily-formal submodule layout); it SKIPs gracefully when the submodule or the lake toolchain is absent — so pub.dev consumers and shallow clones are not broken. CI uses a full checkout + elan, so the proofs are verified for real there.

Each lazily-formal module that has a Dart counterpart has a matching property test that names the universal theorem it mirrors — the guarantees no finite fixture suite can establish:

lazily-formal module Dart test file Mirrored theorems
StateMachine / StateChart test/statechart_properties_test.dart enabled_empty_rejects, send_preserves_chart, determinism-by-construction, single_region_refines_flat_machine, single_region_enabled_at_most_one, parallel_region_confluence, recordHistory_idempotent, send_actions_empty_when_rejected
Reactive test/reactive_properties_test.dart setCell_equal_preserves_graph, setCell_different_invalidates_dependents, recomputeSlot_equal_preserves_dependents, recomputeSlot_different_invalidates_dependents, signal_materialized_after_recompute
ThreadSafe test/thread_safe_test.dart flushBatch_singleton_eq_setCell, flushBatch_dependent_dirty, flushBatch_preserves_nondependent_dirty, coalesced-frontier dedup
Materialization test/thread_safe_reactive_family_test.dart materialize_present_comm, materialize_observe_comm (confluence), materialize_preserves_observe
AsyncMaterialization test/async_reactive_family_test.dart eventual_transparency, async_resolved_matches_sync, observe_pending_is_none, cell_resolved_at_build, resolve_monotone
FamilySync test/familysync_conformance_test.dart applyOp_absent_adopts, present_merge, applyOp_idem, aggregate_converges

lazily-spec IPC

The package:lazily/ipc.dart library implements the language-agnostic lazily-spec wire protocol (Snapshot, Delta, NodeState, ...) so a Dart graph's state can be mirrored to remote observers across processes and languages. It round-trips the canonical fixtures from lazily-spec/conformance/.

The wire on a JavaScript target

The IPC surface is a supported web target, and make check proves it: tool/ipc_browser_check.dart compiles package:lazily/ipc.dart with dart compile js and runs the result under Node on every build and in CI. That gate is newer than the surface it guards — until it landed, the wire did not compile to JavaScript at all, because dart2js rejects an integer literal above 2^53 - 1 and the FNV-1a and SplitMix64 constants were spelled as literals. The older tool/stdlib_browser_check.dart passed the whole time; it imports package:lazily/stdlib.dart and covers none of the protocol.

Support comes with one rule, and it is the same on both codecs: a value this runtime cannot represent is refused, never rounded. Dart's int is 64 bits on the VM and an IEEE-754 double everywhere else, and jsonDecode rounds 9007199254740993 to ...992 without an error — a corrupted node id that decodes cleanly is undetectable downstream. So:

  • On the VM, NodeId/PeerId values above 2^53 round-trip exactly, as protocol.md § NodeId / PeerId allows. Nothing is refused.
  • On a JavaScript target, a frame carrying such a value is rejected with a FormatException. Everything at or below 2^53 - 1 decodes normally, including a small value a peer chose to carry in a wide uint64 tag.
  • contentHash returns the packed 64-bit digest and therefore throws UnsupportedError on a JavaScript target. Use contentHashHex, which is the c: wire form and is exact everywhere; BlockKey.content takes that hex.

Every 64-bit constant and operation in this package lives in lib/src/u64.dart as 32-bit halves, so hashes and the SplitMix64 sampler produce identical results on the VM and in a browser rather than one answer per runtime.

Feature coverage

Coverage by feature family across every binding, generated from coverage.json in lazily-spec. Legend: ✅ shipped · ~ partial · — absent · ⊘ not applicable. The canonical matrix with per-cell notes and platform carve-outs lives in lazily-spec § Cross-Language Coverage.

Summary — family × language

Family Rust Python Kotlin JS Dart Zig Go C++ C# GDScript
Reactive graph ✅ ~ ~ ~ ✅ ✅ ✅ ✅ ✅ ~
Materialization ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Family sync ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Statecharts ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
View ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅
Keyed collections ✅ ✅ ✅ ✅ ✅ ~ ✅ ✅ ✅ —
Reactive queue ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Broadc 8BD0 ast topic ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Work queue ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
CRDT data types ✅ ~ ~ ~ ~ ~ ~ ~ ✅ —
Lossless tree ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Egress ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ~
Ingress ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Wire codec ✅ ✅ ✅ ✅ ~ ✅ ✅ ✅ ✅ —
Transport & FFI ✅ ~ ~ ~ ~ ✅ ✅ ~ ✅ —
Message passing ✅ ✅ ✅ ✅ ✅ ~ ✅ ✅ ✅ —
Reliable sync ~ ~ ~ ~ ~ ~ ~ ~ ~ —
Durable owner ✅ — — — — — — — — —
Durable capability tiers ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
Distributed plane ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Causal receipts ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Security boundary ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Membership ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Coordination ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Presence ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Temporal ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Rate shaping ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Windowing ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Resilience ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Portable stdlib ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Service plane ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —
Instrumentation ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ —

Roll-up rule: a family cell is ✅ only when every required row in that family is ✅; ~ when the family is mixed (some shipped or partial); — when no required row is shipped or partial; ⊘ only when every required row in the family is not applicable. Rows the spec marks MAY (optional) are excluded from the roll-up — declining an optional feature is not a gap.

A family cell summarises 86 feature rows. For row-level marks, per-cell notes, and platform carve-outs see the canonical coverage matrix in lazily-spec.

Benchmarks

Wall-clock benchmarks live in BENCHMARKS.md, with two runnable programs:

  • Micro-benchmarks — the in-library runBenchmarkSuite reactive-core, collection, and CRDT paths (Source/Slot/Computed/batch/SourceMap/ TextCrdt/SeqCrdt). The reactive-core steady state is sub-microsecond per op.
  • Scale — a spreadsheet-shaped graph (N input cells + N formula slots, formula[i] = input[i] + input[i-1]) replicating the lazily-rs scale group and lazily-go. It runs a full 10M-cell Google Sheets workbook (N = 5,000,000): build ~2.5 s, full cold recompute ~4 s, and a one-cell edit
    • bounded-viewport read stays size-independent at ~30 µs (~136,000× cheaper than a full recalc) — only the ~2 dependent formulas recompute.
dart run benchmark/micro_benchmark.dart
dart run benchmark/scale_benchmark.dart                          # N = 1,000,000 (~2M nodes)
LAZILY_SCALE_N=5000000 dart run benchmark/scale_benchmark.dart   # 10M cells (Google Sheets workbook)

See BENCHMARKS.md for the measured results, hardware, and methodology.

Status

Full feature parity on the Dart platform — every row of the lazily-spec cross-language matrix is shipped (✅), including the concurrency layers.

Dart isolates have no shared mutable heap, so the "thread-safe" layers are realized the same way JavaScript ships them on its single-realm event loop: within an isolate, synchronous code runs to completion and already serializes access, so ThreadSafeContext / ThreadSafeReactiveMap use a reentrant run-to-completion guard and the deterministic batch-coalescing kernel proven equivalent to LazilyFormal.ThreadSafe. Genuine cross-isolate parallelism is served by (a) TransferableTypedData for the zero-copy shared-memory blob path (ShmBlobArena.transfer, a zero-copy move — Dart's isolate-model counterpart of mmap/SharedArrayBuffer) and (b) the CRDT wire protocol for replicated state — reconciled with materialization confluence under real multi-isolate workloads (test/shm_isolate_test.dart).

Reactive handles carry a reusable allocator slot, a generation, and a node kind. Disposal validates all three before changing graph or cleanup state, so an old handle is a no-op after same-kind or cross-kind slot reuse. The read-only Context.nodeIdentity and AsyncContext.nodeIdentity projections exist for conformance and diagnostics; a raw slot number alone is never a live occupant identity.

Layer Where
Reactive core — Cell kernel v2 (Source/Cell / Computed+computed/.eager()/.lazy() / Effect / Slot (unguarded) / batch; no Signal compatibility constructor) package:lazily/lazily.dart
Keyed cell collections (ReactiveMap / SourceMap / ComputedMap / SourceTree / reconciliation) package:lazily/lazily.dart
Flat state machine + Harel state charts package:lazily/lazily.dart
TextCrdt (char CRDT) + delta sync package:lazily/lazily.dart
SeqCrdt (move-aware sequence CRDT) + Hlc + LwwRegister package:lazily/lazily.dart
Lossless tree CRDT (LosslessTreeCrdt M1 + dotted-frontier delta sync) package:lazily/lazily.dart
Registers (MV / PnCounter / CellCrdt) package:lazily/lazily.dart
SemTree (memoized semantic tree) package:lazily/lazily.dart
Stable-id alignment package:lazily/lazily.dart
Async reactive context package:lazily/async_context.dart
Queue family across sync / thread-safe / async (QueueCell / TopicCell / WorkQueueCell) package:lazily/lazily.dart
Transport-agnostic reactive ingress across sync / thread-safe / async (IngressCore + IngressCell / ThreadSafeIngressCell / AsyncIngressCell, #designimplementtransport) package:lazily/lazily.dart
Latest-value durable egress across core / sync / thread-safe / async (LatestDurableProjectionCore + reactive shells, #lzlatestdurableprojection) package:lazily/latest_durable_projection.dart
Transport-agnostic reactive egress across sync / thread-safe / async (EgressCore + EgressCell / ThreadSafeEgressCell / AsyncEgressCell, one attached transport Effect per incarnation, #lzegress) package:lazily/lazily.dart
Generic keyed effect compare-and-swap across core / sync / thread-safe / async (EffectCasCore + EffectCas / ThreadSafeEffectCas / AsyncEffectCas, durable image + hydrate, #lzeffectcas) package:lazily/lazily.dart
Keyed reactive map materialization (ComputedMap lazy getOrInsertWith / eager materializeAll, #reactivemap) package:lazily/lazily.dart
Thread-safe context + reactive map (ThreadSafeContext / ThreadSafeReactiveMap / ThreadSafeSourceMap / ThreadSafeComputedMap) package:lazily/lazily.dart
Async reactive map (AsyncReactiveMap / AsyncSourceMap / AsyncComputedMap) package:lazily/lazily.dart
Reactive family sync (#lzfamilysync, materialize-on-ingest) package:lazily/ipc.dart
IPC (Snapshot + Delta + CrdtSync) package:lazily/ipc.dart
Distributed CRDT plane (CrdtPlaneRuntime / anti-entropy) package:lazily/ipc.dart
Causal receipts (CausalReceipt / ReceiptProjection) package:lazily/ipc.dart
Command/RPC message plane (CommandSubmit/Cancel/Events/Projection + CommandRpcClient) package:lazily/ipc.dart
Signaling (SignalingRoom / ClientMessage / ServerMessage) package:lazily/ipc.dart
State projection / mirror (StateProjectionMirror) package:lazily/ipc.dart
ShmBlobArena (blob arena + header validation + zero-copy cross-isolate transfer) package:lazily/ipc.dart
C-ABI FFI boundary (LazilyFfi*, CrdtSync = 3) package:lazily/ffi.dart
Permission boundary (RemoteOp / PeerPermissions) package:lazily/ipc.dart
Capability negotiation package:lazily/capability.dart
Instrumentation (benchmark / runBenchmarkSuite) package:lazily/ipc.dart
Formal model verification (lazily-formal Lean proofs in dart test) tool/formal_check.dart + test/formal_check_test.dart

Keyed cell collections

There is one keyed primitive, ReactiveMap<K, V, H>, generic over the entry's handle kind H, with two specializations (#reactivemap):

  • SourceMap<K, V> = ReactiveMap<K, V, Cell<V>> — input-cell entries; adds cell-only set plus eager value-minting (entry / entryWith).
  • ComputedMap<K, V> = ReactiveMap<K, V, Computed<V>> — guarded derived entries; getOrInsertWith mints a computed on first access (lazy materialization), materializeAll pre-mints the keyset (eager). Its value is derived, so ComputedMap has no set, and there is no eager/lazy mode flag.

The shared surface (getOrInsertWith / remove / move* / membership / order / keys / len / containsKey) lives on ReactiveMap.

SourceMap<K, V> is a composition of cells, not a new cell kind. Each entry is an ordinary Cell; a dedicated membership cell tracks the key set, and a dedicated order cell tracks the ordered key list, so the three reactivity planes are independent:

  • writing one entry's value invalidates only that entry's value readers;
  • adding/removing a key invalidates membership readers (len / containsKey) and order readers (keys), but not unrelated entry value readers;
  • a pure reorder (atomic move) invalidates order readers only.
final ctx = Context();
final scores = SourceMap<String, int>(ctx)
  ..set('alice', 10)
  ..set('bob', 20);

final leaderboard = Slot<List<String>>(ctx, (_) => scores.keys());
leaderboard(); // ['alice', 'bob']

scores.moveTo('bob', 0);
leaderboard(); // ['bob', 'alice']  — recomputed (order changed)

reconcileDiff is the move-minimized keyed reconciliation (#lzkeyrecon): diffs two keyed sequences by stable key and emits the minimal {insert, remove, move, update} op set, holding the longest-increasing subsequence fixed so keys already in relative order do not move.

SourceTree<K, V> is the ordered keyed tree — each node is (stable id, value cell, ordered keyed child collection), inheriting per-level reactivity and the atomic-move guarantee.

Distributed CRDT plane

The CRDT plane rides the same lazily-ipc transport as Snapshot/Delta: CrdtSync is a third IpcMessage variant. State-based and idempotent — out-of-order, duplicated, or batched delivery all converge.

import 'package:lazily/ipc.dart';

final a = CrdtPlane(1);
final stamp = a.tick(12345);                              // local event
final op = CrdtOp.newOp(nodeId, stamp, [1, 2, 3]);        // state to merge
final frame = CrdtSync(
  frontier: a.frontier.toWire(),                          // per-peer stamp frontier
  ops: [op],
);
// → IpcMessage.ofCrdtSync(frame).encodeJson()  is the wire form.

StampFrontier.merge is commutative, associative, idempotent; the causal-stability watermark (stabilityWatermark) is the min over membership — only once every replica has observed a tombstone may it be collected (isCollectable).

FFI boundary

package:lazily/ffi.dart exposes LazilyFfiBytes, LazilyFfiStatus, and LazilyFfiMessageKind (with CrdtSync = 3). A frame is just serialized IpcMessage bytes; the channel decodes each accepted frame as IpcMessage and re-encodes canonical JSON.

import 'package:lazily/ffi.dart';
import 'package:lazily/ipc.dart';

final frame = LazilyFfiBytes(IpcMessage.ofCrdtSync(sync).encodeJson());
final c = lazilyFfiKindJson(frame);
expect(c.kind, LazilyFfiMessageKind.crdtSync);

lazily-dart declares the ffi = host capability (Dart has dart:ffi).

Capability negotiation

package:lazily/capability.dart ships the compatibility handshake. Peers fail closed on protocol_id, protocol_major_version, codec, ordered_reliable, or a required feature the other does not offer.

Async reactive context

package:lazily/async_context.dart is a separate reactive surface for async/future-returning computations, with the full Empty → Computing → Resolved | Error state machine, revision tracking (stale completions discarded), in-flight deduplication, the re-resolve contract, an equality memoAsync guard, serialized async effects (cleanup-before-body), batching, and disposal.

Development

See CONTRIBUTING.md for setup, analysis, tests, and formal model verification.

The lazily family

lazily is one reactive model — the Cell kernel, keyed collections, state machines and charts, CRDTs, and the distributed plane — implemented natively per language and held to the same behaviour by a shared conformance corpus.

  • lazily-spec — language-agnostic wire protocol + the conformance fixtures (IPC and state-chart) every binding replays. It also carries the generated cross-language feature matrix; read that table rather than any per-binding copy.
  • lazily-formal — Lean 4 formal model (shared primitives, the flat StateMachine kernel, and the full Harel StateChart). Not a binding: it is the neutral formal home every binding depends on equally, and the executable reference behind the state-chart fixtures and the deterministic send lazily-dart inherits.
6475
Repo Language
lazily-rs Rust — the reference implementation
lazily-py Python
lazily-go Go
lazily-kt Kotlin / JVM
lazily-js JavaScript / TypeScript
lazily-cs C# / .NET
lazily-cpp C++
lazily-zig Zig
lazily-dart Dart / Flutter — you are here
lazily-react React / Preact bindings layered over lazily-js — not a separate language binding

License

Apache-2.0 — see LICENSE and NOTICE.

About

Lazy reactive primitives for Dart — Slots, Cells, and Signals with automatic dependency tracking and cache invalidation, plus the lazily-spec wire protocol. Flutter + web + native.

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0