Skip to content

Module 13: Big, broken and untrusted files

Learning objectives

By the end of this module, you can:

  • O1. Read a broken file in recovering mode and in strict mode (recover=, --strict-parsing), and say what each mode costs you.
  • O2. Recognise an XMLLimitError, explain the safety limit behind it, and lift the limits with huge_tree (DDIGRAPH_XML_HUGE_TREE) only for a file you trust.
  • O3. Show that ddigraph refuses an entity bomb and never reads an external entity, whatever the settings.
  • O4. Choose the engine that reads a file with --engine auto|lxml|rust, and predict which one auto picks.
  • O5. Stream a large file in chunks with chunk_size and memory_limit, and say when the first chunk arrives.

Prerequisites: Module 12

Time: 50 min self-paced / 65 min instructor-led.

Needs: No server.

New in this module: recover=, --strict-parsing, XMLLimitError, huge_tree, DDIGRAPH_XML_HUGE_TREE, --engine, DDIGRAPH_ENGINE, chunk_size, memory_limit, --memory-limit


1. A broken file, read anyway

So far every file was well-formed. Real files are not always so tidy. A person edits one by hand and types & instead of &. A tool cuts a file short. Someone sends you a file built to cause harm.

This module makes each kind of trouble on purpose, in a few lines of Python, so you can see how ddigraph reacts. The broken files are copies of the sample Labour Force Survey, tests/fixtures/lfs_codebook.xml, with a fault added: none of them is a real file. Start with a copy that has one mistake. Someone edited the label of the variable EDUC by hand, to "Highest level of education & training", with a bare &. XML needs & there.

By default ddigraph recovers: libxml2, the XML parser under lxml, reads past the error and keeps going.

from pathlib import Path

from ddigraph import iter_graph
from ddigraph.ir.model import Text

# A copy of the survey's Codebook with one mistake: a bare & in a label
text = Path("tests/fixtures/lfs_codebook.xml").read_text(encoding="utf-8")
LABEL = "<labl>Highest level of education</labl>"
broken = text.replace(LABEL, "<labl>Highest level of education & training</labl>")
Path("broken.xml").write_text(broken, encoding="utf-8")

nodes = [node for chunk in iter_graph("broken.xml") for node in chunk.nodes]
print("Nodes:", len(nodes))
for node in nodes:
    if node.label == "Variable":
        label = node.properties["label"]
        print(node.properties["name"], repr(label.value if isinstance(label, Text) else label))

Expected output:

Nodes: 80
Text(value='SEX', lang=None) 'Sex of the person'
Text(value='AGE', lang=None) 'Age in completed years'
Text(value='AGEGRP', lang=None) 'Age group'
Text(value='REGION', lang=None) 'Region of residence'
Text(value='EDUC', lang=None) 'Highest level of education  training'
Text(value='ILOSTAT', lang=None) 'Labour force status (ILO)'
Text(value='HOURS', lang=None) 'Usual weekly hours in the main job'

The file has the same 80 nodes as the clean survey file. But look at EDUC: the parser dropped the &, and the label now reads Highest level of education training, with two spaces. Nothing failed. A warning, Recovered DDI XML parse error, went to the log, and that is all.

That is the cost of recovering. You get a graph, but parts of it may differ from what the author meant, and only the log says so.

2. Strict mode refuses the file

Strict mode is the other choice. The parser stops at the first syntax error, with its line and column. In Python, pass recover=False to iter_graph:

from pathlib import Path

from lxml import etree

from ddigraph import iter_graph

text = Path("tests/fixtures/lfs_codebook.xml").read_text(encoding="utf-8")
LABEL = "<labl>Highest level of education</labl>"
broken = text.replace(LABEL, "<labl>Highest level of education & training</labl>")
Path("broken.xml").write_text(broken, encoding="utf-8")

try:
    for chunk in iter_graph("broken.xml", recover=False):
        pass
