On this page

Validate → materialize → import → bind → meld

Prerequisites: an eligible agent room, configuration, and lifetimes. The complete application lesson starts with source strings and ends with working Python objects: a tokenizer, counter, reporter, and a population of independent workers.

Each verb answers a different question

Step

Result to inspect

validate_codegen

accepted, the selected frame, and any validation issues

execute_codegen

The execution payload, including result and error information

materialize_codegen

materialized and the named module's publication result

Import

The generated module's real classes

Bind and meld

Objects managed through the normal registration and lifetime rules

Validation checks the room's policy before execution; it does not prove arbitrary Python safe. Malformed requests and policy refusals have different result/error contracts. Inspect the returned payload before treating a call as completed work.

The complete application

Run Expert 36. It validates and materializes the generated modules, imports and binds the classes, then computes a word-frequency report. The assertions check that record occurs four times, that each object has the expected state, that unique reuses the tokenizer, and that five many workers have independent totals [1, 2, 3, 4, 5].

The core function below uses the source strings defined earlier in the saved file. Open the complete linked lesson to copy or download that setup.

Executing and keeping are separate

Materialization gives code a module address. A subsequent bind records its version and custody. The iteration lesson compares room memory with research history: running code does not itself declare a new research version. Subscribe to the room's memory system before operations when you want to observe those command records.

The workflow in code

These are the core steps from the saved example. Use its complete linked script for all class definitions and setup.

  1def main() -> None:
  2    crystallizer = md.Crystallizer()
  3    crystallizer.activate(
  4        md.CrystallizerConfigurationBuilder().with_defaults().activate(),
  5    )
  6
  7    spellbook_configuration = (
  8        md.SpellbookConfiguration(FRAME).with_defaults().finalize()
  9    )
 10    book = md.Spellbook(aetheric_frame=FRAME,
 11                        configuration=spellbook_configuration)
 12    book.configure_aether_frame(
 13        system_state="dynamic",
 14        disposal=None,
 15        disposal_method_names=None,
 16        rift_enabled=True,
 17        ai_native=True,
 18    )
 19    conduit = book.conjure(name="build-root")
 20
 21    nexus = md.Nexus()
 22    system_configuration = nexus.create_configuration()
 23    system_configuration.with_rift_creation_enabled(True)
 24    system_configuration.with_allowed_target_frame_names([FRAME])
 25    nexus.activate(system_configuration)
 26    rift_configuration = nexus.create_rift_configuration()
 27    rift_configuration.with_space_type("codegen")
 28    rift = nexus.create_rift(configuration=rift_configuration,
 29                             rift_name="builder")
 30    rift.mark_active()
 31    rift.create_frame_link(FRAME)
 32    commands = rift.space.command_system
 33
 34    print("the process is up and NONE of the three classes exist yet")
 35    print()
 36
 37    # WRITE THEM. Validate, materialize, import, bind - per piece.
 38    classes = {}
 39    for module_name, source, class_name in PARTS:
 40        verdict = commands.validate_codegen(source, frame_name=FRAME)
 41        assert verdict["accepted"] is True, verdict
 42        kept = commands.materialize_codegen(
 43            source, module_name=module_name, frame_name=FRAME,
 44        )
 45        assert kept["materialized"] is True, kept
 46        module = importlib.import_module(module_name)
 47        classes[class_name] = getattr(module, class_name)
 48        book.bind(spell=classes[class_name], existence="unique",
 49                  permissions="create", binding_name=class_name.lower())
 50        print("wrote %-9s -> module %-16s -> bound as '%s'"
 51              % (class_name, module_name, class_name.lower()))
 52
 53    # MELD THEM. Now they are objects.
 54    tokenizer = conduit.meld(spell=classes["Tokenizer"],
 55                             binding_name="tokenizer")
 56    counter = conduit.meld(spell=classes["Counter"], binding_name="counter")
 57    reporter = conduit.meld(spell=classes["Reporter"],
 58                            binding_name="reporter")
 59    print()
 60    print("melded three OBJECTS:", type(tokenizer).__name__,
 61          type(counter).__name__, type(reporter).__name__)
 62
 63    # RUN THE THING. This is real work done by code that did not exist
 64    # when this script started.
 65    words = tokenizer.run(TEXT)
 66    counts = counter.run(words)
 67    line = reporter.run(counts)
 68    print()
 69    print("input :", TEXT[:58], "...")
 70    print("output:", line)
 71    assert "record" in line, line
 72    assert counts["record"] == 4, counts
 73    print()
 74    print("that answer was computed by three classes an agent wrote as")
 75    print("strings, in this process, a few milliseconds ago")
 76
 77    # THEY HAVE STATE, like any object.
 78    assert tokenizer.calls == 1
 79    assert counter.total == len(words)
 80    assert reporter.rendered == 1
 81    print()
 82    print("and they are ORDINARY objects: tokenizer.calls =",
 83          tokenizer.calls, "| counter.total =", counter.total)
 84    print("  no tongs required. Generated-ness stopped mattering the")
 85    print("  moment they landed")
 86
 87    # UNIQUE MEANS THE SAME OBJECT BACK.
 88    again = conduit.meld(spell=classes["Tokenizer"],
 89                         binding_name="tokenizer")
 90    assert again is tokenizer, "existence='unique' returns the same object"
 91    print()
 92    print("melding 'tokenizer' again -> the SAME object:",
 93          again is tokenizer)
 94
 95    # MANY MEANS A NEW ONE EVERY TIME - a population from one generated
 96    # class. This is its own class rather than a second binding of
 97    # Counter: two independent binds of one class would put two visible
 98    # spells under the same name, which the validator refuses (expert 30).
 99    commands.validate_codegen(WORKER, frame_name=FRAME)
100    kept = commands.materialize_codegen(
101        WORKER, module_name="build_worker", frame_name=FRAME,
102    )
103    assert kept["materialized"] is True, kept
104    worker_class = importlib.import_module("build_worker").Worker
105    book.bind(spell=worker_class, existence="many", permissions="create",
106              binding_name="worker")
107
108    workers = [conduit.meld(spell=worker_class, binding_name="worker")
109               for _ in range(5)]
110    assert len({id(worker) for worker in workers}) == 5, (
111        "existence='many' must build a NEW instance per meld"
112    )
113    for index, worker in enumerate(workers):
114        worker.run(["job"] * (index + 1))
115    totals = [worker.total for worker in workers]
116    assert totals == [1, 2, 3, 4, 5], totals
117    print()
118    print("a fourth generated class, bound existence='many':")
119    print("  5 melds ->", len({id(w) for w in workers}), "distinct objects")
120    print("  independent state:", totals)
121    print("  one class an agent wrote, a population you control")
122
123    print()
124    print("string -> module -> spell -> object -> answer")
125    print("and the module has no file, so its SOURCE IS THE RECORD -")
126    print("which is why this world can be rebuilt, not just re-run")

Runnable examples

All expert examples · Level contents · Full contents

Canonical page source