The Rust engine¶
ddigraph reads a DDI XML file with lxml, in Python. The Rust engine is a second way to read it. It gives the same graph: the same nodes and relationships, in the same order, with the same counts of references and conflicts.
The engine lives in its own package, ddigraph-core, which ddigraph installs with
itself. By default, ddigraph picks the engine for each file, as
Which engine reads a file says. lxml stays the reference
the engine is checked against.
Install it¶
pip install ddigraph also installs ddigraph-core, at the same version. Where a
ready-made wheel fits your system, pip takes it, so nothing is compiled:
- Linux (x86_64 and aarch64), macOS (Intel and Apple silicon) and Windows (x64);
- one wheel for Python 3.12 to 3.14, and another for Python 3.15, with or without the GIL.
Anywhere else, pip takes a stand-in of the same name, with no engine in it. ddigraph then reads every file with lxml, as it always did.
The engine itself runs without the GIL. But ddigraph cannot be installed on a free-threaded Python yet, since one of its dependencies, orjson, does not build there. And lxml 6.1 turns the GIL back on when it is imported.
To build the engine yourself from a clone of ddigraph, you need a Rust toolchain, which rustup installs:
pip install --force-reinstall ./rust
Which engine reads a file¶
The engine setting takes one of three values:
auto, the default, reads a file with the Rust engine when two things hold. The engine must be installed, and its memory peak for the file must fit the memory limit (--memory-limit,DDIGRAPH_MEMORY_LIMIT_MB). Otherwise it reads the file with lxml.rustalways reads with the Rust engine. Without it, ddigraph stops before it reads the file, with a message that says how to build it.lxmlalways reads with lxml.
With auto, lxml also reads any file the Rust engine refuses, such as a file that is not
well-formed XML. A file that passes a safety limit is the one exception: lxml stops at
the same limit, so that error stands. So auto gives the graph lxml gives, apart from
the rare cases in How it differs from lxml.
The memory peak counts as the file's size times 64 for Codebook, 16 for DDI-L and 8 for
DDI-CDI. That is about 1.5 times what the bench measured. With the default limit of
256 MB, auto uses the engine for a Codebook file up to 4 MB, a DDI-L file up to 16 MB
and a DDI-CDI file up to 32 MB. store add and a load through the store give the parse
half the limit. Raise the limit to use the engine for larger files.
Use it¶
Pass --engine to load, export, preview or store add:
ddigraph load study.xml --engine rust
ddigraph export study.xml -o study.ttl --engine lxml
Or set it once, for these four commands and for the HTTP API:
export DDIGRAPH_ENGINE=rust
In Python, pass engine to ddigraph.ir.parse, ddigraph.iter_graph,
ddigraph.export or ddigraph.preview. ddigraph.load reads it from its settings:
import ddigraph
from ddigraph import ir
from ddigraph.config import Settings
chunks = ir.parse("study.xml", engine="rust")
result = ddigraph.load("study.xml", dry_run=True, settings=Settings(engine="rust"))
To read files you do not trust, see The sandbox.
What it reads¶
The engine reads every flavor ddigraph reads:
- DDI Codebook 2.x (
codebook); - DDI-CDI 1.0 (
cdi) and the experimental DDI-CDI 1.1 (cdi11); - DDI-Lifecycle 3.1 to 3.3, in a FragmentInstance file (
lifecycle); - the experimental DDI-Lifecycle 4.0, in an ItemContainer file (
lifecycle4).
ddigraph_core.UnsupportedFlavorError, a ValueError, means a flavor name the engine
does not know. ddigraph.ir.parse refuses such a name before it calls the engine.
Speed¶
The Rust engine reads a file 5 to 7.5 times as fast as the lxml engine, counting the start of the process. It holds the whole parse in memory, though, so it needs more of it: about 1.1 GB for a file of 400,000 elements, where lxml stays near 80 MB. That is 5.6 to 43 times the size of the file, by flavor. Bulk Import and Large Files gives the numbers.
How it differs from lxml¶
It differs in three main ways. A few rare cases, named below, differ too.
- It reads well-formed XML only. lxml can read past some syntax errors, such as a
bare
&in a text, unless you ask for strict parsing. The Rust engine always stops at the first one, with aValueErrorthat gives its line and column. The list below says what else this covers. - It holds the whole file in memory. It accepts
--memory-limit(DDIGRAPH_MEMORY_LIMIT_MB) and does not apply it. For a file larger than your memory, use the lxml engine, which sorts past the limit in temporary files. - It reads fewer encodings. It reads UTF-8, UTF-16, US-ASCII, ISO-8859-1 to
ISO-8859-16, windows-874, windows-1250 to windows-1254, windows-1256, windows-1257,
KOI8-R and IBM866. It knows them by the names libxml2 knows them by, such as
latin2orIBM819. A file in another encoding, such as UTF-32, Shift_JIS or windows-1255, raises aValueErrorthat saysUnsupported encoding. Use the lxml engine for it.
As it reads well-formed XML only, the engine also stops at what lxml reads past unless it parses strictly:
- a colon in the target of a processing instruction, or in the name of an entity;
- a namespace name that is not a URI, such as one with a space in it;
- an entity whose text is not well-formed where the file uses it. Its text may not hold
a character reference to no character, or a stray
&. In element text, it may not hold]]>.
It keeps the same safety limits as the lxml engine. It never fetches a DTD and never
reads an external entity. It refuses an entity whose text holds markup. A text, a depth
or a name past its limit raises the same XMLLimitError, and huge_tree
(DDIGRAPH_XML_HUGE_TREE) lifts the same limits. An entity bomb raises it too,
wherever it is in the file. So does any piece of markup that fills the 10 MB buffer of
libxml2, the library under lxml. lxml feeds that buffer 32 KB at a time, and the engine
follows it: a piece just under 10 MB can still fill the buffer.
libxml2 checks its buffer once it has parsed the whole 32 KB it was fed. So the engine reads the elements of that 32 KB first, as lxml does: an error in one of them comes before the buffer's limit.
Some limits stop nothing at once. libxml2 notes them, drops what passed the limit, and reads on. These are a name over 50,000 bytes in an attribute, an entity reference or a processing instruction, a CDATA section over 10 MB, an entity's text or an attribute's default over 10 MB, and entities nested too deep in an attribute value. lxml raises the first of them later: at its next check of the 32 KB it has read, at the end of the file, or in place of a later limit. The engine raises it at the same point.
libxml2 keeps an attribute value over 10 MB as it is, unless it must change it, for example to expand a reference. lxml refuses it at the first event of its element that the reader asks for, and so does the engine, with the same line.
lxml also looks ahead for these limits. From time to time, it checks the whole 32 KB it
has read for a limit. So when a limit comes soon after another error, lxml may raise the
limit first. The engine looks ahead at the same points, so it raises the same error.
There is one exception. With strict parsing (--strict-parsing), lxml skips the check
at the root of a DDI-L file, so it may raise the other error first. The engine always
checks as lxml does by default.
The lines it gives are lxml's too. lxml keeps a line in 16 bits, so past line 65,535 it takes the line from a nearby node, and the engine does the same. It also hands over text in parts, as libxml2 does at the end of each 32 KB, so a line found in a text is the same. Past line 65,535, these rare cases differ:
- the line in the error for an empty top-level element, such as an empty
TopLevelReference; - the line of an item that holds a nested
Fragment, when no text comes before the item's first child. lxml can take it from a node after theFragment; - the line in the error for an attribute value over 10 MB, when lxml takes it from a
node the engine does not keep. That is an empty top-level DDI-L element, an empty
DDI-CDI object, a DDI-CDI container (
WrapperorDDICDIModels), or a DDI-L root that starts past that line.
Six other rare cases differ:
- an attribute name over 50,000 bytes. libxml2 drops the attribute and mends the rest of the start tag, which may change what follows;
- a comment over 10 MB in an element. lxml may read the end of it as text, and then name the limit of a text;
- a processing instruction of nearly 10 MB or more at the very start of the file. libxml2 may give it up just short of the limit of its buffer, and lxml then reads the file as empty;
- a namespace declaration that the DTD gives a type other than CDATA, when its value refers to an entity with spaces in its text. libxml2 drops or merges those spaces, and the engine does not;
- a limit met in the text of an entity that an element's text refers to. That is an
entity bomb, entities nested too deep, or an entity that refers to itself. Both
engines raise an
XMLLimitErrorfor the same limit. But lxml gives a line in the entity's text, and the engine gives the line of the reference; - a well-formed file in which libxml2 notes 100 errors and reads on, such as an
xml:idused twice. lxml then stops with anXMLLimitError, and the engine reads the file.
Compare it with lxml¶
ddigraph.conform reads each file with both engines and lists every way they differ:
python -m ddigraph.conform run --corpus tests/fixtures --engine rust
python -m ddigraph.conform run --corpus my-files --engine rust --generated 300
It reads each file under each --resolve mode, at one node per chunk and at the
default chunk size. lxml reads it as it does by default. The two engines must give the
same graph, the same chunks in the same order, and the same report. Where lxml raises an
error, the engine must raise one of the same type, with the same message.
--generated N adds N generated documents.
The command prints a line per file, then a total. It also lists two kinds of files it sets aside:
- Not checked: a file of a flavor that the installed
ddigraph-coredoes not read, as an older build may not. - Skipped: a file whose DDI flavor cannot be found, which neither engine reads.
Also a file that is not well-formed XML: lxml reads it only by recovering, and the
engine refuses it. A file that the engine reads is compared, even if a strict lxml
read stops on it, as on an
xml:idused twice.
It exits with 1 when it finds any difference, with 2 when it cannot start (for example without ddigraph-core), and with 0 otherwise.
Validating in the same pass (experimental)¶
The Rust engine can also check a file against its XSD while it reads it. It turns each content model of the XSD into an automaton, and checks each element as it comes. It keeps one state for each open element, and the IDs it has seen, since an ID must be unique. So the state of the check grows with the depth of the file, not its size. The engine still holds the whole file in memory while it reads it, as a parse does.
This is experimental. lxml's XMLSchema stays the default and the
reference. Whenever the engine cannot decide, lxml decides.
Ask for it¶
ddigraph validate survey.xml --engine rust
In Python, pass engine="rust":
from ddigraph.validation import validate
result = validate("survey.xml", engine="rust")
print(result.valid, result.engine, result.unsupported)
result.engine says which engine decided. When the Rust engine could
not, result.unsupported says why, and lxml checked the file. The Rust
engine stops at the first issue, so result.issues holds that one only.
DDIGRAPH_ENGINE does not choose the engine here: only --engine and
engine= do.
To read a file's graph and check it in one pass, call the engine itself
with validate=True. A third item, the verdict, then follows the chunks
and the report. The chunks are the ones the engine gives without it:
import ddigraph_core
chunks, report, verdict = ddigraph_core.parse(
"survey.xml",
"cdi",
dataset_id="survey",
dataset_name=None,
chunk_size=1000,
resolve="exact",
huge_tree=False,
memory_limit=256 * 2**20,
validate=True,
)
status, line, message = verdict # "valid", "invalid" or "unsupported"
ddigraph_core.validate(path, flavor) gives the same verdict without the
graph.
What it checks¶
It checks DDI-Codebook 2.6, DDI-Lifecycle 3.1 to 3.3 and DDI-CDI 1.0. It reads the content models that the metamodel records, never the XSDs. The XSDs of DDI-L 3.1 and 3.2 that ddigraph ships are those of 3.3, but for the version in their namespaces. So the engine reads them with the tables of 3.3. It checks:
- the order and the number of child elements: sequences, choices, substitution groups and wildcards. A bounded number is a counter;
- empty, element-only, mixed and simple content;
- required, optional and prohibited attributes, fixed values and attribute wildcards;
- the built-in types, and the facets of simple types: enumerations, patterns, lengths, bounds and digits, lists and unions;
- that each ID is used once.
Like libxml2, it checks a value of a name type, such as ID or
NMTOKEN, with the letters of the fourth edition of XML 1.0. The
patterns \i and \c use them too. The names of the file itself follow
the fifth edition, so an element's name may hold lj, but an ID may not.
What it leaves to lxml¶
It answers "unsupported", with a reason, for:
- an element of a schema the metamodel does not read, such as XHTML in a text element;
- an element or a type the metamodel does not keep, because another namespace declares its name first, such as the record layouts of the DDI-L ncube schemas;
xsi:typeandxsi:nil, which it does not follow;xml:id, since libxml2 counts those IDs as it parses;- a file whose DTD declares elements, attributes or notations, since libxml2 checks those declarations and counts the IDs they declare;
- a
base64Binaryvalue, a pattern with Unicode classes, and a bound on a date; - DDI-Lifecycle 4.0 and DDI-CDI 1.1, for which it holds no tables;
- a file it cannot read, such as one in an encoding it does not decode.
It goes on past such a part. An error it finds later still counts, and the verdict is then "invalid".
How well it agrees¶
The gate (tests/test_validate_rust_gate.py) compares its verdicts with
lxml's on the fixtures and on 5,000 generated documents of the three
flavors. A DDI-L document is 3.1, 3.2 or 3.3. Half of the documents have
one change that the XSD forbids: a child dropped, repeated or swapped, an
unknown element, an attribute dropped or undeclared, a value outside its
enumeration, or a value not of its type.
| Measure | Result |
|---|---|
| Documents | 5,009 (2,203 valid and 2,806 invalid for lxml) |
| Answered | 4,481, each with lxml's verdict |
| Unsupported | 528, all for XHTML content |
| First error on lxml's line | 2,798 of 2,799 invalid documents |
| Graph of each valid document | the same as lxml's, with or without validate |
Where the first error's line differs, lxml's first error is in a part the engine does not check, such as XHTML.
Past line 65,535, the first error's line can differ too. lxml keeps a line in 16 bits, so past that line it takes the line from a nearby node: the element's first child, or else a sibling. The automaton gives the line of the element's start tag, unlike a parse, which gives lxml's line.
Speed¶
These times are for the bench's files (ddigraph.bench), all of them
valid, the best of three runs on 4 CPUs. lxml compiles the XSD once, and
that time is not counted.
| Flavor | Elements | Size | lxml parse and XMLSchema |
Rust check | Rust read | Rust read and check | lxml read |
|---|---|---|---|---|---|---|---|
| Codebook | 50,000 | 3.3 MB | 0.08 s | 0.13 s | 0.45 s | 0.54 s | 4.21 s |
| Codebook | 400,000 | 26.9 MB | 0.95 s | 1.21 s | 4.21 s | 5.03 s | 37.12 s |
| DDI-L | 50,000 | 13.0 MB | 0.30 s | 0.38 s | 0.55 s | 0.78 s | 4.09 s |
| DDI-L | 400,000 | 104.6 MB | 2.37 s | 3.17 s | 4.83 s | 6.97 s | 38.17 s |
| DDI-CDI | 50,000 | 27.5 MB | 0.24 s | 0.57 s | 0.65 s | 0.94 s | 5.65 s |
| DDI-CDI | 400,000 | 220.9 MB | 1.90 s | 4.81 s | 5.84 s | 8.59 s | 50.50 s |
"Rust check" is ddigraph_core.validate, and "Rust read" is the engine's
read without validate. "lxml read" is ddigraph.ir.parse with the lxml
engine. Checking adds 20 to 47% to the Rust engine's read. lxml compiles
the XSD of DDI-CDI in 0.6 s, and those of Codebook and DDI-L in under
0.1 s.
lxml checks a file faster than the Rust engine can: libxml2's validator is fast, and it builds no graph. The engine wins when you need both the graph and the verdict. One pass of the Rust engine gives both, where lxml must read the file for the graph and check it again. For both, the Rust engine is 5.6 to 7.9 times as fast.
For contributors¶
The engine's code is in rust/: the engine in crates/ddigraph-core, and its Python
module, ddigraph_core, in crates/ddigraph-core-py. Check it from that folder:
cargo fmt --all --check
cargo clippy --all-targets -- -D warnings
cargo test
scripts/ci_local.sh runs these checks when cargo is installed. CI builds the wheel
and runs the comparison above on every pull request.
In a clone, uv sync installs the stand-in, so you need no Rust to work on ddigraph.
To run the tests with the engine, build it over the stand-in. Then run with --no-sync,
since uv run would put the stand-in back:
uv pip install --reinstall-package ddigraph-core ./rust
uv run --no-sync pytest
A release publishes both packages at the same version: the wheels, the engine's source, and the stand-in.