except etree.XMLSyntaxError as error:
    print("Refused:", error.msg)

Expected output:

Refused: xmlParseEntityRef: no name, line 87, column 41

On the command line, load recovers unless you pass --strict-parsing (DDIGRAPH_STRICT_PARSING). A strict load reads the whole file once before it writes anything, so a refused file leaves the database as it was. A dry run needs no database, so you can try both here:

# The same broken copy, made with sed (\& is a literal & in sed)
sed 's|<labl>Highest level of education</labl>|<labl>Highest level of education \& training</labl>|' tests/fixtures/lfs_codebook.xml > broken.xml

# Recovering (the default): the load finishes, and the log names the error
ddigraph load broken.xml --dry-run 2> log.txt | tail -n 1
grep -o "Recovered DDI XML parse error.*" log.txt

# Strict: the load stops before it writes anything
ddigraph load broken.xml --dry-run --strict-parsing > /dev/null 2> error.txt \
  || echo "Refused: $(tail -n 1 error.txt)"

Expected output:

Ingestion complete: dataset_id=broken, nodes_written=80, relationships_written=48, stubs=0, references=41, resolved=41, unresolved=0, conflicts=0
Recovered DDI XML parse error column=41 dataset_id=broken line=87 parse_error="xmlParseEntityRef: no name"
Refused: .../broken.xml: not well-formed XML: xmlParseEntityRef: no name, line 87, column 41

The counts are those of the clean survey file: every reference resolved, and no conflicts. So only the log shows that something went wrong. With --strict-parsing, conflicts refuse a file too: Node identity explains them.

Which mode should you use? Recover when you explore a file and want to see what is in it. Use strict mode when a load feeds something people rely on, such as a catalogue. There, a quiet change to a label is worse than a load that stops.

3. Safety limits stop a tree that is too deep

libxml2 has safety limits. It stops at a text over 10 MB, at a tree more than 256 levels deep, and at a name over 50,000 characters. A small file can describe a huge tree, and these limits stop it before it uses up your memory. ddigraph turns such a stop into an XMLLimitError, a ValueError whose message says what to do.

You can build a file that is too deep in a few lines: 300 <notes> elements, each one inside the one before, after the label of HOURS. No real file nests notes like this. This copy is made to break the limit.

from pathlib import Path

from ddigraph import iter_graph
from ddigraph.utils.parsing import XMLLimitError

text = Path("tests/fixtures/lfs_codebook.xml").read_text(encoding="utf-8")
LABEL = "<labl>Usual weekly hours in the main job</labl>"
deep = "<notes>" * 300 + "</notes>" * 300
Path("deep.xml").write_text(text.replace(LABEL, LABEL + deep), encoding="utf-8")


def count(**options):
    """Return how many nodes ddigraph reads from deep.xml."""
    return sum(len(chunk.nodes) for chunk in iter_graph("deep.xml", **options))


try:
    count()
except XMLLimitError as error:
    print("XMLLimitError:", str(error).split(": ")[1])
    print("Hint names the setting:", "DDIGRAPH_XML_HUGE_TREE" in str(error))

print("With huge_tree:", count(huge_tree=True), "nodes")

Expected output:

XMLLimitError: the XML parser stopped at line 109
Hint names the setting: True
With huge_tree: 80 nodes

huge_tree=True lifts the limits: a tree may then be 2,048 levels deep, and a text about 1 GB. On the command line, set DDIGRAPH_XML_HUGE_TREE=true, or pass --tune xml_huge_tree=true to one load. Every command that reads DDI XML follows the setting:

python -c "
from pathlib import Path
text = Path('tests/fixtures/lfs_codebook.xml').read_text(encoding='utf-8')
label = '<labl>Usual weekly hours in the main job</labl>'
deep = '<notes>' * 300 + '</notes>' * 300
Path('deep.xml').write_text(text.replace(label, label + deep), encoding='utf-8')
"
ddigraph preview deep.xml > /dev/null 2>&1 || echo "Without the setting: refused"
DDIGRAPH_XML_HUGE_TREE=true ddigraph preview deep.xml | sed -n 2p

