On this page

Codegen create modify iterate๏ƒ

๐Ÿ”ต Expert ยท Lesson 26

THE LOOP TURNED MORE THAN ONCE - AND THE TWO BOOKS IT WRITES. Expert 12 drove the codegen verbs once. This iterates them, and in doing so hits the distinction that catches everyone: a codegen room and a research record keep DIFFERENT BOOKS, and only one is about your code.

THE TURN - four verbs, only two of which change anything: research_preview(code, frame_name=) what WOULD this do validate_codegen(code, frame_name=) am I permitted execute_codegen(code, frame_name=) do it materialize_codegen(code, module_name=, frame_name=) keep it Running is not keeping. materialize takes a module_name because durability needs an ADDRESS, and that is a separate decision from having run the code.

research_preview is CODEGEN-ROOMS-ONLY, and that is the tell for why room types differ at all: it TAKES CODE, so it only exists where writing code is already the room's business. A codegen room owns the full 34-command research family; a capability room owns twenty-one reads; a static room none.

THE TWO BOOKS THE ROOM'S what CODE was written. One record per SUCCESSFUL TOP-LEVEL public command - every command, not just codegen ones - with a call-depth counter suppressing the tree underneath each call. THE RESEARCH what VERSIONS exist. Written by bind (active), bind_inactive (staged) and a notch (promotion), and by NOTHING else. So execute_codegen writing a module does not mint a version. A BIND does. Cutting a lane and running three codegen turns leaves that lane EMPTY, and this lesson asserts it.

AND SINGLE RESIDENCE IS WHY YOU CANNOT JUST FILE IT ELSEWHERE. One binding-signature SHA256 lives in exactly ONE lane, network wide, permanently - there is no release verb. bind_inactive already declared the staged version onto default, so register_spell(..., lane=...) for that id raises the REDISCOVERY signal naming the holding lane. That raise is a signal, not a failure: identical content rebinds to the same SHA, and this is the system saying "you built this before, here". The way to file it under a name is a different SET - a set is its own residence partition, so a version resident in one is simply unknown to another.

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

Download this collection ยท Source on GitHub

Public surface๏ƒ

CodegenCommandSystem.research_preview / validate_codegen / execute_codegen / materialize_codegen / research_create_lane / research_walk, MutationResearch.research_set / create_research_set, ResearchSet.register_spell / create_lane / walk, Conduit.bind_inactive

