On this page

A world that outlives its own runtime๏ƒ

๐Ÿ”ต Expert ยท Lesson 27

TEAR THE RUNTIME DOWN ON PURPOSE, THEN COME BACK. Expert 24 walked the five checkpoint verbs while the world stayed up. This is the harder half: seal a world, DESTROY the Aether singleton, collect the garbage, and unfold the record into a runtime that has never seen it.

THE ONE FACT THE WHOLE LESSON TURNS ON Ledger -> in-process, dies with the singleton Cache -> bytes at rest, survives it create_checkpoint() mints into the LEDGER. That is memory. Tear the root down without flushing and the checkpoint goes with it - nothing to come back to and NO ERROR to tell you so, because nothing went wrong. flush_checkpoint(id) is what makes a record outlive the process.

THE TEARDOWN IS PUBLIC, AND IDENTITY-CHECKED aether.cleanup() Singleton bookkeeping is cleared in a finally - _instance and _initialized - so it resets even when a child teardown raises. Before that finally existed, one failing child left a CLEANED HUSK installed as the process singleton for the rest of the run. cleanup() IS the reset; the private _reset_singleton_for_tests beside it is for test isolation, and nothing below reaches for it.

gc.collect() here is real work, not ceremony: melder cleans deterministically rather than leaving owned objects to the collector, so a collect is how the old world is PROVEN gone.

AND THE LAST RUNG DEMANDS A COMPLETE BUNDLE Unfolding into a virgin runtime is the strictest act here and the one that can refuse. load_checkpoint is MEDIATED: the folded chain PRE-FLIGHTS before any replay, and a blockers verdict refuses at the one seam owning authoritative folded truth. A refusal ends "nothing was built" - all-or-nothing declining to START rather than half-building a world and unwinding it.

THE CHAIN COMES FROM THE LEDGER, which is the part worth knowing. plan_checkpoint_load detaches the target's SAME-PROFILE CHAIN in creation order, not the single id you named. After a teardown the fresh ledger is empty and reload_cached_checkpoint restores only the id you ask for - so a world sealed across SEVERAL checkpoints and partially reloaded folds an INCOMPLETE chain and refuses exactly as a corrupt one would. Seal more than once and you want flush_checkpoint() with NO argument, then every id back.

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

Download this collection ยท Source on GitHub

Public surface๏ƒ

md.Crystallizer create_checkpoint / flush_checkpoint / list_checkpoint_ids / list_cached_checkpoint_ids / reload_cached_checkpoint / load_checkpoint, md.Aether cleanup, and the codegen room's validate_codegen / execute_codegen / materialize_codegen across the boundary