Expected output:

Without the setting: refused
Nodes: 80   Relationships: 48

Lift the limits only for a file you trust, and only where nobody else can send files to the process. On a server that takes uploads, keep the setting off. Very large XML files gives the full rule.

4. Too many errors count as a limit

libxml2 reports only the first 100 syntax errors of a file. Past them, a recovering parse could go over a safety limit without a word. So ddigraph treats a file with 100 or more syntax errors as past a limit too, even in recovering mode. This copy has the same note, with a bare &, 100 times after the label of HOURS. It is made to cross the limit:

from pathlib import Path

from ddigraph import iter_graph
from ddigraph.utils.parsing import XMLLimitError

# 100 notes, each with a bare & in its text: 100 syntax errors
text = Path("tests/fixtures/lfs_codebook.xml").read_text(encoding="utf-8")
LABEL = "<labl>Usual weekly hours in the main job</labl>"
notes = "<notes>Count paid & unpaid overtime.</notes>" * 100
Path("messy.xml").write_text(text.replace(LABEL, LABEL + notes), encoding="utf-8")

try:
    list(iter_graph("messy.xml"))
except XMLLimitError as error:
    print(str(error).split(". ")[0])

Expected output:

messy.xml: the XML parser found at least 100 syntax errors, the first at line 109: xmlParseEntityRef: no name

The fix is to correct the file. If you trust it, huge_tree=True reads it, and ddigraph logs a warning that parts of the file may be missing.

5. Entity bombs and external entities

An XML file can declare entities: short names that stand for longer text. That opens two classic attacks.

  • An entity bomb (also called "billion laughs") declares entities that repeat each other. Ten levels of ten copies give a billion copies, from a file of a few kilobytes.
  • An external entity names a file or a URL. A careless parser reads it and puts its text in the document, so a DDI file could leak a file from your disk.

Build a bomb on purpose: declare the entities in a copy of the survey file, and use the last one as the name of the variable HOURS:

from pathlib import Path

from ddigraph import iter_graph
from ddigraph.utils.parsing import XMLLimitError

# e1 is ten copies of e0, e2 ten copies of e1, ... e9 stands for 10**9 "ha"s
entities = ['<!ENTITY e0 "ha">']
for n in range(1, 10):
    ten_copies = f"&e{n - 1};" * 10
    entities.append(f'<!ENTITY e{n} "{ten_copies}">')
doctype = "<!DOCTYPE codeBook [" + "".join(entities) + "]>\n"

text = Path("tests/fixtures/lfs_codebook.xml").read_text(encoding="utf-8")
body = text.split("\n", 1)[1]  # the file without its XML declaration
bomb = doctype + body.replace('name="HOURS"', 'name="&e9;"')
Path("bomb.xml").write_text(bomb, encoding="utf-8")
print(f"bomb.xml: about {Path('bomb.xml').stat().st_size // 1000} KB")

for huge_tree in (False, True):
    try:
        list(iter_graph("bomb.xml", huge_tree=huge_tree))
    except XMLLimitError as error:
        print(f"huge_tree={huge_tree}:", str(error).split(". ")[-1])

Expected output:

bomb.xml: about 6 KB
huge_tree=False: The file's entities expand far beyond its own size, so it is not read.
huge_tree=True: The file's entities expand far beyond its own size, so it is not read.

huge_tree does not help here, on purpose. No trusted file needs a billion copies of anything.

Now an external entity, which points at a file on the disk:

from pathlib import Path

from ddigraph import iter_graph

