On this page

The record crosses as a json string๏ƒ

๐Ÿ”ต Expert ยท Lesson 28

NO FILE, NO DATABASE, NO DRIVER - A PYTHON STRING. Merge two research lanes, turn the whole record into TEXT, throw the live set away, and rebuild it from that text with its identity intact.

THE TWO VERBS THAT MAKE A RECORD PORTABLE research_set.describe() -> Dict[str, object] md.ResearchSet.from_payload(d) -> ResearchSet

describe_composition() guarantees "PLAIN-VALUE THROUGHOUT. Every nested value is JSON-safe", which is why this script calls json.dumps(payload) with NO default= handler. The strict call IS the guard: the day something non-plain lands in that payload it raises TypeError and names the offender. A default=str would turn a broken guarantee into a silently lossy round trip - a datetime would go out as a string, come back as a string, and nothing would notice.

WHAT SURVIVES, AND WHY IT MATTERS from_payload RESTORES THE RECORDED IDENTITY - the rebuilt set keeps its set_id and created_at rather than minting new ones. So this is not "a set that looks like the old one"; it is the SAME set, hydrated. Contrast expert 24/27, where a restored WORLD is deliberately equivalent-not-identical and hands you a translation map. Runtime objects are rebuilt; the RECORD is restored.

It also carries network_versioner, so the undo ring survives and restore_network still reaches pre-death shapes on the rebuilt set. Rebuild is SILENT by design: on_mutation is suppressed during hydration and installed at the end, so rehydrating does not re-fire persistence for every recorded node.

AND THE JOIN ORDER IS LOAD-BEARING. The clean join happens while the receiver still sits at the anchor; move the receiver first and even the "clean" branch is divergent. The lanes stay EMPTY on purpose - bind_inactive declares its version into default automatically, and single residence means that id then lives in exactly one lane, so registering it onto a branch would raise the rediscovery signal instead (expert 26 shows that refusal). And the staged version is bound the way the index's first one was: Policy under the string category 'Policy' - the address a bare bind of Policy has - with binding name 'wire-policy', and PolicyV2 the same; bind_inactive refuses a version bound any other way (2026-10-25).

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/28_the_record_crosses_as_a_json_string.py
py -3.14t UX_and_AIX_experiences/04_expert/28_the_record_crosses_as_a_json_string.py

Download this collection ยท Source on GitHub

Public surface๏ƒ

md.ResearchSet.from_payload, ResearchSet.describe / lane_names / walk / set_id / network_snapshot_shas, research_create_lane / research_join / research_heads, Conduit.bind_inactive, and the mesh quartet (with_store_handler / with_fetch_handler)