Code๏ƒ

  1"""
  2TIER: expert (27)
  3GOAL: TEAR THE RUNTIME DOWN ON PURPOSE, THEN COME BACK. Expert 24 walked
  4      the five checkpoint verbs while the world stayed up. This is the
  5      harder half: seal a world, DESTROY the Aether singleton, collect
  6      the garbage, and unfold the record into a runtime that has never
  7      seen it.
  8
  9      THE ONE FACT THE WHOLE LESSON TURNS ON
 10        Ledger  ->  in-process, dies with the singleton
 11        Cache   ->  bytes at rest, survives it
 12      `create_checkpoint()` mints into the LEDGER. That is memory. Tear
 13      the root down without flushing and the checkpoint goes with it -
 14      nothing to come back to and NO ERROR to tell you so, because
 15      nothing went wrong. `flush_checkpoint(id)` is what makes a record
 16      outlive the process.
 17
 18      THE TEARDOWN IS PUBLIC, AND IDENTITY-CHECKED
 19        aether.cleanup()
 20      Singleton bookkeeping is cleared in a `finally` - `_instance` and
 21      `_initialized` - so it resets even when a child teardown raises.
 22      Before that `finally` existed, one failing child left a CLEANED
 23      HUSK installed as the process singleton for the rest of the run.
 24      `cleanup()` IS the reset; the private `_reset_singleton_for_tests`
 25      beside it is for test isolation, and nothing below reaches for it.
 26
 27      `gc.collect()` here is real work, not ceremony: melder cleans
 28      deterministically rather than leaving owned objects to the
 29      collector, so a collect is how the old world is PROVEN gone.
 30
 31      AND THE LAST RUNG DEMANDS A COMPLETE BUNDLE
 32      Unfolding into a virgin runtime is the strictest act here and the
 33      one that can refuse. `load_checkpoint` is MEDIATED: the folded
 34      chain PRE-FLIGHTS before any replay, and a `blockers` verdict
 35      refuses at the one seam owning authoritative folded truth. A
 36      refusal ends "nothing was built" - all-or-nothing declining to
 37      START rather than half-building a world and unwinding it.
 38
 39      THE CHAIN COMES FROM THE LEDGER, which is the part worth knowing.
 40      `plan_checkpoint_load` detaches the target's SAME-PROFILE CHAIN in
 41      creation order, not the single id you named. After a teardown the
 42      fresh ledger is empty and `reload_cached_checkpoint` restores only
 43      the id you ask for - so a world sealed across SEVERAL checkpoints
 44      and partially reloaded folds an INCOMPLETE chain and refuses
 45      exactly as a corrupt one would. Seal more than once and you want
 46      `flush_checkpoint()` with NO argument, then every id back.
 47SURFACE EXERCISED: md.Crystallizer create_checkpoint / flush_checkpoint /
 48                   list_checkpoint_ids / list_cached_checkpoint_ids /
 49                   reload_cached_checkpoint / load_checkpoint,
 50                   md.Aether cleanup, and the codegen room's
 51                   validate_codegen / execute_codegen /
 52                   materialize_codegen across the boundary
 53VERIFY: rides the owner's 3.14t harness; asserts are the contract.
 54"""
 55import gc
 56
 57import melder as md
 58
 59
 60FRAME = "outlive-world"
 61
 62FIRST_EDIT = "policy_version = 1\nresult = policy_version\n"
 63SECOND_EDIT = "policy_version = 2\nresult = policy_version * 50\n"
 64
 65
 66class Vault:
 67    def __init__(self) -> None:
 68        self.contents = []
 69
 70
 71def build_world():
 72    """Stand up custody, record, world and codegen room."""
 73    crystallizer = md.Crystallizer()
 74    crystallizer.activate(
 75        md.CrystallizerConfigurationBuilder().with_defaults().activate(),
 76    )
 77    research = md.MutationResearch()
 78    configuration = research.create_configuration()
 79    configuration.with_defaults().activate()
 80    research.activate(configuration)
 81
 82    spellbook_configuration = (
 83        md.SpellbookConfiguration(FRAME).with_defaults().finalize()
 84    )
 85    book = md.Spellbook(aetheric_frame=FRAME,
 86                        configuration=spellbook_configuration)
 87    book.configure_aether_frame(
 88        system_state="dynamic",
 89        disposal=None,
 90        disposal_method_names=None,
 91        rift_enabled=True,
 92        ai_native=True,
 93    )
 94    book.bind(spell=Vault, existence="unique", permissions="create",
 95              binding_name="outlive-vault")
 96    conduit = book.conjure(name="outlive-root")
 97
 98    nexus = md.Nexus()
 99    system_configuration = nexus.create_configuration()