doctype = '<!DOCTYPE codeBook [<!ENTITY secret SYSTEM "file:///etc/hostname">]>\n'
text = Path("tests/fixtures/lfs_codebook.xml").read_text(encoding="utf-8")
body = text.split("\n", 1)[1]  # the file without its XML declaration
LABEL = "<labl>Usual weekly hours in the main job</labl>"
leak = doctype + body.replace(LABEL, "<labl>&secret;</labl>")
Path("leak.xml").write_text(leak, encoding="utf-8")

for chunk in iter_graph("leak.xml"):
    for node in chunk.nodes:
        if node.properties.get("name") == "HOURS":
            print("Label of HOURS:", node.properties.get("label"))

Expected output:


The label is empty: ddigraph never opened the file. It reads no DTD, never fetches anything over the network, and leaves an entity in element text as it is. A file that declares an entity with markup in its text is refused with a ValueError, since it cannot be read without expanding it. The CLI reference lists these rules. For files from strangers, the sandbox adds a second wall around the parser.

6. Two engines read XML

ddigraph has two engines, two pieces of code that read a DDI XML file into the same graph:

  • lxml is Python code over libxml2. It is the reference.
  • rust is the compiled engine of the ddigraph-core package. It reads a file 5 to 7.5 times as fast, but holds the whole file in memory, and it reads well-formed XML only: it never recovers.

--engine (DDIGRAPH_ENGINE, or engine= in Python) picks one. lxml and rust force an engine. auto, the default, uses rust when two things hold:

  1. The compiled engine is installed. Some installs hold only a stand-in package, with no engine in it.
  2. Its memory peak fits the memory limit. The peak counts as the file's size times 64 for Codebook, 16 for DDI-L and 8 for DDI-CDI.

Otherwise auto uses lxml. It also falls back to lxml for a file the rust engine refuses, such as our broken copy, but not for a file past a safety limit. So auto always gives you lxml's graph:

from ddigraph import iter_graph


def graph(engine):
    """Return the key and label of each node that an engine reads."""
    chunks = iter_graph("tests/fixtures/lfs_codebook.xml", engine=engine)
    return [(node.key, node.label) for chunk in chunks for node in chunk.nodes]


print("auto gives the lxml graph:", graph("auto") == graph("lxml"))

# The rule auto follows: the largest file each flavor sends to rust
peak = {"codebook": 64, "lifecycle": 16, "cdi": 8}
for limit_mb in (256, 1024):
    sizes = ", ".join(f"{flavor} {limit_mb // factor} MB" for flavor, factor in peak.items())
    print(f"--memory-limit {limit_mb}: rust reads up to {sizes}")

Expected output:

auto gives the lxml graph: True
--memory-limit 256: rust reads up to codebook 4 MB, lifecycle 16 MB, cdi 32 MB
--memory-limit 1024: rust reads up to codebook 16 MB, lifecycle 64 MB, cdi 128 MB

Is the compiled engine installed on your machine? Ask for it by name. If it is there, it gives the same preview as lxml. If not, the command stops with a message that says how to build it. The last line depends on your install, so the output below shows ... there:

ddigraph preview tests/fixtures/lfs_codebook.xml --engine lxml > lxml.txt
if ddigraph preview tests/fixtures/lfs_codebook.xml --engine rust > rust.txt 2> error.txt; then
  cmp -s lxml.txt rust.txt && echo "rust engine: installed, same preview as lxml"
else
  echo "rust engine: not installed, $(grep -o 'pip install --force-reinstall ./rust' error.txt)"
fi

Expected output:

rust engine: ...

The Rust engine page has the rare cases where the two engines differ, and how to build the engine yourself.

7. Big files arrive in chunks

iter_graph never hands you the whole graph at once. It yields chunks: lists of at most chunk_size nodes, or chunk_size relationships. A load writes each chunk in one transaction. Your own code can handle each chunk and let it go, so its memory stays small.

A bigger file is easy to make from the survey. Some archives publish a harmonised file: one data file that holds the same variables for many quarters, each under its own name, such as SEX_1996Q1. Build the codebook of such a file. It holds the survey's 7 variables for each quarter from 1996 to 2025: 840 variables, each with its question, concept and full code list. Then stream it:

import re
from pathlib import Path

from ddigraph import iter_graph

# The survey's 7 variables, with their questions, concepts and code lists
text = Path("tests/fixtures/lfs_codebook.xml").read_text(encoding="utf-8")
start = text.index("<dataDscr>") + len("<dataDscr>")
variables = text[start : text.index("</dataDscr>")]

# A copy for each quarter: V1 becomes V1_1996Q1, SEX becomes SEX_1996Q1, and so on
quarters = [f"{year}Q{n}" for year in range(1996, 2026) for n in range(1, 5)]
copies = "".join(re.sub(r'(ID|name)="([^"]+)"', rf'\1="\2_{q}"', variables) for q in quarters)
head = (
    '<codeBook xmlns="ddi:codebook:2_6"><stdyDscr><citation><titlStmt>'
    "<titl>Labour Force Survey, harmonised file 1996 to 2025</titl>"
    "</titlStmt></citation></stdyDscr>"
    '<fileDscr ID="F1"><fileTxt><fileName>lfs_1996_2025.csv</fileName></fileTxt></fileDscr>'
)
# newline="\n" writes the same bytes on Windows, so the size is the same
Path("big.xml").write_text(
    f"{head}<dataDscr>{copies}</dataDscr></codeBook>", encoding="utf-8", newline="\n"
)
print(f"big.xml: {Path('big.xml').stat().st_size:,} bytes")

chunks = nodes = relationships = largest = 0
for chunk in iter_graph("big.xml", chunk_size=500, memory_limit=16 * 2**20):
    chunks += 1
    nodes += len(chunk.nodes)
    relationships += len(chunk.relationships)
    largest = max(largest, len(chunk.nodes), len(chunk.relationships))

print("Chunks:", chunks, "- largest:", largest, "items")
print("Nodes:", nodes, "- relationships:", relationships)

Expected output:

big.xml: 484,238 bytes
Chunks: 22 - largest: 500 items
Nodes: 6487 - relationships: 4922

Two settings shape the stream:

  • chunk_size (--chunk-size, default 200) caps each chunk. It changes the number of transactions, never the graph.
  • memory_limit (--memory-limit in MB, default 256, at least 16) caps the memory ddigraph uses to sort what it reads. Past it, the sort spills to temporary files.

One thing surprises people: the first chunk comes only after the whole file is read. ddigraph must see every element before it can settle each key and reference. So a big file pauses at the start, then streams fast.

The same on the command line, as a dry run:

python - <<'EOF'
import re
from pathlib import Path

text = Path("tests/fixtures/lfs_codebook.xml").read_text(encoding="utf-8")
start = text.index("<dataDscr>") + len("<dataDscr>")
variables = text[start : text.index("</dataDscr>")]
quarters = [f"{year}Q{n}" for year in range(1996, 2026) for n in range(1, 5)]
copies = "".join(re.sub(r'(ID|name)="([^"]+)"', rf'\1="\2_{q}"', variables) for q in quarters)
head = (
    '<codeBook xmlns="ddi:codebook:2_6"><stdyDscr><citation><titlStmt>'
    "<titl>Labour Force Survey, harmonised file 1996 to 2025</titl>"
    "</titlStmt></citation></stdyDscr>"
    '<fileDscr ID="F1"><fileTxt><fileName>lfs_1996_2025.csv</fileName></fileTxt></fileDscr>'
)
Path("big.xml").write_text(f"{head}<dataDscr>{copies}</dataDscr></codeBook>", encoding="utf-8")
EOF
ddigraph load big.xml --dry-run --chunk-size 500 --memory-limit 16 2> /dev/null | tail -n 1

Expected output:

Ingestion complete: dataset_id=big, nodes_written=6487, relationships_written=4922, stubs=0, references=4920, resolved=4920, unresolved=0, conflicts=0