Code๏ƒ

  1"""
  2TIER: expert (26)
  3GOAL: THE LOOP TURNED MORE THAN ONCE - AND THE TWO BOOKS IT WRITES.
  4      Expert 12 drove the codegen verbs once. This iterates them, and in
  5      doing so hits the distinction that catches everyone: a codegen room
  6      and a research record keep DIFFERENT BOOKS, and only one is about
  7      your code.
  8
  9      THE TURN - four verbs, only two of which change anything:
 10        research_preview(code, frame_name=)  what WOULD this do
 11        validate_codegen(code, frame_name=)  am I permitted
 12        execute_codegen(code, frame_name=)   do it
 13        materialize_codegen(code, module_name=, frame_name=)   keep it
 14      Running is not keeping. `materialize` takes a module_name because
 15      durability needs an ADDRESS, and that is a separate decision from
 16      having run the code.
 17
 18      `research_preview` is CODEGEN-ROOMS-ONLY, and that is the tell for
 19      why room types differ at all: it TAKES CODE, so it only exists
 20      where writing code is already the room's business. A codegen room
 21      owns the full 34-command research family; a capability room owns
 22      twenty-one reads; a static room none.
 23
 24      THE TWO BOOKS
 25        THE ROOM'S      what CODE was written. One record per SUCCESSFUL
 26                        TOP-LEVEL public command - every command, not
 27                        just codegen ones - with a call-depth counter
 28                        suppressing the tree underneath each call.
 29        THE RESEARCH    what VERSIONS exist. Written by `bind` (active),
 30                        `bind_inactive` (staged) and a notch (promotion),
 31                        and by NOTHING else.
 32      So `execute_codegen` writing a module does not mint a version. A
 33      BIND does. Cutting a lane and running three codegen turns leaves
 34      that lane EMPTY, and this lesson asserts it.
 35
 36      AND SINGLE RESIDENCE IS WHY YOU CANNOT JUST FILE IT ELSEWHERE.
 37      One binding-signature SHA256 lives in exactly ONE lane, network
 38      wide, permanently - there is no release verb. `bind_inactive`
 39      already declared the staged version onto `default`, so
 40      `register_spell(..., lane=...)` for that id raises the REDISCOVERY
 41      signal naming the holding lane. That raise is a signal, not a
 42      failure: identical content rebinds to the same SHA, and this is the
 43      system saying "you built this before, here".
 44      The way to file it under a name is a different SET - a set is its
 45      own residence partition, so a version resident in one is simply
 46      unknown to another.
 47SURFACE EXERCISED: CodegenCommandSystem.research_preview /
 48                   validate_codegen / execute_codegen /
 49                   materialize_codegen / research_create_lane /
 50                   research_walk,
 51                   MutationResearch.research_set / create_research_set,
 52                   ResearchSet.register_spell / create_lane / walk,
 53                   Conduit.bind_inactive
 54VERIFY: rides the owner's 3.14t harness; asserts are the contract.
 55"""
 56import melder as md
 57
 58
 59FRAME = "iterate-world"
 60
 61
 62class Rate:
 63    def __init__(self) -> None:
 64        self.value = 1
 65
 66
 67class RateV2:
 68    def __init__(self) -> None:
 69        self.value = 2
 70
 71
 72TURNS = (
 73    ("turn-1", "rate_multiplier = 1\nresult = rate_multiplier\n"),
 74    ("turn-2", "rate_multiplier = 2\nresult = rate_multiplier * 10\n"),
 75    ("turn-3", "rate_multiplier = 3\nresult = rate_multiplier * 100\n"),
 76)
 77
 78UNGRANTED = "import socket\nresult = socket\n"
 79
 80
 81def main() -> None:
 82    # Custody and record FIRST: the research seams no-op unless the root
 83    # already exists and is active, and they never construct one.
 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    # A recorded world must be born configured, and POSTURE GOES BEFORE
 94    # BIND - a bind into a not-yet-dynamic frame declares nothing.
 95    spellbook_configuration = (
 96        md.SpellbookConfiguration(FRAME).with_defaults().finalize()
 97    )
 98    book = md.Spellbook(aetheric_frame=FRAME,
 99                        configuration=spellbook_configuration)
