Architecture topic

cell_memory — Architecture

Author: Lee Man Hoi Simon (see AUTHORS)

This document explains the design of cell_memory (package:cell_memory): why the durability layer exists, how it sits on cell, and how a domain pulse becomes a durable record. It is the Memory counterpart to cell's own architecture notes.

Feature catalog: FEATURES-Memory.md. Application view from the Cell side: packages/cell/guide/HowTo-Memory.md. Machinery deep dive: guide/HowTo-Memory.md. Design record: doc/design/memory.md.


1. The core idea

cell is a graph of nodes (Cell), signals (Pulse), integrity gates (TestCell), and receptors. That is enough to hold state and notify observers — but nothing survives a restart.

cell_memory adds a durability layer on top of the same graph:

  1. A MemoryCell<T> is a Cell that wraps a domain cell.
  2. The domain cell keeps owning the value T; the memory cell owns the record — one durable row per id, carrying (revision, generation, payload, updatedAt, …).
  3. Every write is a compare-and-swap on (revision, generation), decided by one pure rule engine (MemoryCas) that every backend runs inside its own atomic section.
  4. All durability actions are turns on one FIFO mailbox, so a cell is a serialized executor, not a pile of races.

The graph, locks, validation, and provenance stay in cell. Memory only decides what gets written, when, and under which conflict rule.

cell             identity, lock, TestCell, Context, Synapses
cell_memory      one durable record per id; CAS; mailbox turns

Memory does not invent a second graph. A memory cell is a cell.


2. Progressive disclosure

Cognitive load should match the task. Persisting a counter must not require reading MemoryCellNucleus.

Tier What you use When
1. Sugar rememberState, remember Cell.state and common shapes — one call
2. MemoryCell.open The five config objects Full control of binding, lifecycle, policy
3. Config objects MemoryRecord, MemoryStrategy, MemoryLifecycle, MemoryInfrastructure, MemoryGovernance Codecs, TTL, debounce, ownership
4. Instruction catalog MemoryInfrastructure.customCatalog + the nine instruction classes Audit, veto, per-action replacement
5. Deep replacement SaveInstruction.writeTurn + MemoryFlushContext Replace persistence itself (encryption, custom CAS)
6. Surface composition MemoryCell.fromNucleus, MemoryCellNucleus, MemoryCellSlots, MemoryRuntime Capability views, link reconstruction

Moving from 1 toward 6 is a choice. If a Tier 1 call required nucleus knowledge to use correctly, that would be a design smell.


3. Component map

Component Role
MemoryCell<T> The surface: open, the turn API, snapshot, deputies. interface class — implementable externally, extendable in-library
MemoryCellNucleus<T> The machinery record: receptor, test rule, context, synapses, MemoryCellSlots
MemoryCellSlots<T> Immutable per-open configuration: id, store, codec, policy, scheduler, clock, source, lifecycle hooks, runtime, catalog
MemoryRuntime<T> The mutable state holder: revision, generation, baseline, counters, conflict, errors stream
MemorySnapshot The record view (a flyweight — compare fields, never identical)
MemoryPulse<T> / MemoryEvent The signal: loaded, applied, stored, conflicted, resolved, failed, unloaded, removed
MemoryEnvelope The durable row shape (schema 2, strict validation, canonical payload)
MemoryStore The backend contract (C1–C8) every store implements
MemoryDraft / MemoryVersion What a writer proposes / the (revision, generation) it read
MemoryCas The pure compare-and-swap rule engine; MemoryCasCommit / MemoryCasAlreadyApplied / MemoryCasConflict
MemoryCodec / JsonPayloadKey Value boundary: name + version + encode/decode; canonical payload equality
MemoryWritePolicy / MemoryScheduler / MemoryClock When writes happen; time is injectable
MemoryConflictPolicy / MemoryResolution The four conflict rules and the resolve commands
Nine instruction classes One subclassable decision unit per MemoryAction
MemoryFlushContext<T> The per-turn flush toolkit for deep replacement
_MemoryCellDeputy, UnmodifiableMemoryCell Narrowed surfaces over the same runtime

4. The five config pillars

MemoryCell.open takes five objects — one per architectural concern, all const-constructible except MemoryRecord (which validates its id):

Pillar Fields Concern
MemoryRecord<T> id, store, codec Identity: which durable row, where, encoded how
MemoryStrategy write, conflict, ttl Governance of writes: cadence, conflict rule, expiry
MemoryLifecycle<T> read, hydrate, project, mode Domain wiring: how to read/hydrate the domain, what pulses mean
MemoryInfrastructure scheduler, clock, ownsStore, customCatalog Machinery: time, scheduling, store ownership, instruction overrides
MemoryGovernance context, testRule, synapses, ephemeralPolicy Framework gate: the cell-level quartet on top of the domain