Large files has the benchmarks and the temporary files, and Performance tuning the other settings.


Exercises

Scenario

Your team takes DDI files from three partners. One partner edits files by hand, one sends very large exports, and one you have never worked with. You set up the reading step so that each file is read safely, and so that nobody is surprised by what it does.

Exercise 1 (O1). The survey team edits its DDI-L file by hand. In a copy of tests/fixtures/lfs_lifecycle.xml, the HOURS question now starts How many paid & unpaid hours a week, with a bare &. Make that copy. Read it recovering and print the text of the HOURS question (DDI ID q-hours). Then read it strictly and print the error. Last, fix the copy by writing &amp;, and show that a strict read now gives the question text with its &.

Expected output:

Recovered: 'How many paid  unpaid hours a week do you usually work in your main job?'
Strict: xmlParseEntityRef: no name, line 161, column 75
Fixed: 'How many paid & unpaid hours a week do you usually work in your main job?'
Answer
from pathlib import Path

from lxml import etree

from ddigraph import iter_graph
from ddigraph.ir.model import Text


def question(path, **options):
    """Return the text of the HOURS question that ddigraph reads from a DDI-L file."""
    for chunk in iter_graph(path, **options):
        for node in chunk.nodes:
            if node.properties.get("ddi_id") == "q-hours":
                text = node.properties["question_text"]
                return text.value if isinstance(text, Text) else text


text = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
old = "How many hours a week"
Path("hand-edited.xml").write_text(
    text.replace(old, "How many paid & unpaid hours a week"), encoding="utf-8"
)
print("Recovered:", repr(question("hand-edited.xml")))
try:
    question("hand-edited.xml", recover=False)
except etree.XMLSyntaxError as error:
    print("Strict:", error.msg)

Path("fixed.xml").write_text(
    text.replace(old, "How many paid &amp; unpaid hours a week"), encoding="utf-8"
)
print("Fixed:", repr(question("fixed.xml", recover=False)))
Recovered: 'How many paid  unpaid hours a week do you usually work in your main job?'
Strict: xmlParseEntityRef: no name, line 161, column 75
Fixed: 'How many paid & unpaid hours a week do you usually work in your main job?'

The recovering read loses the & without stopping. The strict read names the line, so you can fix the file at its source, where the fix belongs.

Exercise 2 (O2). A partner's export tool wraps its content in many levels of elements. Play that file: make a copy of the survey's DDI-CDI file, tests/fixtures/lfs_cdi.xml, with 260 nested <extra> elements just after the start tag of its root, <Wrapper>. Read it with iter_graph, and print the type of the error. Then read it with huge_tree=True and print the number of nodes. Would you set DDIGRAPH_XML_HUGE_TREE=true on a web service that takes uploads?

Expected output:

Refused: XMLLimitError
With huge_tree: 91 nodes
Answer
from pathlib import Path

from ddigraph import iter_graph

text = Path("tests/fixtures/lfs_cdi.xml").read_text(encoding="utf-8")
root = '<Wrapper xmlns="http://ddialliance.org/Specification/DDI-CDI/1.0/XMLSchema/">'
deep = "<extra>" * 260 + "</extra>" * 260
Path("deep-cdi.xml").write_text(text.replace(root, root + deep), encoding="utf-8")

try:
    list(iter_graph("deep-cdi.xml"))
except ValueError as error:
    print("Refused:", type(error).__name__)
nodes = sum(len(chunk.nodes) for chunk in iter_graph("deep-cdi.xml", huge_tree=True))
print("With huge_tree:", nodes, "nodes")
Refused: XMLLimitError
With huge_tree: 91 nodes

No. On a service that takes uploads, the next deep file may come from an attacker. Lift the limit for one trusted file, in one command, with DDIGRAPH_XML_HUGE_TREE=true or --tune xml_huge_tree=true, and keep it off everywhere else.

