Module 11: Reload, history and differences¶
Learning objectives
By the end of this module, you can:
- O1. Add a DDI file to the store as a new generation with
ddigraph store add, and readstore listand the store's folder. - O2. Read a generation's manifest with
store show, and find the generation that was HEAD at a given time with--as-of. - O3. Compare two generations with
store diff, and explain when a node counts as added, removed or changed. - O4. Follow a dataset's changes with
store changes --since N, from the command line and with theStoreclass in Python.
Prerequisites: Module 10
Time: 40 min self-paced / 55 min instructor-led.
Needs: No server. Section 8 is optional and uses the Neo4j server from Module 7.
New in this module: ddigraph store add, store list, store show, store diff, store changes, --as-of, generation, HEAD, ddigraph.store.Store, ddigraph load --store
1. Files change¶
Metadata is not written once. A new wave of a survey relabels a variable, adds an answer, drops a question. You get a new version of the DDI file, and you want to know three things:
- What changed since the last version?
- What did the graph look like on a given day?
- Can a database get only the changes, not the whole file again?
A plain ddigraph load cannot answer these. It merges the file into
Neo4j, and keeps no record of the version before.
The store can. It keeps each dataset's graph on disk, in a folder, as a series of numbered generations. Each time you add a file, its graph becomes the dataset's next generation. A generation never changes once it is written. The dataset's HEAD names its current generation, the last one written. The store needs no database and no extra.
2. Add a file to the store¶
This module follows the sample Labour Force Survey in its Codebook file,
tests/fixtures/lfs_codebook.xml. Work on a copy, lfs.xml, so you can
edit it later. ddigraph store add reads the file and writes its graph as
a generation. The dataset ID is the file name without its extension, as
for load:
cp tests/fixtures/lfs_codebook.xml lfs.xml
ddigraph store add lfs.xml
ddigraph store list
find ddigraph-store | sort
Expected output:
Generation 1 of dataset 'lfs': 80 nodes, 48 relationships
lfs: HEAD 1, 1 generations
ddigraph-store
ddigraph-store/lfs
ddigraph-store/lfs/000001
ddigraph-store/lfs/000001/MANIFEST.json
ddigraph-store/lfs/000001/nodes.seg
ddigraph-store/lfs/000001/relationships.seg
ddigraph-store/lfs/HEAD
ddigraph-store/lfs/LOCK
The store is a plain folder, ddigraph-store by default. --store DIR
picks another one. It holds a folder per dataset, and in it a folder per
generation, 000001 here:
MANIFEST.jsondescribes the generation;nodes.segandrelationships.seghold the graph, sorted by key;HEADholds the number of the current generation;LOCKlets only one process write the dataset at a time.
3. Look at a generation¶
ddigraph store show prints the manifest of the dataset's HEAD:
cp tests/fixtures/lfs_codebook.xml lfs.xml
ddigraph store add lfs.xml > /dev/null
ddigraph store show lfs
Expected output:
{
"number": 1,
"created": "...",
"key_scheme": "b3-128/1",
"dataset_id": "lfs",
"dataset_key": "fc01e3add92c1c11565250caadaf0fb8",
"nodes": {
"rows": 80,
"sha256": "...",
"blocks": [
{
"first": "0dd72ce252f92a36fb4439b4e508bf78",
"offset": 0
}
]
},
"relationships": {
"rows": 48,
"sha256": "...",
"blocks": [
{
"first": [
"195bc8feaa9f94e650e87d3cf243beae",
"ASKED_AS",
"9b90d3520b93a9990a8649e5b6255393",
null
],
"offset": 0
}
]
},
"model_hash": "...",
"root": "..."
}
The ... marks values that change on each run. The fields you need most:
numberis the generation's number, from 1.createdis when the store wrote it, in UTC. This is transaction time: when the store learned about the graph, not the date the metadata describes.dataset_keyis the key of the dataset's Dataset node.rowscounts the nodes and the relationships. Thesha256and theblockslet the store check each file and jump to a key.rootsums up the whole generation in one hash. Two generations with the same root hold the same graph.
--generation N shows another generation. --json prints the graph
itself, in the shape of ddigraph export --format json.
4. Change the file, and add it again¶
Now play the part of the survey team. They send a new version of the file, with two changes that survey teams often make:
A new region. The country made a new region, Central, from parts of the North and the South. So the categories of REGION go from five to six:
| Code | Before | After |
|---|---|---|
| 1 | Capital region | Capital region |
| 2 | North | North |
| 3 | South | South |
| 4 | East | East |
| 5 | West | West |
| 6 | Central |
A reworded question. Some people left their overtime out of their usual hours. So the HOURS question now says that overtime counts:
| Version | Text of the HOURS question |
|---|---|
| Before | How many hours a week do you usually work in your main job? |
| After | How many hours a week do you usually work in your main job, including overtime? |
This small Python step makes both changes, on the lines that are already
there, so no other element moves. Then the file goes into the store again,
and store diff compares the two generations:
cp tests/fixtures/lfs_codebook.xml lfs.xml
ddigraph store add lfs.xml
python - <<'EOF'
from pathlib import Path
path = Path("lfs.xml")
text = path.read_text(encoding="utf-8")
text = text.replace("<labl>West</labl></catgry>", "<labl>West</labl></catgry><catgry><catValu>6</catValu><labl>Central</labl></catgry>")
text = text.replace("usually work in your main job?", "usually work in your main job, including overtime?")
path.write_text(text, encoding="utf-8")
EOF
ddigraph store add lfs.xml
ddigraph store list
ddigraph store diff lfs 1 2
Expected output:
Generation 1 of dataset 'lfs': 80 nodes, 48 relationships
Generation 2 of dataset 'lfs': 81 nodes, 49 relationships
lfs: HEAD 2, 2 generations
Nodes: 1 added, 0 removed, 2 changed
Relationships: 1 added, 0 removed
The new region is one added node, a Category. Its USES_CATEGORY edge
from REGION is one added relationship. The new wording changed two nodes,
as the next section shows. Generation 1 is still there, unchanged, and
HEAD is now 2.
5. What counts as a change¶
store diff --json prints the rows themselves. This step reads them and
prints, for each row, what kind of change it is, the node's type and its
label:
cp tests/fixtures/lfs_codebook.xml lfs.xml
ddigraph store add lfs.xml > /dev/null
python - <<'EOF'
from pathlib import Path
path = Path("lfs.xml")
text = path.read_text(encoding="utf-8")
text = text.replace("<labl>West</labl></catgry>", "<labl>West</labl></catgry><catgry><catValu>6</catValu><labl>Central</labl></catgry>")
text = text.replace("usually work in your main job?", "usually work in your main job, including overtime?")
path.write_text(text, encoding="utf-8")
EOF
ddigraph store add lfs.xml > /dev/null
ddigraph store diff lfs 1 2 --json | python -c "
import json, sys
delta = json.load(sys.stdin)
for kind, rows in delta.items():
for row in rows:
what = row.get('label') or row.get('type')
label = row['properties'].get('label') or {}
print(kind, what, label.get('value', ''))
"
Expected output:
added Category Central
changed Variable Usual weekly hours in the main job
changed Question How many hours a week do you usually work in your main job, including overtime?
added_relationships USES_CATEGORY
The Question changed: its text is new. The Variable HOURS changed too,
though its label did not. In a Codebook, a variable keeps a copy of its
question's text, in its question_text property, so that copy changed
as well.
The rules behind those words:
- A node is the same node in both generations when it has the same key (Module 4). A key the newer generation lacks is removed; a key only the newer one has is added.
- A node is changed when its properties, its type label, its stub reason or its provenance differ. Provenance is where the node was read: the file's path and the line. So a node that only moved in the file counts as changed, and so does every node of a file read from another path (Exercise 3). That is why the Python step above kept every element on its line.
- A relationship is known by its start, its type, its end and its ordinal. It is only ever added or removed. When its resolution or properties change, the old one is removed and the new one added.
6. Follow the changes¶
store diff compares any two generations. store changes is made for a
program that follows a dataset. --since N names the generation the
program holds, and --to M the one it wants, HEAD by default. Without
--json, it prints the counts. With --json, it prints one JSON object per
line, then a last line with the generation it reached:
cp tests/fixtures/lfs_codebook.xml lfs.xml
ddigraph store add lfs.xml > /dev/null
python - <<'EOF'
from pathlib import Path
path = Path("lfs.xml")
text = path.read_text(encoding="utf-8")
text = text.replace("<labl>West</labl></catgry>", "<labl>West</labl></catgry><catgry><catValu>6</catValu><labl>Central</labl></catgry>")
text = text.replace("usually work in your main job?", "usually work in your main job, including overtime?")
path.write_text(text, encoding="utf-8")
EOF
ddigraph store add lfs.xml > /dev/null
ddigraph store changes lfs --since 1
ddigraph store changes lfs --since 1 --json
Expected output:
Nodes: 1 added, 0 removed, 2 changed
Relationships: 1 added, 0 removed
{"change":"added","row":{"key":"7f7871d6b3e7886f0c5d070a9109c442","label":"Category",...}}
{"change":"changed","row":{"key":"8108b790af0484c90f7174ca08253e3c","label":"Variable",...}}
{"change":"changed","row":{"key":"84475a04f0a2e39eefc99684d883f9fd","label":"Question",...}}
{"change":"added_relationship","row":{"type":"USES_CATEGORY","start":"2df0c080b51783641d565baffce1b668",...}}
{"generation":2,"root":"..."}
The rows come in the order a database applies them: removed
relationships, removed nodes, added and changed nodes, then added
relationships. So a program applies the lines in order, then keeps the
generation of the last line as its next --since. --since 0 gives the
whole generation, as if the program held nothing.
7. Time travel with --as-of¶
store show --as-of TIME shows the generation that was HEAD at that time.
A time with no offset is UTC. This step saves the created time of
generation 1, adds generation 2, then asks which generation was HEAD at
the saved time, and which one is HEAD now:
cp tests/fixtures/lfs_codebook.xml lfs.xml
ddigraph store add lfs.xml > /dev/null
first=$(ddigraph store show lfs | python -c "import json, sys; print(json.load(sys.stdin)['created'])")
python - <<'EOF'
from pathlib import Path
path = Path("lfs.xml")
text = path.read_text(encoding="utf-8")
text = text.replace("<labl>West</labl></catgry>", "<labl>West</labl></catgry><catgry><catValu>6</catValu><labl>Central</labl></catgry>")
text = text.replace("usually work in your main job?", "usually work in your main job, including overtime?")
path.write_text(text, encoding="utf-8")
EOF
ddigraph store add lfs.xml > /dev/null
ddigraph store show lfs --as-of "$first" | python -c "import json, sys; print('then:', json.load(sys.stdin)['number'])"
ddigraph store show lfs | python -c "import json, sys; print('now:', json.load(sys.stdin)['number'])"
ddigraph store show lfs --as-of 2000-01-01T00:00:00 2>&1 || echo "exit code $?"
Expected output:
then: 1
now: 2
The store has no generation of dataset 'lfs' created at or before 2000-01-01T00:00:00
exit code 1
A time before the first generation is refused, with exit code 1.
--as-of works with --json too, to read the whole graph as it was then
(Exercise 2). The store page covers gc, which
removes old generations, and stubs.
8. Optional: reload Neo4j with only the changes¶
A load through the store writes the file as the next generation, then
sends Neo4j only the delta since the generation Neo4j holds. Neo4j keeps a
small marker node per dataset that names that generation. Add --store
after the file. This step needs the Neo4j server and the
DDIGRAPH_NEO4J_* variables you set in Module 2. It uses the dataset
m11-lfs, and removes the dataset and its marker at the end:
cp tests/fixtures/lfs_codebook.xml lfs.xml
ddigraph load lfs.xml --dataset-id m11-lfs --store | tail -n 2
python - <<'EOF'
from pathlib import Path
path = Path("lfs.xml")
text = path.read_text(encoding="utf-8")
text = text.replace("<labl>West</labl></catgry>", "<labl>West</labl></catgry><catgry><catValu>6</catValu><labl>Central</labl></catgry>")
text = text.replace("usually work in your main job?", "usually work in your main job, including overtime?")
path.write_text(text, encoding="utf-8")
EOF
ddigraph load lfs.xml --dataset-id m11-lfs --store | tail -n 2
python - <<'EOF'
import os
from neo4j import GraphDatabase
from ddigraph.lens.neo4j import Neo4jLens
auth = (os.environ["DDIGRAPH_NEO4J_USER"], os.environ["DDIGRAPH_NEO4J_PASSWORD"])
with GraphDatabase.driver(os.environ["DDIGRAPH_NEO4J_URI"], auth=auth) as driver:
print("purged", Neo4jLens(driver).purge("m11-lfs"), "nodes")
driver.execute_query("MATCH (marker:DDILoad {dataset_id: $id}) DELETE marker", id="m11-lfs")
EOF
Expected output:
Ingestion complete: dataset_id=m11-lfs, nodes_written=80, relationships_written=48, ...
Store: generation=1, delta_from=None, nodes_removed=0, relationships_removed=0
Ingestion complete: dataset_id=m11-lfs, nodes_written=3, relationships_written=1, ...
Store: generation=2, delta_from=1, nodes_removed=0, relationships_removed=0
purged 81 nodes
The first load wrote the whole generation: delta_from=None. The second
wrote only the three nodes and the one relationship that changed, as the
delta from generation 1. On a file of 100,000 nodes where ten change, that
is the difference between minutes and a second. The
store page explains how a crash in the middle
still ends in the right graph, and how ddigraph repair puts back what
someone changed by hand.
Exercises¶
Scenario
You run the metadata pipeline of a statistical agency. Each quarter, the Labour Force Survey team sends new versions of its DDI files. Your users ask what changed, and the website wants only the changes.
Exercise 1 (O1). Make a store in a folder called agency-store (use
--store). Add the survey's DDI-L file, tests/fixtures/lfs_lifecycle.xml,
as the dataset lfs-lifecycle, and its DDI-CDI file,
tests/fixtures/lfs_cdi.xml, as the dataset lfs-cdi. Then list the
store.
Expected output:
Generation 1 of dataset 'lfs-lifecycle': 87 nodes, 108 relationships
Generation 1 of dataset 'lfs-cdi': 91 nodes, 92 relationships
lfs-cdi: HEAD 1, 1 generations
lfs-lifecycle: HEAD 1, 1 generations
Answer
ddigraph store add tests/fixtures/lfs_lifecycle.xml --dataset-id lfs-lifecycle --store agency-store
ddigraph store add tests/fixtures/lfs_cdi.xml --dataset-id lfs-cdi --store agency-store
ddigraph store list --store agency-store
Generation 1 of dataset 'lfs-lifecycle': 87 nodes, 108 relationships
Generation 1 of dataset 'lfs-cdi': 91 nodes, 92 relationships
lfs-cdi: HEAD 1, 1 generations
lfs-lifecycle: HEAD 1, 1 generations
Each dataset has its own folder and its own HEAD, so one store holds
many files of any flavor, here the same survey in two of them.
store list sorts the datasets by ID.
Exercise 2 (O2). Make the two generations of lfs as in section 4,
saving the created time of generation 1. Then use store show --as-of
with --json to print the text of the HOURS question (DDI ID Q-HOURS)
as it was at that time, and store show --json to print it now.
Expected output:
then: How many hours a week do you usually work in your main job?
now: How many hours a week do you usually work in your main job, including overtime?
Answer
cp tests/fixtures/lfs_codebook.xml lfs.xml
ddigraph store add lfs.xml > /dev/null
first=$(ddigraph store show lfs | python -c "import json, sys; print(json.load(sys.stdin)['created'])")
python - <<'EOF'
from pathlib import Path
path = Path("lfs.xml")
text = path.read_text(encoding="utf-8")
text = text.replace("<labl>West</labl></catgry>", "<labl>West</labl></catgry><catgry><catValu>6</catValu><labl>Central</labl></catgry>")
text = text.replace("usually work in your main job?", "usually work in your main job, including overtime?")
path.write_text(text, encoding="utf-8")
EOF
ddigraph store add lfs.xml > /dev/null
cat > label.py <<'EOF'
import json
import sys
graph = json.load(sys.stdin)
for node in graph["nodes"]:
if node["properties"].get("ddi_id") == "Q-HOURS":
print(sys.argv[1], node["properties"]["label"]["value"])
EOF
ddigraph store show lfs --as-of "$first" --json | python label.py then:
ddigraph store show lfs --json | python label.py now:
then: How many hours a week do you usually work in your main job?
now: How many hours a week do you usually work in your main job, including overtime?
Generation 1 never changes, so --as-of reads the graph exactly as it
was when it was written. In the JSON, a text property is an object with
its value and its lang.
Exercise 3 (O3). A colleague renames the file before adding it again,
with no change to its content. Add lfs.xml, copy it to renamed.xml,
add the copy to the same dataset with --dataset-id lfs, and print the
diff. Explain the result.
Expected output:
Generation 2 of dataset 'lfs': 80 nodes, 48 relationships
Nodes: 0 added, 0 removed, 80 changed
Relationships: 0 added, 0 removed
Answer
cp tests/fixtures/lfs_codebook.xml lfs.xml
ddigraph store add lfs.xml > /dev/null
cp lfs.xml renamed.xml
ddigraph store add renamed.xml --dataset-id lfs
ddigraph store diff lfs 1 2
Generation 2 of dataset 'lfs': 80 nodes, 48 relationships
Nodes: 0 added, 0 removed, 80 changed
Relationships: 0 added, 0 removed
Every node is changed, though no value is. Each node's provenance holds the file's path, and the path changed. So keep a dataset's file at one path, or expect a diff that lists every node.
Exercise 4 (O4). Make the two generations of lfs as in section 4.
Then write a Python script that uses ddigraph.store.Store to print the
dataset's HEAD, the number of nodes in each generation, the label of each
added node and the type of each changed node from generation 1 to 2, and
each row of changes(since=1), with the class name of the row.
Expected output:
HEAD 2
generation 1: 80 nodes
generation 2: 81 nodes
added: ['Central']
changed: ['Variable', 'Question']
added Node
changed Node
changed Node
added_relationship Relationship
Answer
import shutil
from pathlib import Path
from ddigraph import ir
from ddigraph.store import Store
shutil.copyfile("tests/fixtures/lfs_codebook.xml", "lfs.xml")
store = Store("ddigraph-store")
store.write("lfs", ir.parse("lfs.xml", dataset_id="lfs"), memory_limit=64 * 2**20)
path = Path("lfs.xml")
text = path.read_text(encoding="utf-8")
text = text.replace(
"<labl>West</labl></catgry>",
"<labl>West</labl></catgry><catgry><catValu>6</catValu><labl>Central</labl></catgry>",
)
text = text.replace(
"usually work in your main job?", "usually work in your main job, including overtime?"
)
path.write_text(text, encoding="utf-8")
store.write("lfs", ir.parse("lfs.xml", dataset_id="lfs"), memory_limit=64 * 2**20)
print("HEAD", store.head("lfs"))
for generation in store.generations("lfs"):
print(f"generation {generation.number}: {generation.nodes.rows} nodes")
delta = store.diff("lfs", 1, 2)
print("added:", [node.properties["label"].value for node in delta.added])
print("changed:", [node.label for node in delta.changed])
for change, row in store.changes("lfs", since=1):
print(change, type(row).__name__)
HEAD 2
generation 1: 80 nodes
generation 2: 81 nodes
added: ['Central']
changed: ['Variable', 'Question']
added Node
changed Node
changed Node
added_relationship Relationship
Store.write takes any graph stream, here from ir.parse, and a
memory limit for its sort. diff gives the whole delta at once;
changes streams it as (change, row) pairs, each row an IR Node or
Relationship, in the order a database applies them.
Quiz¶
Question 1 (O1): You add a new version of a file to the store. What happens to the generation before it?
A. It is replaced by the new one.
B. It stays on disk, unchanged; HEAD now names the new generation.
C. It is merged with the new one, as ddigraph load merges.
D. It is deleted once the new one is written.
Answer
B. A generation never changes once written, and old ones stay
until store gc removes them. C is tempting because it is what a
plain load does to Neo4j, but the store keeps each version whole.
Question 2 (O2): A manifest's created is 2026-03-02T09:15:00Z, but the survey describes 2025. What does created record?
A. The reference period of the survey.
B. The date in the DDI file's citation.
C. When the store wrote the generation, in UTC: the time the store learned about the graph.
D. The last time someone read the generation.
Answer
C. It is transaction time. A and B are tempting because they are dates about the metadata, but the store never reads them: DDI keeps those in its own versions and dates.
Question 3 (O2): You run store show lfs --as-of 2026-03-01T12:00:00. Generation 1 was created at 09:00 UTC that day and generation 2 at 15:00 UTC. Which do you get?
A. Generation 1, the newest one created at or before that time.
B. Generation 2, the nearest one in time.
C. An error, since no generation was created at exactly 12:00.
D. It depends on your computer's time zone.
Answer
A. --as-of gives the generation that was HEAD at that time. D
is tempting, but a time with no offset is always read as UTC,
whatever your computer's time zone.
Question 4 (O3): You add a blank line at the top of a DDI file and add it to the store again. What does store diff report?
A. No change, since no value changed.
B. Every node whose element starts below the new line is changed, because its line is part of its provenance.
C. Every node is removed and added again.
D. Only the Dataset node is changed.
Answer
B. The key does not change, so nothing is removed or added (C). But provenance holds the line, so the nodes that moved are changed. A is what you might expect, which is why section 4 edits the file without adding lines.
Question 5 (O3): A reference moves from the second place to the first in an ordered list. How does the diff show it?
A. As one changed relationship.
B. As a removed relationship and an added one, since the ordinal is part of its identity.
C. It does not show: order is not stored.
D. As a changed node at the start of the relationship.
Answer
B. A relationship is known by its start, type, end and ordinal, so a new ordinal makes a new relationship. A is tempting, but a relationship is never "changed", only removed and added.
Question 6 (O4): A program has applied the rows of store changes lfs --since 3 --json. Which --since should it pass next time?
A. 3 again, to be safe.
B. 4.
C. The generation of the last line of the output it applied.
D. 0, to get everything.
Answer
C. The last line names the generation the rows lead to, which may be more than one step past 3. B assumes one new generation per run, which is often wrong. D works but sends the whole graph every time.
Check yourself¶
- I can add a DDI file to the store as a new generation with
ddigraph store add, and readstore listand the store's folder. (O1) - I can read a generation's manifest with
store show, and find the generation that was HEAD at a given time with--as-of. (O2) - I can compare two generations with
store diff, and explain when a node counts as added, removed or changed. (O3) - I can follow a dataset's changes with
store changes --since N, from the command line and with theStoreclass in Python. (O4)