Engine
keyrill-core converts text between layouts, decides whether a typed word is a layout mistake,
parses personal vocabulary and tracks the word session. It makes proposals and never reads or edits
a native document. The C ABI over it is described in porting and include/keyrill.h;
how Keyrill works walks one decision through with real numbers.
Layout mapping
Layouts are US QWERTY and Russian ЙЦУКЕН. Apple’s Russian layout and the PC Russian layout differ on
the ё key and are separate Keyboard values; the macOS adapter uses the Apple map. A verified
Windows or Linux layout table is the adapter’s job, not something to infer from Apple’s Russian-PC
layout.
Mapping::EnToRu and RuToEn convert physical key positions. Mapping::Manual converts each
supported letter and leaves punctuation and unsupported UTF-16 units, including unpaired surrogates,
unchanged. It is not an involution; don’t test it as one.
A word is a run of EN/RU letters (mapping::is_letter). In English mode the keys that type х, ъ, ж,
э, б, ю and ё in Russian ([ ] ; ' , ., the ё key for the session’s keyboard, \ on Apple and
` on PC, and their shifted forms) are provisional letters: inference::is_provisional units
can start or continue a word, so [jhjij becomes хорошо and ;bpym becomes жизнь. A word that
isn’t corrected is committed exactly as typed, so hello, stays hello, and a lone ... or ;
stays punctuation. Such a key is part of the composition rather than passed to the host, so host
behavior tied to the key itself, such as smart quotes or bracket pairing, doesn’t apply to it. In
Russian mode these keys are letters and nothing else changes.
| US key | [ | ] | ; | ' | , | . | \ (Apple), ` (PC) |
|---|---|---|---|---|---|---|---|
| Russian letter | х | ъ | ж | э | б | ю | ё |
Inference
At Space, Session::propose_with_inference evaluates the owned complete word against borrowed model
and vocabulary snapshots and keeps no borrowed input in its pending plan. After the eligibility,
personal-vocabulary and known-word checks below, a typed word w whose other-layout reading c is
in the target lexicon with Zipf at least 2.5 is corrected when
where f is the candidate’s word frequency, P the order-2 character chain’s likelihood of the
typed letters, p = 0.001 the error prior, k the context factor (19 when the session’s recent
words are in the target language, 1/19 when they are in the source language, 1 otherwise), C = 100
the false-change cost, and π a length penalty of 4, 2 and 1 for one, two and three UTF-16 units.
Policy holds p, C, the minimum Zipf and the known-word gate values.
Note
These are uncalibrated ranking parameters, not probabilities; the numeric domain limits the Zipf values and margins to 0..=9. The evaluation records their measured behavior and the limits of the policy experiments.
A typed string that is a word in its own layout’s lexicon (Known, reason 3) yields to the other
reading only when it is rare and the other reading is far more frequent: its Zipf score must be
below 3 and the candidate’s must exceed it by at least 2.5, or 3.5 for a word of two UTF-16 units
without context in the target language. A yielding word is corrected on the frequencies alone,
scored by the difference of the two Zipf values, which is the base-10 logarithm of their frequency
ratio; the character chain adds nothing for a string the lexicon already has. So yf (Zipf 2.37)
becomes на (7.25) and ghb becomes при, while lf (3.40) stays lf. A word of one unit never
yields; the rule counts the whole word, so e. is two units.
For a provisional word the candidate is the whole key sequence read in Russian. Case is judged on
that reading. The English reading is the letters alone: the character chain scores them, and each
provisional unit before, inside or after the letters adds log10 of how often such punctuation
appears there in English words (−2.3, −1.6 and −1.0, measured on the EWT dev split). Only
punctuation at the end leaves an English core, and that core gets known-word protection, so it.
doesn’t become шею and he, doesn’t become руб. A word without letters is ineligible.
A three-unit word with a candidate Zipf of at least 4 gets another 3 log10 units of evidence per
leading provisional unit, unless context supports the source language. This lets [jl become ход
and ,sk become был without preceding context. It can also convert an intentional literal
fragment; personal-vocabulary and known-word protection still apply before scoring.
The engine abstains on unknown modes, unsupported or mixed-script tokens, mixed case, multi-letter
all-capital words and invalid policy values. A single initial capital is eligible (Ghbdtn becomes
Привет). Decision reasons are numbered for the reference vectors:
| Reason | Meaning |
|---|---|
| 0 | Correction |
| 1 | Ineligible token |
| 2 | Protected by personal vocabulary |
| 3 | Known word in the source language |
| 4 | Candidate forbidden by personal vocabulary |
| 5 | Evidence too weak |
| 6 | A configured dictionary is missing |
| 7 | Explicit manual or reversal intent |
Personal recognized and rare words are protected. A forbidden entry overrides personal and general protection, and a forbidden candidate is rejected. Candidate membership doesn’t supply a frequency or justify a correction by itself. Mapped punctuation outside the target alphabet is ineligible.
Both personal sources must be ready before automatic correction runs. A valid empty source is ready;
a missing one is not, though a host may publish a missing default-path file as empty (macOS does,
with KR_SOURCE_MISSING_IS_EMPTY). Manual conversion works regardless. Manual and reversal intent
stop reinference of that word; a typo fix alone doesn’t.
Context
Language context comes from the session’s own verified finished words, at most 256 UTF-16 units, never from reading the document. A finished word plus Space is appended on an acknowledged finish; a still-reversible Space mark is not. Refusal, unknown effects, reset, mode changes and unowned host actions clear it. So does printable punctuation, because the host’s action on it isn’t acknowledged. The context scan takes the last two known same-language letter runs on the current line, skipping non-letters and stopping at LF/CR; dropping punctuated context can remove the protective factor of 19, so change that scan only with a new evaluation.
Personal vocabulary
The engine reads Vim .add word lists
(:help spell), UTF-8, at most 1
MiB, line by line as Vim reads them. Supported: an initial BOM, LF/CRLF, blank and comment lines,
/encoding=utf-8, /regions=, and the flags =, ?, ! and 1 through 9. A line whose first
byte is # is a comment whatever follows, because Vim’s zw, zug and zuw comment out an entry
by overwriting that byte. A line that isn’t UTF-8, an unknown directive or flag, a word with a
control character and other bad lines are skipped and counted (Vocabulary::skipped). NUL anywhere,
oversized input or a leading /encoding= other than utf-8 rejects the whole file. Unicode
whitespace at line edges, including NBSP, is stripped.
A lowercase entry protects lowercase, capitalized and uppercase forms; a cased entry protects its
exact and uppercase forms; /= requires exact case. Across matching entries, forbidden (!) wins,
then recognized, then rare (?).
| Entry | Matches | Effect |
|---|---|---|
hello | hello, Hello, HELLO | Recognized: never corrected |
iPhone | iPhone, IPHONE | Recognized |
iPhone/= | iPhone only | Recognized |
colour/? | as for hello | Rare: still protected |
ghbdtn/! | as for hello | Forbidden: overrides any protection and is never a correction’s result |
A /regions= line and the region flags 1 through 9 are validated and then dropped, so lookup
doesn’t depend on locale; the flags are accepted even without a declared region name. A malformed
/regions= line is skipped like any other bad line.
vocabulary::Snapshot::replace parses the whole candidate before publishing it. Readers keep the
old immutable Arc and a failed candidate never partially replaces it. keyrill-ffi reads the
files for the adapter; see macOS.
Words the user taught the OS spell checker (Learn Spelling on macOS, Add to dictionary on Windows)
are a second kind of source. Vocabulary::parse_words reads such a list as one word per line, UTF-8
with an optional BOM or UTF-16 LE with its BOM; every line is a word, so # and / are ordinary
characters. Each word takes the case rule of an unflagged Vim entry and is recognized, or forbidden
when the list holds excluded words. The lists go into Dictionaries::learned and protect and forbid
together with the Vim sources, but readiness depends only on the two Vim sources: a learned list
that is missing or unreadable never holds correction back.
Model
flowchart TD
W["wordfreq 3.1.1"] -->|"model/tools/build_model.py"| I["model/data/model.inc.gz<br/>pinned by hash"]
I -->|"tools/pack-model.py"| B["assets/model.bin"]
B -->|"include_bytes!"| C["keyrill-core"]
C -->|"Model::parse, once per process"| M["Model, borrowed<br/>by every decision"]
assets/model.bin holds 89,656 English and 241,624 Russian words with log10 frequencies, plus an
order-2 character chain per language. It is derived from wordfreq 3.1.1 large lists. The loader
checks the magic, version, source-hash field, alphabets, counts, offsets, word indices, ordering,
section bounds and trailing bytes, and validates once outside input callbacks. Header checks are
consistency, not authentication: tools/pack-model.py --check regenerates every asset from the
pinned source in model/data/model.inc.gz and compares bytes. Its docstring specifies the format.
The packer stores every value as a signed integer in micro-units and reproduces all 396,107 source
values bit-exactly as f64. It doesn’t retrain, recalibrate or renormalize anything. To regenerate
the source itself, see model/README.md.
Evaluation
./tools/verify evaluate runs model/tools/evaluate.py against tools/inference-probe, offline,
over the pinned Universal Dependencies dev and test splits of English EWT and Russian Taiga, and
fails if a gate below fails. Reports, including every false correction, go to
target/evaluation/docs/results/. No personal dictionary is read. The current policy was selected
on dev after inspecting earlier holdout and test failures; repeated test results are exploratory,
not independent confirmation.
The evaluation types text through the real Session the way the macOS adapter drives it: a word
starts only after whitespace or at the start of the document, a write is applied only if the
simulated composition holds exactly the plan’s expected text and is acknowledged after it is
applied, and a mode change finishes the word and resets the session. A mismatch, or a passed key
that would land inside the composition, stops the evaluation with an error. Each sentence is one
document, typed in one go with a Space after it.
- Wrong-layout replay. Every sentence (
# text) is typed on the keys of its own Apple layout while the other mode is active, so Russian,arrives as^in English mode and English,asбin Russian mode. Per language: token recall is the share of whitespace tokens that changed under the wrong layout and come out exactly as intended; word recall is the same over tokens that are letters only; first-error recall is the share of sentences whose first wrong token is fixed, the one that matters when a correction switches the input source. A token changed to anything else is a miscorrection. - Right-layout replay. The same sentences typed correctly, each token in the mode of its script, so Latin words in Russian text switch modes. Any change is a false correction.
- Negative set. Isolated tokens, each typed as
tokenin a fresh session, so no context protects them: corpus words the model knows (known) and doesn’t know (oov), proper nouns (names), simple Latin transliterations of the Russian words (translit), and every single-edit keyboard typo of the corpus words, made by deletion, transposition, or substituting or inserting a neighboring key, including the keys that are provisional letters (typo). The report also counts how many tokens reach the scoring step.
Results with the default policy:
| Split | RU token / first-error recall | EN token / first-error recall | Right-layout false | Typo false (per 10,000) | Other negatives false |
|---|---|---|---|---|---|
| dev | 54.5% / 54.2% | 62.0% / 48.4% | 0 of 35,031 | 23 EN (0.92), 29 RU (0.73) | 1 translit of 5,197 |
| test | 49.7% / 50.7% | 61.6% / 48.0% | 0 of 33,899 | 24 EN (0.97), 23 RU (0.66) | 0 |
Correct corpus words, known or not, never reach the scoring step; names reach it once on test and never on dev. These cases guard against regressions but supply little evidence for choosing a threshold. Typos and transliterations do: about 600 of the roughly 600,000 typos per split reach scoring, and they are what bounds the minimum candidate Zipf. The known-word gate can only open for lexicon words, so its whole exposure is the list of lexicon words whose other reading passes it, which the negative set below pins.
Remaining misses include words finished by punctuation rather than Space, protected lexicon words
such as lf for да, candidates absent from the model or below the frequency floor, and candidates
whose scores remain below the length-adjusted threshold. Return and Tab also finish the word without
running inference.
The gates, in tools/evaluate-model.py, apply to both splits:
| Gate | Bound | Why |
|---|---|---|
| Token recall, RU / EN | ≥ 44% / ≥ 58% | About two points under the original policy’s lower split |
| First-error recall, RU and EN | ≥ 45% | About two points under the original policy’s lower split |
| Right-layout false corrections, both languages | ≤ 2 | Measured 0; 2 of about 34,000 tokens is under 1 per 10,000 |
| Wrong-layout miscorrections | ≤ 2 | Measured 0 |
| Known, OOV and name false corrections | ≤ 2 | Measured 0 |
| Transliteration false corrections | ≤ 3 | Measured 1 on dev, 0 on test |
| Typo false corrections, per language | ≤ 1 per 10,000 | Measured 0.66 to 0.97 |
Important
Errors are synthetic, typos and transliterations are generated, every sentence is typed without Backspace or source switching, and wordfreq’s sources may overlap these corpora. None of this estimates precision on real typing.
The release target is fewer than one false automatic correction per 10,000 eligible correct words. No offline source with a redistribution license covers real chat, code review, identifiers or Russian social text beyond Taiga; adding one means pinning it by hash with its license next to the existing corpora.
A policy change needs the evaluation rerun on dev, the reference vectors still passing and the negative set below unchanged except for cases the change is meant to open. Don’t edit expected values to remove failures.
Reference tests
crates/keyrill-core/tests/fixtures/engine-vectors.jsonl has 1,217 expected outputs: 90 mapping,
120 vocabulary, 7 context and 1,000 inference requests. Inference scores are compared with a
relative tolerance of 1e-12 and an absolute tolerance of 1e-10. The request protocol:
| Request | Response |
|---|---|
map K MODE TEXT | MODE 0 manual, 1 EN→RU, 2 RU→EN; output as UTF-16 hex |
vocab SOURCE WORD | Parse success 0/1, entry count, lookup (0 absent, 1 recognized, 2 rare, 3 forbidden) |
context PREFIX | Language tag |
infer K ACTIVE CONTEXT PRIOR COST MINZIPF EN_ADD RU_ADD WORD | Reason, score, replacement hex or - |
Hex strings are UTF-16 units, - is empty, keyboards are 0 Apple and 1 PC, languages are 0 unknown,
1 EN, 2 RU. negative-words.md describes
766 words and model collisions that must never be corrected, run under three contexts and both
keyboards. Inference requests set three policy values; the known-word gate takes its defaults.