Exercise 3 (O3). A new partner sends a DDI-L file. Check two attacks on a copy of tests/fixtures/lfs_lifecycle.xml. First, add an external entity that names file:///etc/passwd and use it as the text of the SEX question (DDI ID q-sex): print the question text ddigraph reads. Second, add an entity bomb, use it in the xml:lang attribute of that question's text, and show that huge_tree does not let it through.

Expected output:

Question text: None
Bomb refused, even with huge_tree: True
Answer
from pathlib import Path

from ddigraph import iter_graph
from ddigraph.utils.parsing import XMLLimitError

text = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
body = text.split("\n", 1)[1]  # the file without its XML declaration

leak = '<!DOCTYPE FragmentInstance [<!ENTITY secret SYSTEM "file:///etc/passwd">]>\n'
leak += body.replace("What is your sex?", "&secret;")
Path("leak.xml").write_text(leak, encoding="utf-8")
for chunk in iter_graph("leak.xml"):
    for node in chunk.nodes:
        if node.properties.get("ddi_id") == "q-sex":
            print("Question text:", node.properties.get("question_text"))

entities = ['<!ENTITY e0 "ha">']
for n in range(1, 10):
    ten_copies = f"&e{n - 1};" * 10
    entities.append(f'<!ENTITY e{n} "{ten_copies}">')
bomb = "<!DOCTYPE FragmentInstance [" + "".join(entities) + "]>\n"
bomb += body.replace('"en">What is your sex?', '"&e9;">What is your sex?')
Path("bomb.xml").write_text(bomb, encoding="utf-8")
try:
    list(iter_graph("bomb.xml", huge_tree=True))
except XMLLimitError:
    print("Bomb refused, even with huge_tree: True")
Question text: None
Bomb refused, even with huge_tree: True

The external entity is never read, so the question has no text at all. The bomb is refused at any setting, because no trusted file needs it.

Exercise 4 (O4, O5). A registry keeps every version of the survey's DDI-CDI metadata: one version for each quarter of the last ten years, 40 in all. It exports them in one file. Build that file from tests/fixtures/lfs_cdi.xml: copy everything inside the root element 40 times, and give the objects of copy number n the version n. Stream the file with a chunk size of 300, and print its size, the number of chunks and the number of nodes. Then work out which engine auto would pick for it, with the default memory limit and with --memory-limit 16, if the compiled engine is installed.

Expected output:

Size: 2.7 MB
Chunks: 25 - nodes: 3601
Default limit: rust
--memory-limit 16: lxml
Answer
from pathlib import Path

from ddigraph import iter_graph

text = Path("tests/fixtures/lfs_cdi.xml").read_text(encoding="utf-8")
start, end = text.index("<Organization>"), text.index("</Wrapper>")
version_1 = "<versionIdentifier>1</versionIdentifier>"
versions = "".join(
    text[start:end].replace(version_1, f"<versionIdentifier>{n}</versionIdentifier>")
    for n in range(1, 41)
)
# newline="\n" writes the same bytes on Windows, so the size is the same
Path("all-versions.xml").write_text(
    text[:start] + versions + text[end:], encoding="utf-8", newline="\n"
)

size = Path("all-versions.xml").stat().st_size
print(f"Size: {size / 2**20:.1f} MB")
chunks = nodes = 0
for chunk in iter_graph("all-versions.xml", chunk_size=300):
    chunks += 1
    nodes += len(chunk.nodes)
print("Chunks:", chunks, "- nodes:", nodes)

# A DDI-CDI file counts 8 times its size against the memory limit
for name, limit_mb in (("Default limit", 256), ("--memory-limit 16", 16)):
    print(f"{name}:", "rust" if size * 8 <= limit_mb * 2**20 else "lxml")
Size: 2.7 MB
Chunks: 25 - nodes: 3601
Default limit: rust
--memory-limit 16: lxml

