diff --git a/apps/albedo/priv/bin/albedo-build b/apps/albedo/priv/bin/albedo-build index 7197974a2..b567a18c9 100755 --- a/apps/albedo/priv/bin/albedo-build +++ b/apps/albedo/priv/bin/albedo-build @@ -29,6 +29,7 @@ duplicated() { } cd "$root" +rm -f "$app/.build-digest" "$app/.build-digest-v2" "$app/.extensions-key" "$app/.extensions.etf" gleam build &2 module=$(duplicated) if [ -n "$module" ]; then diff --git a/apps/albedo/src/albedo/composition/extension_cache.gleam b/apps/albedo/src/albedo/composition/extension_cache.gleam index 5f44e55a3..a913af75e 100644 --- a/apps/albedo/src/albedo/composition/extension_cache.gleam +++ b/apps/albedo/src/albedo/composition/extension_cache.gleam @@ -2,8 +2,8 @@ //// of calling every extension's constructor on boot. Functions in the term //// refer to the sealed beams by module, index, and checksum, in albedo's //// application and in the workspace packages beside it, such as the SDK. -//// So the cache is keyed on every application in the build, not on albedo's -//// build digest alone, and is only read beside the key its seal wrote. +//// The cache and build identity share the digest of every application. +//// The cache is only read beside the matching key its seal wrote. import albedo_bytes/term_codec import albedo_env diff --git a/apps/albedo/src/albedo/lifecycle/build_identity.gleam b/apps/albedo/src/albedo/lifecycle/build_identity.gleam index ac7b780b1..c3f333781 100644 --- a/apps/albedo/src/albedo/lifecycle/build_identity.gleam +++ b/apps/albedo/src/albedo/lifecycle/build_identity.gleam @@ -1,5 +1,5 @@ //// The content digest of this daemon's own build: SHA-256 over the sorted -//// relative paths and bytes of every regular file under the albedo app's +//// relative paths and bytes of every regular file under every runtime app's //// `ebin/` and `priv/` trees, symlinks followed, or the builder's sealed //// sidecar. The CLI hashes its candidate build with the same recipe //// (cli/cmd/albedo/build_identity.go). The shared fixture in @@ -8,6 +8,7 @@ import albedo/composition/extension_cache import albedo/composition/extensions import albedo_bytes/digest +import albedo_file import gleam/bit_array import gleam/crypto import gleam/dynamic.{type Dynamic} @@ -15,24 +16,21 @@ import gleam/dynamic/decode import gleam/erlang/atom.{type Atom} import gleam/io import gleam/list +import gleam/option.{None} import gleam/result import gleam/string -const seal_name = ".build-digest" +const seal_name = ".build-digest-v2" -/// The build digest, memoized for the VM's life, so a tree edited under a -/// running daemon keeps the digest it booted with. Empty when the tree cannot -/// be read. An empty digest is not memoized. +/// Capture once for the VM's life, before code-cache relocation. Even an +/// unreadable build stays unknown rather than acquiring a later tree's identity. pub fn build_digest() -> String { - case get_term(memo_key(), "") { - "" -> - case compute() { - "" -> "" - digest -> { - let _ = put_term(memo_key(), digest) - digest - } - } + case get_term(memo_key(), "uninitialized") { + "uninitialized" -> { + let digest = compute() + let _ = put_term(memo_key(), digest) + digest + } digest -> digest } } @@ -46,11 +44,18 @@ pub fn app_dir() -> Result(String, Nil) { } } -/// The digest a builder sealed into `app_dir`, when the sidecar holds exactly -/// 64 characters and a newline. +/// A v2 seal contains exactly 64 lowercase hexadecimal digits and a newline. +/// Old root-only seals are ignored. Seals are trusted builder output, not a +/// check against later edits: mutable copies must discard them before editing. pub fn read_seal(app_dir: String) -> Result(String, Nil) { - case read_file(join(app_dir, seal_name)) { - Ok(<>) -> bit_array.to_string(sealed) + case read_head(app_dir) { + Ok(<>) -> { + use sealed <- result.try(bit_array.to_string(sealed)) + case valid_digest(sealed) { + True -> Ok(sealed) + False -> Error(Nil) + } + } _ -> Error(Nil) } } @@ -59,17 +64,9 @@ fn compute() -> String { case app_dir() { Error(Nil) -> "" Ok(app_dir) -> - case read_head(app_dir) { - Ok(<>) -> - case bit_array.to_string(sealed) { - Ok(sealed) -> - case valid_digest(sealed) { - True -> sealed - False -> tree_digest(app_dir) - } - Error(Nil) -> tree_digest(app_dir) - } - _ -> tree_digest(app_dir) + case read_seal(app_dir) { + Ok(sealed) -> sealed + Error(Nil) -> tree_digest(app_dir) } } } @@ -92,53 +89,60 @@ fn valid_digest(text: String) -> Bool { |> list.all(fn(character) { string.contains("0123456789abcdef", character) }) } -/// Seal a completed build whose albedo app is `app_dir`: write the app's -/// digest beside it, then the extension cache, keyed on every application -/// in the build (`applications_digest`). Remove the sidecars before editing -/// the build's files. +/// Seal only after every application's files and helper fixups are final. +/// Invalidate previous sidecars first; write the cache, then publish the seal. pub fn seal_build(app_dir: String) -> Result(Nil, String) { - // A cache an earlier seal wrote must not outlive this one, whether or not - // this seal writes another. + use _ <- result.try(remove_seal(join(app_dir, seal_name))) + use _ <- result.try(remove_seal(join(app_dir, ".build-digest"))) extension_cache.clear(app_dir) case tree_digest(app_dir) { "" -> Error("unreadable_build") digest -> { - let assert True = - write_file(join(app_dir, seal_name), digest <> "\n") - == atom.to_dynamic(atom.create("ok")) - as "build digest not written" - case applications_digest(dirname(app_dir)) { - "" -> + case extension_cache.write(app_dir, digest, extensions.declared) { + Ok(Nil) -> Nil + Error(reason) -> io.println_error( - "extension cache not written: " - <> string.inspect(atom.create("unreadable_applications")), + "extension cache not written: " <> string.inspect(reason), ) - key -> - case extension_cache.write(app_dir, key, extensions.declared) { - Ok(Nil) -> Nil - Error(extension_cache.EnvironmentDependent) -> - io.println_error( - "extension cache not written: " - <> string.inspect(atom.create("environment_dependent")), - ) - Error(extension_cache.NotWritten(reason)) -> - io.println_error( - "extension cache not written: " <> string.inspect(reason), - ) - } } - Ok(Nil) + albedo_file.replace( + join(app_dir, seal_name), + <>, + sync: False, + mode: None, + ) + |> result.replace_error("build digest not written") } } } -/// The digest of the `ebin` and `priv` trees under `app_dir`, or `""` when a -/// path cannot be read. A missing root contributes nothing. +fn remove_seal(path: String) -> Result(Nil, String) { + let removed = delete(path) + case removed == atom.to_dynamic(atom.create("ok")) { + True -> Ok(Nil) + False -> + case decode.run(removed, decode.at([1], atom.decoder())) { + Ok(reason) -> + case reason == atom.create("enoent") { + True -> Ok(Nil) + False -> Error("cannot remove build seal") + } + Error(_) -> Error("cannot remove build seal") + } + } +} + +/// Hash the runtime output containing `app_dir`, including its dependencies. +/// A missing albedo ebin or unreadable output fails the identity. pub fn tree_digest(app_dir: String) -> String { - digest_roots([ - #(join(app_dir, "ebin"), "ebin"), - #(join(app_dir, "priv"), "priv"), - ]) + case read_file_info(join(app_dir, "ebin")) { + Ok(info) -> + case info_type(info) { + "directory" -> applications_digest(dirname(app_dir)) + _ -> "" + } + Error(_) -> "" + } } /// The digest of every application in the build `output`, the directory @@ -146,24 +150,44 @@ pub fn tree_digest(app_dir: String) -> String { /// each app's `ebin` and `priv` trees, by paths that start with the app's /// name, or `""` when a path cannot be read. A sealed build's extension /// cache holds functions of any of these applications, so it is keyed on -/// all of them, while the build digest stays albedo's own. The seal and +/// all of them, as is the build identity. The seal and /// cache sidecars sit beside `ebin`, so they are never hashed. pub fn applications_digest(output: String) -> String { case list_dir(output) { Error(_) -> "" - Ok(names) -> - names - |> list.map(characters_to_binary) - |> list.sort(string.compare) - |> list.filter(fn(name) { is_directory(join(join(output, name), "ebin")) }) - |> list.flat_map(fn(name) { - let app = join(output, name) - [ - #(join(app, "ebin"), name <> "/ebin"), - #(join(app, "priv"), name <> "/priv"), - ] - }) - |> digest_roots + Ok(names) -> { + let roots = + list.try_fold(names, [], fn(roots, name) { + let name = characters_to_binary(name) + let app = join(output, name) + case read_file_info(join(app, "ebin")) { + Ok(info) -> + case info_type(info) { + "directory" -> + Ok([ + #(join(app, "ebin"), name <> "/ebin"), + #(join(app, "priv"), name <> "/priv"), + ..roots + ]) + _ -> Ok(roots) + } + Error(reason) -> + case + list.contains( + [atom.create("enoent"), atom.create("enotdir")], + reason, + ) + { + True -> Ok(roots) + False -> Error(Nil) + } + } + }) + case roots { + Ok([]) | Error(Nil) -> "" + Ok(roots) -> digest_roots(roots) + } + } } } @@ -179,13 +203,6 @@ fn digest_roots(roots: List(#(String, String))) -> String { } } -fn is_directory(path: String) -> Bool { - case read_file_info(path) { - Ok(info) -> info_type(info) == "directory" - Error(_) -> False - } -} - /// Every regular file below `root`, as relative and absolute paths, added to /// `files`. fn build_files( @@ -196,7 +213,7 @@ fn build_files( case read_file_info(root) { Ok(info) -> case info_type(info) { - "directory" -> walk(root, relative, files) + "directory" -> walk(root, relative, files, 0) _ -> Ok(files) } Error(reason) -> @@ -211,7 +228,12 @@ fn walk( directory: String, relative: String, files: List(#(String, String)), + depth: Int, ) -> Result(List(#(String, String)), Nil) { + use _ <- result.try(case depth > 256 { + True -> Error(Nil) + False -> Ok(Nil) + }) use names <- result.try(list_dir(directory) |> result.replace_error(Nil)) list.try_fold(names, files, fn(files, name) { let name = characters_to_binary(name) @@ -221,7 +243,7 @@ fn walk( Error(_) -> Error(Nil) Ok(info) -> case info_type(info) { - "directory" -> walk(path, child, files) + "directory" -> walk(path, child, files, depth + 1) "regular" -> Ok([#(child, path), ..files]) _ -> Ok(files) } @@ -297,9 +319,6 @@ fn close(file: File) -> Dynamic @external(erlang, "file", "read_file") fn read_file(path: String) -> Result(BitArray, Dynamic) -@external(erlang, "file", "write_file") -fn write_file(path: String, text: String) -> Dynamic - @external(erlang, "file", "read_file_info") fn read_file_info(path: String) -> Result(Dynamic, Atom) @@ -311,3 +330,6 @@ fn get_term(key: Atom, default: String) -> String @external(erlang, "persistent_term", "put") fn put_term(key: Atom, value: String) -> Dynamic + +@external(erlang, "file", "delete") +fn delete(path: String) -> Dynamic diff --git a/apps/albedo/src/albedo/lifecycle/server.gleam b/apps/albedo/src/albedo/lifecycle/server.gleam index 3a86feb4e..b50a24ae3 100644 --- a/apps/albedo/src/albedo/lifecycle/server.gleam +++ b/apps/albedo/src/albedo/lifecycle/server.gleam @@ -951,6 +951,8 @@ pub fn main() -> Nil { lifecycle.refuse_home(home) Error(error) -> panic as error.message } + // Capture the shipment identity before code paths move into the home cache. + let _ = startup.measure("build digest", build_identity.build_digest) startup.measure("preserve code", fn() { boot_code.prepare(home) }) let installed = startup.measure("extension declarations", extensions.defaults) // Before anything opens storage: a home a newer build upgraded past what @@ -977,7 +979,6 @@ pub fn main() -> Nil { // Before readiness, so a client that sees the daemon can already inspect it. inspection.start(home) watch_stalls() - let _ = startup.measure("build digest", build_identity.build_digest) let assert Ok(_) = startup.measure("publish readiness", fn() { lifecycle.ready(home, port, webhook_port, token) diff --git a/apps/albedo/test/albedo/lifecycle/build_digest_test.gleam b/apps/albedo/test/albedo/lifecycle/build_digest_test.gleam index 5b3e1b80d..c880caf47 100644 --- a/apps/albedo/test/albedo/lifecycle/build_digest_test.gleam +++ b/apps/albedo/test/albedo/lifecycle/build_digest_test.gleam @@ -1,14 +1,24 @@ -//// The daemon and the CLI hash a build with one recipe. The shared fixture -//// in test/fixtures/build-digest pins both implementations to the same -//// constant, so a drift on either side fails here and in -//// cli/internal/daemon/build_identity_test.go. +//// Cross-language identity fixtures catch a CLI that keeps a daemon after +//// package changes. Each case keeps albedo identical and changes only a +//// dependency's code, presence, or helper asset (also reached through a link). import albedo/lifecycle/build_identity +import albedo_file +import gleam/bit_array +import gleam/list +import gleam/string import gleeunit/should pub fn tree_digest_matches_the_shared_fixture_test() -> Nil { - build_identity.tree_digest("test/fixtures/build-digest") - |> should.equal( - "a8f2d0de5c26845d69d69f9a98111ab795b83d4ab24e6f18068b57145c13fe42", - ) + let root = "test/fixtures/build-digest/" + let assert Ok(bytes) = albedo_file.read(root <> "expected.txt") + let assert Ok(expected) = bit_array.to_string(bytes) + expected + |> string.trim + |> string.split("\n") + |> list.each(fn(line) { + let assert [name, digest] = string.split(line, " ") + build_identity.tree_digest(root <> name <> "/albedo") + |> should.equal(digest) + }) } diff --git a/apps/albedo/test/fixtures/build-digest/added/albedo b/apps/albedo/test/fixtures/build-digest/added/albedo new file mode 120000 index 000000000..99b51daa2 --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/added/albedo @@ -0,0 +1 @@ +../base/albedo \ No newline at end of file diff --git a/apps/albedo/test/fixtures/build-digest/added/dependency b/apps/albedo/test/fixtures/build-digest/added/dependency new file mode 120000 index 000000000..029b997a0 --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/added/dependency @@ -0,0 +1 @@ +../base/dependency \ No newline at end of file diff --git a/apps/albedo/test/fixtures/build-digest/added/new_package/ebin/new.beam b/apps/albedo/test/fixtures/build-digest/added/new_package/ebin/new.beam new file mode 100644 index 000000000..c10e37840 --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/added/new_package/ebin/new.beam @@ -0,0 +1 @@ +new package diff --git a/apps/albedo/test/fixtures/build-digest/added/sdk/ebin/shared.beam b/apps/albedo/test/fixtures/build-digest/added/sdk/ebin/shared.beam new file mode 100644 index 0000000000000000000000000000000000000000..667511876486583e1e64db882c6988004d18a69f GIT binary patch literal 15 WcmXR&OwLYBPgO|HPf2C?&jkQ2l?9Oi literal 0 HcmV?d00001 diff --git a/apps/albedo/test/fixtures/build-digest/added/sdk/priv/helper-link b/apps/albedo/test/fixtures/build-digest/added/sdk/priv/helper-link new file mode 120000 index 000000000..f5d0149bb --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/added/sdk/priv/helper-link @@ -0,0 +1 @@ +helper.py \ No newline at end of file diff --git a/apps/albedo/test/fixtures/build-digest/added/sdk/priv/helper.py b/apps/albedo/test/fixtures/build-digest/added/sdk/priv/helper.py new file mode 100644 index 000000000..53e37a0d9 --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/added/sdk/priv/helper.py @@ -0,0 +1 @@ +print("helper") diff --git a/apps/albedo/test/fixtures/build-digest/asset/albedo b/apps/albedo/test/fixtures/build-digest/asset/albedo new file mode 120000 index 000000000..99b51daa2 --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/asset/albedo @@ -0,0 +1 @@ +../base/albedo \ No newline at end of file diff --git a/apps/albedo/test/fixtures/build-digest/asset/dependency b/apps/albedo/test/fixtures/build-digest/asset/dependency new file mode 120000 index 000000000..029b997a0 --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/asset/dependency @@ -0,0 +1 @@ +../base/dependency \ No newline at end of file diff --git a/apps/albedo/test/fixtures/build-digest/asset/sdk/ebin/shared.beam b/apps/albedo/test/fixtures/build-digest/asset/sdk/ebin/shared.beam new file mode 100644 index 0000000000000000000000000000000000000000..667511876486583e1e64db882c6988004d18a69f GIT binary patch literal 15 WcmXR&OwLYBPgO|HPf2C?&jkQ2l?9Oi literal 0 HcmV?d00001 diff --git a/apps/albedo/test/fixtures/build-digest/asset/sdk/priv/helper-link b/apps/albedo/test/fixtures/build-digest/asset/sdk/priv/helper-link new file mode 120000 index 000000000..f5d0149bb --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/asset/sdk/priv/helper-link @@ -0,0 +1 @@ +helper.py \ No newline at end of file diff --git a/apps/albedo/test/fixtures/build-digest/asset/sdk/priv/helper.py b/apps/albedo/test/fixtures/build-digest/asset/sdk/priv/helper.py new file mode 100644 index 000000000..2b5bd0ad9 --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/asset/sdk/priv/helper.py @@ -0,0 +1 @@ +print("changed helper") diff --git a/apps/albedo/test/fixtures/build-digest/_gleam_artefacts/cache.bin b/apps/albedo/test/fixtures/build-digest/base/albedo/_gleam_artefacts/cache.bin similarity index 100% rename from apps/albedo/test/fixtures/build-digest/_gleam_artefacts/cache.bin rename to apps/albedo/test/fixtures/build-digest/base/albedo/_gleam_artefacts/cache.bin diff --git a/apps/albedo/test/fixtures/build-digest/ebin/alpha.beam b/apps/albedo/test/fixtures/build-digest/base/albedo/ebin/alpha.beam similarity index 100% rename from apps/albedo/test/fixtures/build-digest/ebin/alpha.beam rename to apps/albedo/test/fixtures/build-digest/base/albedo/ebin/alpha.beam diff --git a/apps/albedo/test/fixtures/build-digest/ebin/sub/nested.beam b/apps/albedo/test/fixtures/build-digest/base/albedo/ebin/sub/nested.beam similarity index 100% rename from apps/albedo/test/fixtures/build-digest/ebin/sub/nested.beam rename to apps/albedo/test/fixtures/build-digest/base/albedo/ebin/sub/nested.beam diff --git a/apps/albedo/test/fixtures/build-digest/include/left.out b/apps/albedo/test/fixtures/build-digest/base/albedo/include/left.out similarity index 100% rename from apps/albedo/test/fixtures/build-digest/include/left.out rename to apps/albedo/test/fixtures/build-digest/base/albedo/include/left.out diff --git a/apps/albedo/test/fixtures/build-digest/priv/config.json b/apps/albedo/test/fixtures/build-digest/base/albedo/priv/config.json similarity index 100% rename from apps/albedo/test/fixtures/build-digest/priv/config.json rename to apps/albedo/test/fixtures/build-digest/base/albedo/priv/config.json diff --git a/apps/albedo/test/fixtures/build-digest/priv/deep/nested.txt b/apps/albedo/test/fixtures/build-digest/base/albedo/priv/deep/nested.txt similarity index 100% rename from apps/albedo/test/fixtures/build-digest/priv/deep/nested.txt rename to apps/albedo/test/fixtures/build-digest/base/albedo/priv/deep/nested.txt diff --git a/apps/albedo/test/fixtures/build-digest/base/albedo/priv/link.json b/apps/albedo/test/fixtures/build-digest/base/albedo/priv/link.json new file mode 100644 index 000000000..2b63c950f --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/base/albedo/priv/link.json @@ -0,0 +1 @@ +{"kind": "fixture"} diff --git a/apps/albedo/test/fixtures/build-digest/base/dependency/ebin/dependency.app b/apps/albedo/test/fixtures/build-digest/base/dependency/ebin/dependency.app new file mode 100644 index 000000000..c1c6c310a --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/base/dependency/ebin/dependency.app @@ -0,0 +1 @@ +{application, dependency, []}. diff --git a/apps/albedo/test/fixtures/build-digest/base/sdk/ebin/shared.beam b/apps/albedo/test/fixtures/build-digest/base/sdk/ebin/shared.beam new file mode 100644 index 0000000000000000000000000000000000000000..667511876486583e1e64db882c6988004d18a69f GIT binary patch literal 15 WcmXR&OwLYBPgO|HPf2C?&jkQ2l?9Oi literal 0 HcmV?d00001 diff --git a/apps/albedo/test/fixtures/build-digest/base/sdk/priv/helper-link b/apps/albedo/test/fixtures/build-digest/base/sdk/priv/helper-link new file mode 120000 index 000000000..f5d0149bb --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/base/sdk/priv/helper-link @@ -0,0 +1 @@ +helper.py \ No newline at end of file diff --git a/apps/albedo/test/fixtures/build-digest/base/sdk/priv/helper.py b/apps/albedo/test/fixtures/build-digest/base/sdk/priv/helper.py new file mode 100644 index 000000000..53e37a0d9 --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/base/sdk/priv/helper.py @@ -0,0 +1 @@ +print("helper") diff --git a/apps/albedo/test/fixtures/build-digest/changed/albedo b/apps/albedo/test/fixtures/build-digest/changed/albedo new file mode 120000 index 000000000..99b51daa2 --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/changed/albedo @@ -0,0 +1 @@ +../base/albedo \ No newline at end of file diff --git a/apps/albedo/test/fixtures/build-digest/changed/dependency b/apps/albedo/test/fixtures/build-digest/changed/dependency new file mode 120000 index 000000000..029b997a0 --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/changed/dependency @@ -0,0 +1 @@ +../base/dependency \ No newline at end of file diff --git a/apps/albedo/test/fixtures/build-digest/changed/sdk/ebin/shared.beam b/apps/albedo/test/fixtures/build-digest/changed/sdk/ebin/shared.beam new file mode 100644 index 0000000000000000000000000000000000000000..2ef7544383e0f66890a6b9bd9974143efa0b7c39 GIT binary patch literal 23 ecmXRdNJ%V7O;IRFOwLYBPgO|HPf2C?&jkQ!;s}@k literal 0 HcmV?d00001 diff --git a/apps/albedo/test/fixtures/build-digest/changed/sdk/priv/helper-link b/apps/albedo/test/fixtures/build-digest/changed/sdk/priv/helper-link new file mode 120000 index 000000000..f5d0149bb --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/changed/sdk/priv/helper-link @@ -0,0 +1 @@ +helper.py \ No newline at end of file diff --git a/apps/albedo/test/fixtures/build-digest/changed/sdk/priv/helper.py b/apps/albedo/test/fixtures/build-digest/changed/sdk/priv/helper.py new file mode 100644 index 000000000..53e37a0d9 --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/changed/sdk/priv/helper.py @@ -0,0 +1 @@ +print("helper") diff --git a/apps/albedo/test/fixtures/build-digest/deleted/albedo b/apps/albedo/test/fixtures/build-digest/deleted/albedo new file mode 120000 index 000000000..99b51daa2 --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/deleted/albedo @@ -0,0 +1 @@ +../base/albedo \ No newline at end of file diff --git a/apps/albedo/test/fixtures/build-digest/deleted/dependency b/apps/albedo/test/fixtures/build-digest/deleted/dependency new file mode 120000 index 000000000..029b997a0 --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/deleted/dependency @@ -0,0 +1 @@ +../base/dependency \ No newline at end of file diff --git a/apps/albedo/test/fixtures/build-digest/expected.txt b/apps/albedo/test/fixtures/build-digest/expected.txt new file mode 100644 index 000000000..cb01629e5 --- /dev/null +++ b/apps/albedo/test/fixtures/build-digest/expected.txt @@ -0,0 +1,5 @@ +base 0fd1ea9298559c24fde62c8f6ec297fd5b940795bc8a51a6fa73f8d4268f671e +changed 526565b8a0f0ced57c4d6338697a10473481bd938b4da530b34a9b119505b14d +added 4c222d16179f37f64130f7140dfd09825dc50412b3238779a136ef346afda4e0 +deleted a0ed306e092ab62d69a3688247308c520069d81b95b1506782e57cfd44d592a4 +asset babf0868807a5003acd7ceb4e8caa30f82c026c61deaea80c99c2d263be87ca5 diff --git a/apps/albedo/test/fixtures/build-digest/priv/link.json b/apps/albedo/test/fixtures/build-digest/priv/link.json deleted file mode 120000 index 0cffcb348..000000000 --- a/apps/albedo/test/fixtures/build-digest/priv/link.json +++ /dev/null @@ -1 +0,0 @@ -config.json \ No newline at end of file diff --git a/cli/cmd/albedo/build_identity.go b/cli/cmd/albedo/build_identity.go index 9a9255f88..7ff5a586d 100644 --- a/cli/cmd/albedo/build_identity.go +++ b/cli/cmd/albedo/build_identity.go @@ -10,6 +10,7 @@ import ( "path/filepath" "sort" "strings" + "syscall" "albedo/cli/internal/daemon" ) @@ -74,12 +75,12 @@ func hasEbin(dir string) bool { // digestTree reads a sealed build identity or hashes a mutable tree the way // the daemon hashes its own running tree (build_digest in // apps/albedo/src/albedo/lifecycle/build_identity.gleam): sha256 over the sorted relative -// paths and bytes of every regular file under ebin/ and priv/, symlinks +// paths and bytes of every regular file under each sibling app's ebin/ and priv/, symlinks // followed. An unreadable path fails the whole digest, the call the daemon's // walker makes too, and the shared fixture in apps/albedo/test/fixtures/build-digest pins // both implementations to one constant. func digestTree(appDir string) string { - if file, err := os.Open(filepath.Join(appDir, ".build-digest")); err == nil { + if file, err := os.Open(filepath.Join(appDir, ".build-digest-v2")); err == nil { data, err := io.ReadAll(io.LimitReader(file, 66)) file.Close() if err == nil && len(data) == 65 && data[64] == '\n' { @@ -89,11 +90,20 @@ func digestTree(appDir string) string { } } } + if !hasEbin(appDir) { + return "" + } + output := filepath.Dir(appDir) + entries, err := os.ReadDir(output) + if err != nil { + return "" + } var paths []string - for _, sub := range []string{"ebin", "priv"} { - root := filepath.Join(appDir, sub) - info, err := os.Stat(root) - if errors.Is(err, fs.ErrNotExist) { + applications := 0 + for _, entry := range entries { + app := filepath.Join(output, entry.Name()) + info, err := os.Stat(filepath.Join(app, "ebin")) + if errors.Is(err, fs.ErrNotExist) || errors.Is(err, syscall.ENOTDIR) { continue } if err != nil { @@ -102,11 +112,28 @@ func digestTree(appDir string) string { if !info.IsDir() { continue } - paths, err = appendTreePaths(paths, root, sub) - if err != nil { - return "" + applications++ + for _, sub := range []string{"ebin", "priv"} { + root := filepath.Join(app, sub) + info, err := os.Stat(root) + if errors.Is(err, fs.ErrNotExist) { + continue + } + if err != nil { + return "" + } + if !info.IsDir() { + continue + } + paths, err = appendTreePaths(paths, root, entry.Name()+"/"+sub, 0) + if err != nil { + return "" + } } } + if applications == 0 { + return "" + } sort.Strings(paths) hasher := sha256.New() // One buffer for every file: io.Copy from an *os.File allocates its own @@ -114,7 +141,7 @@ func digestTree(appDir string) string { buf := make([]byte, 32*1024) for _, rel := range paths { hasher.Write([]byte(rel)) - file, err := os.Open(filepath.Join(appDir, rel)) + file, err := os.Open(filepath.Join(output, rel)) if err != nil { return "" } @@ -127,7 +154,10 @@ func digestTree(appDir string) string { return hex.EncodeToString(hasher.Sum(nil)) } -func appendTreePaths(paths []string, dir, rel string) ([]string, error) { +func appendTreePaths(paths []string, dir, rel string, depth int) ([]string, error) { + if depth > 256 { + return nil, errors.New("build tree exceeds 256 directory levels") + } entries, err := os.ReadDir(dir) if err != nil { return nil, err @@ -141,7 +171,7 @@ func appendTreePaths(paths []string, dir, rel string) ([]string, error) { } switch { case info.IsDir(): - if paths, err = appendTreePaths(paths, child, childRel); err != nil { + if paths, err = appendTreePaths(paths, child, childRel, depth+1); err != nil { return nil, err } case info.Mode().IsRegular(): diff --git a/cli/cmd/albedo/build_identity_test.go b/cli/cmd/albedo/build_identity_test.go index f5fb5f364..629a676ce 100644 --- a/cli/cmd/albedo/build_identity_test.go +++ b/cli/cmd/albedo/build_identity_test.go @@ -21,16 +21,24 @@ func write(t *testing.T, path, content string) { // fixture in apps/albedo/test/fixtures/build-digest pins both implementations together. func TestDigestTreeMatchesTheSharedFixture(t *testing.T) { fixture := filepath.Join("..", "..", "..", "apps", "albedo", "test", "fixtures", "build-digest") - const want = "a8f2d0de5c26845d69d69f9a98111ab795b83d4ab24e6f18068b57145c13fe42" - if got := digestTree(fixture); got != want { - t.Fatalf("digestTree(fixture) = %q, want %q", got, want) + expected, err := os.ReadFile(filepath.Join(fixture, "expected.txt")) + if err != nil { + t.Fatal(err) + } + for line := range strings.SplitSeq(strings.TrimSpace(string(expected)), "\n") { + fields := strings.Fields(line) + t.Run(fields[0], func(t *testing.T) { + if got := digestTree(filepath.Join(fixture, fields[0], "albedo")); got != fields[1] { + t.Fatalf("digest = %q, want %q", got, fields[1]) + } + }) } } // An unreadable path must fail the whole digest rather than hash a subset the // daemon would hash differently. func TestDigestTreeFailsClosedOnUnreadablePaths(t *testing.T) { - root := t.TempDir() + root := filepath.Join(t.TempDir(), "albedo") write(t, filepath.Join(root, "ebin", "readable.beam"), "readable") sealed := filepath.Join(root, "ebin", "sealed.beam") write(t, sealed, "sealed") @@ -44,11 +52,15 @@ func TestDigestTreeFailsClosedOnUnreadablePaths(t *testing.T) { } func TestDigestTreeUsesOnlyValidSealedIdentities(t *testing.T) { - root := t.TempDir() + root := filepath.Join(t.TempDir(), "albedo") beam := filepath.Join(root, "ebin", "module.beam") write(t, beam, "original beam") want := digestTree(root) - sidecar := filepath.Join(root, ".build-digest") + write(t, filepath.Join(root, ".build-digest"), strings.Repeat("0", 64)+"\n") + if got := digestTree(root); got != want { + t.Fatalf("old seal accepted: %q", got) + } + sidecar := filepath.Join(root, ".build-digest-v2") write(t, sidecar, want+"\n") write(t, beam, "a mutable copy must discard its seal") if got := digestTree(root); got != want { @@ -63,7 +75,7 @@ func TestDigestTreeUsesOnlyValidSealedIdentities(t *testing.T) { } func TestAppDirRecognizesTheKnownLayouts(t *testing.T) { - root := t.TempDir() + root := filepath.Join(t.TempDir(), "albedo") packaged := filepath.Join(root, "pkg") write(t, filepath.Join(packaged, "bin", "albedo-daemon"), "#!/bin/sh\n") diff --git a/cli/internal/localdaemon/standby_unix.go b/cli/internal/localdaemon/standby_unix.go index 2facf4082..5e47b942a 100644 --- a/cli/internal/localdaemon/standby_unix.go +++ b/cli/internal/localdaemon/standby_unix.go @@ -61,7 +61,7 @@ func sealedDigest(executable string) string { } dir := filepath.Dir(resolved) for _, app := range []string{filepath.Join(dir, "..", "lib", "albedo", "albedo"), filepath.Join(dir, "albedo"), filepath.Dir(filepath.Dir(dir))} { - data, err := os.ReadFile(filepath.Join(app, ".build-digest")) + data, err := os.ReadFile(filepath.Join(app, ".build-digest-v2")) if err == nil && len(data) == 65 && data[64] == '\n' && strings.Trim(string(data[:64]), "0123456789abcdef") == "" { return string(data[:64]) } diff --git a/docs/daemon-lifecycle.md b/docs/daemon-lifecycle.md index 66002733f..da5f48a98 100644 --- a/docs/daemon-lifecycle.md +++ b/docs/daemon-lifecycle.md @@ -179,14 +179,9 @@ The daemon owns its home directory and token: by default it uses `~/.albedo` and generates a random token. It publishes `daemon.json` atomically with mode `0600` inside the private home directory. The record contains the endpoint, PID, protocol, token, and optional build identity: an `ALBEDO_BUILD` label plus a -content digest of the code tree the daemon runs (sha256 over the sorted relative -paths and bytes of every regular file under the application's `ebin/` and -`priv/` trees, symlinks followed. The CLI hashes its candidate build with the -same recipe, pinned across both implementations by the fixture in -[build-digest fixtures](../apps/albedo/test/fixtures/build-digest)). It is a -local discovery file, not an API compatibility contract. Discovery checks the -recorded PID against the authenticated `/server` response when the daemon -reports one. +content [build identity](#build-identity). It is a local discovery file, not an +API compatibility contract. Discovery checks the recorded PID against the +authenticated `/server` response when the daemon reports one. The shared [`apps/albedo/priv/bin/albedo-daemon`](../apps/albedo/priv/bin/albedo-daemon) @@ -211,6 +206,63 @@ Cancellation ends discovery, lock acquisition, startup waits, shutdown waits, and the restart prompt. It does not kill a detached daemon that has already started. A client disconnect cannot stop a daemon shared by other clients. +## Build identity + +[`build_identity`](../apps/albedo/src/albedo/lifecycle/build_identity.gleam) +owns the digest recipe, shared with the +[CLI candidate reader](../cli/cmd/albedo/build_identity.go). Both hash compiled +runtime output, not source files. A package edit becomes visible after rebuild. + +The output is the directory containing the `albedo` application and its sibling +applications. Discovery selects every immediate child with an `ebin` directory, +matching the shipment and snapshot launchers' `*/ebin` code paths. This includes +workspace packages, extensions, and third-party dependencies. Development output +also includes compiled test applications. OTP's installed runtime outside this +output and arbitrary extra code paths supplied through `ERL_FLAGS` are outside +this identity. The `ALBEDO_BUILD` label remains available for launcher identity. + +Each application's `ebin` and optional `priv` trees contribute every regular +file. This includes application metadata, Python files, native helpers, and +other assets. Symlinks are followed, including directory links and external +helper targets, but their logical relative paths are hashed. Paths use `/`, +start with the output application name, and sort by UTF-8 bytes. SHA-256 +consumes each path's bytes followed immediately by that file's bytes, in that +order, without separators, timestamps, permissions, or absolute paths. The +shared [fixtures](../apps/albedo/test/fixtures/build-digest) pin this recipe in +Go and Gleam with package changes, additions, deletions, and linked helper +assets. + +Missing optional roots contribute nothing. Entries without an `ebin` directory +are not applications. An absent albedo `ebin`, empty application discovery, +unreadable path or file, or broken link within a tree returns an unknown +identity, never a digest of a readable subset. Special files are ignored. +Traversal fails beyond 256 directory levels, which also bounds directory-link +cycles. Builders must provide readable, stable trees without cycles while +hashing. + +Builders write `.build-digest-v2` beside albedo's `ebin` after all application +contents and helper fixups are final. The seal contains exactly 64 lowercase +hexadecimal digits and a newline. Readers ignore old `.build-digest` files and +malformed seals, then hash the output. A valid seal is trusted builder output, +not authentication or a check for later tampering. Never retain a seal or +extension-cache sidecars when changing a sealed tree. Source `albedo-build` +removes them before compiling. `seal_build` removes old sidecars, calculates the +application digest once, writes the extension cache with that key, and publishes +the seal last. Sidecars are outside `ebin` and `priv` and do not hash +themselves. Nix seals after fixup, release packaging after helper installation +and Python bytecode compilation, and test snapshots after copying all +applications. + +The daemon captures its identity once before moving code paths into +`code-cache`, including an unknown identity if hashing fails. It keeps that boot +identity for its lifetime. Standbys accept only the versioned seal and retain +their captured identity through handover. The CLI uses the same seal validation +and recipe. Older running daemons still report their old root-only digest, so an +updated CLI sees a difference and uses the existing restart confirmation. This +does not change service ownership, ACP attachment, nonterminal attachment, or +restart recovery. Restart interrupts active work and preserves saved sessions +through the existing recovery flow. + ## Client development Use `Attach(ctx, snapshot, rediscovery)` for a validated API connection. Supply diff --git a/e2e/build_identity_support.py b/e2e/build_identity_support.py new file mode 100644 index 000000000..2f19ff612 --- /dev/null +++ b/e2e/build_identity_support.py @@ -0,0 +1,67 @@ +"""Rebuild one library in a private runtime output owned by the lifecycle harness.""" + +from pathlib import Path +import shlex +import shutil +import subprocess + +from harness import Albedo, ROOT + + +class PackageBuild: + def __init__(self, app: Albedo) -> None: + self.output = app.root / "runtime" + source = Path(app.env["ALBEDO_DAEMON"]).parent + for package in source.iterdir(): + if (package / "ebin").is_dir(): + target = self.output / package.name + target.mkdir(parents=True) + for tree in ("ebin", "priv"): + if (package / tree).is_dir(): + shutil.copytree(package / tree, target / tree) + self.package = app.root / "albedo_bytes" + shutil.copytree(ROOT / "packages/albedo_bytes/src", self.package / "src") + shutil.copy(ROOT / "packages/albedo_bytes/gleam.toml", self.package) + self.rebuild("before") + # A recognized packaged layout runs the same private output. The + # harness owns the daemon and cleanup, including any upgraded process. + launcher = app.root / "bin/albedo-daemon" + launcher.parent.mkdir() + library = app.root / "lib" + library.mkdir() + (library / "albedo").symlink_to(self.output) + launcher.write_text( + "#!/bin/sh\nexec " + + shlex.quote(str(ROOT / "apps/albedo/priv/bin/albedo-daemon")) + + " erl -pa " + + shlex.quote(str(self.output)) + + "/*/ebin -eval 'albedo@@main:run(albedo)' -noshell -extra \"$@\"\n" + ) + launcher.chmod(0o755) + app.env.update( + ALBEDO_DAEMON=str(launcher), ALBEDO_STANDBY="0", ALBEDO_INSPECT="1" + ) + app.env.pop("ALBEDO_PRELOAD", None) + + def rebuild(self, value: str) -> None: + (self.package / "src/albedo_bytes/build_probe.gleam").write_text( + f'pub fn value() -> String {{ "{value}" }}\n' + ) + subprocess.run( + [ + "gleam", + "compile-package", + "--target", + "erlang", + "--no-dev", + "--package", + str(self.package), + "--out", + str(self.output / "albedo_bytes"), + "--lib", + str(ROOT / "apps/albedo/build/dev/erlang"), + ], + check=True, + capture_output=True, + text=True, + ) diff --git a/e2e/daemon_test.py b/e2e/daemon_test.py index 44063ade3..b966baac7 100644 --- a/e2e/daemon_test.py +++ b/e2e/daemon_test.py @@ -180,7 +180,7 @@ def delayed_request(app, method, path, body, headers): class DaemonTest(unittest.TestCase): def test_server_reports_the_sealed_build_identity(self): assert harness._executable is not None - stamp = Path(harness._executable).parent / "albedo" / ".build-digest" + stamp = Path(harness._executable).parent / "albedo" / ".build-digest-v2" expected = stamp.read_text().strip() self.assertRegex(expected, r"^[0-9a-f]{64}$") with Albedo() as app: @@ -990,7 +990,7 @@ class DaemonTest(unittest.TestCase): albedo.mkdir() for entry in ("ebin", "priv"): (albedo / entry).symlink_to((source / "albedo" / entry).resolve()) - for sidecar in (".build-digest", ".extensions-key"): + for sidecar in (".build-digest-v2", ".extensions-key"): shutil.copy(source / "albedo" / sidecar, albedo / sidecar) subprocess.run( [ diff --git a/e2e/lifecycle_test.py b/e2e/lifecycle_test.py index bf75b350f..3118fe02b 100644 --- a/e2e/lifecycle_test.py +++ b/e2e/lifecycle_test.py @@ -1,5 +1,6 @@ """CLI attachment and startup must preserve an independently owned real daemon.""" +import hashlib import json import os import pty @@ -13,6 +14,7 @@ import termios import time import unittest +from build_identity_support import PackageBuild from inspect_support import Inspection from harness import Albedo, Provider, alive, exclusive, operation_id, python, text @@ -307,6 +309,70 @@ class LifecycleTest(unittest.TestCase): self.assertNotEqual(app.connection["pid"], previous["pid"]) self.assertNotEqual(app.connection["token"], previous["token"]) + def test_package_rebuild_offers_upgrade_and_unchanged_build_keeps_sessions(self): + builds = [] + + def prepare(app): + builds.append(PackageBuild(app)) + + with Albedo(prepare=prepare) as app: + build = builds[0] + previous = dict(app.connection) + session = app.session() + app.prompt(session, "keep this session through the package upgrade").close() + app.idle(session) + history = app.history(session)["items"] + expression = "io:put_chars(Call('albedo_bytes@build_probe', value, []))" + self.assertEqual(Inspection(app).evaluate(expression), "before") + # A terminal would prompt for an unknown identity. With the same + # complete identity it exits without waiting for an answer. + unchanged = TerminalCommand(app, "daemon") + self.assertEqual(unchanged.process.wait(timeout=20), 0) + os.close(unchanged.master) + self.assertEqual( + json.loads((app.home / "daemon.json").read_text()), previous + ) + root_files = { + str(path.relative_to(build.output)): hashlib.sha256( + path.read_bytes() + ).hexdigest() + for path in (build.output / "albedo").rglob("*") + if path.is_file() + } + build.rebuild("after") + self.assertEqual( + root_files, + { + str(path.relative_to(build.output)): hashlib.sha256( + path.read_bytes() + ).hexdigest() + for path in (build.output / "albedo").rglob("*") + if path.is_file() + }, + ) + self.assertEqual(Inspection(app).evaluate(expression), "before") + self.assertEqual( + json.load(app.api("/server"))["digest"], previous["digest"] + ) + terminal = TerminalCommand(app, "daemon") + terminal.prompt() + self.assertEqual(terminal.answer("y"), 0) + app.daemon._refresh() + self.assertNotEqual(app.connection["pid"], previous["pid"]) + self.assertNotEqual(app.connection["digest"], previous["digest"]) + self.assertFalse(alive(previous["pid"])) + self.assertEqual(Inspection(app).evaluate(expression), "after") + self.assertEqual(app.history(session)["items"], history) + app.prompt(session, "continue after upgrade").close() + app.idle(session) + unchanged = TerminalCommand(app, "daemon") + self.assertEqual(unchanged.process.wait(timeout=20), 0) + os.close(unchanged.master) + self.assertEqual( + json.loads((app.home / "daemon.json").read_text())["pid"], + app.connection["pid"], + ) + def test_restart_confirmation_cannot_replace_a_newer_daemon(self): with Albedo() as app: terminal = TerminalCommand(app, "daemon") @@ -323,6 +389,10 @@ class LifecycleTest(unittest.TestCase): self, ): fixture = {} + builds = [] + + def prepare(app): + builds.append(PackageBuild(app)) def script(request): messages = request["messages"] @@ -343,7 +413,7 @@ class LifecycleTest(unittest.TestCase): provider = Provider(script) self.addCleanup(provider.close) - with Albedo(provider) as app: + with Albedo(provider, prepare=prepare) as app: fixture["effect"] = app.workspace / "effect" session = app.session() operation = operation_id() @@ -365,6 +435,7 @@ class LifecycleTest(unittest.TestCase): == "running" ) previous = dict(app.connection) + builds[0].rebuild("after") terminal = TerminalCommand(app, "daemon") terminal.prompt() self.assertEqual(terminal.answer("y"), 0) diff --git a/e2e/standby_test.py b/e2e/standby_test.py index f1b06a969..da20bf3f8 100644 --- a/e2e/standby_test.py +++ b/e2e/standby_test.py @@ -26,7 +26,7 @@ def snapshot(): def snapshot_digest(): - return (snapshot() / "albedo" / ".build-digest").read_text().strip() + return (snapshot() / "albedo" / ".build-digest-v2").read_text().strip() class Standbys: @@ -210,7 +210,7 @@ def other_build(out): for entry in ("ebin", "priv"): (albedo / entry).symlink_to((source / "albedo" / entry).resolve()) digest = "f" * 64 - (albedo / ".build-digest").write_text(digest + "\n") + (albedo / ".build-digest-v2").write_text(digest + "\n") launcher = out / "albedo-daemon" launcher.write_text( "#!/bin/sh\n" diff --git a/release/inside.sh b/release/inside.sh index c02c1769e..9b0579cbb 100755 --- a/release/inside.sh +++ b/release/inside.sh @@ -128,7 +128,7 @@ tar -xzf "$(fetch "$RG_URL")" -C /tmp && cp /tmp/ripgrep-*/rg "$tree/bin/rg" "$py" "$tree/lib/albedo/albedo/priv/python" >/dev/null || true ALBEDO_BUILD_APP="$tree/lib/albedo/albedo" erl +S 2:2 -pa "$tree"/lib/albedo/*/ebin -noshell \ -eval 'application:ensure_all_started(crypto), {ok, nil} = albedo@lifecycle@build_identity:seal_build(unicode:characters_to_binary(os:getenv("ALBEDO_BUILD_APP"))), halt().' -test -s "$tree/lib/albedo/albedo/.build-digest" +test -s "$tree/lib/albedo/albedo/.build-digest-v2" # --- every bundled ELF may need only glibc, or a library the tree itself ships bundled_libs="$(find "$tree" -name '*.so*' -printf '%f\n' | sort -u)" diff --git a/robot-docs/contributing.md b/robot-docs/contributing.md index da3fd36ec..0e648ac10 100644 --- a/robot-docs/contributing.md +++ b/robot-docs/contributing.md @@ -3,16 +3,6 @@ These project rules guide implementation changes. The linked feature pages describe current behavior and its limits. -> **Restart the daemon after a change confined to a workspace package.** The -> build digest that tells the CLI a checkout was rebuilt covers only the -> `albedo` application, not the libraries under `packages/` or the extensions -> under `extensions/`. After an edit only to a package, the CLI keeps the -> running daemon and its old package code. Run `albedo daemon --stop` and then -> `albedo daemon` under the same environment before testing the change by hand. -> The gate and the end-to-end harness start their own daemons from a fresh -> build, so they are not affected. See -> [how albedo consumes a package](workspace-packages.md#how-albedo-consumes-a-package). - ## Choose the owning layer Core modules under `apps/albedo/src/albedo` are grouped by subsystem. The @@ -85,8 +75,9 @@ module that calls it. Packages are [layered](workspace-packages.md#layers): a package depends only on layers below its own, and nothing but albedo depends on an extension package. Run `test/packages.sh check` after changing a package or its `gleam.toml`, and re-lock a refused manifest with `test/packages.sh sync`, -never by hand. Restart the daemon after a change confined to a package, as the -note at the top of this page says. +never by hand. Rebuild before attaching a CLI to test package changes. The +[build identity](../docs/daemon-lifecycle.md#build-identity) covers every +runtime application. Keep a `package.nix` beside every first-party `gleam.toml`. Call the shared `mkGleamPackage` helper and keep package overrides colocated. Discovery imports diff --git a/robot-docs/workspace-packages.md b/robot-docs/workspace-packages.md index 6fe0c8d57..6a1f64c21 100644 --- a/robot-docs/workspace-packages.md +++ b/robot-docs/workspace-packages.md @@ -588,30 +588,19 @@ atom, so a module renamed as it moves into a package must be renamed there too. [test/manual/record_boot_modules.py](../test/manual/record_boot_modules.py) records every loaded module whatever its application. -The [build digest](../apps/albedo/src/albedo/lifecycle/build_identity.gleam) -hashes only the `albedo` application's `ebin` and `priv`. A change confined to a -workspace package leaves a source checkout's digest unchanged, so the CLI does -not see a rebuilt checkout as a different build, and keeps the running daemon -with the old package code until it is restarted explicitly. A differing -`ALBEDO_BUILD` label does not help: equal nonempty digests decide sameness. Nix -builds are not affected in practice, because the digest also covers files that -embed the daemon's store path, which changes when a package does. Restart the -daemon after changing only a package until the digest covers every workspace -application. Since the clock, protect, byte, environment, process, port, file -and JSON helpers, the HTTP clients, the SSE parser, the OAuth and JWT pieces, -the SQLite pool and checkpointer, image headers, negotiation, the settings -journal, the model types, the stream reducer and pump, the OpenAI-compatible, -Anthropic and Google wires, the whole SDK, the shared extension libraries, and -the extensions that moved into packages, a change to any of them falls in this -gap too. - -A sealed build's extension cache is keyed apart from the build digest. It holds -functions of the SDK's and other packages' modules, so `seal_build` keys it on -`applications_digest`, the `ebin` and `priv` trees of every application in the -sealed output, and writes that key to `.extensions-key` beside albedo's -`.build-digest`, after the cache. A cache whose key does not match is not read, -so a seal after a change confined to a package never boots from the cache an -earlier seal left. The daemon reads the cache after +The [build identity](../docs/daemon-lifecycle.md#build-identity) covers every +application in the compiled runtime output, including workspace libraries, +extensions, and third-party dependencies. Rebuild after a package edit. The CLI +then offers the existing restart flow when the running daemon has older code. An +unchanged build keeps the daemon and its sessions warm. + +A sealed build's extension cache uses the same digest as the build identity. It +holds functions of the SDK's and other packages' modules, so `seal_build` keys +it on `applications_digest`, the `ebin` and `priv` trees of every application in +the sealed output, and writes that key to `.extensions-key` beside albedo's +`.build-digest-v2`, after the cache. A cache whose key does not match is not +read, so a seal after a change confined to a package never boots from the cache +an earlier seal left. The daemon reads the cache after [`boot_code`](../apps/albedo/src/albedo/lifecycle/boot_code.gleam) points the code path at its copies under `code-cache`, so the copy of albedo's application carries the cache and its key with its beams. A build in a pinned Nix store path diff --git a/test/harness/extension_cache_seal_test.py b/test/harness/extension_cache_seal_test.py index 3743f5efa..6727615e4 100644 --- a/test/harness/extension_cache_seal_test.py +++ b/test/harness/extension_cache_seal_test.py @@ -3,8 +3,7 @@ The cache holds the installed extensions' declarations, and their functions name the code of the module that made each one by checksum. Most of them are the SDK's, which lives in the albedo_sdk application, not albedo's. A change -to albedo_sdk alone leaves albedo's build digest as it was, so a cache keyed on -that digest would be decoded into functions the changed code no longer has. +to albedo_sdk alone changes the build identity and cache key together. The seal keys the cache on every application, and a cache an earlier seal left behind is not read. Only a sealed tree shows this: a daemon scenario boots a build that was sealed once. @@ -83,7 +82,7 @@ class ExtensionCacheSealTest(unittest.TestCase): " {ok, nil} = 'albedo@lifecycle@build_identity':seal_build(" f"<<{json.dumps(str(self.albedo))}/utf8>>)," ) - return (self.albedo / ".build-digest").read_text() + return (self.albedo / ".build-digest-v2").read_text() def test_a_sealed_build_boots_from_its_cache_and_its_functions_run(self): self.seal() @@ -117,7 +116,7 @@ class ExtensionCacheSealTest(unittest.TestCase): app = self.out / "albedo_sdk" / "ebin" / "albedo_sdk.app" app.write_text(app.read_text() + "%% rebuilt\n") resealed, rekeyed = self.seal() - self.assertEqual(resealed, digest) + self.assertNotEqual(resealed, digest) self.assertNotEqual(rekeyed, key) # A cache the earlier seal wrote, left beside the new key. (self.albedo / ".extensions.etf").write_bytes(stale) @@ -128,14 +127,19 @@ class ExtensionCacheSealTest(unittest.TestCase): ) def test_a_seal_that_writes_no_cache_removes_the_old_one(self): - digest, _ = self.seal() + self.seal() # An application whose files cannot be read, so the seal cannot key # a cache. Albedo's own application still reads. unreadable = self.out / "unreadable" / "ebin" / "unreadable.beam" unreadable.parent.mkdir(parents=True) unreadable.write_bytes(b"") unreadable.chmod(0) - self.assertEqual(self.seal_digest(), digest) + self.vm( + "{ok, _} = application:ensure_all_started(crypto)," + " {error, <<\"unreadable_build\">>} = 'albedo@lifecycle@build_identity':seal_build(" + f"<<{json.dumps(str(self.albedo))}/utf8>>)," + ) + self.assertFalse((self.albedo / ".build-digest-v2").exists()) self.assertFalse((self.albedo / ".extensions.etf").exists()) self.assertFalse((self.albedo / ".extensions-key").exists())