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).

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).
 41SURFACE EXERCISED: md.ResearchSet.from_payload, ResearchSet.describe /
 42                   lane_names / walk / set_id /
 43                   network_snapshot_shas, research_create_lane /
 44                   research_join / research_heads,
 45                   Conduit.bind_inactive, and the mesh quartet
 46                   (with_store_handler / with_fetch_handler)
 47VERIFY: rides the owner's 3.14t harness; asserts are the contract.
 48"""
 49import json
 50
 51import melder as md
 52
 53
 54FRAME = "wire-world"
 55
 56# The entire "wire" for the mesh coda: a dict of JSON strings in RAM.
 57WIRE: dict = {}
 58
 59
 60class Policy:
 61    def __init__(self) -> None:
 62        self.tag = "v1"
 63
 64
 65class PolicyV2:
 66    def __init__(self) -> None:
 67        self.tag = "v2"
 68
 69
 70def store(kind: str, profile_name: str, unit_id: str, payload: dict) -> None:
 71    WIRE[(kind, unit_id)] = json.dumps(payload, default=str, sort_keys=True)
 72
 73
 74def fetch(kind: str, unit_id: str):
 75    raw = WIRE.get((kind, unit_id))
 76    return None if raw is None else json.loads(raw)
 77
 78
 79def list_units(kind: str, profile_name: str):
 80    return [unit for (stored_kind, unit) in WIRE if stored_kind == kind]
 81
 82
 83def main() -> None:
 84    crystallizer = md.Crystallizer()
 85    crystallizer.activate(
 86        md.CrystallizerConfigurationBuilder().with_defaults().activate(),
 87    )
 88    research = md.MutationResearch()
 89    configuration = research.create_configuration()
 90    configuration.with_defaults().activate()
 91    research.activate(configuration)
 92
 93    spellbook_configuration = (
 94        md.SpellbookConfiguration(FRAME).with_defaults().finalize()
 95    )
 96    book = md.Spellbook(aetheric_frame=FRAME,
 97                        configuration=spellbook_configuration)
 98    book.configure_aether_frame(
 99        system_state="dynamic",
100        disposal=None,
101        disposal_method_names=None,
102        rift_enabled=True,
103        ai_native=True,
104    )
105    v1 = book.bind(spell=Policy, existence="unique", permissions="create",
106                   binding_name="wire-policy")
107    conduit = book.conjure(name="wire-root")
108
109    nexus = md.Nexus()
110    system_configuration = nexus.create_configuration()
111    system_configuration.with_rift_creation_enabled(True)
112    system_configuration.with_allowed_target_frame_names([FRAME])
113    nexus.activate(system_configuration)
114    rift_configuration = nexus.create_rift_configuration()
115    rift_configuration.with_space_type("codegen")
116    rift = nexus.create_rift(configuration=rift_configuration,
117                             rift_name="wirer")
118    rift.mark_active()
119    rift.create_frame_link(FRAME)
120    commands = rift.space.command_system
121
122    research_set = research.research_set()
123    original_set_id = research_set.set_id
124    print("v1 recorded:", v1[:12], "| set", original_set_id[:12], "...")
125
126    # Two branches from one anchor. A lane starts EMPTY - anchoring
127    # records ancestry, it does not copy nodes.
128    for lane in ("wire-clean", "wire-forced"):
129        cut = commands.research_create_lane(
130            lane, attach_to="default", attach_at_spell_id=v1,
131            reason="%s branch" % lane,
132        )
133        assert cut["anchor_spell_id"] == v1 and len(cut["nodes"]) == 0
134    print("two lanes cut from one anchor; open lanes:",
135          len(commands.research_heads()))
136
137    # CLEAN JOIN FIRST, while the receiver is still at the anchor.
138    commands.research_join("wire-clean", into="default",
139                           reason="nothing diverged")
140    print("join('wire-clean') accepted - an empty line is a legal line;")
141    print("  what makes it clean is the ANCHOR agreeing with the tip")
142
143    # Now move the receiver, so the second branch is provably stale.
144    v2 = conduit.bind_inactive(
145        spell=PolicyV2,
146        spell_index=conduit.get_spell_by_id(v1).spell_index,
147        existence="unique", permissions="create",
148    )
149    print("v2 staged; the default lane moved on:", v2[:12], "...")
150
151    try:
152        commands.research_join("wire-forced", into="default")
153        raise AssertionError("expected a refusal: divergent join")
154    except RuntimeError as error:
155        print("join('wire-forced') refused -", str(error)[:100])
156
157    commands.research_join("wire-forced", into="default", force=True,
158                           reason="explicit supersede; content reconciled "
159                                  "in the workshop, not by the record")
160    print("join(force=True) accepted - a SUPERSEDE, never a merge")
161
162    merged_lanes = research_set.lane_names()
163
164    # THE WHOLE RECORD, AS TEXT. Strict dumps - no `default=`.
165    payload = research_set.describe()
166    assert isinstance(payload, dict)
167    assert "organization" in payload and "journal" in payload
168    wire = json.dumps(payload, sort_keys=True)
169    assert isinstance(wire, str)
170    print()
171    print("describe() ->", len(payload), "keys ->", len(wire), "chars of TEXT")
172    print("  head:", wire[:80], "...")
173
174    # Throw the live set away - we hold only text now.
175    del research_set, payload
176
177    rebuilt = md.ResearchSet.from_payload(json.loads(wire))
178    assert rebuilt.set_id == original_set_id, (
179        "from_payload must restore the recorded identity - a rebuilt set "
180        "is the SAME set hydrated, not an equivalent copy"
181    )
182    assert sorted(rebuilt.lane_names()) == sorted(merged_lanes)
183    assert isinstance(rebuilt.walk("default"), list)
184    assert isinstance(rebuilt.network_snapshot_shas(), list)
185    print("from_payload -> set_id preserved,", len(rebuilt.lane_names()),
186          "lanes, the joins intact, undo ring carried")
187
188    # THE MESH CODA - the same plain payload across four callables.
189    mesh = md.ExternalPersistenceManagerConfiguration()
190    mesh.with_store_handler(store)
191    mesh.with_fetch_handler(fetch)
192    mesh.with_list_units_handler(list_units)
193    crystallizer.configure_external_persistence_manager(mesh)
194    assert isinstance(crystallizer.describe_external_persistence_manager(),
195                      dict)
196
197    checkpoint_id = crystallizer.create_checkpoint()
198    crystallizer.flush_checkpoint(checkpoint_id)
199    assert WIRE, (
200        "flush must reach the store handler - upload_on_flush defaults "
201        "True, which is why an empty config refuses to freeze"
202    )
203    (kind, unit_id), raw = next(iter(WIRE.items()))
204    assert isinstance(raw, str)
205    assert fetch(kind, unit_id) == json.loads(raw)
206    assert fetch(kind, "never-stored") is None
207    print()
208    print("flush ->", len(WIRE), "unit(s) crossed as text; kind =", kind)
209    print("  store(kind, profile_name, unit_id, payload: dict) is the whole")
210    print("  integration - melder never imports your storage")
211
212    WIRE.clear()
213    assert fetch(kind, unit_id) is None
214    print("wire cleared - the 'database' was a dict, and it is gone")
215
216
217if __name__ == "__main__":
218    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๏ƒ