Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189"""Persisted terms decode in a VM that has loaded nothing yet.
A safe `binary_to_term` refuses an atom the VM has not created, and arecord's tag is its constructor's name, an atom that exists once a moduleusing it is loaded. A daemon preloads most modules before it reads itsstore, so a daemon scenario hides a decoder that relies on that: a storagemigration, or a module renamed so a preload names nothing, reads data back asinvalid. Each fixture here is decoded first thing in a fresh VM, thencompared with what the same build decoded with every module loaded(robot-docs/migrations.md, "Persisted terms").
The fixtures under apps/albedo/test/fixtures/persisted-terms were recorded before anymodule moved, by apps/albedo/test/albedo/manual/record_persisted_terms.gleam and this file's`--record`. Do not re-record them to make a rename pass: a changedconstructor name, field order, or arity must fail here."""
from __future__ import annotations
import base64import concurrent.futuresimport osfrom pathlib import Pathimport subprocessimport sysimport tempfileimport unittest
ROOT = Path(__file__).resolve().parents[2]FIXTURES = ROOT / "apps/albedo/test/fixtures/persisted-terms"
READ = "fun(_) -> {error, nil} end"
# Each family's production decoder, applied to `Bytes`. A rename changes the# module named here; the fixtures and expected values stay.DECODERS = { "submission": "'albedo@session@turn':decode(Bytes)", "display": "'albedo@storage@operations':decode_display(Bytes)", "transcript": f"'albedo_sdk@transcript_codec':unpack(Bytes, {READ})", "transcript-fit": (f"'albedo_sdk@transcript_codec':unpack_fit(Bytes, {READ})"), "transcript-list": (f"'albedo_sdk@transcript_codec':unpack_list(Bytes, {READ})"), "cell": f"'albedo@kernel@cell_codec':unpack(Bytes, {READ})", "cell-trace": "'albedo@kernel@cell_codec':unpack_trace(Bytes)", "mcp": "'albedo_ext_mcp@catalogue':saved({some, Bytes})", "memory": "'albedo_ext_memory@files':decode_receipt(Bytes)", # The index is read beside a catalog of the revision it names. The # catalog is not JSON, so only the index can answer. "models-index": ( "begin" ' Catalog = filename:join(Scratch, <<"models.json">>),' ' ok = file:write_file(Catalog, <<"not json!">>),' ' ok = file:write_file(<<Catalog/binary, ".index">>, Bytes),' " {ok, nil} =" " 'albedo_file@revision':set_modified(Catalog, 1700000000)," " 'albedo_models_dev@catalog_cache':catalog(Catalog)" " end" ),}
# Funs carry their module's checksum, which any rebuild changes; a decoded# stored image holds its reader as one. Everything else is compared exactly.NORMALIZE = ( "Norm = fun Norm(T) when is_function(T) -> function;" " Norm(T) when is_tuple(T) -> list_to_tuple([Norm(E) || E <- tuple_to_list(T)]);" " Norm(T) when is_list(T) -> [Norm(E) || E <- T];" " Norm(T) when is_map(T) ->" " maps:from_list([{Norm(K), Norm(V)} || {K, V} <- maps:to_list(T)]);" " Norm(T) -> T end,")
# Record mode loads every module first, so it answers what the decoder means,# whatever a fresh VM would have created.LOAD_ALL = ( '[code:ensure_loaded(list_to_atom(filename:basename(F, ".beam")))' ' || D <- code:get_path(), F <- filelib:wildcard(filename:join(D, "*.beam"))],')
def ebins() -> list[str]: # The gate's sealed snapshot when there is one: `gleam test` may be # rebuilding build/dev while this runs. snapshot = os.environ.get("ALBEDO_TEST_DAEMON") root = Path(snapshot).parent if snapshot else ROOT / "apps/albedo/build/dev/erlang" found = sorted(str(path) for path in root.glob("*/ebin")) if not found: raise RuntimeError(f"no compiled applications under {root}") return found
def fixtures() -> list[tuple[str, Path]]: found = [(path.parent.name, path) for path in sorted(FIXTURES.glob("*/*.etf"))] unknown = {family for family, _ in found} - DECODERS.keys() if unknown: raise RuntimeError(f"fixture families without a decoder: {unknown}") return found
def erlang_binary(text: str) -> str: return '<<"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"/utf8>>'
def decode(family: str, fixture: Path, *, load_all: bool) -> str: """The base64 of the normalized decoded term, decoded first thing in a fresh VM unless `load_all`.""" with tempfile.TemporaryDirectory(prefix="persisted-terms-") as scratch: expression = ( f"{{ok, Bytes}} = file:read_file({erlang_binary(str(fixture))})," f" Scratch = {erlang_binary(scratch)}," + (LOAD_ALL if load_all else "") + f" Decoded = try {DECODERS[family]} catch C:R -> {{crashed, C, R}} end," + NORMALIZE + " io:put_chars(base64:encode(term_to_binary(Norm(Decoded)," " [deterministic]))), halt()." ) result = subprocess.run( ["erl", "+S", "2:2", "-noshell", "-pa", *ebins(), "-eval", expression], capture_output=True, text=True, timeout=120, ) if result.returncode != 0: raise AssertionError( f"{fixture}: the VM failed\n{result.stdout}{result.stderr}" ) return result.stdout.strip()
def show(encoded: str) -> str: """The term as Erlang prints it, for a failure message.""" result = subprocess.run( [ "erl", "-noshell", "-eval", f'io:format("~p", [binary_to_term(base64:decode(<<"{encoded}">>))]),' " halt().", ], capture_output=True, text=True, timeout=60, ) return result.stdout
def expected_path(fixture: Path) -> Path: return fixture.with_suffix(".expected")
class PersistedTermsTest(unittest.TestCase): def test_each_fixture_decodes_first_in_a_fresh_vm(self): cases = fixtures() self.assertTrue(cases, "no persisted-term fixtures") with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: decoded = list( pool.map(lambda case: decode(case[0], case[1], load_all=False), cases) ) for (family, fixture), actual in zip(cases, decoded): with self.subTest(family=family, fixture=fixture.name): expected = base64.b64encode( expected_path(fixture).read_bytes() ).decode() if actual != expected: self.fail( f"{fixture.relative_to(ROOT)} decodes differently in a" f" fresh VM.\nexpected:\n{show(expected)}\n" f"actual:\n{show(actual)}" )
def record() -> None: cases = fixtures() with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: decoded = list( pool.map(lambda case: decode(case[0], case[1], load_all=True), cases) ) for (_, fixture), encoded in zip(cases, decoded): term = show(encoded) if term.startswith(("{crashed", "{error", "none")): raise SystemExit(f"{fixture}: the decoder refused it: {term}") expected_path(fixture).write_bytes(base64.b64decode(encoded)) print(f"{len(cases)} expected values written under {FIXTURES}")
if __name__ == "__main__": if sys.argv[1:] == ["--record"]: record() else: unittest.main()