Dictionary format
This document specifies the normalized dictionary input formats consumed by
gukhanmun-mkdict and the FST/CDB dictionary file layouts produced from those
inputs. It is the boundary between dictionary extractors, user-maintained
glossaries, and backend builders.
Canonical TSV input
The primary input format is UTF-8 TSV with a required header row. Each file must contain at least these columns:
These optional columns are recognized:
Boolean values are true, false, 1, or 0. Empty optional boolean cells
are treated as false.
Additional columns such as category, source, or note are allowed as
future extension space. The current builder does not consume them; it emits a
short warning and ignores their values.
Example:
Candidate rows
Optional preference (an unsigned 32-bit integer) and suffix_reading columns
retain competing readings and a candidate's non-word-initial form. A nonempty
preference, including 0, opts the row into a candidate set. All rows for that
key in the same file must opt in together. The source_ids column is accepted
as build-time provenance; the TSV column alone is not embedded in the
dictionary. Compiled source evidence is supplied separately with --evidence.
Larger preference wins. Identical (reading, suffix) pairs merge their marks by OR and keep their greatest preference. After deduplication, preferences are stored relative to the smallest preference. Ties are broken by reading, then suffix, in UTF-8 byte order. Marks never merge across unrelated readings. Empty suffix cells mean no positional form.
JSONL accepts optional preference and suffixReading/suffix_reading; a null
preference is a legacy row, and an explicit empty suffix string is invalid.
Rows without a preference are legacy rows, even when they carry a suffix,
and keep the duplicate-key merge semantics described below. Across input files,
merge policies replace or reject complete sets for a key. They never merge a
user override with a lower-priority set. Annotation rules operate on each
candidate, so a reading rule affects only that reading.
CSV and JSONL input
gukhanmun-mkdict chooses the input parser from each file extension. .tsv
uses the canonical TSV parser, .csv uses the CSV parser, .jsonl uses the
JSON Lines parser, and unknown extensions are treated as TSV for compatibility.
CSV files use the same header names as TSV:
Each JSONL line is one object. The boolean fields accept either snake_case or camelCase spellings:
Merge policy
When multiple input files are supplied, or when one input file repeats a
hanja key, gukhanmun-mkdict applies the configured merge policy:
error: fail on the first duplicate key. This is the default.first-wins: keep the first entry and ignore later duplicates.last-wins: replace earlier entries with the last duplicate.
After merging, entries are sorted by UTF-8 key bytes before backend encoding. This makes generated FST and CDB artifacts deterministic for the same normalized inputs and metadata.
Build metadata
Every generated backend file embeds CBOR metadata. The minimum keys are:
entry_count, version, max_word_chars, max_key_bytes, and
prefix_count are reserved and cannot be supplied with --metadata. Other
--metadata KEY=VAL pairs are preserved as string values.
For reproducible builds, the builder does not use the current clock by default.
If build_date is not passed explicitly and SOURCE_DATE_EPOCH is set, the
epoch is formatted as UTC RFC 3339. If neither value is present, the fixed date
1970-01-01T00:00:00Z is used.
FST backend file
The first implemented backend format is fst. The file contains:
- A fixed 64-byte little-endian header.
- A CBOR metadata map.
fst::Mapbytes.- A contiguous reading/payload table.
The fixed header fields are:
Each FST key is the UTF-8 bytes of the hanja column. Each FST value is a
64-bit integer:
The reading bytes are stored in the reading string table, not in the FST value, because FST values are fixed-width integers.
At runtime, gukhanmun-fst decodes the fixed header and CBOR metadata eagerly.
The FST map bytes and contiguous reading table then share a single byte backing
store: owned heap bytes for FstDictionary::open() and
FstDictionary::from_bytes(), static bytes for
FstDictionary::from_static_bytes(). The crate intentionally does not expose a
safe file-backed mmap loader because Rust cannot enforce that another file
descriptor or process will keep the mapped file immutable while the dictionary
is live.
entries() and has_homophone() enumerate the FST and therefore remain
full-dictionary scans; callers that need repeated homophone checks should use
the core homophone middleware's batch index.
CDB backend file
The CDB backend format is cdb. It uses a trie embedded in CDB key space:
each prefix of each dictionary key is written as a CDB key. Prefix records
that are complete dictionary entries carry the reading and mark bits; prefix
records that only lead to longer entries carry no reading.
The metadata CBOR map is stored under the reserved key
__gukhanmun_meta__.
The runtime CDB backend reads files into owned bytes; from_bytes() copies
its input, while from_static_bytes() borrows a static slice without copying
the file data. Loading validates record framing and hash tables, then builds
an in-memory range index sorted by hash, key and probe order. Each key lookup
uses key comparisons for records, even with hash collisions.
Candidate payloads are decoded when accessed.
The record and lookup indexes together are limited to 64 MiB of requested storage, checked before allocation. This limit excludes the file bytes, decoded metadata and allocator overhead. Static backing avoids a file-data copy, not the index allocation.
Version 2 candidate payloads
The builder writes v1 when every key has one candidate without a suffix, and v2 otherwise. New readers accept both versions; readers released before this extension reject v2 files. Rebuild candidate-aware files with the new builder and update the consuming crate or binding together. A single-candidate file continues to work with old readers.
In v2, mark value 0x80 identifies a payload instead of a scalar reading. For
FST, the existing 16-bit length and 40-bit offset address its bytes. For CDB,
the 16-bit length at offset 2 is the payload length and bytes begin at offset 4.
Scalar records retain their v1 layout. The payload starts with a little-endian
u16 candidate count, followed by each candidate:
Payloads must fit within 65,535 bytes and contain a nonempty canonical set.
Readers reject truncation, invalid UTF-8 or mark bits, empty readings, trailing
bytes, duplicate identities, noncanonical ordering or weights, and payload tags
in v1 files. A singleton without a suffix must use the scalar representation.
Exact lookup returns decode errors; infallible iteration retains the backend's
skip/abort policy. lookup().candidates() and the candidate trait methods
expose full sets; reading(), mark(), matches_at() and entries() project
defaults.
Validation
With --validate, gukhanmun-mkdict writes the output, opens it again with
the selected backend, and checks that every merged entry can be recovered with
the same full candidate set, including relative preferences, positional forms
and marks. Entry counts are compared per key, not per candidate. Validation
failure is fatal.
Version 4 critical source evidence
--evidence source-evidence.json supplies typed source evidence separately from
canonical candidate rows. The standard dictionary extractor produces this file
with --evidence-output; the loanword update task derives it from every
candidate's original source IDs. Evidence links use the key plus the complete
initial/suffix reading pair. Preferences, marks and aliases stay in their
original candidate payloads.
A build with evidence always writes container version 4, including a scalar-only
dictionary. Without evidence, the builder retains version 1 for scalar entries,
version 2 for candidate sets and version 3 for aliases. New readers support all
four; older readers reject version 4. The public JSON evidence schema has its
own schema_version, currently 1.
The CBOR metadata adds the reserved, non-string candidate_evidence member:
role is override, reference or loanword. Contributions retain unsigned
64-bit word/sense IDs in separate fields and native, foreign, mixed or
unknown origin. A relation witness distinguishes a word target from a sense
target even when their numeric values coincide. Authorized forms and diagnostics
use their typed evidence fields; CBOR tuples compact the repeated candidate and
contributor fields without changing the separate JSON schema.
Before exposing evidence, readers check tuple structure, schema and role,
nonempty forms, duplicate identities and exact links to stored candidates.
Absence of both critical evidence members in version 4, evidence in an older
container, unsupported schemas, duplicate critical metadata and stale candidate
links are errors. Partial evidence is allowed; uncovered candidates have
unknown evidence. The string metadata API omits this typed member; Rust callers
inspect it through HanjaDictionary::source_evidence().
The dictionary updater preserves exact numeric tokens while comparing evidence artifacts, including IDs above JavaScript's safe integer range. Custom JSON processing must likewise preserve unsigned 64-bit IDs.
Critical phrase evidence
--phrase-evidence phrase-evidence.json embeds a separate, typed
phrase_evidence member in the container's CBOR metadata. It carries
PhraseEvidence, whose schema_version and policy_version are both
currently 1. The existing DictionaryEvidence/candidate_evidence schema
remains version 1; phrase rules do not extend its candidate authorization
tuples. Both members are critical and excluded from the string metadata API.
Rust callers inspect phrase rules through HanjaDictionary::phrase_evidence().
Either evidence member makes the container version 4. Version 4 requires at least one of them and permits both; versions 1–3 cannot carry either member. Consumers must support the phrase extension before loading a phrase-bearing file. Rebuild the dictionary and update its consuming runtime together. Runtime loading uses the dictionary file alone, with no filename discovery, network lookup or evidence sidecar.
A rule retains its source word IDs and ordered chunks. Each chunk records its complete attested reading and exact source spellings; each spelling links to original candidate initial/suffix pairs. Runtime restrictions require that same complete output pair as well as the source anchor. Additional sibling spellings require explicit source witnesses. Literal-only chunks can have no dictionary links. Terminal extensions retain complete child spellings and typed parent-word to child-word witnesses, rather than an inferred grammatical suffix. The builder validates links against final normalized candidates, after aliases and rules have been applied.
The standard dictionary extractor writes the build input and its admission
manifest with --phrase-evidence-output and --phrase-manifest-output; supply
both options together. These are reproducible build artifacts. The audit
phrase-manifest.json stays in the repository and is excluded from the
published gukhanmun-stdict crate; the runtime phrase-evidence.json remains
bundled. The extractor compiles phrase constraints separately from word
candidate rows. It does not insert phrases as lookup keys or pin their
component readings. At runtime, all participating chunks must align with the
fixed path and the owning leaf's eligible candidates before any target receives
a restriction. A caret admits zero or one U+0020; whole-chunk hangul
alternatives do not authorize arbitrary character-wise hanja/hangul mixtures.
Readers reject unsupported schema/policy versions, duplicate critical members,
malformed witness records, stale candidate links and evidence exceeding host
limits. The metadata byte limit is checked before decoding; rule, chunk,
alternative and span limits are checked before exposing evidence. Runtime
discovery/match limits withhold evidence for the affected finite interval
rather than accepting an arbitrary subset of constraints. On a conflict or
limit, the resolver keeps the legacy particle-aware reading.
ResolutionReport records that decision.