Code๏ƒ

  1"""
  2TIER: expert (28)
  3GOAL: NO FILE, NO DATABASE, NO DRIVER - A PYTHON STRING. Merge two
  4      research lanes, turn the whole record into TEXT, throw the live set
  5      away, and rebuild it from that text with its identity intact.
  6
  7      THE TWO VERBS THAT MAKE A RECORD PORTABLE
  8        research_set.describe()         -> Dict[str, object]
  9        md.ResearchSet.from_payload(d)  -> ResearchSet
 10
 11      `describe_composition()` guarantees "PLAIN-VALUE THROUGHOUT. Every
 12      nested value is JSON-safe", which is why this script calls
 13      `json.dumps(payload)` with NO `default=` handler. The strict call
 14      IS the guard: the day something non-plain lands in that payload it
 15      raises TypeError and names the offender. A `default=str` would turn
 16      a broken guarantee into a silently lossy round trip - a datetime
 17      would go out as a string, come back as a string, and nothing would
 18      notice.
 19
 20      WHAT SURVIVES, AND WHY IT MATTERS
 21      `from_payload` RESTORES THE RECORDED IDENTITY - the rebuilt set
 22      keeps its `set_id` and `created_at` rather than minting new ones.
 23      So this is not "a set that looks like the old one"; it is the SAME
 24      set, hydrated. Contrast expert 24/27, where a restored WORLD is
 25      deliberately equivalent-not-identical and hands you a translation
 26      map. Runtime objects are rebuilt; the RECORD is restored.
 27
 28      It also carries `network_versioner`, so the undo ring survives and
 29      `restore_network` still reaches pre-death shapes on the rebuilt
 30      set. Rebuild is SILENT by design: `on_mutation` is suppressed
 31      during hydration and installed at the end, so rehydrating does not
 32      re-fire persistence for every recorded node.
 33
 34      AND THE JOIN ORDER IS LOAD-BEARING. The clean join happens while
 35      the receiver still sits at the anchor; move the receiver first and
 36      even the "clean" branch is divergent. The lanes stay EMPTY on
 37      purpose - `bind_inactive` declares its version into `default`
 38      automatically, and single residence means that id then lives in
 39      exactly one lane, so registering it onto a branch would raise the
 40      rediscovery signal instead (expert 26 shows that refusal). And the
 41      staged version is bound the way the index's first one was: Policy
 42      under the string category 'Policy' - the address a bare bind of
 43      Policy has - with binding name 'wire-policy', and PolicyV2 the
 44      same; bind_inactive refuses a version bound any other way
 45      (2026-10-25).
 46SURFACE EXERCISED: md.ResearchSet.from_payload, ResearchSet.describe /
 47                   lane_names / walk / set_id /
 48                   network_snapshot_shas, research_create_lane /
 49                   research_join / research_heads,
 50                   Conduit.bind_inactive, and the mesh quartet
 51                   (with_store_handler / with_fetch_handler)
 52VERIFY: RUN GREEN 2026-10-25 on 3.14t, GIL off and on; asserts are the
 53        contract.
 54"""
 55import json
 56
 57import melder as md
 58
 59
 60FRAME = "wire-world"
 61
 62# The entire "wire" for the mesh coda: a dict of JSON strings in RAM.
 63WIRE: dict = {}
 64
 65
 66class Policy:
 67    def __init__(self) -> None:
 68        self.tag = "v1"
 69
 70
 71class PolicyV2:
 72    def __init__(self) -> None:
 73        self.tag = "v2"
 74
 75
 76def store(kind: str, profile_name: str, unit_id: str, payload: dict) -> None:
 77    WIRE[(kind, unit_id)] = json.dumps(payload, default=str, sort_keys=True)
 78
 79
 80def fetch(kind: str, unit_id: str):
 81    raw = WIRE.get((kind, unit_id))
 82    return None if raw is None else json.loads(raw)
 83
 84
 85def list_units(kind: str, profile_name: str):
 86    return [unit for (stored_kind, unit) in WIRE if stored_kind == kind]
 87
 88
 89def main() -> None:
 90    crystallizer = md.Crystallizer()
 91    crystallizer.activate(
 92        md.CrystallizerConfigurationBuilder().with_defaults().activate(),
 93    )
 94    research = md.MutationResearch()
 95    configuration = research.create_configuration()
 96    configuration.with_defaults().activate()
 97    research.activate(configuration)
 98
 99    spellbook_configuration = (
100        md.SpellbookConfiguration(FRAME).with_defaults().finalize()
101    )
102    book = md.Spellbook(aetheric_frame=FRAME,
103                        configuration=spellbook_configuration)
104    book.configure_aether_frame(
105        system_state="dynamic",
106        disposal=None,
107        disposal_method_names=None,
108        rift_enabled=True,
109        ai_native=True,
110    )
111    v1 = book.bind(spell=Policy, spellframe="Policy", existence="unique",
112                   permissions="create", binding_name="wire-policy")
113    conduit = book.conjure(name="wire-root")
114
115    nexus = md.Nexus()
116    system_configuration = nexus.create_configuration()
117    system_configuration.with_rift_creation_enabled(True)
118    system_configuration.with_allowed_target_frame_names([FRAME])
119    nexus.activate(system_configuration)
120    rift_configuration = nexus.create_rift_configuration()
121    rift_configuration.with_space_type("codegen")
122    rift = nexus.create_rift(configuration=rift_configuration,
123                             rift_name="wirer")
124    rift.mark_active()
125    rift.create_frame_link(FRAME)
126    commands = rift.space.command_system
127
128    research_set = research.research_set()
129    original_set_id = research_set.set_id
130    print("v1 recorded:", v1[:12], "| set", original_set_id[:12], "...")
131
132    # Two branches from one anchor. A lane starts EMPTY - anchoring
133    # records ancestry, it does not copy nodes.
134    for lane in ("wire-clean", "wire-forced"):
135        cut = commands.research_create_lane(
136            lane, attach_to="default", attach_at_spell_id=v1,
137            reason="%s branch" % lane,
138        )
139        assert cut["anchor_spell_id"] == v1 and len(cut["nodes"]) == 0
140    print("two lanes cut from one anchor; open lanes:",
141          len(commands.research_heads()))
142
143    # CLEAN JOIN FIRST, while the receiver is still at the anchor.
144    commands.research_join("wire-clean", into="default",
145                           reason="nothing diverged")
146    print("join('wire-clean') accepted - an empty line is a legal line;")
147    print("  what makes it clean is the ANCHOR agreeing with the tip")
148
149    # Now move the receiver, so the second branch is provably stale. The
150    # new version is bound the way the index's first one was.
151    v2 = conduit.bind_inactive(
152        spell=PolicyV2,
153        spell_index=conduit.get_spell_by_spell_id(v1).spell_index,
154        spellframe="Policy", binding_name="wire-policy",
155        existence="unique", permissions="create",
156    )
157    print("v2 staged; the default lane moved on:", v2[:12], "...")
158
159    try:
160        commands.research_join("wire-forced", into="default")
161        raise AssertionError("expected a refusal: divergent join")
162    except RuntimeError as error:
163        print("join('wire-forced') refused -", str(error)[:100])
164
165    commands.research_join("wire-forced", into="default", force=True,
166                           reason="explicit supersede; content reconciled "
167                                  "in the workshop, not by the record")
168    print("join(force=True) accepted - a SUPERSEDE, never a merge")
169
170    merged_lanes = research_set.lane_names()
171
172    # THE WHOLE RECORD, AS TEXT. Strict dumps - no `default=`.
173    payload = research_set.describe()
174    assert isinstance(payload, dict)
175    assert "organization" in payload and "journal" in payload
176    wire = json.dumps(payload, sort_keys=True)
177    assert isinstance(wire, str)
178    print()
179    print("describe() ->", len(payload), "keys ->", len(wire), "chars of TEXT")
180    print("  head:", wire[:80], "...")
181
182    # Throw the live set away - we hold only text now.
183    del research_set, payload
184
185    rebuilt = md.ResearchSet.from_payload(json.loads(wire))
186    assert rebuilt.set_id == original_set_id, (
187        "from_payload must restore the recorded identity - a rebuilt set "
188        "is the SAME set hydrated, not an equivalent copy"
189    )
190    assert sorted(rebuilt.lane_names()) == sorted(merged_lanes)
191    assert isinstance(rebuilt.walk("default"), list)
192    assert isinstance(rebuilt.network_snapshot_shas(), list)
193    print("from_payload -> set_id preserved,", len(rebuilt.lane_names()),
194          "lanes, the joins intact, undo ring carried")
195
196    # THE MESH CODA - the same plain payload across four callables.
197    mesh = md.ExternalPersistenceManagerConfiguration()
198    mesh.with_store_handler(store)
199    mesh.with_fetch_handler(fetch)
200    mesh.with_list_units_handler(list_units)
201    crystallizer.configure_external_persistence_manager(mesh)
202    assert isinstance(crystallizer.describe_external_persistence_manager(),
203                      dict)
204
205    checkpoint_id = crystallizer.create_checkpoint()
206    crystallizer.flush_checkpoint(checkpoint_id)
207    assert WIRE, (
208        "flush must reach the store handler - upload_on_flush defaults "
209        "True, which is why an empty config refuses to freeze"
210    )
211    (kind, unit_id), raw = next(iter(WIRE.items()))
212    assert isinstance(raw, str)
213    assert fetch(kind, unit_id) == json.loads(raw)
214    assert fetch(kind, "never-stored") is None
215    print()
216    print("flush ->", len(WIRE), "unit(s) crossed as text; kind =", kind)
217    print("  store(kind, profile_name, unit_id, payload: dict) is the whole")
218    print("  integration - melder never imports your storage")
219
220    WIRE.clear()
221    assert fetch(kind, unit_id) is None
222    print("wire cleared - the 'database' was a dict, and it is gone")
223
224
225if __name__ == "__main__":
226    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.

More expert examples ยท Level guide

API contracts๏ƒ