Rebuild BlaC's reactivity engine from the ground up in four stages — the dirty channel, the path interner, the recording proxy, the observed skeleton, and cross-bloc dependencies.
This chapter rebuilds BlaC’s reactivity engine from the ground up, one stage at a
time. By the end you will be able to point at every moving part — the dirty
channel, the path interner, the recording proxy, the observed skeleton, and the
cross-bloc dependency layer — and say exactly what it does and why it has to.
If you only want the rules for writing components, read
Tracking and Dependency Tracking.
This page is for when you want the machine. It is grounded directly in the
source: the engine lives in @dirtytalk/engine, the path machinery in
@dirtytalk/structural, and BlaC’s lifecycle layer in @blac/core’s
StateContainer. The companion design narrative is the
Mental Model; the distilled standalone version is
DirtyTalk.
We build in four stages, each strictly on top of the last:
Stage 1 state + listeners "something changed — wake everyone"
│ (DirtyChannel, coalesced flush)
▼
Stage 2 paths "what changed — as interned integers"
│ (PathInterner, PathSet, intersection)
▼
Stage 3 the skeleton "who reads what — diff once, fan out cheap"
│ (trackRender proxy + observed skeleton)
▼
Stage 4 cross-bloc deps "one bloc leans on another"
(StateContainer.depend / registry)
Stage 1 — State and listeners
Start with the smallest honest model: a value, a set of listeners, and a way to
say “I changed.” Every reactive store has this core. The naive version notifies
every listener synchronously on every change.
BlaC’s real notification core is DirtyChannel<Region> from @dirtytalk/engine,
but we approach it from the outside in. From the outside, that contract is what
Cubit exposes: a value behind
state, mutated by emit / update, with watch (or the lower-level
subscribe) firing on every coalesced flush. This block type-checks
against the real @blac/core surface:
Cubit<S> is a StateContainer<S> that exposes mutation publicly.
That is the whole difference, and it is a real one: on StateContaineremit / patch / update are protected, so a container mutates itself
from its own methods and callers go through the API it chooses to publish.
Cubit re-declares the three as public for the cases where a caller
legitimately drives state from outside — test helpers, devtools
time-travel, benchmarks.
Reach for StateContainer when business logic should live in the class,
and Cubit when the caller owns the transitions.
Cubit<S> is a StateContainer<S> that exposes mutation publicly.
That is the whole difference, and it is a real one: on StateContaineremit / patch / update are protected, so a container mutates itself
from its own methods and callers go through the API it chooses to publish.
Cubit re-declares the three as public for the cases where a caller
legitimately drives state from outside — test helpers, devtools
time-travel, benchmarks.
Reach for StateContainer when business logic should live in the class,
and Cubit when the caller owns the transitions.
Cubit<{
count: number
count:number}>{
constructor(){
super({
count: number
count:0});
}
CounterCubit.increment(): void
increment(){
// Immutable replacement. Several synchronous emits coalesce into ONE flush.
Ensure an instance exists without taking ownership (no ref added). Instance
identity is derived purely from args, matching acquire.
ensure(
classCounterCubit
CounterCubit);
const c:CounterCubit
c.
CounterCubit.increment(): void
increment();
const c:CounterCubit
c.
CounterCubit.increment(): void
increment();// two emits, same tick → callback fires once with count: 2
conststop:()=>void
stop();
Underneath, watch is a thin bridge over the real notification core:
DirtyChannel<Region> from @dirtytalk/engine. It is generic over a Region —
an opaque “what changed” value governed by a Space<Region> algebra
(empty, isEmpty, union, intersects). Two properties make it more than a
plain EventEmitter. Modeled with a trivial boolean Region where “dirty” is
just true (illustrative — @dirtytalk/engine is the engine package, not a
docs dependency, so this block is shown rather than type-checked):
import{ DirtyChannel, SyncScheduler,type Space }from'@dirtytalk/engine';
// The simplest possible Region: a boolean. `true` = "something changed".
const BoolSpace:Space<boolean>={
empty:()=>false,
isEmpty:(r)=> r ===false,
union:(a, b)=> a || b,
// Any non-empty dirty wakes any interested subscriber.
Marks accumulate, flushes coalesce.mark(region) unions the region into
an accumulator and asks the scheduler to flush once. Several synchronous
marks collapse into a single flush — so three emits in one tick wake each
listener at most once.
Interests are thunks evaluated at flush time. A subscriber registers
subscribe(() => interest, cb). On flush the channel evaluates the interest
thunk, tests space.intersects(interest, dirty), and calls cb only on a
hit. (This is the seam Stage 2 and 3 exploit; here the region is just
“everything.”)
Stage 1: mark → flush → wake everyone
increment() increment() (same tick)
│ │
▼ ▼
mark(true) mark(true) union → still `true`
└─────┬──────┘
▼
scheduler.request(flush) coalesced: scheduled once
│
▼
flush: dirty = true ───────────► every subscriber whose
interest intersects → cb()
This is everything a Cubit does at the listener level. The
watch(BlocClass, cb) helper is exactly this: it bridges every
flush to a callback that wakes on any change, regardless of what changed,
applied from outside React. The flush is microtask-coalesced, which is why
several synchronous emits produce a single notification.
What’s missing: “wake everyone” is wasteful. A container with twenty fields
wakes a listener that reads one of them on all twenty kinds of change. Stage 2
makes “what changed” precise.
Stage 2 — Paths
Replace the boolean region with a set of changed paths. A path is a dotted
route to a leaf in the state tree: user.name, items, user.address.city. A
mutation marks the paths it touched; a listener declares the paths it reads; the
channel wakes a listener only when those two sets intersect.
Comparing and unioning dotted strings on every mutation would be wasteful, so
every path is interned into a small integer PathId once. PathInterner
(in @dirtytalk/structural, used internally by every BlaC container) is a
bidirectional string ↔ PathId table: intern(path) returns a stable id (the
next sequential integer, starting at 0), idempotently; lookup(id) reverses
it.
interner.intern('user.name');// 0 again — idempotent
interner.lookup(0);// 'user.name'
interner.size;// 2
Ids are only comparable inside one interner’s namespace, so BlaC keeps one
interner per container subclass, keyed by constructor in a WeakMap
(StructuralContainer.getInternerFor). Every instance of one Cubit subclass
shares an interner, so their ids line up and can be unioned/intersected freely;
distinct subclasses get distinct interners even if their state shapes match. The
WeakMap lets the interner be collected once the class is gone.
A PathSet is the unit of both “interest” and “dirtiness.” It is either a
concrete Set<PathId> or the ALL_PATHS sentinel ("every possible path").
The set algebra is a Space<PathSet> — PathSetSpace — the same Space
contract from Stage 1, now over path sets instead of booleans:
import{
PathInterner,
PathSetSpace,
ALL_PATHS,
type PathSet,
}from'@dirtytalk/structural';
const interner =newPathInterner();
const name = interner.intern('user.name');// 0
const email = interner.intern('user.email');// 1
// A listener that reads user.name; a mutation that changed user.email.
ALL_PATHS and the PathSet type are the only path primitives BlaC re-exports
from @blac/core (for plugins composing subscribe and consume calls); this
type-checked block uses them directly:
import{
const ALL_PATHS:typeof ALL_PATHS
ALL_PATHS,type
typePathSet=typeof ALL_PATHS |Set<number>
PathSet}from'@blac/core';
// A plugin or devtools panel can declare blanket interest in every change.
const
const blanketInterest:PathSet
blanketInterest:
typePathSet=typeof ALL_PATHS |Set<number>
PathSet=
const ALL_PATHS:typeof ALL_PATHS
ALL_PATHS;
void
const blanketInterest:typeof ALL_PATHS
blanketInterest;
The channel is identical to Stage 1; only the Region changed from boolean to
PathSet. intersects does the discrimination: iterate the smaller set, look
up in the larger, return on the first hit. That is the entire per-listener cost
of a change — no tree walk.
Where do the changed paths come from? The mutators compute them:
emit(next) installs a new immutable state, then diffs to find which
observed paths changed value (Stage 3 covers the skeleton bound on that diff).
patch(partial) is exactly emit(deepMerge(state, partial)): it goes
through the same diff as emit, which is value-filtered and prunes unchanged
references. So an over-spread patch that re-sets a whole parent when one field
changed does not over-wake the siblings, and a patch that replaces an array
with equal contents wakes readers of the whole array but not of its unchanged
children.
update(fn) is sugar for emit(fn(state)).
From the public surface, the three mutators look like this — and all type-check:
Cubit<S> is a StateContainer<S> that exposes mutation publicly.
That is the whole difference, and it is a real one: on StateContaineremit / patch / update are protected, so a container mutates itself
from its own methods and callers go through the API it chooses to publish.
Cubit re-declares the three as public for the cases where a caller
legitimately drives state from outside — test helpers, devtools
time-travel, benchmarks.
Reach for StateContainer when business logic should live in the class,
and Cubit when the caller owns the transitions.
Cubit<S> is a StateContainer<S> that exposes mutation publicly.
That is the whole difference, and it is a real one: on StateContaineremit / patch / update are protected, so a container mutates itself
from its own methods and callers go through the API it chooses to publish.
Cubit re-declares the three as public for the cases where a caller
legitimately drives state from outside — test helpers, devtools
time-travel, benchmarks.
Reach for StateContainer when business logic should live in the class,
and Cubit when the caller owns the transitions.
Cubit<
interfaceUserState
UserState>{
constructor(){
super({
UserState.user: {
name: string;
email: string;
}
user:{
name: string
name:'Ada',
email: string
email:'ada@x.io'},
UserState.items: string[]
items:[]});
}
// patch: deep-merges; marks only paths whose value actually changed.
// Here only `user.email` moves → `user.name` consumers stay asleep.
Merge partial into the state. Plain-object branches merge recursively;
arrays, class instances, Map, Set, Date and primitives replace the
slot. A key cannot be removed this way (undefined is stored as a
value); use emit or update for that.
@see ― emit for the StateContainer concerns layered onto super.patch.
patch({
user?:{
name?: string |undefined;
email?: string |undefined;
}|undefined
user:{
email?: string |undefined
email}});
}
// update: sugar for emit(fn(state)); replace immutably.
What’s still missing: a listener must somehow declare its path set. Writing it
by hand is a selector — the exact thing BlaC avoids. Stage 3 makes the read
itself the declaration.
Stage 3 — The recording proxy and the observed skeleton
A consumer declares which paths it reads by reading them. trackRender(state, interner) wraps state in a recording Proxy and returns
{ value, paths }: value is the proxy you read during render, paths is a
liveSet<PathId> that grows as you touch properties off value.
trackRender is internal (@dirtytalk/structural); the React adapter calls it
for you on every render, so you never import it directly. Shown here to make the
mechanism concrete:
The recording rules are deliberate, and each one earns its keep:
Leaf-only (maximal) recording. Reading user.name records user.name and
drops the intermediate user from the set. So when an immutable update
replaces the whole user object because a sibling (user.email) changed, a
consumer that only read user.name does not wake — its recorded leaf
still resolves to the same value. Read the whole user object (no deeper key)
and user stays your leaf, so any change inside it wakes you.
Own, non-symbol reads only. Symbol keys (Symbol.iterator) and inherited
prototype props never record. Re-reads are idempotent (it’s a Set).
Nested plain objects/arrays return child proxies recording into the same
set, cached per target so value.user === value.user within one render.
Iteration is per item..map / .find / for..of run against the
proxy, so they record items.length and each field the callback reads
(items.0.title, …). includes / indexOf / lastIndexOf run on the raw
array and record items.
Leaf collection types are not recursed.Map, Set, Date, and class
instances are returned raw (wrapping them would rebind receiver-checked
built-ins like Map.prototype.get). A reference change to the whole value
still wakes you, but an in-place .set() does not.
Now the payoff. With N consumers sharing a container, the naive way to find
who to wake is per-consumer diffing: N tree walks. BlaC does one walk plus
one lookup per changed path instead.
The trick is the observed skeleton: the union of every consumer’s watched
paths. On a mutation, emit diffs prev vs nextonly along the
skeleton — it reads each skeleton path in both states and includes it iff the
value moved (Object.is by default). The container keeps the skeleton as a path
trie, so the walk stops at every unchanged reference: replacing one item of a
1,000-item list compares 1,000 item references and descends into one. That one
walk produces the dirty set; then each changed path is looked up in an index of
the consumers watching it (Stage 2). You feed the skeleton through the public
consume / setPaths API:
Cubit<S> is a StateContainer<S> that exposes mutation publicly.
That is the whole difference, and it is a real one: on StateContaineremit / patch / update are protected, so a container mutates itself
from its own methods and callers go through the API it chooses to publish.
Cubit re-declares the three as public for the cases where a caller
legitimately drives state from outside — test helpers, devtools
time-travel, benchmarks.
Reach for StateContainer when business logic should live in the class,
and Cubit when the caller owns the transitions.
Cubit<S> is a StateContainer<S> that exposes mutation publicly.
That is the whole difference, and it is a real one: on StateContaineremit / patch / update are protected, so a container mutates itself
from its own methods and callers go through the API it chooses to publish.
Cubit re-declares the three as public for the cases where a caller
legitimately drives state from outside — test helpers, devtools
time-travel, benchmarks.
Reach for StateContainer when business logic should live in the class,
and Cubit when the caller owns the transitions.
Merge partial into the state. Plain-object branches merge recursively;
arrays, class instances, Map, Set, Date and primitives replace the
slot. A key cannot be removed this way (undefined is stored as a
value); use emit or update for that.
@see ― emit for the StateContainer concerns layered onto super.patch.
Register a reader. It watches nothing until setPaths is called; after
that cb runs, once per flush, when a watched path changed value. cb
receives the changed path ids among those any consumer watches.
consume(()=>
var console:Console
console.
Console.log(...data: any[]): void
The console.log() static method outputs a message to the console.
Replace the watched paths. The set is indexed as passed and must not be
mutated afterwards; passing the current set again is a no-op.
ALL_PATHS wakes on every change.
Register a reader. It watches nothing until setPaths is called; after
that cb runs, once per flush, when a watched path changed value. cb
receives the changed path ids among those any consumer watches.
consume((
dirty: PathSet
dirty)=>
var console:Console
console.
Console.log(...data: any[]): void
The console.log() static method outputs a message to the console.
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
map((
id: number
id)=>
const interner:PathInterner
interner.
PathInterner.lookup(id: PathId): string
lookup(
id: number
id))),
);
const b:Consumer
b.
Consumer.setPaths(paths: PathSet): void
Replace the watched paths. The set is indexed as passed and must not be
mutated afterwards; passing the current set again is a no-op.
ALL_PATHS wakes on every change.
// The skeleton is {user.name, user.email}. ONE diff walk, bounded to it,
// finds that only user.email moved: B wakes, A stays asleep.
const bloc:UserCubit
bloc.
UserCubit.setEmail(email: string): void
setEmail('ada@new.io');
consume(cb) registers a consumer and setPaths(paths) replaces what it
watches; the container recomputes the skeleton as the union of all consumers’
paths, and dispose() drops one.
emit(next) ─► diff(prev, next) along skeleton ◄── the ONE walk
│
▼
dirty = {user.email}
┌────────────┴────────────┐
▼ ▼
A ∩ dirty = ∅ B ∩ dirty = {user.email}
asleep WAKE
How React ties in
useBloc needs no selector because the JSX is the interest declaration.
Per render it renders against the recording proxy, then at commit calls
consumer.setPaths(paths) on its container.consume(...) consumer — after
render, since during render the set is still empty and would freeze an empty
skeleton, silently dropping wakeups. On unmount it calls consumer.dispose().
The consumer re-renders only when a watched path changed.
Conditional reads therefore reshape the skeleton automatically, render to
render. To opt out and gate re-renders by a derived value array instead, pass
select to useBloc.
Stage 4 — Cross-bloc dependencies
The final layer: one bloc leaning on another. This lives in @blac/core’s
StateContainer (the class Cubit extends), not in the structural engine —
deps are about identity and lifecycle, not path diffing.
this.depend(OtherBloc) declares a dependency and returns a DepHandle.
Calling .untracked() or .track() on the handle resolves the dependency
against the registry, so the declaring bloc never holds a stale instance
reference across dep churn:
Cubit<S> is a StateContainer<S> that exposes mutation publicly.
That is the whole difference, and it is a real one: on StateContaineremit / patch / update are protected, so a container mutates itself
from its own methods and callers go through the API it chooses to publish.
Cubit re-declares the three as public for the cases where a caller
legitimately drives state from outside — test helpers, devtools
time-travel, benchmarks.
Reach for StateContainer when business logic should live in the class,
and Cubit when the caller owns the transitions.
Cubit<S> is a StateContainer<S> that exposes mutation publicly.
That is the whole difference, and it is a real one: on StateContaineremit / patch / update are protected, so a container mutates itself
from its own methods and callers go through the API it chooses to publish.
Cubit re-declares the three as public for the cases where a caller
legitimately drives state from outside — test helpers, devtools
time-travel, benchmarks.
Reach for StateContainer when business logic should live in the class,
and Cubit when the caller owns the transitions.
Cubit<S> is a StateContainer<S> that exposes mutation publicly.
That is the whole difference, and it is a real one: on StateContaineremit / patch / update are protected, so a container mutates itself
from its own methods and callers go through the API it chooses to publish.
Cubit re-declares the three as public for the cases where a caller
legitimately drives state from outside — test helpers, devtools
time-travel, benchmarks.
Reach for StateContainer when business logic should live in the class,
and Cubit when the caller owns the transitions.
Cubit<{
ready: boolean
ready:boolean}>{
// `depend` returns a handle resolved against the registry per call.
Declare a cross-bloc dependency. Returns a branded handle with two
accessors — the dep instance is resolved against the registry on each call,
which keeps the surface immune to dep-instance churn:
handle.track(options?) — reactive read. Returns [state, instance].
Inside a getter reached through the React proxy this subscribes the
reading component to the dep's changes (base impl: live, no subscription).
handle.untracked(options?) — returns the live instance with no tracking,
for imperative method calls and one-off reads.
defaultArgs resolves the dep instance when an accessor is called without
its own args; per-call options.args overrides it and can derive from
current state. This does NOT auto-resubscribe outside the React proxy;
non-React consumers needing updates should subscribe explicitly.
depend separates .track() from .untracked().this.depend(AuthCubit)
records the dependency (visible via the dependencies getter) and returns a
DepHandle. Inside a method or background action, call this.auth.untracked()
to resolve the live AuthCubit via ensure() without registering a render
subscription. Inside a getter read during a React render, call
this.auth.track() — the active DepSession opened by useBloc’s getter
wrapper wraps the dependency in its own tracking proxy and subscribes the
consuming component to the exact leaf paths read on AuthCubit (without
creating a bloc-to-bloc channel cycle).
Per-consumer deps are a separate, owner-keyed mechanism. The
APPLY_DEPS / REMOVE_DEPS_OWNER symbols (from @blac/core/internal,
used by the React adapter) let each consumer inject a slice of deps keyed by an owner id;
StateContainer shallow-merges all live owners’ slices, dev-warns on
cross-owner key collisions (last write wins), and fires onDepsChanged only
when the merged view actually changes. This is distinct from depend’s
bloc-to-bloc resolution.
reads dep.state (.track() records leaf paths into the active
useBloc DepSession; .untracked() reads raw state)
StateContainer adds the rest of the lifecycle around these four stages:
identity ($blac.name, $blac.id), disposal, hydration, an
onSystemEvent('stateChanged' | 'dispose' | 'hydrationChanged', cb) surface,
and a dev-only emit-rate circuit breaker that warns once when a runaway loop
pushes too many changes through state in a second. But the reactivity itself is
the four stages above: a coalescing channel, interned paths, a recording proxy
feeding an observed skeleton, and a registry resolving cross-bloc deps.
Putting it together: one update, end to end
A single emit flows through all four stages:
A method calls emit / update / patch. StateContainer runs its guards
(disposed, equality short-circuit, emit-rate check), captures the
prev/next change, and delegates change-detection to
StructuralContainer. (Stage 1 + 4 wrapper.)
The container installs the new immutable state and computes the dirty
PathSet by diffing against the observed skeleton (patch is emit of the
merged state, so both take this path), then marks it on its channel.
(Stage 2 + 3.)
The DirtyChannel coalesces marks and schedules one flush per tick. (Stage 1.)
On flush, consumers are found by looking up each dirty path in the
container’s path index; ALL_PATHS consumers (subscribe, watch, plugins)
are woken by every flush. Only consumers whose watched paths changed have
their callback fired (React re-render, watch
callback, plugin sink). (Stage 1 + 2.)
On the next render, the proxy re-records each consumer’s interest from
scratch, so conditional reads reshape the skeleton automatically. (Stage 3.)
The practical takeaway is the same sentence the whole machine exists to make
true, cheaply: read exactly the state you render, keep state immutable, and
BlaC re-renders the minimum.
See also
Mental Model — the design narrative behind these stages.
Tracking — the React-time recording rules in reference form.