Language module — offline truth — implementation plan
Scope: every language-module surface answers from the local store, immediately, for everything the learner does on this device; the server folds the same acts into the learner model for its own derivations and syncs them down as the eventual truth. It touches the verdict path, the additive statistics, the definition batch, and two small offline gaps. It adds one client-written table, renames one, and removes one from the client sync set.
Status: ratified 2026-09-12. Grounded in an offline-dependency survey of develop at c066481a (two
independent code sweeps; its findings are the Grounding section below) and the rulings the maintainer gave
that day.
Grounding (verified 2026-09-12)
Section titled “Grounding (verified 2026-09-12)”- Every learner-model fact reaches the client through one loop only: event → outbox → server queue →
projector (a separate Bun process,
apps/api/src/lang-event-consumer.ts) → projector-written row → sync down. Offline the loop never closes; online it takes seconds.lang_node_policy_output,lang_node_fact,lang_day_fact,goal_progressandgoal.statusare all on the far side of it. - Only exclusions are immediate today:
lang_node_declarationis client-written and the verdict feed overrides with it (packages/offline-data/src/lang-verdict-feed.ts:139). A grade writeslang_cardand the event, and nothing local says “aids off”. - The predecessor’s final shape was one client-written row per word (
wordstate:first_success_date,excluded), written in the same act as the grade; the aids-off set was one indexed scan of it (transcrobes/packages/wlib/src/data/domain/stats.ts:85-94). Scanning cards and a materialized view were both tried and rejected as too slow. Aggregate statistics were down-sync only. - ADR-0058 decision 12 recorded, and backlogged, the composition this plan adopts for the additive facts: “a client view composing down-synced aggregates with the pending outbox”.
- The definition batch is half right:
backfilldiffs against the local cache and fetches the missing ids in chunks ofDEFINITION_BATCH_MAX_LEXEMES = 200per request (packages/db/src/lang-dictionary/definitions.ts:14,packages/offline-data/src/definition-cache.ts:394-412). But the entries are written one INSERT per entry through the worker bridge (definition-cache.tsupsertEntries), and nothing preloads them into the renderer store, so every token runs the full lookup chain at render — seven local round trips per token (definition-cache.ts:511-580,resolution-index.ts:202-229). - The settings drawer’s dictionaries section seeds only from
GET /workflow/lang-dictionaries(LangSettingsDrawer.tsx:88-125); the cache already keeps the accessible set locally, by id only (definition-cache-schema.ts:112-117). - The “N of M ready” map is reset on every provider mount and seeded only inside
ensureLanguageShapesafter a networkflush()(sync.tsx:1420,:2249,:2264), so a fully synced device offline shows0 of 5.client.isSynced(key)answers from boot, offline included (pgxsinkit ADR-0059). - The client is published before catch-up is awaited and a warm store is trusted without connectivity
(
sync.tsx:1330,:2429), so everything client-written already works offline; this plan does not touch the provider’s trust rule.
Rulings
Section titled “Rulings”- R1 — One verdict, computed locally. “Does this learner need aids for this word” and “does this
word count as known” are pure functions of the client-written word state: aids off when the word has
a first success or is excluded; counts as known when it has a first success and is not excluded;
SRS-eligible when not excluded. The encounter-only inference (aids off after unaided encounters) is
DROPPED; the predecessor never had it, and it was the only input the client could not hold. The
function lives once in
@emergent/domainand is evaluated by the client for every surface and by the projector for its derivations. (Ruled 2026-09-12: Q1 = A.) - R2 —
lang_word_statereplaceslang_node_declaration. One client-written row per (person, lexeme):excluded(as today) plusfirst_success_at, set once byrecordGradeon the first pass and never moved. Owner-readwrite, optimistic overlay, LWW likelang_card. The verdict feed becomes one live query over its overlay view, keyed by lexeme, no join. Thelang_declarationevent stays (the archive holds the speech act); the fold reads the row as it reads the declaration row today. (Ruled 2026-09-12: Q2 = B.) - R3 — Additive facts are composed locally with the pending outbox. Counts and monotone timestamps
(
lang_node_fact: encounter, unaided, aid, grade, success counts; first/last timestamps) and the day tallies (lang_day_fact, including reading milliseconds) are read assynced row ⊕ pending events, where the pending events are the outbox rows of the four language streams not yet accepted by the server. The composition is keyed by LEXEME (events carry lexeme ids; synced facts reach the lexeme through the node bridge; a never-folded lexeme contributes pending-only rows) and by UTC day for the tallies. Offline it cannot go down; after the server has folded and synced, it cannot go down either. This promotes ADR-0058 decision 12’s backlogged candidate to the design. - R4 — The online dip is closed by a grace ledger. An event leaves the outbox when the server accepts it into the queue, before the fold and the sync-down, so a composed value would drop for seconds online. Accepted events stay in the composition until the synced row’s stamp overtakes them or 60 s elapse (the projector’s observed fold latency with margin). (Ruled 2026-09-12: 60 s.)
- R5 — The outbox is read through pgxsinkit’s public shape; the acked ledger is built upstream. The
outbox table’s shape is public contract (pgxsinkit ADR-0053 decision 2) and
getOutboxTableis the Drizzle object for it; the composition is a live query over it filtered to the four language streams. What pgxsinkit lacked was the ledger R4 needs: an acked row was deleted on the server’s verdict. Upstream (pgxsinkit ADR-0060, 2026-09-12): the outbox hasacked_at_us(null = pending); anackedverdict stamps it instead of deleting; a sweep in each flush pass deletes acked rows older thanevents.ackedRetentionMs(library default 0 = delete on ack; emergent sets 60 000); the drain signal, batch assembly,diagnosticsand thedestroy()refusal count pending rows only. The composition drops an acked event as soon as it observes the synced row change after the ack (both instants on the client clock, so server skew cannot mislead it), and the retention bound (60 s, R4) is the fallback. - R6 —
lang_node_policy_outputis dropped, server included. No client surface reads it once R1–R3 land, and the only server-side reader (list mastery,lang-projector/list-state.ts) joinslang_word_stateon the same two-column predicate at the same cost. The projector evaluates the R1 function overlang_word_statewherever it derivesperson_competency_state, evidence transitions, list mastery and goal progress. A future server-side derivation that needs a materialized figure gets its own table, named for that derivation; it never becomes the reading verdict. The policy-version replay class that recomputed the table is retired with it. (Ruled 2026-09-12: A.) - R7 — The definition batch is whole and transactional. One backfill per model: diff locally in one
query, fetch the missing ids in chunks of a configurable cap, write each chunk in ONE local
transaction, then read the model’s definitions in ONE local query and push them into the renderer
store before mount, so a token never looks up what the batch already holds. Cap default 1000 per
request, server-configurable (
LANG_DEFINITION_BATCH_MAX_LEXEMES), the client chunks at the same constant and a request over the cap is refused loudly, never truncated. (Ruled 2026-09-12: 1000.) - R8 — The accessible-dictionary list is local truth between reconciliations. The coverage state records id, title, scope and language of every accessible dictionary at each reconciliation; the settings drawer and the dictionary page seed from it and refresh from the network when it answers.
- R9 — Readiness is seeded from the client’s own state. The “N of M ready” map is seeded from
client.isSynced(key)for the pursued language the moment the client attaches, before any flush;groupReadythen only flips keys that were not already started. - R10 — A cold store is stated, not fixed. A never-synced device offline cannot declare a language or render anything; the predecessor needed a first sync too. The shell says so instead of showing loaders forever.
Slices
Section titled “Slices”- S1 — word state. LANDED (2026-09-12). Schema: rename
lang_node_declaration→lang_word_state, addfirst_success_at; migration; registry entry, RLS, apply function regenerated;recordGradewrites the row in the same act as the card;declareExclusionunchanged in meaning;useExclusionsand the verdict feed read the new view; R1 function in@emergent/domain, used by the feed and the projector; Phase-7 import writesfirst_success_atfromuserword.first_success_date; policy-only replay.LANG_MODULE_POLICY_VERSIONis 3 (the encounter route is gone); the policy table still exists and the fold still writes it — S2 retires it. - S2 — verdict consumers. LANDED (2026-09-12). Every reader of the policy table moved to the word
state — home counts, list percentages, level line, learner facet, practice candidates — and the table is
GONE, server included: schema, client registry, erasure registry, the merge’s referrer set, the Circuits
publication list, the fold’s judgment step and the migration set. The practice pool’s source is now the
union of
lang_node_fact(words the projector has seen the learner meet) andlang_word_state(words they graded or excluded), so a word graded offline is drillable in the next session. List mastery counts a known member with anEXISTSover the word state through thelang_lexemebridge; the policy-only replay class scans the module’s stampedperson_competency_staterows for staleness instead. ADR-0058 decision 5(c) is amended accordingly. - S3 — the acked ledger (pgxsinkit). Upstream:
acked_at_uson the outbox, stamp-not-delete on ack behindevents.ackedRetentionMs, pending =acked_at_us IS NULLeverywhere; pgxsinkit ADR-0060. Landed 2026-09-12 (pgxsinkit 786edf4); emergent consumes the dev build. - S4 — composed facts. LANDED (2026-09-13).
packages/offline-datareads pgxsinkit’s Outbox throughgetOutboxTable(the four observation streams, named from their declarations) and folds it with the projector’s own rules: lexeme-keyed overlang_node_factand UTC-day-keyed overlang_day_fact, each behind ONE feed of the verdict feed’s shape (one live query over the synced table, one over the Outbox, refolded on either delivery;hydratedfollows the synced half).events.ackedRetentionMsis 60 000 in BOTH client modes, and the grace rule drops an acked event as soon as the feed observes its key’s synced values change after the ack — both instants on the client clock — with the retention as the backstop. Presence (the encountered set, words met, words graded) is composed as a UNION and never as a sum. The encountered feed is RETIRED into the node feed, so one module answers “have I met this word”; grade-page candidacy anti-joins the Outbox in SQL — every row of it, ACKED ones included, because a pending-only filter would leave the ack→fold→sync window covered by neither that predicate nor the fact row, and an anti-join cannot double-hide — and the surface’s session-local saved set is GONE (the skipped set stays — a skip records nothing anywhere); the getting-started gate, the home statistics, the streak, the chart and the learner facet read the compositions. - S5 — definitions. LANDED (2026-09-13). Cap 1000, configurable per deployment
(
LANG_DEFINITION_BATCH_MAX_LEXEMES, malformed = refuse at boot), reported asbatchMaxLexemeson the accessible-dictionary response and stored in the coverage state, which is what the client chunks at; a chunk of lexemes local holds NOTHING for is ONE local transaction of exactly two statements — a Drizzle DELETE of the answered lexemes’ rows and aCOPY … FROM '/dev/blob'of the chunk (pgxsinkit’sbuildCopyFromBlobStatement), replacing those lexemes wholesale in place of the per-entry upsert (S5b narrows the other case, a lexeme local already holds);readDefinitionsis the one local read a host pushes into the renderer store throughpreloadDefinitions, and the paste and reader-section hosts backfill then preload before mount. The per-token lookup remains only as the fallback for a token the batch did not cover. - S5b — a gained dictionary is fetched alone. LANDED (2026-09-13). The coverage state stamps each
accessible dictionary with the generation it became reachable at (
gainedAt), so completeness iscovered(D, L) ⟺ gainedAt(D) ≤ stamp(L)and the diff partitions an ask into held / stale (grouped by stamp) / never: a held-but-stale lexeme costs ONE request narrowed to the dictionaries gained since its stamp (dictionaryIdson the batch endpoint, capped at 100 and only ever narrowing — the entitlement predicate is still joined in), one COPY of those dictionaries’ rows, a DELETE scoped to exactly the keys the COPY writes, and one set-based restamp; no other dictionary’s rows are re-fetched, deleted or rewritten. A gained dictionary that has since lapsed costs the restamp alone with no request; a changed revision is a lapse plus a gain.backfillreports{ requested, missing, stale, fetched }. - S6 — small gaps. LANDED (2026-09-13). R8: the coverage state’s fingerprints carry the whole
AccessibleDictionarySummary(title, scope, both language tags) besidegainedAt, written at every reconciliation with no fallback for a fingerprint without them, andaccessibleDictionaries()answers the list from them with no network; the settings drawer and the dictionary page seed from it and let the endpoint’s answer replace the seed, reporting a failure only when there was no seed either (an empty coverage state is NOT a seed — it is a device whose first entitlement check has never run). R9: the readiness map is seeded fromclient.isSyncedthe moment the client attaches, over every launch language’s keys — the pursuits are a live read the provider cannot make of itself at attach time, and asking about a language nobody pursues costs a synchronous peek that answers false — and again at the head of the activation ABOVE its flush, so an offline flush rejection leaves the honest answer;groupReadycontinuations and the seed both only ever flip a key on. R10:coldStore= fresh store + not caught up +SyncRuntimeStatus.phase === "degraded", exposed on the provider and read throughuseColdStore; the pursuit picker, the home’s gated cards and the reader route state it instead of an unresolvable loader, and it yields to the ordinary gates with no reload. The trust rule is untouched.
Records forced elsewhere
Section titled “Records forced elsewhere”- ADR-0058: decision 12 promoted (R3–R5) — amended 2026-09-13; decision 5(c) narrowed to server-side use or
removed (R6); the Phase-5 exception on client-written derived state extended to
lang_word_state(R2). - Phase-3 plan R2 (“a grade’s effect on aids_off arrives with sync”) and R6 (the feed over
lang_node_policy_output) amended to R1/R2 here; Phase-5 plan grounding bullet corrected. packages/db/src/schema/lang-card.tsdocblock (“aids and known-ness still flow through the projector”) corrected;lang-node-declaration.tsretired intolang-word-state.ts.- pgxsinkit: ADR-0060, the acked ledger (S3).