Two rules shape everything:

  • read defaults to the domain ValueCell.value — a non-ValueCell domain without an explicit read is an ArgumentError.
  • hydrate is the only store→domain path. A load or a conflict adoption writes back through hydrate; nothing else touches the domain. adopt/merge conflict policies require it.

MemoryCell.open(source, record:, strategy:, lifecycle:, infrastructure:, governance:)
1. Validate            adopt/merge requires hydrate; id grammar checked by MemoryRecord
2. Build slots         one immutable record: id, store, codec, policy, clock, source,
                       read/hydrate/project, conflict, ttl, ownsStore, runtime, catalog
3. Build catalog       the nine defaults, then merge infrastructure.customCatalog
4. Build receptor      Receptor.instruction(_memoryDispatcherChain(catalog))
5. Build nucleus       MemoryCellNucleus(slots:, receptor:, context:, synapses:,
                       testRule:, ephemeralPolicy:)
6. Activate            MemoryCell._(nucleus) -> CellBase.fromNucleus -> the live surface
7. Open mode           load / seed / loadOrSeed / dormant — the initial I/O contract

The dispatcher chain is the runtime heart:

pulse (command or ingress)
    │
    ▼
_memoryActionOf(pulse)            action from the command type or the ingress shape
    │
    ▼
catalog[action]                   fail-closed: a missing entry completes the
    │                              command with StateError; missing apply drops
    ▼
instruction.handle / turn         the decision unit
    │
    ▼
resume + synapses                 one broadcast per registry; deputies mirror to
                                   the root cell's registry first

6. The pulse path: domain pulse → durable row

domain cell pulse
    │
    ▼
apply instruction                  project(pulse) -> payload?  (null suppresses)
    │
    ▼
touched = true; pulseCounter++
    │
    ▼
write policy schedules a flush    immediate (coalesced) / debounced+maxWait /
                                   explicit (nothing until save())
    │
    ▼
writeTurn(cell, flush)             the save instruction; barriers (save, unload,
    │                              close, seed) all route through the same turn
    ▼
flush.read!()                      reads the domain NOW — never the pulse
    │
    ▼
payloadKey                        canonical payload key == baseline? -> clean, no write
    │
    ▼
store.write(MemoryDraft,          MemoryCas.decide inside the store's atomic section
  expected: MemoryVersion?)
    │
    ├── MemoryCasCommit            -> committed envelope (store assigns revision)
    ├── MemoryCasAlreadyApplied    -> the stored row (lost-response retry)
    └── MemoryCasConflict          -> MemoryConflict; route through conflict policy
    │
    ▼
adoptCommitted                    baseline adopted; touched=false; emit MemoryPulse(stored)

Invariants this path enforces:

  • The flush reads the domain now. A pulse that scheduled a write is not the payload of that write.
  • Equal payload keys mean clean. The same value is never rewritten.
  • The store assigns revisions. Caller numbering bugs are impossible; every backend runs the same MemoryCas.decide.
  • Expired is equivalent to absent for read, write, CAS, and list.

7. The conflict protocol

Every write carries expected = (revision, generation). When the store holds a different row:

Policy Rule
fail Report MemoryConflict, suspend autosave until resolve
overwrite Rebase to the stored row and retry — still CAS-protected
adopt (default) Decode the stored row, hydrate the domain, drop local
merge fn(local, remote) → hydrate → rebase → write

MemoryResolution closes the loop: takeLocal, takeRemote, or a custom adoption. The generation column is the ABA guard: a stale writer from a previous record life carries the old generation and can never install a revision into the recreated history. Lost-response retries (same content, adjacent revision) are successful no-ops, never double-writes.


8. The mailbox: every action is a turn

