Skip to content

Plan Lazy Language Loading

github-actions[bot] edited this page Nov 23, 2026 · 7 revisions

Plan: load only the selected language at startup, the others when they are selected, and never on the UI thread

Source of truth: this wiki page.

Written 2026-11-22; status 2026-11-23: P-A to P-C are built and the default is lazy (see the P-C notes), P-D (removal of the whole path) is next. Its decision record is ADR-0062. It builds on ADR-0048 (the catalog snapshot), ADR-0051 (the replay snapshot), ADR-0047 (per-language versions, batching), ADR-0034 (the skill map) and ADR-0037 (downloads).

Owner order, 2026-11-22: "Load only the language selected on startup (then load others when they are selected), not all of them. And not in UI thread."

How to read this page: every claim is tagged FACT (read in the code or the data at origin/main 555c3d333 on 2026-11-22, with its file and line) or INFERENCE (reasoned from facts, not measured; to be checked by the instrumentation of work package P-A). Line numbers are of that commit and drift; the symbol names do not.

1. The problem in one paragraph

A cold start lists and reads every deck file of every downloaded language, copies all of the text to an isolate that parses all of it, and gets the whole catalog back; then the UI isolate loops over every card of every deck to build the skill map, and every screen that reads state.decks sees every language. The learner looks at one language at a time (the language bar, #461), so almost all of that work is for languages that are not on screen. The decks on decks-live are 85.6 MB of YAML in 7,174 files (ja 16.4, sa 10.0, bn 8.2, hi 7.6, gu 6.7, te 6.0, zh 5.7, es 4.3, fr 4.2, mr 3.9 MB); a phone holds the languages (and the native layers) it downloaded, so a learner of six languages pays for six, and the cost grows with every language added.

2. How a start loads the decks today (FACTS)

# Fact Where
F1 main() opens storage, builds DeckDownloads and the catalog, then runApp. StartupMarks already exists with point marks storage ready, catalog ready, first ready frame, runApp, and the replay marks snapshot loaded / review log replayed. It has no spans and says nothing of the catalog's inner steps. lib/main.dart:74-233, lib/app/startup_marks.dart
F2 AppState._load awaits deckDownloads.open() (reads the manifest _onPhone, the kept index, the shared texts: themes, sections, creators, recommendations), then deckCatalog.load(), then progress.ready, then _mapSkills(). Nothing shows or records until all are done. lib/app/app_state.dart:1387-1415
F3 DeckCatalog._load lists every path of DeckSources (the bundled theme list, the shared texts, FileDownloadedDecks), reads each file's text one after the other on the main isolate, adds every file of added/ and of the active private/ packages, and puts all of it in one Map<String, String>. lib/app/deck_catalog.dart:675-710
F4 _fromSnapshot reads the single catalog-snapshot.json (the whole phone's trees), takes each file's SHA-256 from the downloads' manifest (knownShas) or hashes it, builds one CatalogJob of all files, all SHA-256s and the snapshot text, and runs runCatalogJob in Isolate.run (runJobInIsolate). The text of every file is copied into the isolate. lib/app/deck_catalog.dart:712-751, :490-512, :598-605
F5 runCatalogJob calls DeckCatalog.parseAll(files): no language filter. parseAll sorts all paths, parses cores, guides, layers, facts, situations, numbers, paths, romanisations, sounds, topics, creators, recommendations, then every deck, then _withRefs, _withRules, _coursePaths, _placed, _inTeachingOrder over all decks. The result is one Catalog. :529-596, :753-1227
F6 The partition is closed: of 4,131 files in the index's files lists, 0 lie outside decks/<code>/ of their own language; card ids and deck ids start with the language code (ADR-0018, languageOfId); _withRefs and _withRules resolve card ids, which name their language, so no ref crosses a language. The shared files are decks/themes.yaml, decks/sections.yaml and, per language, decks/creators/<code>.yaml and decks/recommendations/<code>.yaml (sharedKindOf). decks/index.json, lib/core/private/private_ids.dart:79, lib/core/decks/shared_data.dart:20-45, deck_catalog.dart:1349-1480
F7 The cross-language links are few: _inTeachingOrder needs the theme list; _withRules groups words by native code (ids still name the language); a private package may replace a built-in language's path (privatePaths, asPrivatelyModified) and merges its topics, creators and recommendations into that language's; soundsOfWord and ipaAnswerTargets read the IPA course (language ipa) while a learner studies another language; rudeAlikesOf looks up a partner card by id in allDecks. deck_catalog.dart:~1099-1230, app_state.dart:4019-4065, lib/features/review/review_words.dart:55-72
F8 AppState._mapSkills loops over every card of every deck for hearsForm, over every deck for needsAlphabet, and calls primaryScript(code) once per language (each scans all decks: O(languages x decks)). It then sets progress.skills. app_state.dart:1363-1385, :2882-2903
F9 MemoryProgress.skills = value calls _replace: a synchronous full replay of the whole review log on the calling (UI) isolate whenever the new SkillMap differs by value. The replay at open (ADR-0051, replayInIsolate) is made with the empty SkillMap, so the first _mapSkills after launch replays the log again, on the UI isolate. _reloadDecks (a download, a private package, an added deck) does _mapSkills again. lib/app/memory_progress.dart:327-335, :576-615, lib/app/database_progress.dart:238-244
F10 AppState._view runs Catalog.forAdult over every card of every deck (deckForAdult) when the catalog or the Adult-content setting changes. app_state.dart:848-856, deck_catalog.dart:322-356
F11 The learner sees one language at a time. shownLanguage is LanguageChoice.shown(settings.languageChoice, languageChoices); Today (profileDecks is _learnedDecks(onlyShown: true)), the Decks tab and its search (_languages(state) is the shown language alone), Progress (All was removed on 2026-11-16, progressShowsAll is false) and the path all read the shown language's content. Search builds its items per language (ItemSearchIndex.of(catalog, language)). app_state.dart:1024-1110, lib/features/decks/decks_page.dart:185-192, lib/app/item_search.dart:33-60
F12 But languageChoices, languages and about 30 screens that only list or name languages derive them from the loaded decks (_view.languages is "every target language the decks teach"), and languageGlyph(language, decks) scans decks for an icon. So the language bar needs the catalog only for names, icons and which languages are on the phone. deck_catalog.dart:434-441, app_state.dart:1055-1080, lib/ui/widgets/language_glyph.dart:9-17
F13 The index already carries per-language data: IndexLanguage has code, name, own_name, icon, script, natives, size, path, units (has per native, words, grammar, milestone), files (with sha256, native, deck, kind), fonts, shelves. LanguageOffer.catalogLanguages already prefers the index to the decks, and falls back to catalogLanguageFromDecks only where no index is kept. lib/core/decks/deck_index.dart:494-640, lib/app/language_offer.dart:30-70
F14 Downloads fetch only the layers for the learner's spoken natives (filesFor(natives)), so a phone holds a language's core files plus its layers for those natives. Downloads, updates and removals are per language (DeckDownloads.remove(language), _applyUpdate), and every one ends in onFilesChanged, which is AppState._filesDownloaded, which runs _reloadDecks: invalidate and reload the whole catalog. deck_downloads.dart:461, :1759, :1824, app_state.dart:1156-1195
F15 The caches in AppState are keyed per language by _stampOf(code), which includes _structureVersion; any notifyListeners that is not marked "keep structure" bumps it and drops every cached queue. Several screens key their caches on the identity of state.decks (cardLookupOf, _tagsOf, ProgressNumbers, the review queue memo). app_state.dart:2140-2200, :2260-2270, lib/features/stats/stats_numbers.dart:15-35, progress_numbers.dart:222-240, :378-390, review_queue_page.dart:148
F16 Progress is by card id and never part of a deck file. The log, the replay snapshot, the progress index and versionOf(language) need no decks. A language's removal "keeps its progress, by card id" (removeLanguage). The reminder forecast (dueForecast, _countsAsDue(onlyShown: false)) builds a set of every learned card id of every language. lib/app/memory_progress.dart:55-62, app_state.dart:1350-1360, :1993-2019
F17 A saved-summary precedent exists: TodaySummaries keeps Today's tiles for the shown language in the settings, so that Today draws before the catalog is read; the scope is worked out "from the languages learned alone, never the catalog". app_state.dart:2355-2380, lib/app/today_summary.dart

INFERENCE (to be measured in P-A): the work is dominated by (a) reading and decoding about 86 MB of text on the main isolate and copying it into the isolate (cheap in CPU, large in memory and in the first-frame jank budget), (b) JSON decode of the one snapshot of every file and the parsers' mapping of every card, in the isolate (off the UI thread but on the splash's critical path), (c) F9's UI-isolate replay, and (d) F8 and F10 (UI-isolate loops over every card). Items (c), (d) and the main-isolate reads are what the owner's "not in the UI thread" refers to, whether or not the owner knows each by name.

3. Target architecture

3.1 The unit: one language's catalog

A language unit is everything the catalog holds for one language code L:

  • its deck files decks/L/** as downloaded (cores, layers for the natives on the phone, language files: path, facts, situations, numbers, romanisation, sounds, script guide, topics);
  • the shared per-language files decks/creators/L.yaml and decks/recommendations/L.yaml;
  • the files of active private packages whose language is L (private/<id>/...), including a package that modifies a built-in language;
  • the learner-added decks (added/...) whose language.code is L;
  • the hidden decks of L downloaded from a search result.

A unit is parsed by the existing DeckCatalog.parseAll, called on only that unit's files plus the shared unit: decks/themes.yaml and decks/sections.yaml (the bundled copy, replaced by the downloaded one as today, SharedDeckSource). Both are at most 512 KB (maxSharedFileBytes) and are read on the main isolate and passed as text. The result is a LanguageCatalog:

LanguageCatalog {
  code, decks, hidden, broken, facts, situations, topics, creators, recommendations,
  numberRules, languagePath, paths (its courses, 'L/native'), sounds, romanisations,
  scriptGuides, scriptFeatures, dataProblems, kindProblems
}
SharedCatalog { themes, sections }
CatalogSet {                       // lib/app/catalog_set.dart, replaces DeckCatalog's role
  shared, directory (the summaries), units: Map<String, LanguageCatalog>,
  Future<LanguageCatalog> ensureLoaded(code), LanguageLoad loadOf(code), int versionOf(code)
}

Catalog (the type every screen reads today) is kept in P-A to P-C as a composed view: Catalog.compose(shared, loadedUnits) with the same members, built by concatenating the loaded units' maps and decks. This is why the migration can go consumer by consumer: the old API keeps working over "what is loaded", and a consumer that needs a language that may not be loaded is moved to ensureLoaded/the summary (section 5). P-D deletes the composed view.

Partition check. The unit loader asserts that every deck in decks/L/ has language.code == L; a mismatch becomes a BrokenDeck named "filed under L but teaches M" and is logged. (INFERENCE: the validator already forbids it; F6 found none in the index.)

3.2 What runs where, and what crosses

The owner's rule is that nothing of this runs on the UI isolate. The job is:

UI isolate                                  worker isolate (Isolate.run, one per unit load)
-----------                                 ----------------------------------------------
ensureLoaded('te')
  paths+SHAs for te from the manifest   -->  LanguageJob { code, root dir, [relative paths + sha],
  shared texts (themes, sections),                         added/private file paths, snapshot path,
  summary stamp, app version                               shared texts, app version, format }
                                             read each file with dart:io (no text on the UI isolate)
                                             read decks-snapshot/te.json, reuse trees whose SHA matches
                                             DeckCatalog.parseAll(files of te + shared)
                                             build the LanguageSummary of te
                                             encode the next snapshot of te (if it changed)
                                        <--  LanguageOutcome { LanguageCatalog, LanguageSummary,
                                                               snapshotText? }   (returned by Isolate.exit:
                                                               transferred, not copied)
UI isolate: store the unit, notify
unawaited: write snapshot and summary (temp file, rename)
  • File reads and decode happen in the isolate: the job carries the directory path and relative paths (strings), never the text. A plain DiskDeckFiles(root, paths), constructible inside an isolate from strings, reads what FileDownloadedDecks, FileDeckStore and FilePrivateStore keep on disk. Where an isolate cannot run (the web build; widget tests) a MemoryDeckFiles reads through the DeckSource in place, as parseInPlace does today; the web build still loads per language (lazily, one await per file so the main loop is not held).
  • Only the parsed per-language model crosses back. It is plain Dart data like today's Catalog (Isolate.run returns by Isolate.exit, which transfers). INFERENCE: transferring a unit costs microseconds, not a copy; the 86 MB of text is never on the UI isolate at all. If a unit contains an object that cannot cross, the existing try/catch fallback to in-place parsing stays (runJobInIsolate), and the failure is logged once.
  • The job is pure: no storage, no Flutter, in lib/core where it does not need AppLog (as runCatalogJob is today); lib/app only does the file layout and the isolate call.
  • Concurrency. At most one unit load at a time (a FIFO queue in CatalogSet); a load for the selected language jumps the queue; prefetch loads wait for an idle slot (section 3.6). Loads of the same language are joined, as DeckCatalog.load joins today.

3.3 Snapshots per language (ADR-0048, per language)

catalog-snapshot.json (one file, all files' trees, keyed by SHA-256 and AppInfo.version) becomes catalog-snapshots/<code>.json with the same content for one language: the tree of each of its files and the file's SHA-256, the format version and the app version. A snapshot of another format or version is not used (as ADR-0048). The rules of ADR-0048 stand unchanged: a file's tree is used only if its SHA-256 matches; a missing, damaged or foreign snapshot is no snapshot; a failing parse of a kept tree re-parses from YAML; the write goes to a temporary file and is renamed, off the first screens' path.

What changes is the consequence: an app update invalidates a language's snapshot only when that language is loaded (its unit job finds the version differs, parses YAML once, rewrites the snapshot). A language the learner never opens after an update costs nothing. A download that changes te rewrites te.json only. The old single catalog-snapshot.json is read once by the first lazy load that finds no per-language file (to take its trees for that language), then deleted by the junk cleanup (lib/app/junk_cleanup.dart) after the per-language files exist, so a learner updating from the old layout does not pay a YAML parse for the selected language.

3.4 Summaries: what the screens that list languages read

A LanguageSummary is a small JSON record per language on the phone, computed by the same unit job that parses the language (so it has one source of truth, the Dart parsers, and counts "as tools/deck_index.py counts them" with countsAsWord, as catalogLanguageFromDecks does today), and stored in one file language-summaries.json (all languages, rewritten whenever one entry changes). It is read in full at startup (about 2 to 4 KB per language, INFERENCE: 25 languages is under 100 KB) on the worker isolate with the rest of the startup job.

Field Used by (section 5 rows)
code, info (the full LanguageInfo: iso, name, script, scripts, rtl, tts, icon, typed), ownName, isNotation, isSign, isIpa the language bar and its wheel, the language picker, every screen that lists or names languages (state.languages), languageGlyph
natives[] (code, name, deck counts), courses[] (per native: unit count, deck count, card count, word count by countsAsWord, culture-card count, the B1Unit list as b1Units makes it: planned, words, milestone, grammar, has) B1Progress, course lines, the picker's coverage, the Languages page
decks[] (id, path, native, kind, genre, theme, hidden, adult, card count, bundled/private) replaced-deck sets (placedDecks), ownDecks(state.decks).length, "your decks", reviewer pair lists (offeredPairs), language skills sheet
scriptDecks[] (deck ids that needsAlphabet), hasAlphabet, primaryScript, formHeardCards[] (card ids where Card.hearsForm: letters, digits, hears: form) the skill map (section 4.2)
hasPath, planUnits, hasFacts, hasSituations, hasTopics, hasCulture, hasRomanisation, hasSounds, hasNumbers, scriptGuideKeys the entry points of Today's fact, situations, topics, culture, sound-check, script-check and number drills, so that a button can be drawn or hidden without loading
credits (deck sources lines, media credit lines, the ContentCredit set) Settings > Sources, which scans every card today (sourcesOf, mediaCreditsOf, creditsOf)
ipaSymbols[] (only for the ipa unit: every answer target and alternative, ipaAnswerTargets) the IPA keyboard, which must offer symbols while a learner types in any language
learnedShare cache (per course: value, and the progress.versionOf(L) stamp it was worked out at) the picker's "you" percentages (section 4.3)
stamp: { format, filesDigest (SHA-256 over the sorted (path, sha) pairs of the unit's files), app } freshness

Where it is computed. Not in the Python index tool: that tool cannot see the phone's actual files (a partial download, the learner's native layers, private and added decks) and would duplicate the parsers' counting rules, which catalogLanguageFromDecks already says must match. The index keeps serving the languages not on the phone (F13). On the phone the summary is produced by (1) any unit load, and (2) a download or update of language L: DeckDownloads.onFilesChanged(language) (the callback gains the language) enqueues a summarise job: the same worker job, with no result kept in memory beyond the summary (the unit is dropped unless it is the selected language). So the summary of a language exists as soon as it is downloaded, before it is ever selected.

Staleness (stale-while-revalidate). A summary is fresh when its filesDigest equals the digest of the manifest's current files for that language and its format is current. After an app update the app differs: the summary is still used (the parsers' output for the fields above changes rarely) but marked refresh, and CatalogSet queues a background summarise job for each such language, one at a time in idle slots, the selected language first (it is loaded anyway). A summary whose filesDigest differs (files changed with no summarise run, for example a crash between the move-in of files and the job) is not trusted: that language falls back to the index entry (CatalogLanguage.fromIndex) until its job has run. LanguageSummary.format is raised only when the shape of the record changes; a test compares the summary of a fixed fixture language to a golden, so that a parser change that alters a summary field fails CI and forces a deliberate bump.

3.5 The startup path

  1. main() as today up to deckDownloads.open() (F2): the manifest _onPhone gives the languages on the phone and the SHA-256 of every file without reading one.
  2. Resolve the startup language without the catalog. StartupLanguage.resolve(settings, profile, languagesOnPhone, directory) mirrors languageChoices and shownLanguage (LanguageChoice.options and shown) over the summaries' language list instead of the loaded decks. _todayScope already does this for the saved Today summary (F17); this generalises it. INFERENCE: settings and the current profile are available before the catalog (_todayScope reads both while the catalog loads, F17).
  3. One worker job, startup job, with: the shared texts, language-summaries.json, and the unit job of the startup language (3.2). Output: CatalogSet with shared, directory and one unit. The main isolate reads no deck text.
  4. progress.ready (the log's replay, already an isolate, ADR-0051), in parallel with step 3 (as today). The skill map is complete after step 3 from the summaries (4.2), so progress.skills is set once and no unit load ever changes it; INFERENCE: it can even be passed into the open's replay job so that the second, UI-isolate replay of F9 disappears. That is a separate, measurable step of P-B.
  5. status = ready; the first screens draw from the startup language's unit and the directory. Every other language is LanguageLoad.notLoaded.
  6. _afterLaunch as today (downloads resume, update check). It no longer implies a reload: an update of L re-summarises L and, if L is loaded, reloads that unit only (3.8).

If no language is selected (first launch, nothing downloaded), step 3 loads no unit: only the shared files and the summaries (none yet). If the startup language has no unit (its files were removed), the next language of the options is used.

Failure. The startup job never fails the start: a unit that fails to parse as a whole (as opposed to a broken deck, which is a BrokenDeck as today) leaves the language LanguageLoad.failed(error) with a retry, logged with describeError; the app still opens on whatever else works.

Cache-first startup (owner, 2026-11-22: "Startup loads only the selected language... from cache... Off the ui thread runs will just verify the data, and only if data is mismatching, the fits will run (also off the ui thread and lazily)")

Startup shows what the cache holds and recomputes nothing when a cache exists. The cache is the per-language snapshot (3.3), language-summaries.json (3.4), the skill map (4.2) and the replay snapshot (ADR-0051), each stamped with what it was made from.

  1. Show the cache. The summaries and the selected language's snapshot are read at once; the learner sees the cached state with no wait on any parse of the decks or replay of the log.
  2. Verify, off the UI isolate, and only verify. One worker job (catalog.verify span) compares each stamp with the phone: the summary's {format, filesDigest, app} with the digest of the file manifest's SHA-256s for that language and the running app version, and later the skill-map inputs and the replay snapshot's log stamp. It parses no file and reads no deck text. Its answer is match or mismatch(reason) (no summary, format changed, files changed, app updated) for each language (verifyLanguageCache, CatalogSet.verify).
  3. Recompute only on a mismatch. A mismatching language is rebuilt by the unit job in a worker (catalog.unit.<code>.rebuild span), lazily and in idle time: the shown language first, the others only when selected or in idle slots. The new unit, summary and snapshot replace the cache, are written back (temporary file, then rename) and are swapped in, so a learner sees no change from a stale but valid cache. After an app update the summary is refresh: used as it is while it is rebuilt.
  4. What the stamps cover. The digest covers the files the downloads' manifest lists. A deck the learner adds or a private package is not in the manifest, so adding one invalidates its language through the catalog (invalidate), not through the verify job; this is a known limit of P-A.

3.6 Selecting another language

  • AppState.showLanguage(code) (and a profile switch, a deep link, a reminder tap, a search hit, a language added in the picker) calls ensureLoaded(code) first. The language bar's selection is applied at once (the bar and the wheel read the directory, which is complete) and the content area shows a loading state for the language until its unit is ready: the same skeleton the Decks and Today screens already show while the catalog loads (CatalogStatus.loading), scoped to that language (LanguageLoad.loading). Nothing blocks input: the bar stays usable, so a learner can swipe on to the next language while the first is loading; the superseded load continues in the background (its result is kept: it is not wasted), and the content shown is that of the language last selected.
  • A notification of the load goes through notifyListeners marked "keep structure" for every other language (F15), so no other language's cached queue is dropped. _structureVersion becomes per language (structureOf(code)), bumped by that language's unit changing; the settings and profile bumps stay global. The stamp of F15 gains the unit's version (catalog.versionOf(code)).
  • Warm selection (the unit has a fresh snapshot): the job reads one small JSON and maps it. Cold selection (new version or changed file): one YAML parse of one language. INFERENCE: sub-second to a few seconds for the largest (ja 16.4 MB on decks-live, of which a learner holds the core plus their native layers); the loading state exists for that case.
  • Prefetch (optional, P-E). After the first ready frame and an idle period, load the language the learner is most likely to select next: the next language in the bar's order, or the language they last used before the current one, one unit at a time in Priority.idle slots (as lazyFor schedules Today's other languages, F15 and ADR-0047). Prefetch never starts while a drill session is open or the app is not in the resumed lifecycle state. Default off until the startup numbers of P-B are in.
  • Memory. A loaded unit stays loaded until the app closes (no eviction) by default; a language is up to a few tens of MB of objects (INFERENCE; measured in P-A as the heap size from the Dart VM service in a profile run). If a learner of many languages hits a memory ceiling, an LRU of the last 3 loaded units is the fallback (open question Q4).

3.7 Downloads, updates, removals and adds: one unit

onFilesChanged becomes onFilesChanged(language) (and a null for a font-only or shared change). AppState._filesDownloaded then:

  • shared files changed (themes, sections): reparse the shared unit (small), and mark every loaded unit's theme order stale: _inTeachingOrder depends on themes, so reload loaded units that have theme decks (cheap with snapshots: only the shared change), others on their next load;
  • language L changed: re-summarise L; if L is loaded, reload L's unit only; keep every other unit and its caches;
  • removeLanguage(L): drop L's unit, summary and snapshot; the progress stays by card id (F16);
  • an added deck: DeckStore.save records the deck's language in added-index.json (a few bytes: id to language) so that the partition is known without parsing; a file not in it is routed by a header read (the first lines, as _headerOf) in the worker; reload that language's unit only;
  • a private package: the package's manifest names its language (PrivateStore already keeps one, lib/app/private_languages.dart:60-80); reload that language's unit (and the directory entry, since a private language adds an entry to the language list).

3.8 The review log for a language that is not loaded

See section 4. In short: the log, the progress index, versionOf(L) and the replay snapshot never need the cards; what needs the cards is building a session (needs unit L), and the numbers that count cards (due counts that must agree with what a session would serve).

4. Progress, skills and due counts for languages that are not loaded

4.1 What the log gives without any card (FACTS and INFERENCES)

  • FACT (F16): ProgressStore keeps the events with their states, the per-language index and versionOf(L) from the log alone; Abilities.languageOf(cardId) and languageOfId(deckId) give a pair's language from its id. Stats group by language this way and fall back to the id when the catalog lacks the deck (LanguageTable.of, stats_numbers.dart:36-60).
  • INFERENCE: therefore these need no unit: streak, days practised, week strip, hours (spent and left are per language from the log; "hours left" needs the plan, which is in the summary's courses[].units), answers per language, the how-you-learn fits per language, time per skill, the activity counters, and the number of pairs due per language, if "due" is defined by the log.

4.2 The skill map from summaries, and the replay that must not repeat

SkillMap has three inputs (ADR-0034): formHeardCards (card ids), scriptDecks (deck ids) and primaryScripts (per language). All three are pure functions of one language's decks and its path, so the summary stores them (3.4). CatalogSet.skillMap is the union over the summaries of the languages on the phone; it is available at startup (3.5, step 3) and never changes when a unit loads. It changes only when a language's summary changes (a download, an update): then progress.skills is set once.

This fixes a cost that exists even without lazy loading (F9): today every set of progress.skills that differs triggers a synchronous full replay on the UI isolate, at every launch and at every _reloadDecks. With the map known at startup the replay at open can be given the map (INFERENCE: replayInIsolate takes the skills, or is given them, so that its result is already right and _mapSkills' assignment is value == _skills, a no-op). When a summary does change at run time, the replay should be restricted to that language's events: INFERENCE (to verify in P-B with a test that replays both ways and compares): a language's states depend on the skill map only through its own cards' formHeardCards, scriptDecks and primaryScripts[L], and on the log-wide lastStudied only for the parameter choice, which the skill map does not touch. If the verification fails, the fallback is the full replay moved to an isolate (as ADR-0051 does for the open).

The skill map's equality (SkillMap.==) compares sets by value (skill_map.dart:156): with a union of per-language contributions the comparison costs the size of the union (letters and digits only: INFERENCE, a few hundred ids per language).

4.3 What each consumer of "due" needs

Question Needs cards? Plan
Today's count for the shown language, its tiles, its daily plan, buildSession Yes: unit L L is loaded (it is the shown language).
Today's rings for other languages Today already shows only the shown language since #461 (F11: profileDecks is shown-only); the saved summary (TodaySummaries) lets it draw before the catalog. No change; lazyFor stays for the languages of a profile that Today lists. If Today lists a language that is not loaded, it shows the log-derived due count with a "load" affordance, never a spinner that blocks. Default: Today lists the shown language only (Q3).
Due counts of unloaded languages (reminders, dueForecast, dueTomorrow across languages) Only to drop the pairs whose card was removed from the decks by an update Default: count the language's due pairs from the log (and the leech set-asides), without the card check, for languages not loaded; exact (with the card check) for loaded ones. The error is bounded by cards removed from decks since the review, which the deck-format rules make rare (card ids are permanent; a card is retired, not deleted).
A session for a language that is not loaded (a reminder tap, a deep link, a profile switch) Yes ensureLoaded(L) first, then buildSession; the Today screen shows the loading state.
Review items due for a language whose files were removed No They are not due: _countsAsDue requires the card to be in a learned deck (F16); unchanged: progress waits by card id.
learnedShare(L) (picker, language skills sheet, download page) Words of each unit by id Default: a stamped cache in the summary: value and the progress.versionOf(L) it was worked out at; recomputed when L is loaded and the stamp is stale; for an unloaded language with a stale stamp (after a restore or import, which touch every language) a background summarise job loads the unit, works it out and writes it (the unit is then dropped). Alternative, rejected as default: store the word-id lists per unit in the summary (about 80 KB per language for a 4,000-word plan: INFERENCE; heavy for a startup file) or in a sidecar words/<code>.json read by the picker alone (Q5).
unlocks, recentAnswers, unlockCountsFor(L), unlockedSince Cards of L Unlocks is built over every card of every deck today (unlocks.dart:41-47); it becomes per language (unlocksFor(L)), built from unit L only, keyed by versionOf(L). The parametersOf map byDeck is built from the unit's decks (the id's language prefix is the fallback it already has).

5. Every consumer of the catalog, and what it needs instead

Legend for "Needs": dir = the language directory (summaries, loaded at startup, synchronous reads), unit(L) = the loaded unit of language L (the shown one, or loaded on demand), shared = themes and sections (always loaded), log = the review log and progress only. "P-C1..P-C5" are the work packages of section 7.

5.1 (a) Screens that list or name languages

Consumer (file:line) Reads today Needs instead Package
AppState.languages (app_state.dart:1056, _view.languages, deck_catalog.dart:434) and the ~30 screens that name or list languages: app.dart:305, ui/widgets/report_button.dart:30, features/culture/culture_parts.dart:28, features/stats/leeches_page.dart:37, how_you_learn_page.dart:713, hours_tiles.dart:37, features/profiles/new_profile_page.dart:76, profile_text.dart:25, review/review_languages_page.dart:307, review/offensive_review_page.dart:66, review/daily_questions_page.dart:90, summary/summary_page.dart:51, settings/settings_page.dart:126,257, voices_page.dart:104, activities_page.dart:51,190,220,239, adjust_section.dart:149, profiles_privacy_page.dart:28, restore_sheet.dart:19, private/private_notes.dart:80, placement/native_choice.dart:161, placement_page.dart:366, today/fact_languages_sheet.dart:65, topics/topic_page.dart:97, decks/decks_page.dart:190,362, languages/language_skills_sheet.dart:942 every target language of every deck, from decks dir: AppState.languages returns the directory's LanguageInfo list (same order: path order of the first deck, i.e. language code order; stored as order in the summaries). Synchronous, no unit. P-C1
AppState.languageChoices, shownLanguage, showsLanguage, _todayScope (app_state.dart:1062-1110, :2363) languages filtered by the profile, ordered by LanguageChoice.options dir and languagesOnPhone; this is StartupLanguage.resolve (3.5) P-B
Language bar and wheel (ui/widgets/language_bar.dart:334,350,425,717,751,768,809,904,934), languageGlyph(language, decks) (ui/widgets/language_glyph.dart:9), hours_tiles.dart:40, decks/script_offers.dart:63, situations/situations_editor.dart:94 languages from languageChoices; glyph by scanning decks for an icon dir for the list; languageGlyph(language) reads info.icon (summary), no deck scan. A language's selection never waits for its unit. P-C1
Languages page (features/languages/languages_page.dart:342 ownDecks(state.decks).length, language_skills_sheet.dart:942,1034,1693, language_pick_list.dart:112) decks for the "your decks" count, learnedShare, languages dir (decks[] filtered by !bundled && !private for the own-deck count; info; learnedShare cache). The skills sheet's per-skill switches read settings. P-C1
Language picker / Add a language (placement/language_picker_page.dart:313,471,549,596,836,1407, language_card.dart, language_row.dart, language_sheet.dart:420, language_download.dart:188, course_line.dart) LanguageOffer.catalogLanguages (index first, decks as fallback, F13), learnedShare, scriptPreview(code) (the first letters of a script deck), state.decks to find the deck ids a placement replaces index for languages not on the phone (as today); dir for the on-phone fallback in place of catalogLanguageFromDecks (language_offer.dart:71, b1Units :118); learnedShare cache; scriptPreview needs the script deck's first cards: a field scriptPreview[] (letter, reading, up to 8) in the summary; the replaced ids come from decks[].id in the summary P-C1
B1Progress.of, catalogLanguageFromDecks, learnedShare, learnedWords (language_offer.dart:43-215, core/decks/language_catalog.dart:82) all decks of the course, _learnedCards() B1Unit lists from courses[].units (summary), learnedShare as in 4.3. learnedWords(L) (no B1 plan) becomes a stamped summary value as well. P-C1
AppState.catalogLanguages ordering (languagesOnOffer) the language directory asset plus private languages (language_directory_loader.dart) unchanged (it does not read decks) none
Placement entry (placement/onboarding_placement.dart:79, placement_page.dart:644, app/placement.dart, placement_plan.dart, placement_run_setup.dart, placement_bank.dart, core/data/placement_course.dart) state.decks to name the deck ids to replace; the course's decks and bank from the catalog unit(L) for the language being placed (ensureLoaded(L) before the check starts; the placement page shows the loading state; placement is a one-language flow); replaced ids from dir decks[] P-C3
Native choice (placement/native_choice.dart:161, needsNativeChoice) state.languages, courses dir (natives[]) P-C1
Settings > Your decks (settings/your_decks_page.dart:60), Your data (your_data_page.dart:76), Appearance (appearance_page.dart:317), Voices (voices_page.dart:81,500), Speech test (speech_test_sheet.dart:40) state.decks across languages (own decks; card lookups for the review log rows; voices per language deck) Your decks: dir decks[] own entries. Your data: the newest events only (take(limit)), so a card lookup per event's language, ensureLoaded of at most the languages of those rows, else the row shows the id (it shows a placeholder already when the card is gone). Appearance: the shown language's themes only. Voices: VoiceStatus per language needs a sample deck per language: summary voiceSample (up to 3 target strings) per language; the speech test loads the unit of the language tested. P-C5
Settings > Sources (settings/sources_page.dart:186-192) every card of every deck (sourcesOf, mediaCreditsOf, creditsOf) dir credits per language; no unit P-C5
Downloads UI (features/downloads/*, DeckDownloads getters) the index and manifest unchanged (manifest and index; they never read decks) none
Backup, restore, export (app/backups.dart, backup_store.dart, backup_files.dart, settings/restore_sheet.dart:19) the review log, settings; restore_sheet names languages log and dir (names). A restore touches every language's log: versionOf of all changes (_touchAll), the learned-share caches go stale and refresh in the background (4.3). Backups hold no decks. P-C1
Profiles (profiles/new_profile_page.dart:76, profile_text.dart:25, profiles_privacy_page.dart:28, profileDecks, learnedDecks) languages and decks of the profile's languages dir for the names; profileDecks is shown-language-only (F11), so unit(shown) P-C1, P-C2
Reminders and notifications (app/reminder_service.dart:86, AppState.dueForecast :2015, _countsAsDue :1993, reminder_words.dart) every learned card id of every language (F16) log with the language-level "learned" check (4.3), exact for the loaded units P-C2
Widgets and home-screen data none: no home-screen widget exists (grep finds no widget code in lib/); the reminder is the only background surface none; INFERENCE: if one is added it reads the saved Today summary (F17) none

5.2 (b) Content screens, per language

Consumer (file:line) Reads today Needs instead Package
Today: TodayNumbers.of (features/today/today_numbers.dart:148-210), profileDecks (app_state.dart:1024), todayLanguages (:2039), lazyFor (:2282), dailyPlanFor, newWordsToday, skillTile, buildSession decks of the shown language (F11), per-language caches by _stampOf unit(shown) and log; lazyFor's idle batching stays for the languages Today lists; the saved summary draws the tiles before the unit is ready (as for the catalog today, F17); the stamp gains versionOf(code) of the catalog unit P-C2
Decks tab, path, unit pages (features/decks/decks_page.dart, path_model.dart:158,803, unit_page.dart:102, unit_labels.dart:37-64, card_blocks.dart:20, card_bases.dart:82, word_sheet.dart:145, path_view.dart) state.decks, state.catalogView unit(shown) (a deck or unit of another language is opened only from that language's own context; a deep link to a deck calls ensureLoaded(languageOfId(deckId))) P-C2
Deck search (decks/unit_search.dart:344,566,592,767, search_tabs.dart, search_item_rows.dart, app/item_search.dart:33-165, core/search/card_index.dart, ADR-0049) the shown language's decks (_languages(state)); ItemSearchIndex.of(catalog, language); FTS5 index built lazily per deck unit(shown). Search is the shown language only today (F11), so nothing changes for the learner. A global search across languages is not offered and not planned here (Q2). P-C4
Culture, proverbs, recommendations, creators, works (app/culture.dart:28,118, culture_list.dart:39, recommendation_feed.dart:19-30, recommendation_questions.dart:89, features/culture/culture_parts.dart, culture_works.dart:162, work_questions_page.dart:51, recommendation_progress.dart) catalog.decks, catalog.recommendations[L], catalog.creators[L], languagePaths[L] unit(L): creators and recommendations are shared files per language, part of unit L (3.1), so the culture settings of a language read its unit; the culture switch screen reads dir hasCulture and culture-card count P-C4
Topics, situations, facts, sections (app/topics.dart:97,121, features/topics/*, app/situations.dart, features/situations/*, features/today/fact_languages_sheet.dart, AppState facts :921-968) catalog.topics[L], situations[L], facts[L], sections unit(L); sections is shared. Today's daily fact for each learned language (the fact sheet lists every language the profile learns) reads facts[L] per language: summary fact field (today's fact is chosen by date from a list: store the list of fact ids only if short; default: the fact sheet loads the units it needs, one at a time, with the loading state, and Today shows the shown language's fact only) P-C4
Script, sounds, romanisation, number rules, script guides (app_state.dart:4175-4204, app/script_test.dart, features/*script*) numberRules[L], scriptGuideFor, sounds[L], romanisations[L] unit(L) (the shown language), buttons drawn from dir hasNumbers, hasSounds, hasRomanisation, scriptGuideKeys P-C4
IPA (soundsOfWord app_state.dart:4019, ipaAnswerTargets :4046, the IPA keyboard #836, learnsIpa, the IPA course) every IPA card of the catalog the ipa unit is a dependency language: ensureLoaded('ipa') when the learner opens "The sounds of this word" or an IPA-typed question (the button is shown from the card's ipa field and enabled when the unit is ready); the keyboard's symbols come from the dir ipaSymbols, so typing never waits. If the learner learns IPA, ipa is just another language. P-C4
Drill and session screens (drill/drill_page.dart:166, app/session.dart, AppState.buildSession, _buildSession, siblingsOf, hearsForm, targetShown, courseNative, courseUnits) decks of the language of the session unit(L) of the session's language; DrillRequest carries the language; buildSession(request) for a language that is not loaded returns "loading" (the Today/tile caller calls ensureLoaded first) P-C2
Progress / Stats (features/stats/stats_numbers.dart:20-60, progress_numbers.dart:222-240,378-390, progress_mastery.dart:152, all_tags_page.dart:118, leeches_page.dart:37-60, hours_tiles.dart, how_you_learn_page.dart) state.decks for the card lookup (CardLookup), the tag tables, the language table; the log by language log for numbers; unit(shown) for the card lookup and tags of the shown language (cardLookupOf(state) and _tagsOf key on unit.decks identity, not on all decks, F15); LanguageTable.of uses dir (deck id to language is languageOfId plus the directory's codes, which it already falls back to). The leeches page for one language (language != null) loads that unit; the "every language" leeches list (language null) lists leeches by id with a per-row card lookup that loads units on demand, or names the language and shows "open to see" (default) P-C2
Review queues, flagged lists, reviewer UX, deck sheets (features/review/*: review_waiting.dart:44-110,233-334, review_queue_page.dart:148, flagged_page.dart:21,114, review_words.dart:65-121, review_sheets.dart:222, review_page.dart:415, review_section.dart:67,76, suggest_bases.dart:80, daily_questions.dart:23, offensive_review_page.dart, app/reviewing.dart, reviewer_check_records.dart, app/unlocks.dart) state.decks (all of the reviewer's courses), reviewDecks, allDecks; the deck index's languages for the offered pairs The reviewer's pairs come from the index and dir (offeredPairs already starts from the index). A reviewer works one language at a time in Languages you review (review_languages_page.dart): its pages take unit(L) for the language in hand, ensureLoaded(L) on entry. reviewDecks/allDecks become reviewDecksOf(L). Daily questions (daily_questions.dart:23) generate questions over the reviewer's decks across courses: default: only the loaded units (the shown language) plus those of the reviewer's courses loaded by the reviewer screens; a question set for a language that is not loaded is built when it is next loaded (the day's set is cached with its date). rudeAlikesOf (review_words.dart:65) searches the partner card by id: ensureLoaded(languageOfId(pair.id)) (the partner is in the same language by ADR-0018) P-C3
Unlocks, RecentAnswers, unlock counts (app/unlocks.dart:17-75) all cards of all decks per language, unit(L) (4.3) P-C2
Private languages (app/private_languages.dart, private_import.dart:341, private_notes.dart, features/private/*) catalog.decks, hidden, the package list the package's language names its unit; import/validation of a package reads only the package's files (it already parses private/<id> separately for the check); a package that modifies a built-in language loads that language's unit with it P-C5
Hidden / added-from-search decks (DeckDownloads.fetchHidden, removeHidden, addedHiddenDecks app_state.dart:870) catalog.hidden part of unit(L) (3.1) P-C4
Gallery and fixtures (features/gallery/*, *_fixtures.dart) DeckCatalog(MemoryDeckSource(...)) CatalogSet.memory(files) that loads every language in place at once (the gallery has few decks) P-D

5.3 (c) Skills and the adult filter

Consumer Reads today Needs instead Package
SkillMap (core/scheduling/skill_map.dart:40-170; built by _mapSkills, app_state.dart:1363) all cards, all decks, primaryScript(code) per language the summaries (4.2): formHeardCards, scriptDecks, primaryScript; set once at startup, passed into the open's replay P-B (map and replay), P-C2 (the consumers progress.skills.scriptDecks in today_numbers.dart:150, app_state.dart:2479,3634, fsrs_tuner.dart:165)
Catalog.forAdult / _view (deck_catalog.dart:322, app_state.dart:848) every card, when the catalog or the setting changes LanguageCatalog.forAdult(adult) per unit, memoised by (unit version, adult); applied inside the unit job for the setting's value at load time and redone in the isolate if the setting flips while loaded (so the flip never scans cards on the UI isolate); the composed view _view is the union of the loaded units' scoped lists P-B (per unit), P-C (consumers)
isUnratedAdultDeck, reviewDecks _catalog.decks per unit (reviewDecksOf(L)), the adult flag also in the summary decks[].adult P-C3

6. Migration, flag and rollback

  • One flag, two modes. CatalogMode { whole, lazy }, a persisted setting (settings.catalogMode, hidden in Settings > Your data > Diagnostics with the log tools, alongside the app log) with the default from a compile-time constant kLazyCatalogDefault. whole runs the current path through the same CatalogSet interface: one unit holding every language, loaded in the worker job, so that even the old path moves the file reads off the UI isolate (the first, nearly risk-free win, in P-A). lazy is the new path.
  • Order of defaults. P-A, P-B ship with whole as the default and lazy available to the owner's builds (the diagnostics switch). The default flips to lazy at the end of P-C, in the same release as the changelog line, after the startup numbers meet section 8. P-D removes whole and the composed view and the flag only after one release has shipped with lazy as the default and no regression is open.
  • Rollback. Before P-D: flip kLazyCatalogDefault in a patch release, or the learner sets the diagnostics switch; the summaries and per-language snapshots are caches and can be deleted at any time (as ADR-0048 and ADR-0051 say of theirs), and the old single catalog-snapshot.json is not deleted until P-D. After P-D: revert the PR that removed the flag.
  • No data migration. Decks, the review log and the settings are untouched; the two new files (language-summaries.json, catalog-snapshots/) are caches; added-index.json is rebuilt from a header scan if missing.
  • Cache keys. DeckCatalog.invalidate (whole) becomes CatalogSet.invalidate(code); _structureVersion becomes per language (F15); every cache keyed on state.decks identity is re-keyed on the unit's version (a test per cache).

7. Work packages

Each package is one pull request, built by one Sonnet coder, with one Sonnet review (CLAUDE.md: Sonnet for complex multi-file work, one review per pull request, tests only in CI). Haiku can take the mechanical consumer moves inside P-C once the Sonnet-written API is in; each is a byte-sized, fully specified task (files, exact behaviour, what not to touch) with its try/catch and app-log rule. Every package adds a CHANGELOG line only if a learner can see or feel it (the changelog skill): P-B and P-C's flip do ("Faster start The app opens straight to your language and loads the others when you pick them."); P-A, P-D and the tests do not.

Instrumentation (all packages are accepted by these numbers, which the perf package 1 of the performance work adds; FACT: only point marks exist today, F1, so P-A adds the spans it needs if that package has not landed): StartupMarks gains span(name) returning a closer that logs Startup: <name> took N ms and emits a Timeline async span; the names used here: deckdownloads.open, catalog.shared, catalog.summaries, catalog.unit.<code>.read (bytes read in the isolate), catalog.unit.<code>.snapshot (hit or miss, files reused), catalog.unit.<code>.parse, catalog.unit.<code>.cross (the receive on the UI isolate), skills.map, skills.replay (must be 0 runs on the UI isolate), adult.scope, ui.firstReadyFrame. Every span also logs counts: files read, bytes read on the main isolate (target 0 for deck text), cards parsed, units loaded, and jank: the longest UI-isolate gap (SchedulerBinding.addTimingsCallback, frames over 16 ms during the splash) per load.

P-A: summaries, the unit API behind the whole-catalog API

  • Scope. LanguageSummary (model, JSON codec, golden), the summary computation in lib/core/decks/language_summary.dart, LanguageJob/LanguageOutcome and the pure unit job in lib/core/decks/language_unit.dart (parse one language plus shared; the partition and misfiling check), CatalogSet and LanguageLoad in lib/app/catalog_set.dart, DiskDeckFiles/MemoryDeckFiles, per-language snapshots (catalog-snapshots/<code>.json, read of the old single file as a seed), DeckDownloads.onFilesChanged(language) and the summarise job, added-index.json. CatalogSet.catalog returns the composed Catalog, so nothing outside lib/app/catalog_set.dart, deck_catalog.dart, main.dart and main_web.dart changes. In whole mode the one unit holds all languages; in lazy mode ensureLoaded is used only by tests.
  • Files touched. New: lib/core/decks/language_summary.dart, language_unit.dart, lib/app/catalog_set.dart, lib/app/disk_deck_files.dart, lib/app/summary_store.dart. Changed: lib/app/deck_catalog.dart (parseAll split so that it can run on a subset; DeckCatalog delegates to CatalogSet), lib/app/file_snapshot_store.dart (per-language store), lib/core/data/catalog_snapshot.dart (stamps per language), lib/app/deck_downloads.dart (onFilesChanged(language)), lib/app/stored_downloaded_decks.dart (a root and manifest paths for the isolate), lib/app/added_decks.dart, lib/app/startup_marks.dart (spans), lib/main.dart, lib/main_web.dart, lib/app/junk_cleanup.dart.
  • Cache-first (owner, 2026-11-22). P-A adds CatalogSet.verify and verifyAndRebuild: the verify job runs off the UI isolate and parses nothing; a mismatch rebuilds only that language. Test: test/catalog_set_test.dart (a valid cache parses zero files; one changed file rebuilds only its language).
  • Tests. test/language_unit_test.dart: the union of every language's unit equals parseAll of all files, member by member (decks in the same order, paths, facts, topics, creators, recommendations, broken lists), on a fixture of three languages with cores and layers, a private package and an added deck, and on the real decks-live sample the CI already checks out (the "Released app reads the decks" check); a misfiled deck becomes a BrokenDeck. test/language_summary_test.dart: the golden of a fixed fixture; b1Units equals LanguageOffer.b1Units and the counts equal tools/deck_index.py's for the fixture (the existing parity test of catalogLanguageFromDecks); a stale and a digest-mismatch summary behave as 3.4 says. catalog_snapshot_test.dart extended: a per-language snapshot of another app version is ignored for that language only; a damaged one falls back to YAML for that language only; the old single file seeds a language. catalog_isolate_test.dart extended: a unit crosses an isolate and equals the in-place result; the in-place fallback. test/summarise_on_download_test.dart: a download writes the summary before the language is selected.
  • Acceptance. whole mode: startup log shows bytes read on the main isolate = 0 for deck text (the reads moved into the isolate) and catalog ready no later than the baseline measured on the same phone; lazy mode in a profile run: loading one language's unit logs files read = that unit's files only. No consumer changed; the full test suite is green.
  • Risks. (1) Isolate.exit of a unit with an object that cannot be sent: covered by the fallback and the isolate test. (2) DiskDeckFiles inside an isolate and FileDownloadedDecks' atomic move-in (a read during a move): the job reads only the paths of the manifest, which lists a file only after its move-in (putAll writes the manifest last). (3) The union-equals-whole property is the one to keep honest: it fails on a cross-language dependency this page missed (F7); the test is the net. (4) Summaries diverge from the index's counts (two sources): the parity test names the rule.

P-B: startup loads only the selected language

  • Scope. Startup is from the cache (see 3.5, Cache-first startup): the shown state comes from the per-language snapshot, the summaries, the skill map and the replay snapshot, read at once; a verify-only job off the UI isolate compares their stamps and only a mismatch rebuilds (unit, summary, skill map, replay, fits), also off the UI isolate and lazily, shown language first; the rebuilt cache replaces the old one and is swapped in. StartupLanguage.resolve (lib/app/startup_language.dart, pure, in lib/core/ if it needs no AppState), AppState._load calls it and loads the startup job (3.5), the LanguageLoad states and ensureLoaded in AppState (a thin pass-through to CatalogSet), the loading state in the shell (the existing splash gate plus a per-language skeleton for Today and Decks), the directory-backed languages, languageChoices, shownLanguage, _todayScope (so the bar and the wheel never wait), the skill map from summaries and its pass-through into the open's replay (4.2) and a single progress.skills assignment, forAdult per unit, and the per-language _structureVersion (F15), the showLanguage path calling ensureLoaded. The composed Catalog is built from the loaded units, so a consumer that has not moved yet still sees the loaded languages (and nothing else: this is the package's main risk, mitigated by P-C landing before the default flips). In lazy mode only; whole stays the default.
  • Files touched. lib/app/app_state.dart (_load :1387, _mapSkills :1363, _view :848, languages/languageChoices/shownLanguage :1056-1110, _reloadDecks :1156, _filesDownloaded :1188, showLanguage, _stampOf :2260), lib/app/catalog_set.dart, lib/app/memory_progress.dart and lib/app/database_progress.dart (skills at open, replayInIsolate takes the map), lib/core/scheduling/replay.dart (entry that accepts the map), lib/features/splash/splash_progress.dart (the catalog stage means "shared + directory + selected unit"), lib/features/today/* and lib/features/decks/* (the loading state only), lib/ui/widgets/language_bar.dart and language_glyph.dart (read the directory), lib/main.dart.
  • Tests. test/startup_language_test.dart (the choice with no catalog equals shownLanguage with the catalog for a table of profiles, chosen languages, removed languages, first launch). test/lazy_catalog_test.dart (AppState with three languages: startup loads one unit only (counted loads); showLanguage('hi') shows the loading state then the content; a load for language B does not drop language A's cached queue (the per-language structure test, sessionBuilds unchanged); a superseded selection still completes; a failing unit shows failed and retry and leaves the others working; the web in-place path). test/skill_map_summary_test.dart (the map from summaries equals the map _mapSkills builds from all cards for a fixture; loading a unit leaves progress.skills equal, so replays does not increase; the per-language replay equals the full replay on a fixture log with a script deck, a hears: form card and an implied review: the verification of 4.2). test/adult_scope_test.dart (the flip is applied per unit, off the UI isolate in the stub runner; the composed view equals Catalog.forAdult).
  • Acceptance. Startup log, in lazy mode, on the owner's phone with the languages it holds and on a fixture phone with 10 languages: catalog.unit.* shows exactly one unit; deck bytes read on the main isolate 0; skills.replay 0 runs on the UI isolate after the first frame (INFERENCE the open's replay already has the map); the longest frame gap during the splash does not exceed the baseline's and the count of frames over 16 ms during the splash drops; ui.firstReadyFrame improves by at least the share of the phone's deck bytes that are not the selected language's, scaled by the parse share of the baseline (the target is recorded after the P-A baseline, section 8).
  • Risks. (1) Consumers that still read decks see one language: P-B changes the default only behind the flag and the diagnostics switch; the gallery and the existing widget tests run in whole. (2) The skill map's replay equivalence (4.2) is an inference: its test decides whether the open's replay or an isolate fallback is used. (3) The startup language resolve must equal the old shownLanguage for every state, including "chosen language is no longer learned" and "first of options": tested by the table. (4) A learner whose only on-phone language is not in languageChoices (a profile that learns nothing downloaded): the existing "download page" route (missingLanguages) runs from languagesOnPhone, not from decks.

As built (P-B, behind the flag). CatalogMode is chosen at launch from the persisted settings.catalogMode (lazy, whole or unset for kLazyCatalogDefault, which stays false); no Diagnostics screen exists yet, so the setting is the only switch. In lazy mode AppState._load opens the summaries, lists the files (CatalogSet.codesOnPhone), resolves the language with StartupLanguage.resolve, gives progress.skills the map from the summaries (skillMapOf; the open's replay already waits for it, #1699, so no replay runs on the UI isolate) and loads only that unit in a worker; verify then compares stamps off the UI isolate and _verifyCaches rebuilds a mismatching language in an idle slot, the shown one first. languages, languageChoices and shownLanguage read the directory (CatalogSet.directory); contentStatus is the per-language loading state Today and Decks draw a skeleton for; ensureLoaded is called by showLanguage and by a listener whenever the shown language has no unit. forAdult is applied per unit inside the unit job (LanguageOutcome.scoped), and only a change of the setting scopes a loaded unit again, in place. A summary whose stamp matches is reused by the job and not written again. The verify stamp now covers every file of a language, including decks the learner added, private packages and the language's shared files, which the verify job reads and hashes in the worker (P-A forced such a language to rebuild at every start). Not built: the per-language replay of 4.2 (the open's replay under the summaries' map, and the isolate replay of a later change, make it unnecessary), and the Diagnostics switch. A change of files in lazy mode (_filesDownloaded, an added deck, a private package) compares caches again and rebuilds only the languages that differ; a change of the theme list or sections reads the loaded units again.

P-C: every consumer moved (five pull requests, each an independent consumer group)

Each moves its consumers from the composed view to dir / unit(L) as section 5 says, adds ensureLoaded(L) where a screen is entered for a language that may not be loaded, and a test that the screen draws with only its unit and the directory loaded.

  • P-C1: language lists, the picker, the Languages page, the bar's glyphs, backup/restore names, profile names. Files: lib/app/language_offer.dart, lib/app/app_state.dart (languages consumers), lib/ui/widgets/language_bar.dart, language_glyph.dart, report_button.dart, lib/features/placement/language_*.dart, course_line.dart, native_choice.dart, lib/features/languages/*, lib/features/profiles/*, lib/features/settings/{settings_page,adjust_section,activities_page,profiles_privacy_page,restore_sheet}.dart, lib/app.dart, lib/features/summary/summary_page.dart, lib/features/today/fact_languages_sheet.dart (names only), lib/features/private/private_notes.dart. Tests: each screen's widget test runs with a directory of three languages and no unit loaded (CatalogSet with an empty unit map); learnedShare cache (stamp stale after a log restore triggers one background summarise); catalogLanguageFromDecks is deleted, its parity test now targets the summary. Acceptance: opening Languages, the picker and Add a language logs 0 unit loads.
  • P-C2: Today, Decks, path, drills, Progress/Stats, skills consumers, unlocks, reminders. Files: lib/features/today/*, lib/features/decks/* (except search), lib/features/drill/drill_page.dart, lib/features/stats/*, lib/app/{unlocks,daily_plan,session,reminder_service}.dart, app_state.dart (profileDecks, _learnedDecks, _countsAsDue, dueForecast, unlocks). Tests: dueForecast for unloaded languages equals the log-derived count (and equals the exact count for a fixture with no removed cards); an unloaded-language reminder tap loads then plans; Unlocks per language equals the whole Unlocks restricted to that language's counts; every cache re-keyed on the unit's version has a test that loading another language leaves it. Acceptance: Progress and Stats of the shown language log 0 additional unit loads; the reminder replan logs 0 loads.
  • P-C3: review, reviewer UX, flagged, offensive words, placement flows. Files: lib/features/review/*, lib/app/{reviewing,reviewer_check_records,placement,placement_plan,placement_run_setup,placement_bank}.dart, lib/features/placement/{onboarding_placement,placement_page}.dart. Tests: a reviewer with two courses opens each and the unit of each is loaded on entry only; rudeAlikesOf loads the partner's language; daily questions for an unloaded course are generated when loaded; placement of a not-yet-loaded language loads it first and shows the loading state.
  • P-C4: search, culture, topics, situations, facts, script and sound tools, IPA, hidden decks. Files: lib/app/{item_search,culture,culture_list,topics,situations,recommendation_feed,recommendation_questions,script_test}.dart, lib/features/{culture,topics,situations}/*, lib/features/decks/{unit_search,search_tabs,search_item_rows}.dart, app_state.dart (soundsOfWord, ipaAnswerTargets, numberRules, scriptGuide, sounds, romanisation). Tests: the IPA button enables after ensureLoaded('ipa'); the IPA keyboard offers symbols with the ipa unit not loaded; a search on a language runs on its unit; the culture settings page of a language reads its creators and recommendations from the unit.
  • P-C5: Settings pages that scan decks, Sources, voices, private languages, your decks, your data. Files: lib/features/settings/{your_decks_page,your_data_page,appearance_page,voices_page,speech_test_sheet,sources_page}.dart, lib/app/private_*.dart, lib/features/private/*. Tests: Sources lists every language's credits from the directory with no unit loaded and equals the whole-catalog result for a fixture (the parity test); Your data's rows load at most the languages of the rows it shows.

At the end of P-C the default flips (kLazyCatalogDefault = true); the changelog line ships with it.

As built (P-C2, behind the flag). AppState.decksOf(language) is the unit's own list of decks (the same list until that unit is read again; read whole, the language's part of decks, kept per catalog), and decksKeyOf(language) is what a value kept about a language is kept against. Every cache that was keyed on the identity of state.decks is now keyed on that list: cardLookupOf(state, language:), cardTagsOf, ProgressNumbers, the All tags practice count; each has a test that loading another language leaves it. Unlocks is per language (unlocksFor, kept by keptFor with the unit's version in its stamp, built from that language's cards and answers); unlocks is gone. _countsAsDue(onlyShown: false), and so dueForecast and the reminder replan, count a learned language that is not loaded from the log (Q6 default: no "card still in the decks" check, exact once loaded), and hasDueInLog gives the language bar's dot and the summary's next language for such a language. DrillRequest.languages names the languages a request draws on (its language, else those its deck and card ids name, else the shown one); buildSession returns an empty queue, not kept, while one is on the phone and not loaded (isSessionLoading), and the drill page, the deck page and the unit page call ensureRequestLoaded or ensureLoaded first. A reminder tap calls reminderOpened, which reads the shown language. The leeches page of one language reads that language's unit and shows a spinner meanwhile; the list of every language shows a row per language whose cards are not read (count, tap to read it) (Q10 default). Today needed no change beyond this: it already reads the shown language's unit and the saved summary.

As built (P-C4, behind the flag). AppState.catalogOf(language) is the unit's own catalog as the learner has it (the whole catalog when read whole, empty while the unit is not read), and what is kept about a language's items is kept against it: the typed search index (itemSearchFor), the topics, the culture items, creators and recommendations, the culture list, the path units and the search rows' sections, so that loading another language leaves them. A language's data files (facts, situations, number rules, sounds, romanisation, script guides) are read from its unit; Today's fact is the shown language's alone (Q3). The pages of one language that the learner can open for a language the bar is not on (situation, situation inspect, topic, culture, culture item, timeline, work and its questions) are wrapped by LanguageUnitLoader in AppRoutes.onGenerateRoute: it reads the unit on entry and draws a spinner meanwhile; the Tips page finds the language of a guide key from the directory (scriptGuideKeys, scriptGuideLanguage). The IPA unit is a dependency language: LanguageSummary.format is 3 and the ipa summary holds ipaSymbols, so the IPA keyboard (ipaAnswerTargets) offers its symbols with the unit not read; SoundsOfWordButton and IpaSymbols ask for the unit when they first show (ensureIpaReady), the button is enabled and the symbols drawn once it is read (ipaReady). hasNumberRules reads the directory flag for the number practice row. Not moved: the hasCulture, hasSounds and hasRomanisation flags have no button that needed them; the sections read by the search start hints are the shown language's; situations' card lookup still reads the drill decks of the loaded units (the page loads its unit first); hidden decks come with their unit.

As built (P-C5, behind the flag). LanguageSummary.format is 4: each summary deck has its name, and the summary holds voiceSample (up to three target texts, the first words of the first vocabulary decks that are not rude: voiceSampleOf), privatelyModified and credits (the books the decks name with their kind, the credits of recordings and images, the credits of the pictures of people and works with their licence as written, and the projects whose data the decks use; each line says whether only adult decks and rude cards gave it, so that Adult content off leaves it out). The credit helpers (ContentCredit, cardSources, mediaCredits, creditsOfDecks) moved to lib/core/decks/credits.dart; sources_page.dart exports them. Read one language at a time, Sources (deckCreditsOf) lists every language's credits from the directory with no unit read, Your decks (AppState.ownDecks) lists the learner's own decks from decks[], Voices' Play sample (VoicesPage.sampleFor) and the "Privately modified" tag (isPrivatelyModified) read the summary, and the glyph is glyphOf; voiceLanguages adds the languages of the summaries, so that a language whose unit is not read has its voice asked about. Read whole, each page reads the decks as before (the parity test compares the two). Your data looks a card up in its deck's own language (decksHolding) for the rows it shows and reads the unit of each of those languages, once, after the first frame; a row whose language cannot be read shows the card's id. The speech test and Appearance's preview read the language tested and the shown language. A private package's staging takes the built-in deck ids and the downloadable courses from the summaries, isPrivateLanguage reads the summary, and installing or turning on a package that modifies a built-in language reads that language's unit. Not moved: a language with several voice tags (hi-IN and ur-PK) shows only its first until its unit is read, because the summary names one LanguageInfo per language; the backup voice (_spelledIn) still reads the loaded decks; with Adult content off, a deck left with no card once its rude cards are taken out still names its source in the lazy Sources list.

As built (the default flip, 2026-11-23). kLazyCatalogDefault is true, so a phone with no stored catalogMode reads one language at a time; a stored whole or lazy still overrides it, which is the rollback (no Diagnostics screen exists: a patch release sets the constant to false, and the owner's builds set the stored value). Only main.dart reads the constant, through catalogModeFor: a DeckCatalog made with no mode (the tests, the gallery, the fixtures and the web build, which has no snapshots or isolates) reads whole, so no test changed its mode. The audit before the flip found the composed catalog read in five places that would have been silently partial, now fixed: primaryScript and _ownScriptOf for a language whose unit is not read (the summary holds the primary script; before, latin), the backup voice (backupVoice, _spelledIn) kept against the unit's version, the situations' card lookup kept against the decks read, and the language picker's sheet, which reads the language's unit before it builds the script test and Find my level. The first launch after the flip has no summaries: _loadStartup reads the shown language in a worker and makes the other languages' summaries one at a time in workers (from the old single snapshot where it has the files), and only then replays the log under the complete skill map; later launches start from the caches. Left reading loaded languages only, by design: the reviewer settings' count of decks waiting (review_section.dart), the Decks tab's broken-file rows, and the picker list's script-progress line for a learned language whose unit is not read.

P-D: remove the whole-catalog path

  • Scope. Delete CatalogMode.whole, the composed Catalog view, DeckCatalog.load of all files, catalogLanguageFromDecks, DeckSources' whole listing, the single catalog-snapshot.json code and its junk-cleanup line, Catalog.languages, AppState.decks/allDecks/catalogView (replaced by unitOf(code), shownUnit and dir), the flag and the diagnostics switch; the gallery and fixtures use CatalogSet.memory. Update ADR-0048 (status: amended by ADR-0062), the wiki's Architecture "Deck loading" and "Splash screen" sections, and this plan's status.
  • Tests. The suite compiles with the whole API gone (the compiler finds a consumer that was missed); grep guards in CI (tools/ check, as the repo has for other rules) fail on state.decks outside lib/app/; the Released app reads the decks job still passes.
  • Acceptance. No reference to the whole-catalog API remains; startup numbers equal P-C's; a release with lazy as the default has shipped.
  • Risks. Late discoveries of a consumer that read across languages (the compiler finds them, but the behaviour to choose may not be obvious): each is recorded in the owner questions of this page (section 9) or decided with the default there.

P-E (optional): prefetch the likely next language

3.6's idle prefetch, behind its own setting, default off until measured. Test: prefetch never starts during a session and a started prefetch does not delay a selection.

8. Acceptance numbers

All numbers come from the startup log and the timeline of P-A's instrumentation, measured before P-A (the baseline, whole mode and the old path), after P-B, and after P-C, on the same devices: the owner's phone with its real languages and a fixture phone with ten languages downloaded. The targets below are INFERENCE from the shape of the work and are set to the measured baseline once P-A has produced it; they are written so that the pull requests can be judged by ratios, not by guesses of absolute time.

Number Baseline (today) Target after P-B Target after P-C
deck text bytes read on the UI isolate all of the phone's (up to 86 MB) 0 0
deck files read at startup all the startup language's the startup language's
units parsed at startup all languages (1 job) 1 1
skills.replay runs on the UI isolate during start 1 or more (F9) 0 0
UI-isolate loops over every card (F8, F10) 2 0 0
catalog ready measured at most baseline x (selected language's bytes / phone's bytes) + shared + summaries, and below the baseline for any phone with more than one language same
frames over 16 ms during the splash measured not above baseline not above baseline
selecting a warm (snapshot) language: time to content n/a one frame of loading state, then a unit decode, never a blocked input same
memory after selecting every language all loaded at start same as baseline at most same
unit loads opened by Languages, picker, Sources, backup, reminders whole 0 0

9. Open questions for the owner (each with the default the plan takes; do not block on them)

  1. Q1. Is "the language selected" the language bar's language (shownLanguage)? Default: yes: settings.languageChoice, else the first learned language on the phone, resolved from the directory; no other language is loaded at start.
  2. Q2. Should search ever be global across languages? Today it is the shown language only (F11). Default: no change, the shown language only; a global search would need a per-language trigram file on disk (ADR-0049 builds its index in memory per launch) and is out of this plan.
  3. Q3. Does Today list languages other than the shown one? Today computes only the shown language since #461; the lazyFor machinery serves a profile that lists several. Default: the shown language only; the other languages' due counts show from the log without loading, with a tap to load and open.
  4. Q4. Eviction. Keep a loaded language until the app closes, or keep only the last 3 (LRU)? Default: keep all loaded, switch to the LRU only if the profile run shows a memory ceiling.
  5. Q5. How is the picker's "you X%" kept for languages not loaded? Default: a stamped cache in the summary, refreshed in the background; alternative: word-id lists per unit in a sidecar file (exact, larger).
  6. Q6. Due counts of unloaded languages for reminders. Default: count from the log and the leech set-asides, without the "card still in the decks" check, exact once the language is loaded. Alternative: also store a compact set of card-id hashes per language in the summary (larger, exact).
  7. Q7. After an app update, may summaries of unselected languages be used stale until refreshed in idle time? Default: yes (stale-while-revalidate, 3.4); alternative: refresh all before first use (a startup cost equal to today's, which defeats the point).
  8. Q8. Prefetch of the likely next language. Default: off until P-B's numbers are in; then on, idle slots only, never in a session.
  9. Q9. Daily questions for reviewers (daily_questions.dart) across courses. Default: only the loaded languages' decks; the set for another course is built when that course is next opened. Alternative: a background load of each reviewer course in idle slots (costs memory and battery).
  10. Q10. A global "every language" leeches list (leeches page with language == null). Default: list leeches by id with the language name and open the unit on tap; alternative: remove that entry point. (If language == null is reachable at all: the callers are to be checked in P-C2.)
  11. Q11. The flag. Default: a hidden diagnostics switch plus a compile-time default, removed in P-D; alternative: no learner-visible switch at all, a patch release to roll back.
  12. Q12. Changelog line. Default: one line at the default flip ("Faster start"); the owner may prefer to name it only after the numbers are known.

10. What this plan does not change

Deck format, the deck index schema (the per-language summary is an app cache, not an index field; the index stays the source for languages not on the phone), the download protocol (only the callback gains a language), the review log, FSRS, the replay snapshot format (only its input gains the skill map), the deck validator and tools, and decks-live. lib/core stays free of Flutter imports; no card id changes.

See also: ADR-0062 · ADR-0048 · ADR-0051 · ADR-0047 · Plans Index · Architecture

Clone this wiki locally