Database¶
omnitax build and Taxonomy.save write one SQLite file that holds any number of taxonomies, each
addressed as kind:version. The layout is versioned by its own text (PRAGMA user_version is a CRC of the DDL, omnitax.schema.LAYOUT, so it changes whenever the tables or indexes do; comments and white space of the DDL are not part of it); a file of
another layout, or any other SQLite file, is refused with a message.
Reading¶
Files are opened read-only (mode=ro, query_only). A store keeps a few connections of its own and lends one to each call; a
stream (rows, subtree, ...) keeps its connection until it ends, whichever thread asks for the next row. What a store knows of its
taxonomy (its row id, the ids of its name classes and link sources, its caches) is a view of the file, and every call first checks that the file
is the one the view was made of (the same file, not one renamed over it: a write into it, of any taxonomy, does not make it another; and the taxonomy still has the row id it had):
Each call reads in one transaction (a snapshot), and checks the taxonomy's row id inside it, so a call answers from the taxonomy as it was when the call began, or is read again on the new one; it is never answered from half of a replacement.
- the file was written again (the taxonomy replaced, another added), or renamed over: the next call makes a new view and answers from the new file; calls and streams that are running finish on the file they began on;
- the file has no taxonomy of that label any more: the call raises
KeyError, it never answers from another taxonomy; - the file is missing:
FileNotFoundError; not an omnitax file of this layout:LayoutError(only for what is one: SQLite's "not a database", or notaxonomytable); any other error of SQLite (a read-only directory that has an empty-waland no-shm, a disk error) is raised as itself, with the file's path in its message; locked by another connection for 20 seconds:sqlite3.OperationalError("database is locked"; this cannot happen to a reader of a WAL file, see below); replaced between two steps of one call:FileChanged(a retry reads the new one; calls retry once themselves).
Concurrency and the side files¶
Files are in WAL mode (a mode of the file, kept in its header): a reader never waits for the writer and the writer never waits
for a reader, so a half-read export does not stop a build, and a build (or the VACUUM after a replacement) does not stop omnitax serve. There is one
writer at a time: a second build into the same file waits 60 seconds and then fails with "is being written by another process".
What this means for the files:
- A file that is open (by a build, a server or a Python session) has
FILE-walandFILE-shmfiles beside it. A reader that only reads leaves them there when it closes; they hold nothing that is not inFILEafter a checkpoint, and.gitignoreof this repository ignores*.sqlite-*. Copy a file only when nothing writes to it (and keep-walwith it if a server has it open: the newest commit may still be in it), or copy it withTaxonomy.save(a copy made by the library is a single file). - A file written by
omnitax buildinto a path that does not exist is complete in itself when it appears: there are no side files until a reader opens it. - The file must be on a local disk: WAL needs shared memory between the processes, which network file systems do not give.
- A file on a medium that cannot be written (a read-only mount, a read-only container volume) cannot get its
-shmfile: it is then openedimmutable, which reads the file as it is and does not look at a-walbeside it. Such a file has to be complete (checkpointed: any file that nothing has open is), and must not change while it is read.
Tables¶
Every table is keyed by taxonomy, the row id in taxonomy.
CREATE TABLE taxonomy (
id INTEGER PRIMARY KEY AUTOINCREMENT, -- ids are never reused: a taxonomy that is written again has a new one
kind TEXT NOT NULL, version TEXT NOT NULL, -- UNIQUE (kind, version)
provenance TEXT NOT NULL DEFAULT '{}', -- JSON {"omnitax": version, "files": [{"source", "size", "sha256", "verified"}]}: the files the TREE came from
built TEXT NOT NULL, fuzzy INTEGER NOT NULL,
nodes INTEGER, names INTEGER, aliases INTEGER, links INTEGER,
meta TEXT NOT NULL DEFAULT '{}', -- JSON tables about the taxonomy (NCBI: divisions, genetic codes, `uninformative`: the ids whose members do not vote)
ranks TEXT NOT NULL DEFAULT '{}', -- a cache: JSON {rank: nodes}, what the node table says
name_from INTEGER, name_to INTEGER, -- the ids of the taxonomy's names (they are in rank order)
UNIQUE (kind, version));
CREATE TABLE attrs ( -- one row per distinct attribute set
taxonomy INTEGER NOT NULL REFERENCES taxonomy (id), id INTEGER NOT NULL, json TEXT NOT NULL,
PRIMARY KEY (taxonomy, id)) WITHOUT ROWID;
CREATE TABLE node (
taxonomy INTEGER NOT NULL REFERENCES taxonomy (id), id TEXT NOT NULL,
parent TEXT, -- NULL for a root (also a node whose parent is no node)
rank TEXT NOT NULL,
name INTEGER REFERENCES name (id), -- the node's own name: its row of name (the name is stored once; NULL: no name)
attrs INTEGER, -- attrs.id, NULL when there are none
lft INTEGER, rgt INTEGER, -- nested intervals: the subtree of a node is the nodes whose lft is between its lft and rgt
PRIMARY KEY (taxonomy, id),
FOREIGN KEY (taxonomy, parent) REFERENCES node (taxonomy, id),
FOREIGN KEY (taxonomy, attrs) REFERENCES attrs (taxonomy, id)) WITHOUT ROWID;
CREATE TABLE name_class ( -- the classes of the names of a taxonomy: name, synonym, authority, ...
id INTEGER PRIMARY KEY, taxonomy INTEGER NOT NULL REFERENCES taxonomy (id), name TEXT NOT NULL,
count INTEGER NOT NULL, UNIQUE (taxonomy, name));
CREATE TABLE name ( -- the ids of a taxonomy's names are in the order of name_pref(): the best first
id INTEGER PRIMARY KEY, taxonomy INTEGER NOT NULL REFERENCES taxonomy (id), node TEXT NOT NULL,
name TEXT NOT NULL, class INTEGER NOT NULL REFERENCES name_class (id),
lc TEXT NOT NULL, -- the name as normalize() makes it
rank TEXT NOT NULL, -- the rank of the node: denormalised, for filtering names by rank
FOREIGN KEY (taxonomy, node) REFERENCES node (taxonomy, id));
CREATE TABLE alias ( -- merged ids to their replacement, deleted ids to NULL
taxonomy INTEGER NOT NULL REFERENCES taxonomy (id), old TEXT NOT NULL, new TEXT,
PRIMARY KEY (taxonomy, old)) WITHOUT ROWID;
CREATE TABLE link_source ( -- where links come from: ncbi-assemblies, gtdb:232, taxonomy
id INTEGER PRIMARY KEY, taxonomy INTEGER NOT NULL REFERENCES taxonomy (id), label TEXT NOT NULL,
kind TEXT NOT NULL, -- what its keys are (genome, seq, ncbi, ...): one for all the links of a source
links INTEGER NOT NULL DEFAULT 0, -- how many links it has
provenance TEXT NOT NULL DEFAULT '{}', -- JSON {"files": [...]}: the files the LINKS came from (assembly summaries, GTDB's metadata)
UNIQUE (taxonomy, label));
CREATE TABLE link ( -- a key attached to a node
taxonomy INTEGER NOT NULL REFERENCES taxonomy (id), key TEXT NOT NULL,
source INTEGER NOT NULL REFERENCES link_source (id),
base TEXT NOT NULL, -- the key without its version or region: what lookups ask for (store.split_key)
node TEXT NOT NULL, name TEXT,
attrs INTEGER, -- attrs.id: what else is known of the link (NULL: nothing), shared with the nodes
seq INTEGER NOT NULL, -- the order the links came in: Store.rows() gives them back so (TaxonKit's ids depend on it)
PRIMARY KEY (taxonomy, key, source),
FOREIGN KEY (taxonomy, node) REFERENCES node (taxonomy, id),
FOREIGN KEY (taxonomy, attrs) REFERENCES attrs (taxonomy, id)) WITHOUT ROWID;
CREATE INDEX node_by_parent ON node (taxonomy, parent);
CREATE INDEX node_by_lft ON node (taxonomy, lft);
CREATE INDEX name_by_lc ON name (taxonomy, lc);
CREATE INDEX name_by_rank ON name (taxonomy, rank);
CREATE INDEX name_by_class ON name (taxonomy, class);
CREATE INDEX name_by_node ON name (taxonomy, node);
CREATE INDEX link_by_node ON link (taxonomy, node);
CREATE INDEX link_by_base ON link (taxonomy, base);
- Foreign keys are declared everywhere they hold, all
DEFERRABLE INITIALLY DEFERRED(left out of the DDL above: a node refers to its name and a name to its node, so they are checked at the commit). A build does not enforce them; setOMNITAX_FOREIGN_KEYS=1andwrite_taxonomydoes (the test suite does, and checksPRAGMA foreign_key_checkof the files it writes). A parent that is no node is stored asNULL(a root);alias.newrefers to nodes by id only where it can: it may name a node that is not there. - The tree is checked when it is written: a node listed twice is an error unless the rows are the same (tables made of lineages list their
ancestors again and again), and a cycle (parents that never reach a root) is an error; both name some of the ids, and the file stays as it
was. A node that is its own parent, or whose parent is no node, is a root (the second is logged as a warning, with the count and a few
examples). So
lftandrgtare set for every node. nameholds every name of a node (classnamefor its own, then synonyms, common names,unique names such asMorus <bird>, authorities, ...). Invariant: the ids of a taxonomy's names are in the order of rank, the order ofomnitax.dbwrite.name_prefand thenlc, then the node id (numerically for ids of digits, else as text): the id of a name is its rank, best first, so the best names of a prefix are the first ids,names()isORDER BY idand the word index yields names best first (tests/test_sqlite.pychecks it of every taxonomy it writes).name_fromandname_tobound them.- A node's own name is a row of
name(classname),node.nameis its id: the name is stored once, and a node is read with one more primary key lookup (LEFT JOIN name o ON o.id = n.name). The row exists for any non-empty name, also one thatlcmakes empty. name_classholds the classes of a taxonomy's names (NCBI: 12 or so) with the number of names of each;name.classrefers to it. A class is a label for a reader (Match.name_class,--class), the id is the file's business.- Two columns are caches of what other tables say, kept for speed:
name.rank(the rank of the name's node, so that a search can filter names by rank, throughname_by_rank, without touchingnode) andtaxonomy.ranks({rank: nodes}, for validating ranks and choosing a plan without counting). They are written with the taxonomy and not updated by anything else. lcis the name asomnitax.names.normalizemakes it (case folded, diacritics removed,-_brackets as blanks, quotes dropped); queries are normalised alike. One index (name_by_lc) serves exact and prefix search. Attributes live inattrsonce per distinct set: NCBI has thousands of sets for three million nodes, and a reader reads each when a record first needs it.aliasmaps merged ids to their replacement and deleted ids toNULL. Links whose node was merged are moved on saving (through a chain of merges, at most 100 steps); links of unknown or deleted nodes are dropped.- A link attaches a
keyto anode. A genome is stored under its full accession (GCF_000005845.2; GTDB'sRS_/GB_prefix is removed, the case is upper), so the versions of an assembly and itsGCA_andGCF_accessions are different genomes.link.sourcerefers to a row oflink_source, one per source of links of a taxonomy, in the order they were built: itslabel, thekindof its keys (genome,seq, or the kind of a taxonomy:ncbi), its number oflinksand theprovenanceof the files the links came from (the tree's are intaxonomy.provenance; the links of a taxonomy's own table, labeltaxonomy, came with its tree). The kind belongs to the source, not to the row (a source has one kind; a loader with two kinds of keys uses two labels), so a lookup of a kind askssource IN (the sources of that kind). A source lists a key once, several sources may list it (on different nodes, too); writing the same key twice for one source is an error (the write fails, the file stays as it was), and so is a source of two kinds.baseis the key without its version or region (omnitax.links.split_key), for looking up all versions of a number or regions of a sequence; how a query picks among them is one rule per kind inomnitax.links.match_link, not part of the file. A taxonomy's own ids are links no row stores: every taxonomy carries the implicit key<its kind>:<id>for each node, resolved throughalias.
Word and trigram indexes¶
Each taxonomy has ftN, named after its id N: an FTS5 index of the words of all names except authorities, with the id of the
name as rowid, which is its rank, so it yields names best first (how word starts, long prefixes and substrings are answered).
With fuzzy (the default) it also gets fwN (the vocabulary of those words) and fgN (a trigram index of the vocabulary). A
substring query expands its longest word to the vocabulary words that contain it; a fuzzy query corrects each of its words against
the vocabulary (shared trigrams, then edit distance), finds the names that contain the corrected words and ranks them by
similarity to the whole query. Taxonomy.save(path, fuzzy=False) leaves out fwN and fgN (about 5 % of an NCBI file):
substring search then behaves as prefix search and fuzzy search is an error; ftN stays.
Writing¶
write_taxonomy (behind Taxonomy.save and omnitax build) adds a taxonomy in one transaction:
a taxonomy of the same kind:version is deleted in the same transaction, so a failure (also a tree that is not one, see above) leaves the
file as it was, and readers see the old or the new taxonomy, never half of one. A file that does
not exist yet is written next to its path (to a name of its own, FILE.PID.RANDOM.part, so that two builds of one path do not meet; no syncs, and
a journal in memory, much faster), switched to WAL, written to the disk (fsync) and put in place with a hard link (which, unlike a rename, never replaces a file that is there) and the directory is synced too, so a failed first
build leaves nothing and a crash leaves a file or none. If another build made the path while this one ran, this one fails with FileExistsError ("made by another build") and loses
nothing silently: the other's taxonomies are in the file and this one is not (Taxonomy.save then writes into that file instead). On a file system without hard links the file is renamed. After a replacement the file is
VACUUMed, so it shrinks to what it holds (this needs free disk space of about the file's size; adding a new taxonomy does not). The
taxonomy is written when the VACUUM starts: one that fails (no room) is logged as a warning and does not fail the write, the file just keeps the room of
the old copy. Readers are not held up by it (WAL), but the -wal file grows about as much as the file.