100    system_configuration.with_rift_creation_enabled(True)
101    system_configuration.with_allowed_target_frame_names([FRAME])
102    nexus.activate(system_configuration)
103    rift_configuration = nexus.create_rift_configuration()
104    rift_configuration.with_space_type("codegen")
105    rift = nexus.create_rift(configuration=rift_configuration,
106                             rift_name="outliver")
107    rift.mark_active()
108    rift.create_frame_link(FRAME)
109    return crystallizer, conduit, rift.space.command_system
110
111
112def main() -> None:
113    crystallizer, conduit, commands = build_world()
114    vault = conduit.meld(spell=Vault, binding_name="outlive-vault")
115    vault.contents.append("written before any codegen")
116    print("world up; custody recording:", crystallizer.activated)
117
118    # Two codegen edits, each materialized - running is not keeping, so
119    # each gets an address of its own.
120    for label, code in (("edit-1", FIRST_EDIT), ("edit-2", SECOND_EDIT)):
121        commands.validate_codegen(code, frame_name=FRAME)
122        commands.execute_codegen(code, frame_name=FRAME)
123        commands.materialize_codegen(
124            code,
125            module_name="outlive_policy_%s" % label.replace("-", "_"),
126            frame_name=FRAME,
127        )
128        vault.contents.append(label)
129    print("two edits materialized; vault holds", len(vault.contents),
130          "entries")
131
132    # SEAL. Minting puts it in the LEDGER - memory, which the next step
133    # destroys.
134    checkpoint_id = crystallizer.create_checkpoint()
135    assert checkpoint_id in crystallizer.list_checkpoint_ids()
136
137    # FLUSH. THIS is what survives. Skip it and the rest of this script
138    # has nothing to load, with no error to say why.
139    flushed = crystallizer.flush_checkpoint(checkpoint_id)
140    assert checkpoint_id in flushed
141    assert checkpoint_id in crystallizer.list_cached_checkpoint_ids()
142    print("checkpoint", checkpoint_id[:14], "minted and flushed to cache")
143
144    # ---------------- THE TEARDOWN ----------------
145    aether = md.Aether()
146    del vault, conduit, commands, crystallizer
147
148    aether.cleanup()
149    collected = gc.collect()
150    print()
151    print("aether.cleanup() + gc.collect() ->", collected, "objects collected")
152
153    fresh_aether = md.Aether()
154    assert fresh_aether is not aether, (
155        "cleanup() must clear the singleton - a fresh Aether() may never "
156        "return the cleaned instance"
157    )
158    print("md.Aether() now returns a NEW root")
159    del aether
160
161    # ------- AFTER: a runtime that has never seen this world -------
162    reborn = md.Crystallizer()
163    reborn.activate(
164        md.CrystallizerConfigurationBuilder().with_defaults().activate(),
165    )
166    research = md.MutationResearch()
167    configuration = research.create_configuration()
168    configuration.with_defaults().activate()
169    research.activate(configuration)
170
171    assert checkpoint_id in reborn.list_cached_checkpoint_ids(), (
172        "the flushed checkpoint must survive the singleton teardown - if "
173        "this fails, the cache is not bytes at rest"
174    )
175    print("the cache crossed the teardown; our checkpoint is still there")
176
177    # Cache back into the ledger: bookkeeping, not a boot.
178    summary = reborn.reload_cached_checkpoint(checkpoint_id)
179    assert isinstance(summary, dict)
180    print("reload_cached_checkpoint -> summary keys:", sorted(summary)[:5])
181
182    # THE BOOT VERB. Refuses if the folded chain is incomplete.
183    try:
184        report = reborn.load_checkpoint(checkpoint_id)
185    except RuntimeError as refusal:
186        print()
187        print("load_checkpoint REFUSED at admission:")
188        print("  ", str(refusal)[:130])
189        print("  preflight ran BEFORE any replay and the message ends")
190        print("  `nothing was built` - the chain folded incomplete")
191    else:
192        assert isinstance(report, dict)
193        print()
194        print("load_checkpoint -> RestoreReport keys:", sorted(report))
195        for key in ("identity_translation", "identity_translation_map",
196                    "translation_map", "identity_map"):
197            if key in report:
198                print("   %s: %d remapped" % (key, len(report[key])))
199                print("  rebuilt objects get NEW ids - the world that comes")
200                print("  back is EQUIVALENT, not identical")
201                break
202
203    print()
204    print("the CACHE outlived the runtime that minted it; ledger is memory")
205    print("cleanup() IS the reset, and it is public")
206    print("the last rung wants a COMPLETE bundle, checked before it builds")
207
208
209if __name__ == "__main__":
210    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๏ƒ