On this page
Diffs are derived never stored๏
๐ต Expert ยท Lesson 04
DERIVE A DIFF, THREE WAYS, AND WATCH THE ANSWER CHANGE. Version records are full objects; "what changed" is computed on demand and never written back. "A verdict is an answer, not a fact the system remembers."
A DERIVED DIFF CANNOT GO STALE, because it did not exist until you asked. That is the whole argument for storing full objects and computing comparisons - a stored diff is a second copy of the truth that can disagree with the first.
THREE GRAINS SHIP, AND THEY ARE GENUINELY DIFFERENT QUESTIONS source the TEXT - a rename is enormous structural the SHAPE - a rename is invisible parts the MEMBERS - which pieces moved This lesson runs the SAME pair through all three and prints what each one concluded, because the point is not that three names exist - it is that they disagree, on purpose.
TWO DEFAULTS AT TWO LAYERS, AND THIS TRIPS PEOPLE DiffEngine.diff_materials(...) defaults to "source" the codegen room's research_diff pins "structural" for a spell pair (expert 30) The engine's default is text; the room overrides it with its reasoning layer. Same family, different default, because the room knows it is answering an agent and the engine does not.
THE REGISTRY IS OPEN. register_strategy is public surface, so "what changed" is extensible by you rather than fixed by the library - the engine is open/closed, and "adding a grain means registering a strategy, never editing this class".
AND THE ENGINE NEVER REACHES INTO THE CRYSTALLIZER. It takes an injected material resolver, which is why this lesson can run the whole diff family over material it holds in its hand, with no recorded world at all. diff() resolves through custody; diff_materials() is the door for material you already have - unbound codegen output, for instance.
Before you run๏
Use the Expert guide for prerequisite concepts. Run from a checkout with Melder installed and Python 3.14 free-threading selected. The collection download includes the level's local helper modules.
Run the saved script๏
python UX_and_AIX_experiences/04_expert/04_diffs_are_derived_never_stored.py
py -3.14t UX_and_AIX_experiences/04_expert/04_diffs_are_derived_never_stored.py
Public surface๏
MutationResearch.create_diff_engine, DiffEngine.list_strategy_names / diff_materials, all three shipped strategies over one pair, and the KeyError an unknown grain raises
Code๏
1"""
2TIER: expert (04)
3GOAL: DERIVE A DIFF, THREE WAYS, AND WATCH THE ANSWER CHANGE. Version
4 records are full objects; "what changed" is computed on demand and
5 never written back. "A verdict is an answer, not a fact the system
6 remembers."
7
8 A DERIVED DIFF CANNOT GO STALE, because it did not exist until you
9 asked. That is the whole argument for storing full objects and
10 computing comparisons - a stored diff is a second copy of the truth
11 that can disagree with the first.
12
13 THREE GRAINS SHIP, AND THEY ARE GENUINELY DIFFERENT QUESTIONS
14 source the TEXT - a rename is enormous
15 structural the SHAPE - a rename is invisible
16 parts the MEMBERS - which pieces moved
17 This lesson runs the SAME pair through all three and prints what
18 each one concluded, because the point is not that three names exist
19 - it is that they disagree, on purpose.
20
21 TWO DEFAULTS AT TWO LAYERS, AND THIS TRIPS PEOPLE
22 DiffEngine.diff_materials(...) defaults to "source"
23 the codegen room's research_diff pins "structural" for a spell
24 pair (expert 30)
25 The engine's default is text; the room overrides it with its
26 reasoning layer. Same family, different default, because the room
27 knows it is answering an agent and the engine does not.
28
29 THE REGISTRY IS OPEN. `register_strategy` is public surface, so
30 "what changed" is extensible by you rather than fixed by the
31 library - the engine is open/closed, and "adding a grain means
32 registering a strategy, never editing this class".
33
34 AND THE ENGINE NEVER REACHES INTO THE CRYSTALLIZER. It takes an
35 injected material resolver, which is why this lesson can run the
36 whole diff family over material it holds in its hand, with no
37 recorded world at all. `diff()` resolves through custody;
38 `diff_materials()` is the door for material you already have -
39 unbound codegen output, for instance.
40SURFACE EXERCISED: MutationResearch.create_diff_engine,
41 DiffEngine.list_strategy_names / diff_materials, all
42 three shipped strategies over one pair, and the
43 KeyError an unknown grain raises
44VERIFY: rewritten 2026-08-05 to DERIVE diffs instead of listing verb
45 names; not yet run.
46"""
47import melder as md
48
49
50MODULE = "billing.rate"
51
52BEFORE = '''class Rate:
53 def quote(self, units):
54 return units * 10
55'''
56
57# Same SHAPE, different TEXT: the method was renamed and the constant
58# moved. `structural` and `source` will disagree about this on purpose.
59AFTER = '''class Rate:
60 def price(self, units):
61 return units * 25
62'''
63
64
65def _material(spell_id: str, source: str) -> dict:
66 """One detached material payload, the shape diff_materials takes."""
67 return {
68 "spell_id": spell_id,
69 "sources": {MODULE: source},
70 "fingerprints": {},
71 }
72
73
74def main() -> None:
75 research = md.MutationResearch()
76 configuration = research.create_configuration()
77 configuration.with_defaults().activate()
78 research.activate(configuration)
79
80 # THE SANCTIONED DOOR. A FRESH engine per call, bound to this
81 # singleton's resolver and owned by the caller.
82 engine = research.create_diff_engine()
83 second = research.create_diff_engine()
84 assert second is not engine, "create_diff_engine is a FACTORY"
85 second.cleanup()
86 print("create_diff_engine() -> a fresh, caller-owned engine each call")
87
88 # ASK THE ENGINE WHAT IT KNOWS. Never hardcode this list - a lesson
89 # that hardcodes it is asserting its own tuple, not melder's registry.
90 names = engine.list_strategy_names()
91 assert names == ["parts", "source", "structural"], names
92 print("registered strategies:", names)
93 print(" sorted, and a name absent here cannot be selected for a diff")
94
95 left = _material("left-version", BEFORE)
96 right = _material("right-version", AFTER)
97
98 # THE DEFAULT IS `source`. Text grain, and a rename is enormous.
99 default_verdict = engine.diff_materials(left, right)
100 assert default_verdict["strategy"] == "source", default_verdict
101 assert default_verdict["left_spell_id"] == "left-version"
102 print()
103 print("diff_materials(left, right) with NO strategy ->",
104 default_verdict["strategy"])
105 print(" the ENGINE's default is text. Note that the codegen room")
106 print(" pins `structural` instead for a spell pair (expert 30) -")
107 print(" two layers, two defaults, and the room's is the one an")
108 print(" agent meets first")
109
110 # ALL THREE GRAINS OVER THE SAME PAIR.
111 print()
112 print("the same two versions, asked three different questions:")
113 verdicts = {}
114 for grain in names:
115 verdict = engine.diff_materials(left, right, strategy=grain)
116 assert verdict["strategy"] == grain, verdict
117 assert "result" in verdict, verdict
118 verdicts[grain] = verdict
119 result = verdict["result"]
120 shape = (sorted(result)[:4] if isinstance(result, dict)
121 else type(result).__name__)
122 print(" %-11s -> result keys/type: %s" % (grain, shape))
123
124 print()
125 print(" they are not three formats of one answer. `source` sees a")
126 print(" renamed method as a large textual change; `structural` sees")
127 print(" the shape and may not care; `parts` reports which MEMBERS")
128 print(" moved. Which one is 'the' diff depends on what you are")
129 print(" about to do with it, so the engine refuses to pick for you.")
130
131 # AN UNKNOWN GRAIN RAISES, AND THE ERROR NAMES THE KNOWN ONES.
132 try:
133 engine.diff_materials(left, right, strategy="semantic")
134 raise AssertionError("expected a KeyError for an unknown strategy")
135 except KeyError as unknown:
136 message = str(unknown)
137 assert "semantic" in message, message
138 print()
139 print("strategy='semantic' ->", message[:96])
140 print(" the refusal NAMES the registry, so a typo tells you what")
141 print(" you could have said instead of just failing")
142
143 # NOTHING WAS RECORDED. The verdicts exist only in this process.
144 assert isinstance(verdicts["source"], dict)
145 print()
146 print("three verdicts computed and NOT ONE was written back into the")
147 print("record. A stored diff would be a second copy of the truth that")
148 print("can disagree with the first; a derived one cannot go stale")
149 print("because it did not exist until asked.")
150
151 engine.cleanup()
152
153
154if __name__ == "__main__":
155 main()
Check the outcome๏
The script contains its own assertions or demonstrated refusal paths. Run it to evaluate those checks against your installed version. The code above is taken directly from the saved file; no run output is invented here.