The native event lane and the projector charter
Status: accepted
Date: 2026-08-01
Relates to: ADR-0052 (fine-grained competency referents — amends decision 3’s transport wording;
implements its projector), ADR-0057 (merge lifecycle — decision 4’s merge-touched contract binds
the projector), ADR-0014 (erasure), the C1 archive lane
(packages/db/src/schema/archive.ts), docs/design/language-module-phase-2-plan.md (slices
2a-4 and the queue adapter), the pgxsinkit event-queue ingestion feature (spec delivered to the
pgxsinkit repo 2026-08-01).
Context
Section titled “Context”The language module produces high-volume, append-only client events: token encounters while reading, aid interactions, reading spans, later review grades — thousands per session, on the order of 10⁵ rows/year per committed learner. ADR-0052 decision 3 placed these “on the sync rail as a retention-trimmed buffer” forwarded to the archive. Design review of that transport found it wrong-shaped: events are never read back down (other devices need derived state, not the log), never update and never conflict (LWW/overlay/apply machinery is pure cost), and the rail residence manufactures a retention-vs-consumption ordering problem that exists only because of the transport choice.
Separately, ADR-0052 names a single server-side projector as the only reader of raw events and the only writer of derived learner-model state, and ADR-0057 decision 4 obligates it to honor merge-touched stamps. Phase 2 must charter that projector concretely.
Decisions
Section titled “Decisions”-
Events are queue-shaped, not sync-state-shaped. The client appends events to a local-only outbox (a plain PGlite table, durable, queryable, never in the sync registry) and flushes them in idempotent batches to a server ingestion endpoint, which delivers them through a queue to a consumer callback. The outbox, flush endpoint, queue abstraction (pgmq built-in), and consumer runner are pgxsinkit library infrastructure (maintainer-ratified scope; spec in the pgxsinkit repo). Emergent owns only per-stream payload schemas, the claims/consent gating hooks, and the consumer callback. This amends ADR-0052 decision 3’s transport wording; the summarisation boundary itself is unchanged.
-
The archive is the sole primary store, written on arrival. The consumer callback is “archive-insert + projector fold, atomically per batch”: events land in the C1 archive stream tables (deduped on the client-generated event id) and are folded into derived state in the same transaction. The fold’s input is exactly the rows the archive insert actually inserted —
INSERT … ON CONFLICT DO NOTHING … RETURNING— never the delivered batch payload: a redelivered event deduplicated at the archive can therefore never reach the fold, which is what turns at-least-once queue delivery into effectively-exactly-once processing rather than merely exactly-once storage. Everything the projector writes is rebuildable; the archive is the only thing that is not. -
The C1 forwarder is dormant, and the stream contract splits. With no events resident on the sync rail, the copy-then-delete forwarder has no producers. Its machinery remains (the archive envelope, mandatory retention, and the mandatory anonymization projection are all about the archive itself and stay load-bearing); the forwarder seam is recorded as machinery without a client, kept against future synced-table archival needs. Consequently the current
ArchiveStreamDefinition— which welds durable-stream policy (name, payload version, retention, anonymize) to rail-forwarder bindings (source table/columns, client retention) — is refactored in slice 2a-4: the durable half becomes the base native-stream definition (plus the client-event-id dedupe key), and the rail bindings become an optional adapter layered on it. Native streams register through the base; no dummy rail tables are ever created to satisfy the old shape. -
Event payloads carry lexeme ids (ADR-0059’s identity layer), the ported enriched-content shape: the projector resolves lexeme → node through
lang_lexeme.competency_node_id, minting lazily where the bridge is null. -
The projector’s Phase-2 write-set, per consumed batch, in one transaction with the archive insert: (a) lazy node minting for novel lexemes — through
resolveNodeKey(alias redirects honored per ADR-0057 decision 3),machine-segmentedtier, under the rolling lexicon edition, bridge column set; (b)lang_node_factaccumulation (facts only — counts, timestamps; no interpretation); (c)lang_node_policy_outputrecomputation for touched rows, stamped with the module policy version (the portedLEARNER_POLICY_VERSIONformalism); (d)person_competency_evidencetransitions and summaries through the B4 contract (archive provenance is the consumed rows’ bigint id range); (e)person_competency_statederivation, honoring ADR-0057 merge-touched stamps as standing work items and clearing them after re-derivation. Because a stamp is standing work, its discharge cannot depend on event arrival: the projector runner has two work sources — consumed event batches and a merge-touched sweep that scans for stamped derivation rows on its own cadence — so a merge followed by silence still re-derives. Two seams are named but deliberately deferred: upward aggregation into list/level mastery (Phase 3, when curated list memberships exist) and goal-progress evaluation (Phase 5,goal.criterion_policy_versionis the seam). -
Replay has two classes. Policy-only bump (the common case): recompute
lang_node_policy_outputfrom the facts tables — no archive read, no evidence re-emission — and re-deriveperson_competency_statefor the touched rows (state is a pure function of the derivation inputs; historical evidence rows stay, each stamped with the policy version that emitted it). This is what the Q2 facts/policy table split buys. Full re-derivation (rare): reset the stream cursor and truncate-and-rebuild everything projector-written. Ownership is precise: the module tables (lang_node_fact,lang_node_policy_output) are wholly projector-owned and truncate cleanly; core evidence rows are deleted only where the B4 archive-provenance marker identifies them as projector-authored;person_competency_stateis then re-derived from the surviving evidence plus the re-emitted rows — state contributed by other producers (assessments, declarations) is input to re-derivation, never truncated away. Projector-authored evidence is derived output with archive provenance, not primary fact; deleting and re-emitting it under a new derivation is legitimate by construction. Full re-derivation is a maintenance operation: the consumer runner is quiesced behind the same lock the replay holds, the cursor reset + rebuild happen behind it, and live consumption resumes only after the rebuild commits. Replay reads the archive through the same fold functions the live path uses; the queue is only the live iterator. -
Replay-path-first build order. The fold is implemented as pure functions driven by an archive scan and fully tested there; the queue-consumer callback is a thin adapter added when the pgxsinkit feature ships. No temporary ingest scaffolding is built.
-
Four streams, indefinite retention, anonymization as the privacy control.
lang_token_encounter,lang_aid_interaction,lang_reading_spanregister in Phase 2;lang_review_gradein Phase 5. All declare indefinite retention; each declares its mandatory anonymization projection (the P4 contract) — erasure severs the person and scrubs payload identifiers, and the de-identified corpus remains the research and replay substrate. Strict-zod versioned payloads per stream (the ported transcrobes practice). -
Standards ingestion stays separate. cmi5/xAPI/Caliper endpoints remain the external compatibility surfaces; mapping standards statements into the archive as projector input is deferred until a concrete Phase-3+ need exists, and is recorded as an open mapping question, not an obligation.
-
Order-independence is by construction, not by an ordering contract. The fold is designed commutative: facts are monotone accumulations (counts, first/last timestamps), and policy outputs, evidence transitions, and state are pure functions of the accumulated facts plus a policy version. No canonical cross-stream event ordering exists or is needed — invariant 7’s “orderable and replay-safe” is satisfied by convergence: any interleaving of batches, and any replay, reaches the same derived state. Concurrent consumer batches touching the same person serialize per
(person, node)row through ordinary row locking on the facts tables (batch writes key-ordered to preclude deadlock); where the fold mints or re-points nodes it takes the framework advisory lock first, per the merge machinery’s advisory-before-row-locks ordering. Evidence-transition timing may vary with interleaving; transitions are derived, rebuildable observations, never load-bearing ordering artifacts. -
The consumer gate: erasure is checked at consumption, not only at acceptance. The durable queue is a time window — an event accepted before an erasure pass can be delivered after it, and without a gate it would recreate person-linked archive rows and derived state the pass just removed. The consumer callback therefore checks the person’s erasure tombstone per batch: for an erased person the archive insert applies the stream’s anonymization projection on arrival (person link severed, payload scrubbed — the same terminal state the erasure pass itself produces) and the fold writes nothing derived. The identical gate covers dead-letter redelivery, which is just late delivery. Research-consent withdrawal is deliberately not an event-lane concern: under ADR-0008’s capture-all/gate-use model these events are operational telemetry captured under the operational basis, and withdrawal gates downstream research use (the de-identified projection and the use-gate), never operational capture or the learner-model fold.
-
Offline model advance is backlogged, by explicit ruling. The predecessor never advanced aggregates offline (down-sync only) and shipped fine. The recorded candidate design if it is ever wanted: a client view composing down-synced aggregates with the pending outbox (drained outbox ⇒ committed stats, otherwise best guess — these are sensor-fusion estimates, not balances). The generic outbox’s queryability and drain signal are the enabling hooks; nothing else is built now.
Alternatives rejected
Section titled “Alternatives rejected”- Events on the sync rail (the original ADR-0052 wording): wrong-shaped per Context; also the source of the forwarder/projector ordering problem this ADR dissolves.
- Projector reads the rail with ack-gated deletion: stitched replay (archive + rail, two stores), unbounded rail growth on projector stall.
- Archive-and-project fused into the forwarder: welds the projector’s failure domain and cadence to housekeeping.
- LISTEN/NOTIFY or bespoke trigger design in emergent: delivery pacing is the pgxsinkit consumer runner’s implementation detail (maintainer-ratified), not consumer-app design space.
- Windowed retention on high-volume streams: trades replay-from-origin and longitudinal research value to bound storage that is cheap for years at these row sizes.
Consequences
Section titled “Consequences”- The rail carries only state (operational tier, preferences, resolution index); nothing event-shaped rides replication. Client stores stay lean by construction.
- Emergent’s slice 2a-4 can be built and fully verified before the pgxsinkit feature lands.
- Erasure obligations for the event lane collapse onto the archive (per-stream anonymize) plus the client outbox (local-only; dies with the local store).
- The projector inherits and discharges the two contracts recorded against it in Phase 1: merge-touched stamps (ADR-0057 decision 4) and rolling-edition evidence stamping (decision 6).
Amendments
Section titled “Amendments”Amendment (2026-09-09, language-module Phase 5, ruling R2): lang_card is client-written
Section titled “Amendment (2026-09-09, language-module Phase 5, ruling R2): lang_card is client-written”Decisions 2 and 6 make the server-side projector the only writer of derived learner-model state, and decision 12 backlogs offline model advance outright (“the predecessor never advanced aggregates offline and shipped fine”). Phase 5’s spaced-repetition scheduler is the one place that reading does not hold, and the exception is ruled rather than assumed.
The exception. lang_card — one row per (person, lexeme, card type) carrying the SM-2 schedule
(gap, repetition, efactor, due_at, known, and the three practice instants) — is written by
the CLIENT, in the same act as the grade, and synced last-writer-wins on the ordinary owner-readwrite
posture. Its companion lang_practice_config is ordinary learner configuration and needs no
exception at all. The projector computes no scheduling.
Why. A card’s schedule is derived state by decision 2’s definition, so the projector “should” own it. But an SRS whose grade only takes effect after a server round trip is not offline, and offline is the product: this is a tool people use on trains and planes, and the plan’s red lines state that the next card must appear in under 250–300 ms and that a last-writer-wins overwrite is acceptable wherever it keeps the design simple, fast and offline. Routing the schedule through the projector would mean a learner grading a card on a plane sees nothing change until they land. The predecessor kept card rows client-side and synced them; decision 12’s backlog is about aggregates (counts, coverage, verdicts), which continue to arrive with sync exactly as before.
What the exception does not touch. Everything else in the fold is unchanged. The grade still
lands on the event lane and in the archive (decision 8’s lang_review_grade, Phase-5-extended with a
review source and an optional cardType — a compatible payload change, so the stream keeps its
name and version); lang_node_fact still accumulates from the archive; lang_node_policy_output
still derives aids_off / counts_as_known / srs_eligible; a grade’s effect on aids still arrives
with sync. The projector gains no scheduling responsibility and loses none of its existing ones.
Why it stays safe. Because the grade event is archived, card state remains REBUILDABLE from the archive by construction — the same property decision 2 gives everything else the projector writes. Building that rebuild is a recorded deferral, not a plan: it is a maintenance act for a maintenance need that does not yet exist. The invariant this preserves is the one that matters — the archive is still the only thing that is not rebuildable.
Boundary, for the next author. This is an exception for ONE table, justified by the offline latency requirement of a drill loop. It is not a precedent for client-written derived state in general: anything else that wants it must show the same property (the learner acts on the derived value within the same interaction, offline) and be recorded here the same way.
Amendment (2026-09-12, language-module offline plan, rulings R1/R2): lang_word_state is client-written
Section titled “Amendment (2026-09-12, language-module offline plan, rulings R1/R2): lang_word_state is client-written”The Phase-5 exception above is extended to a second table, for the same reason and on the same terms, and the verdict layer above it changes with it.
lang_word_state is CLIENT-written. One row per (person, lexeme) carrying first_success_at
and excluded, written by the device in the same act as the grade or the exclusion, synced
last-writer-wins on the ordinary owner-readwrite posture. It replaces lang_node_declaration, which
was already client-written and carried the second of those two fields.
The encounter inference is DROPPED. The module policy’s “aids off after three unaided encounters
with no aid asked for since” — v1’s stand-in for the predecessor’s first_success_date, kept in v2
as a weaker second route — is removed. It was the one input a client could not hold, because an
unaided-encounter count is an accumulation the projector owns, so any verdict consulting it could
never be computed offline. LANG_MODULE_POLICY_VERSION is 3, and the verdict is now exactly the
predecessor’s rule over the two fields above, evaluated by one shared function in @emergent/domain
that the client and the projector both call.
Why. The same argument decision 12 does not cover and the lang_card amendment already made:
“does this learner still need help with this word” is asked of every token the renderer draws, and
before this it travelled event → outbox → server queue → projector → sync down. Offline that loop
never closes, so a learner grading a word on a plane kept the gloss for the rest of the flight. The
predecessor wrote this row in the same act as the grade and answered from one indexed scan of it.
Decision 5(c)’s policy table is retired by S2 of that plan. lang_node_policy_output still
exists and the fold still writes it this slice; once every client reader has moved to the word state,
it leaves the client registry and then the schema, and the projector evaluates the shared function
wherever it derives person_competency_state, evidence transitions, list mastery and goal progress.
(Done: see the R6 amendment below.)
Amendment (2026-09-12, language-module offline plan R6): decision 5(c) is retired — no policy table
Section titled “Amendment (2026-09-12, language-module offline plan R6): decision 5(c) is retired — no policy table”There is no materialised verdict. lang_node_policy_output is deleted — from the client registry,
the schema, the erasure registry, the merge’s referrer set, the Circuits publication list and the fold.
The verdict is computeWordVerdict over the client-written lang_word_state, evaluated by the CLIENT for
every surface it draws and by the PROJECTOR for the derivations only a server can make
(person_competency_state, the evidence transitions, list mastery, goal progress).
What follows from it. The fold’s judgment step writes state and evidence only. List mastery counts a
member as known with an EXISTS over the learner’s own word state through the lang_lexeme bridge — the
same two-column predicate at the same cost — conjoined with the demonstrated state row that carries the
ownership rule. The policy-version replay class keeps its name and its role, and scans the module’s own
stamped person_competency_state rows for staleness instead of a verdict table. A merge no longer discards
derived verdicts; the merge-touched stamp on the state row is the whole of how it records that the inputs
moved. LANG_MODULE_POLICY_VERSION stays (it stamps the state rows).
Why a stored verdict was the wrong shape. It could only ever be written by the projector, so every verdict reached a device through event → outbox → server queue → projector → sync down — a loop that never closes offline, for a question asked of every token the renderer draws. Computing it where it is read makes it immediate, and makes “two implementations of what this learner knows” impossible by construction: there is one function, and both sides call it.
A future server-side derivation that needs a materialised figure gets its own table, named for that derivation. It never becomes the reading verdict.
Amendment (2026-09-13, language-module offline plan R3–R5): decision 12 is promoted — additive facts are composed
Section titled “Amendment (2026-09-13, language-module offline plan R3–R5): decision 12 is promoted — additive facts are composed”Decision 12 backlogged offline model advance and recorded the candidate design it would take: “a client view composing down-synced aggregates with the pending outbox”. That candidate is now the DESIGN for the language module’s additive facts, and the three things decision 12 left open are settled here.
What is composed. lang_node_fact (encounter / unaided / aid / grade / success counts and the first-last
windows) and lang_day_fact (the five day tallies, reading milliseconds included) are read as
synced row ⊕ pending events, where the pending events are this device’s Outbox rows on the four language
observation streams. The node axis is keyed by LEXEME — events carry lexeme ids, synced facts reach the lexeme
through the lang_lexeme_<lang>.competency_node_id bridge, and a lexeme the projector has never minted a row
for contributes a pending-only entry — and the day axis by UTC day. The fold rules are the projector’s own,
evaluated on the client over the same imported langGradeIsSuccess and utcDayOf, so a composed figure and
the row it composes with cannot disagree about what a success is or which day something happened on.
Why the projector charter is untouched by it. Nothing here WRITES derived state: the composition is a
READ, assembled per delivery and never persisted, so decisions 2 and 5(b) hold exactly as before — the
projector remains the only writer of lang_node_fact and lang_day_fact, and the archive remains the only
thing that is not rebuildable. This is not a third exception beside lang_card and lang_word_state; it is
the read-side answer that makes further write-side exceptions unnecessary.
The grace rule, because acked does not mean folded. An event leaves the pending set when the SERVER
ACCEPTS it, which is before its consumer folds it and well before the fold syncs back down — so a composition
that dropped it at the ack would DIP for that whole window, online, on a healthy deployment. pgxsinkit’s
acked ledger (ADR-0060) retains an accepted row, stamped with acked_at_us, for events.ackedRetentionMs
(emergent: 60 000 ms). An acked row keeps contributing UNTIL the composition observes the synced row FOR ITS
OWN KEY change at an instant AFTER the ack; both instants are taken on the CLIENT clock, so server skew cannot
retire an event early or hold one late, and the retention is the backstop for the case where the observation
never comes.
Presence is a union; counters are estimates. Decision 12’s own framing — “sensor-fusion estimates, not balances” — is kept and sharpened into a rule with teeth. A SET question (which words have I met, have I graded this word, is this word still a grading candidate) is composed as a UNION of the synced members and the outbox ones — retained acked rows included — so it is immune to the grace window by construction: an event still counted after its fold landed adds a member that is already there, and a SQL union of that shape (an anti-join over the outbox beside one over the projector’s row) cannot double-hide. A COUNTER (how many times have I met this word) may read one high for at most the grace window and then settles. Every surface that shows a number therefore asks the membership question, never the sum — the alternative double-counts precisely the event the ledger is holding for safety.
What it buys, in the terms the plan states. A learner who reads four hundred words on a plane sees four hundred words met; a page of grades saved on a train leaves the grading page at once and stays gone across a reload; today’s streak day exists on the day it is earned. None of that reached a device before, because all of it travelled event → outbox → server queue → projector → sync down.