load, save, resolve, attach, detach, unload, close, and remove are turns on one FIFO mailbox:

  • close() latches admission; queued turns drain; every admitted future completes exactly once.
  • Cross-capability routes (unload's flush barrier, attach's adopt, detach's unwiring) call the other actions through the same catalog — one catalog, one set of custom instructions, no divergent behavior.
  • save() on a fresh, untouched cell is a no-op: a save is not a persist. Use MemoryOpenMode.loadOrSeed/seed or deliver a pulse.

9. The instruction seam

The nine durability actions are nine public, subclassable instruction classes — one per MemoryAction — assembled into a catalog. The dispatcher is fail-closed: a partial catalog is a capability view, not a crash. writeTurn receives a per-turn MemoryFlushContext — the complete flush toolkit (record identity, baseline handles, encoding, adoptCommitted/adoptRemote/suspendConflict) — so a replacement can own persistence without private access. A custom flush that never adopts a baseline owns the baseline: the cell keeps reporting the record unchanged.

The governance gate always sits above the catalog: the cell's TestCell vets the command before any custom instruction runs — no customization can bypass deputy narrowing.


10. Surface reconstruction

The catalog lives in MemoryCellSlots — the nucleus's machinery record, not the cell. MemoryCell.fromNucleus(nucleus, {catalog}) therefore rebuilds surfaces safely:

  • Same-link views (no catalog): same receptor, same runtime, same record — forensic symmetry: lenses on one link.
  • Derivative views (catalog): a fresh chain under the same principal runtime — per-view mix-and-match.
  • Activation belongs to a surface: the walk to the root stops at unactivated principals, so standalone composition units work.

Cell view = memory; is the type-erasure idiom: a consumer that must not see save/load/remove gets the reactive surface only.


11. Backends

MemoryStore is the durable backend contract (C1–C8): typed errors, id grammar before IO, atomic per-id writes through MemoryCas, expired-is-absent, idempotent draining close, settled list, and defensive copies. MemoryStoreCapabilities declares what a backend guarantees (crossProcessCas, serverClock, nativeTtl, recommendedPolicy) so callers can warn instead of assume.

Backend Package Notes
InMemoryMemoryStore cell_memory The reference implementation; the conformance battery runs on it first
FileMemoryStore cell_memory (cell_memory_io.dart) One JSON file per id; dart:io only
FirebaseMemoryStore cell_memory_firebase Firestore documents under users/{uid}/cell_memory/{id}; Flutter only
SqliteMemoryStore cell_memory_sqlite BEGIN IMMEDIATE transactions, schema 2, user_version migrations; Flutter only

12. Cross-package boundaries

Package Relationship
cell The foundation: graph, gates, receptors. Memory consumes it, never the reverse
cell_memory This layer: one durable record per id
cell_tissue_memory Typed wrappers (MemoryTissue, MemoryTissueValue, MemoryTissueMap) persisting tissue snapshots — the tissue book stays in cell_tissue
cell_memory_firebase, cell_memory_sqlite Store backends; same contract, different atomic sections
cell_memory_live_demo The two-kiosk demo: hydrate restore, fail-policy provenance, replay

The documentation mirrors keep the four application views in sync: packages/cell/guide/HowTo-Memory.md, guide/HowTo-Memory.md, packages/cell_tissue/guide/HowTo-Memory.md, and packages/cell_tissue_memory/guide/HowTo-Memory.md.


13. Design invariants

  1. The domain owns T; the memory cell owns the record. snapshot is a MemorySnapshot — never the value.
  2. One baseline per open: (revision, generation, payloadKey).
  3. Flush reads the domain now; equal payload key = clean; no duplicate writes.
  4. hydrate is the only store→domain mutation path.
  5. Conflicts are protocol, not exceptions to hide; the generation column guards ABA across record lives.
  6. One mailbox; every admitted future completes exactly once; close is idempotent and drains.
  7. Stores assign revisions through MemoryCas; backends cannot drift in conflict rules.
  8. The catalog is fail-closed; the governance gate sits above it.
  9. A custom flush owns the baseline it does not adopt.
  10. MemorySnapshot is a flyweight; compare fields, never identical.
  11. A failed open never leaks: the error stream closes and an owned store is closed before the error rethrows.
  12. Ids are ^[A-Za-z0-9._-]{1,128}$, one path segment — validated before any IO in every mode.

14. Verification surface

Suite Proves
test/runtime_test.dart The behavioral contract of every rule above
test/fuzz_test.dart Eight fixed seeds of randomized operations against a fault-injecting store; seven invariants checked every step
test/store_contract_suite.dart The C1–C8 battery every backend runs
test/instruction_catalog_test.dart Catalog interposition, deep replacement, custom routing
test/from_nucleus_test.dart Surface reconstruction, capability views, forensic symmetry
test/guide_snippet_test.dart Every full-program snippet in guide/HowTo-Memory.md
Downstream mirrors packages/cell, packages/cell_tissue, packages/cell_tissue_memory, packages/cell_memory_firebase

A behavior that is not pinned by one of these suites is a behavior the next refactor will silently change.

Classes

MemoryCell<T> Getting Started Features Architecture
A durable Cell implementation that persists its state to a MemoryStore.