DSH plugin projection units: snapshots and change streams
The common projection failure is not a wrong computation; it is conflating "read state" with "subscribe to changes." DSH plugin's session projection is a capability seam: the registry drives, and the domain only computes. Until you separate those duties, you cannot tell when to reach for snapshot(), stateOf(), or onChanged().
Three parties: the registry drives, domains compute
The framework drives, the domain computes, and the client only receives finished values.(source)
The split is strict:
- Service definition and registry —
ctx.sessionProjectionssubscribes tosession/eventexactly once and folds each committed event into every unit; - Domain contributors — each domain registers one pure unit and holds no subscription of its own;
- Carriers — the history tail page of
dsh-session-controllerand the pushedsession/projectionframes.
That division rules out a familiar pattern: a plugin listening to session events, maintaining its own derived state, then reconciling with the registry. Domains do not own subscriptions, and clients never fold domain events — they receive finished values. Host-side state readers require the registry while active, so declare sessionProjections as a required injection.
A unit must satisfy three hard constraints
Pure, synchronous, and JSON-serializable are the preconditions for being driven.(source)
The ProjectionDefinition description is blunt:
- Pure synchronous fold — one synchronous fold plus declarations and an optional client view, never an opaque getter. All functions must be synchronous; async units tear the carrier's read-consistency seam.
- Plain JSON state — a precondition for the persisted cache, not a style preference.
- Same reference for irrelevant events —
applymust return the identical state reference for events the unit does not care about; with an unchanged reference, downstream work is zero.
Three declarations are mandatory: key, stateSchema, and stateVersion. stateSchema validates persisted state before folding, and init receives the immutable SessionHeader plus the exact inheritedEventCount to produce the empty-log state.
stateVersion is a non-negative cache-invalidation version. The official upgrade rule is precise: bump it when state fields or fold semantics change; but a change that only adds an optional field, keeps historical meaning when absent, and makes suffix replay from old checkpoints equivalent to a full replay may keep the version. Before saving that bump, test the equivalence — passing schema validation is not enough.
wire decides client visibility, not rendering
Whether a unit has wire decides client-visible versus host-only; wire governs publication, never rendering.(source)
Only client-visible keys merge into SessionProjectionMap, which constrains their full values. The wire block has three parts: viewSchema, view(state), and an optional summary. viewSchema validates a payload before it leaves the host, and view returns the key's complete current value — the read-side projection.
Publication depends on a detail that is often missed: the live driver keeps the last two raw view results and compares them with Object.is. An object-valued view that wants to suppress publication when only internal state changes must therefore reuse references. Skip that, and the UI receives a frame every time an internal counter moves.
summary defaults to true. It defines the runtime key set, while the client view type follows the SessionProjectionSummaryExcluded marker — the two must be kept in sync by hand. Rendering belongs to the slot system and never to this layer; wire only makes a unit visible to clients.
Snapshot and change stream: one cut, two listeners
A snapshot guarantees values share one sequence; a change stream tells you only what moved.(source)
ProjectionSnapshot has two fields: asOfSeq and values. asOfSeq is the shared watermark — the last event sequence all values reflect, and -1 for an empty log. snapshot() is fully synchronous; the carrier reads it in the same tick that cuts the page slice, so two reads share one sequence and you never see a fresh value above a stale watermark.
Listeners come in two granularities:
onChanged(listener)— fires once per session and key when that unit's rawviewresult changes byObject.is, carryingvalueand the triggeringseq;onEventChanged(listener)— fires once per event that changed at least one client-visible unit, withchangeslisting each key and validatedvalin registration order.
Ordering matters: onEventChanged runs synchronously inside the committed session/event handling, after every unit has been driven and after that event's onChanged calls. There is also a fault-tolerance rule: if a unit or an onChanged listener throws mid-drive, the event-level listener still receives changes produced before the throw.
For live host state, use handle.stateOf(session). It skips unrelated views and returns a borrowed reference that callers must not mutate.
Summary reads: the key set is defined in one place
A list row carries the summary projection, not the full one, and the two key sets are not interchangeable.(source)
A summary includes every registered client view except keys whose SessionProjectionMap entry carries the SessionProjectionSummaryExcluded<T> marker. That marker has no runtime representation: it shapes the client view type, while the runtime key set comes from wire.summary, defaulting to true when omitted. So a marked key should explicitly declare wire.summary: false — the type layer will not force it.
summaryKeys() derives its set from the live registry and keeps returning the same instance until registration changes the key table. Consumers pass it to the existing key-taking read surfaces: snapshot(session, keys) for live sessions, viewCheckpoint(rows, keys) for checkpoint rows. Both use the Set directly without copying, so there is no summary-only read path and the set is defined once.
cachedSnapshot() is deprecated for a practical reason: it returns only values other reads already computed, so keys can be missing. List rows promise the summary key set and nothing more; only the full snapshot after opening a session carries every projection value.
Registration lifecycle: shared by key, removed on last release
Registration belongs to the calling fiber, release is reference-counted, and the handle still reads after release.(source)
register(definition) returns an awaitable ProjectionHandle, and domains must wait for registration before publishing consumers during activation, because registration itself may do async work. Three lifecycle rules:
- Shared by key — registrations with the same key and
stateVersionshare one unit and are counted; incompatible versions fail the registration outright. - Removed on last release — the final release drops the key from global driving, restore, and client snapshots, while checkpoints keep each session's last state until the key is registered again and a new unit re-folds the log.
- Handles keep reading — a
ProjectionHandleretains its synchronous reader after unregistering.stateOf(session)folds newly committed events with the original unit without rejoining global snapshots or notifications, andreaderFor(session)returns a synchronous callback under the same rules that does not own teardown.
Cached units are built lazily: if a unit registers after events exist, or a session predates the registry, the first access — event or read — folds the in-memory log starting from init. That explains "the new plugin read the whole history as soon as it was installed": not preloading, but first-access catch-up.
Two persistence-side read surfaces are worth knowing. checkpoint(session) yields one row per registered key, each a structured clone detached from the live unit — never a live reference. restoreFloor(checkpoint) gives the suffix re-read start, and a single mismatched row version pulls that start back to 0, forcing a full re-fold for that key so a crash-truncated log is never mistaken for a valid cache.
The zero-I/O viewCheckpoint(rows, keys) reads rows only, never the log: values may be as old as the rows, but it never fails. It suits lists and cold starts, not "is this current" judgments.
Verification: walk one session through both paths
Both read paths must converge on the same watermark, or you are reading two truths.(source)
- Register a unit with
wire, makeapplyreturn the same reference for unrelated events, and assert no change fires. - Commit a relevant event, receive one
onChangedcallback, and record itsseq. - Call
snapshot(session)in the same tick and assertasOfSeqequals thatseq. - Register a host-only unit without
wireand assertsnapshot().valuesdoes not contain it. - Call
summaryKeys()twice and assert the same instance; then read withsnapshot(session, keys)to get only summary keys. - Unregister the unit, call
stateOf(session)on a new event, and assert it still folds while producing no global snapshot entry.
If step 3 disagrees, confirm the event was actually committed first — change streams fire only after commit, and asOfSeq reflects only committed watermarks at read time. For cross-window folding and replacement generations, compare derived messages and session log.
One line to close: units stay pure and synchronous, wire controls visibility rather than rendering, snapshots read the watermark while streams read granularity, and summary keys come only from summaryKeys().
FAQ
No. DSH plugin requires every unit function to be synchronous. The unit contract says async units tear the carrier's read-consistency seam, so apply, init, and view must all be synchronous pure functions.
The same state reference. DSH plugin compares with Object.is, and an unchanged reference produces no downstream computation and no publication at all.
No. DSH plugin computes only selected client-visible units. Without a key subset it computes every client-visible unit; host-only units are neither folded nor advanced.
No. DSH plugin's summaryKeys() returns the same instance until registration changes the key table, so you can hold it across lines and pass it to snapshot or viewCheckpoint.
Related Terms
- ProjectionDefinition
- ProjectionDefinition is a state-driven computation unit for one domain: key, stateSchema, init, apply, optional wire, and stateVersion.— packages/session/session-projection/src/index.ts
- ProjectionSnapshot
- ProjectionSnapshot is one consistent read cut over all registered client-visible units of a session, carrying asOfSeq and each key's current value.— packages/session/session-projection/src/index.ts
- asOfSeq
- asOfSeq is the snapshot's shared watermark: the last event sequence all values reflect, and -1 for an empty log.— packages/session/session-projection/src/index.ts
- summaryKeys
- summaryKeys returns the client-visible key set carried by summaries, holding the same instance until key registration changes.— packages/session/session-projection/src/index.ts
Sources
- DeepSeek Harness reference - Session projection· deepseek-ai
- packages/session/session-projection/src/index.ts· deepseek-ai