Each version is a new object for ddigraph, since the version is part of its identity: 40 copies of 90 objects, and the Dataset node. The file counts as about 22 MB for the rust engine. That fits 256 MB easily, but not 16 MB, so auto would read it with lxml there. Either way, you get the same graph: only the speed and the memory change.


Quiz

Question 1 (O1): A recovering load of a hand-edited file finishes with no error. What do you know about its graph?

A. It is the graph the author meant: libxml2 fixed the errors.

B. It may differ from what the author meant where the errors were, and only the log says so.

C. It is empty past the first error.

D. It holds no node from a fragment that had an error.

Answer

B. Recovering reads past an error by guessing, as the dropped & in Highest level of education training showed. A is the tempting one: the load finishes, so it looks fixed, but libxml2 cannot know what the author meant. Read the Recovered DDI XML parse error warnings, or load with --strict-parsing.

Question 2 (O2): A file from your own survey team fails with an XMLLimitError about depth. What do you do?

A. Set DDIGRAPH_XML_HUGE_TREE=true in the server's environment, so it never happens again.

B. Load it with --engine rust, which has no limits.

C. You trust the file, so lift the limit for this one load with --tune xml_huge_tree=true.

D. Delete elements until the file is shallow enough.

Answer

C. The limit guards against hostile files, and this one is yours. A works, but it opens every later upload to a depth bomb. B is wrong: the rust engine keeps the same limits and raises the same XMLLimitError. D throws away real content.

Question 3 (O3): Why does huge_tree not let an entity bomb through?

A. Because the bomb is a syntax error.

B. Because no trusted file needs entities that expand to millions of times the file's size, so ddigraph refuses it at any setting.

C. Because huge_tree only applies to the rust engine.

D. It does: with huge_tree, the bomb is read slowly.

Answer

B. A bomb is well-formed XML, so A is wrong. Its danger is the expansion itself. huge_tree exists for big honest files, and an honest file never needs that expansion, so the limit on it stays.

Question 4 (O4): The compiled engine is installed. Which engine does auto pick for a 10 MB Codebook file with the default memory limit?

A. rust, because it is installed and faster.

B. lxml, because 10 MB times 64 is 640 MB, past the 256 MB limit.

C. rust, because Codebook files are small.

D. lxml, because auto always picks lxml for Codebook.

Answer

B. auto checks the engine's memory peak, the file's size times 64 for Codebook, against the limit. A is tempting: installed and faster are both true, but the peak does not fit. Raise the limit with --memory-limit 1024, and auto would pick rust.

Question 5 (O5): You stream a 2 GB file with chunk_size=500. When does your code get the first chunk?

A. As soon as ddigraph has read 500 elements.

B. After ddigraph has read the whole file.

C. After 500 MB.

D. Never: a 2 GB file goes past the memory limit.

Answer

B. ddigraph must see every element before it can settle each key and reference, so it reads the whole file first, sorting within the memory limit. A is the tempting picture of streaming, but it would give edges to nodes not yet known. D is wrong: past the limit, the sort uses temporary files.

Question 6 (O1, O4): You load a file with one bare & in it, with --engine rust. What happens?

A. The rust engine recovers, like lxml.

B. The load stops: the rust engine reads well-formed XML only.

C. The rust engine hands the file to lxml.

D. The & is kept as it is.

Answer

B. The rust engine never recovers, whatever recover says. C is what auto does, not rust: only auto falls back to lxml for a file the engine refuses.


Check yourself

  • I can read a broken file in recovering mode and in strict mode, and say what each mode costs me. (O1)
  • I can recognise an XMLLimitError, explain its limit, and lift the limits with huge_tree only for a file I trust. (O2)
  • I can show that ddigraph refuses an entity bomb and never reads an external entity. (O3)
  • I can choose an engine with --engine, and predict which one auto picks. (O4)
  • I can stream a large file in chunks with chunk_size and memory_limit, and say when the first chunk arrives. (O5)

Next: Module 14: Ground a language model in the graph