100    book.configure_aether_frame(
101        system_state="dynamic",
102        disposal=None,
103        disposal_method_names=None,
104        rift_enabled=True,
105        ai_native=True,
106    )
107    v1 = book.bind(spell=Rate, existence="unique", permissions="create",
108                   binding_name="iterate-rate")
109    conduit = book.conjure(name="iterate-root")
110    print("v1 bound - an ACTIVE world entry:", v1[:12], "...")
111
112    nexus = md.Nexus()
113    system_configuration = nexus.create_configuration()
114    system_configuration.with_rift_creation_enabled(True)
115    system_configuration.with_allowed_target_frame_names([FRAME])
116    nexus.activate(system_configuration)
117    rift_configuration = nexus.create_rift_configuration()
118    rift_configuration.with_space_type("codegen")
119    rift = nexus.create_rift(configuration=rift_configuration,
120                             rift_name="iterator")
121    rift.mark_active()
122    rift.create_frame_link(FRAME)
123    room = rift.space
124    commands = room.command_system
125
126    # Subscribe before acting: `memory_enabled` is literally "is anyone
127    # listening", so a room with no subscriber keeps nothing.
128    written = []
129    assert room.memory_system.memory_enabled is False
130    subscription = room.memory_system.register_memory_callback(written.append)
131    assert room.memory_system.memory_enabled is True
132
133    # A lane cut BEFORE the loop, so we can prove what the loop does not
134    # write to it. Anchoring records ancestry only - it copies nothing.
135    cut = commands.research_create_lane(
136        "codegen-turns", attach_to="default", attach_at_spell_id=v1,
137        reason="does a codegen turn mint a version? (it does not)",
138    )
139    assert cut["anchor_spell_id"] == v1
140    assert len(cut["nodes"]) == 0
141
142    print()
143    for label, code in TURNS:
144        preview = commands.research_preview(code, frame_name=FRAME)
145        verdict = commands.validate_codegen(code, frame_name=FRAME)
146        outcome = commands.execute_codegen(code, frame_name=FRAME)
147        kept = commands.materialize_codegen(
148            code,
149            module_name="iterate_policy_%s" % label.replace("-", "_"),
150            frame_name=FRAME,
151        )
152        print("%s: preview(%s) -> validate(%s) -> execute(%s) -> keep(%s)" % (
153            label, type(preview).__name__, type(verdict).__name__,
154            type(outcome).__name__, type(kept).__name__))
155
156    # A refusal mid-loop changes the verdict, not the structure. Nothing
157    # compiled, nothing ran, and the loop reads it rather than breaking.
158    denied = commands.validate_codegen(UNGRANTED, frame_name=FRAME)
159    refused = commands.execute_codegen(UNGRANTED, frame_name=FRAME)
160    print("ungranted import: validate ->", type(denied).__name__,
161          "| execute ->", type(refused).__name__)
162
163    room.memory_system.unregister_memory_callback(subscription)
164    assert room.memory_system.memory_enabled is False
165    print()
166    print("room memory:", len(written), "records - the unit is the COMMAND,")
167    print("  not the turn:", len(TURNS), "turns x 4 verbs plus the lane cut")
168
169    # THE RESEARCH BOOK IS UNTOUCHED BY ALL OF IT.
170    walked_turns = commands.research_walk("codegen-turns")
171    assert len(walked_turns) == 0, (
172        "a codegen turn is not a version - executing and materializing "
173        "code writes the ROOM's book, never the research record"
174    )
175    print("research_walk('codegen-turns') ->", len(walked_turns),
176          "nodes, and correctly so")
177
178    # Now mint versions the only way that works: bind / bind_inactive.
179    index = conduit.get_spell_by_id(v1).spell_index
180    assert index.spells_in_index() == {v1}
181    assert conduit.meld(spell=Rate, binding_name="iterate-rate").value == 1
182
183    staged = conduit.bind_inactive(
184        spell=RateV2, spell_index=index,
185        existence="unique", permissions="create",
186    )
187    assert index.spells_in_index() == {v1, staged}
188    assert index.selected_spell_id == v1, "staging must NOT move selection"
189    assert conduit.meld(spell=Rate, binding_name="iterate-rate").value == 1
190    print("v2 STAGED: 2 members, selection unchanged, candidate inert")
191
192    walked_default = commands.research_walk("default")
193    assert len(walked_default) >= 1, (
194        "bind and bind_inactive declare world entries once the MR root is "
195        "active - if this is empty the root was activated too late"
196    )
197    print("research_walk('default') ->", len(walked_default),
198          "nodes - the binds recorded; the codegen calls did not")
199
200    # SINGLE RESIDENCE. The staged id already lives on `default`.
201    try:
202        research.research_set().register_spell(staged, lane="codegen-turns")
203        raise AssertionError("expected the rediscovery signal")
204    except RuntimeError as rediscovery:
205        print()
206        print("register_spell(staged, lane='codegen-turns') REFUSED:")
207        print("  ", str(rediscovery)[:110])
208
209    # A different SET is its own residence partition, so the same id
210    # files cleanly there.
211    #
212    # AND THIS IS THE ONE PLACE THE LESSON LEAVES THE ROOM COMMANDS, for a
213    # reason worth stating plainly: NONE of the room's 34 research verbs
214    # takes a set argument. They reach the record two ways and both land on
215    # the same set - the lane verbs call `research_set()` with no name, and
216    # the group/recent verbs call engine methods that DO accept `set_name`
217    # (`group_impact_view`, `group_drift_view`, `recent_activity_view` and
218    # eleven more) without passing it. Either way: one set.
219    # So a second set cannot be named through the room today, and holding
220    # it directly is the only way to show residence is PER-SET.
221    # `MutationResearch.research_set(name)` and `ResearchSet` are both
222    # public surface - a different LAYER of the public API, not a private
223    # door. Everywhere the room CAN answer, ask the room.
224    audit = research.create_research_set("codegen-audit")
225    audit.create_lane("turns", lane_type="experiment")
226    audit.register_spell(staged, lane="turns", reason="independent audit")
227    assert len(audit.walk("turns")) == 1
228    print("the SAME id accepted in a second set - residence is per-set")
229
230    # The loop stops where the public surface stops (expert 17): the
231    # promoting verb takes the parked OBJECT, and no public door hands
232    # one out - both id->object doors resolve to the ACTIVE member.
233    assert conduit.get_spell_by_id(staged).spell_id == v1
234    assert hasattr(conduit, "notch_spell")
235
236    print()
237    print("preview, permit, run, keep - four questions, four verbs")
238    print("two books: the room keeps CODE, research keeps VERSIONS")
239    print("a lane you never register into is empty, and that is not a bug")
240
241
242if __name__ == "__main__":
243    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๏ƒ