From f344ddf08140b38947d53fbfa4bdb8b68d4d9861 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Fri, 20 Nov 2026 01:17:12 -0500 Subject: [PATCH] test: port the Erlang tests that depended on Gleam record layout gleam build does not recompile an Erlang file when only a generated record header it includes changes, so after a record change gleam test ran stale support code and failed with badrecord (the runtime State record broke a local gate this way). Eight Erlang test files either -included those headers or built and matched Gleam values as positional tuples. All eight are Gleam now, with @external bindings only for OTP calls Gleam has no library for (suspend_process, process_info, trace, sys:get_state, file:open/read, system_monitor, global:whereis_name): - stalls_test, running_test, transfers_test, codex_images_test, attachment_storage_test and daemon_request_test replace their albedo_* Erlang modules one for one; - sdk_c_support replaces albedo_sdk_c_test_support for the four composition tests that bind it; - ownership_support replaces albedo_runtime_ownership_test_support. It reads the runtime's state as a typed State, and matches mailbox messages (a driver Rebind, a runtime Finished or Submitted) by coercing them to their Gleam type, so the compiler keeps it in step. The spare-budget scenario recompiled boot and runtime from their abstract forms to swap in a gated spare starter. runtime.Options now carries start_spare (python.start_spare by default; the state's spare worker calls it), so the scenario is an ordinary Gleam test that also waits on the runtime's state instead of tracing boot functions. No Erlang test file includes a generated record header now, and robot-docs/contributing.md says not to. spare_quiet_test, which boots a real spare, takes albedo_property.within(60) in place of eunit's 5 s. --- apps/albedo/src/albedo/runtime.gleam | 8 +- apps/albedo/src/albedo/runtime/boot.gleam | 2 +- apps/albedo/src/albedo/runtime/state.gleam | 4 + .../composition/albedo_codex_images_test.erl | 52 -- .../composition/albedo_sdk_c_test_support.erl | 78 --- .../albedo/composition/cache_files_test.gleam | 21 +- .../albedo/composition/claude_wire_test.gleam | 6 +- .../composition/codex_images_test.gleam | 57 ++ .../composition/extension_digests_test.gleam | 6 +- .../albedo/composition/sdk_c_support.gleam | 120 ++++ .../composition/sdk_calendar_test.gleam | 6 +- .../albedo/observation/albedo_stalls_test.erl | 98 --- .../test/albedo/observation/stalls_test.gleam | 99 +++ .../albedo_runtime_ownership_test_support.erl | 522 --------------- .../albedo/runtime/ownership_support.gleam | 600 ++++++++++++++++++ .../runtime/runtime_ownership_test.gleam | 96 +-- .../albedo/runtime/spare_quiet_test.gleam | 5 +- .../session/albedo_daemon_request_test.erl | 94 --- .../albedo/session/albedo_running_test.erl | 107 ---- .../albedo/session/daemon_request_test.gleam | 131 ++++ .../test/albedo/session/running_test.gleam | 167 +++++ .../albedo/session/turn_lifecycle_test.gleam | 11 +- .../albedo_attachment_storage_test.erl | 23 - .../storage/attachment_storage_test.gleam | 45 ++ .../albedo/transfer/albedo_transfers_test.erl | 46 -- .../test/albedo/transfer/transfers_test.gleam | 53 ++ robot-docs/contributing.md | 9 + robot-docs/runtime.md | 2 +- 28 files changed, 1387 insertions(+), 1081 deletions(-) delete mode 100644 apps/albedo/test/albedo/composition/albedo_codex_images_test.erl delete mode 100644 apps/albedo/test/albedo/composition/albedo_sdk_c_test_support.erl create mode 100644 apps/albedo/test/albedo/composition/codex_images_test.gleam create mode 100644 apps/albedo/test/albedo/composition/sdk_c_support.gleam delete mode 100644 apps/albedo/test/albedo/observation/albedo_stalls_test.erl create mode 100644 apps/albedo/test/albedo/observation/stalls_test.gleam delete mode 100644 apps/albedo/test/albedo/runtime/albedo_runtime_ownership_test_support.erl create mode 100644 apps/albedo/test/albedo/runtime/ownership_support.gleam delete mode 100644 apps/albedo/test/albedo/session/albedo_daemon_request_test.erl delete mode 100644 apps/albedo/test/albedo/session/albedo_running_test.erl create mode 100644 apps/albedo/test/albedo/session/daemon_request_test.gleam create mode 100644 apps/albedo/test/albedo/session/running_test.gleam delete mode 100644 apps/albedo/test/albedo/storage/albedo_attachment_storage_test.erl create mode 100644 apps/albedo/test/albedo/storage/attachment_storage_test.gleam delete mode 100644 apps/albedo/test/albedo/transfer/albedo_transfers_test.erl create mode 100644 apps/albedo/test/albedo/transfer/transfers_test.gleam diff --git a/apps/albedo/src/albedo/runtime.gleam b/apps/albedo/src/albedo/runtime.gleam index 1c897f11e..dd5fccc60 100644 --- a/apps/albedo/src/albedo/runtime.gleam +++ b/apps/albedo/src/albedo/runtime.gleam @@ -48,7 +48,7 @@ import albedo_sdk/storage import albedo_sdk/store import gleam/dict import gleam/dynamic/decode -import gleam/erlang/process.{type Subject} +import gleam/erlang/process.{type Pid, type Subject} import gleam/erlang/reference import gleam/int import gleam/io @@ -261,6 +261,8 @@ pub type Options { spares: Int, /// Monotonic milliseconds, for how long spares stay wanted. now: fn() -> Int, + /// Warms one spare kernel, preloading the given modules. + start_spare: fn(Pid, List(String)) -> Result(python.Spare, python.Error), ) } @@ -271,6 +273,7 @@ pub fn default_options() -> Options { open_kernel: kernels.open_with_spare, spares: spare_target(), now: albedo_clock.monotonic_ms, + start_spare: python.start_spare, ) } @@ -280,7 +283,7 @@ pub fn start_with_options( config: extensions.Config, options: Options, ) -> Result(Runtime, actor.StartError) { - let Options(open_kernel:, spares:, now:) = options + let Options(open_kernel:, spares:, now:, start_spare:) = options let installed = config.extensions let default_enabled = config.default_enabled // Extension setup includes schema creation and may wait on a busy disk. @@ -389,6 +392,7 @@ pub fn start_with_options( working: dict.new(), open_kernel: open_kernel, now: now, + start_spare: start_spare, )) // Admitted workers are monitored; their exits arrive beside messages. |> actor.selecting( diff --git a/apps/albedo/src/albedo/runtime/boot.gleam b/apps/albedo/src/albedo/runtime/boot.gleam index 3e98545cf..2e716357f 100644 --- a/apps/albedo/src/albedo/runtime/boot.gleam +++ b/apps/albedo/src/albedo/runtime/boot.gleam @@ -266,7 +266,7 @@ fn start( Some(request), fn() { albedo_protect.attempt(fn() { - python.start_spare(runtime_owner, preload) + state.start_spare(runtime_owner, preload) }) |> result.replace_error(python.Unavailable("spare worker exited")) |> result.flatten diff --git a/apps/albedo/src/albedo/runtime/state.gleam b/apps/albedo/src/albedo/runtime/state.gleam index bd7e4a9f6..6fdc481ce 100644 --- a/apps/albedo/src/albedo/runtime/state.gleam +++ b/apps/albedo/src/albedo/runtime/state.gleam @@ -434,6 +434,10 @@ pub type State { open_kernel: KernelOpener, /// Monotonic milliseconds, for `spare_demand`. now: fn() -> Int, + /// Warms one spare kernel for the runtime, preloading these modules, on + /// a spare worker: `python.start_spare` in the daemon. + start_spare: fn(process.Pid, List(String)) -> + Result(python.Spare, python.Error), ) } diff --git a/apps/albedo/test/albedo/composition/albedo_codex_images_test.erl b/apps/albedo/test/albedo/composition/albedo_codex_images_test.erl deleted file mode 100644 index 07c164a6d..000000000 --- a/apps/albedo/test/albedo/composition/albedo_codex_images_test.erl +++ /dev/null @@ -1,52 +0,0 @@ -%% Verify the credential-bearing transport rejects destination confusion before -%% opening a socket. Native calls exercise the boundary even if settings validation -%% is bypassed; no credential store or external provider is involved. --module(albedo_codex_images_test). --include_lib("eunit/include/eunit.hrl"). - -credential_destination_test() -> - Previous = os:getenv("ALBEDO_TEST_CODEX_IMAGE_ENDPOINT"), - try - os:unsetenv("ALBEDO_TEST_CODEX_IMAGE_ENDPOINT"), - [ - rejected(Url, <<"private-token">>, <<"private-account">>) - || Url <- [ - <<"https://example.invalid/backend-api/codex/images/generations">>, - <<"http://127.0.0.1:1/images/generations">>, - <<"https://chatgpt.com@127.0.0.1/backend-api/codex/images/generations">>, - <<"https://chatgpt.com:444/backend-api/codex/images/generations">>, - <<"https://chatgpt.com/backend-api/codex/images/generations?other=1">>, - <<"https://chatgpt.com/backend-api/codex/images/generations#other">>, - <<"https://chatgpt.com/other/images/generations">> - ] - ], - Url = <<"https://chatgpt.com/backend-api/codex/images/generations">>, - os:putenv("ALBEDO_TEST_CODEX_IMAGE_ENDPOINT", "http://127.0.0.1:1"), - rejected(Url, <<"private-token">>, <<"image-fixture-account">>), - rejected(Url, <<"image-fixture-access">>, <<"private-account">>), - [ - begin - os:putenv("ALBEDO_TEST_CODEX_IMAGE_ENDPOINT", Endpoint), - rejected(Url, <<"image-fixture-access">>, <<"image-fixture-account">>) - end - || Endpoint <- [ - "https://example.invalid", - "http://127.0.0.1:1?x=1", - "http://user@127.0.0.1:1", - "http://127.0.0.1:1#x" - ] - ] - after - case Previous of - false -> os:unsetenv("ALBEDO_TEST_CODEX_IMAGE_ENDPOINT"); - Value -> os:putenv("ALBEDO_TEST_CODEX_IMAGE_ENDPOINT", Value) - end - end. - -rejected(Url, Token, Account) -> - ?assertMatch( - {error, _}, - 'albedo_ext_codex@images':post( - Url, Token, Account, <<"s">>, <<"c">>, <<"{}">> - ) - ). diff --git a/apps/albedo/test/albedo/composition/albedo_sdk_c_test_support.erl b/apps/albedo/test/albedo/composition/albedo_sdk_c_test_support.erl deleted file mode 100644 index d1dcb6451..000000000 --- a/apps/albedo/test/albedo/composition/albedo_sdk_c_test_support.erl +++ /dev/null @@ -1,78 +0,0 @@ --module(albedo_sdk_c_test_support). --export([ - codex_legacy/1, - zone/2, - home/1, - mode/1, - unreadable_cache/1, - webhook_headers/0 -]). --include_lib("kernel/include/file.hrl"). - -%% libc caches TZ, so calendar fixtures need a fresh VM for each zone. -zone(Zone, Function) -> - Args = - ["+S", "2", "-noshell", "-pa"] ++ code:get_path() ++ - [ - "-eval", - "'albedo@composition@sdk_calendar_test':" ++ binary_to_list(Function) ++ - "(), halt()." - ], - Port = open_port( - {spawn_executable, os:find_executable("erl")}, - [binary, exit_status, stderr_to_stdout, {args, Args}, {env, [{"TZ", binary_to_list(Zone)}]}] - ), - await(Port, <<>>). - -await(Port, Output) -> - receive - {Port, {data, Bytes}} -> await(Port, <>); - {Port, {exit_status, 0}} -> nil; - {Port, {exit_status, Status}} -> error({calendar_fixture_failed, Status, Output}) - after 15000 -> - port_close(Port), - error(calendar_fixture_timeout) - end. - -home(Run) -> - Path = filename:join( - "/tmp", "albedo-sdk-c-" ++ integer_to_list(erlang:unique_integer([positive])) - ), - ok = file:make_dir(Path), - try - Run(list_to_binary(Path)) - after - file:del_dir_r(Path) - end. - -mode(Path) -> - {ok, #file_info{mode = Mode}} = file:read_file_info(Path), - Mode band 8#777. - -%% A symlink loop makes reading fail even as root. Renaming a new cache over -%% the symlink would still succeed, so a failed read must prevent the write. -unreadable_cache(Home) -> - Path = filename:join(Home, <<"bedrock-inference-profiles.json">>), - ok = file:make_symlink(Path, Path), - 'albedo_ext_bedrock@profiles':save(Home, <<"new">>, <<"model">>), - {ok, Target} = file:read_link(Path), - Path = unicode:characters_to_binary(Target), - nil. - -webhook_headers() -> - [ - false = 'albedo_ext_webhooks@ledger':verify(<<>>, Header, <<>>, <<>>) - || Header <- [nil, [], #{}, 12] - ], - nil. - -codex_legacy(Home) -> - Canonical = <>, - Legacy = unicode:characters_to_binary(binary_to_list(Canonical)), - Name = <<"codex-models.json">>, - Bytes = <<"{\"clientVersion\":\"fixture\",\"accounts\":{}}">>, - ok = filelib:ensure_dir(filename:join(Legacy, Name)), - ok = file:write_file(filename:join(Legacy, Name), Bytes), - [] = 'albedo_ext_codex@catalog':listed(Canonical), - {ok, Bytes} = file:read_file(filename:join(Canonical, Name)), - nil. diff --git a/apps/albedo/test/albedo/composition/cache_files_test.gleam b/apps/albedo/test/albedo/composition/cache_files_test.gleam index a86cce420..d2232b82d 100644 --- a/apps/albedo/test/albedo/composition/cache_files_test.gleam +++ b/apps/albedo/test/albedo/composition/cache_files_test.gleam @@ -2,16 +2,19 @@ //// values, including unknown JSON shapes, an unreadable cache must not be //// replaced, and Codex's cache moves from a legacy Unicode home. +import albedo/composition/sdk_c_support import albedo_ext_bedrock/profiles import albedo_file import gleam/dynamic/decode import gleam/json -@external(erlang, "albedo_sdk_c_test_support", "home") -fn home(run: fn(String) -> Nil) -> Nil +fn home(run: fn(String) -> Nil) -> Nil { + sdk_c_support.home(run) +} -@external(erlang, "albedo_sdk_c_test_support", "mode") -fn mode(path: String) -> Int +fn mode(path: String) -> Int { + sdk_c_support.mode(path) +} pub fn bedrock_cache_preserves_entries_and_ignores_non_objects_test() -> Nil { home(fn(home) { @@ -43,13 +46,15 @@ pub fn unreadable_existing_cache_is_not_replaced_test() -> Nil { unreadable_cache(home) } -@external(erlang, "albedo_sdk_c_test_support", "unreadable_cache") -fn unreadable_cache(home: String) -> Nil +fn unreadable_cache(home: String) -> Nil { + sdk_c_support.unreadable_cache(home) +} pub fn codex_migrates_legacy_unicode_home_cache_test() -> Nil { use home <- home codex_legacy(home) } -@external(erlang, "albedo_sdk_c_test_support", "codex_legacy") -fn codex_legacy(home: String) -> Nil +fn codex_legacy(home: String) -> Nil { + sdk_c_support.codex_legacy(home) +} diff --git a/apps/albedo/test/albedo/composition/claude_wire_test.gleam b/apps/albedo/test/albedo/composition/claude_wire_test.gleam index a48e1620f..7642fe0b4 100644 --- a/apps/albedo/test/albedo/composition/claude_wire_test.gleam +++ b/apps/albedo/test/albedo/composition/claude_wire_test.gleam @@ -1,6 +1,7 @@ //// The Anthropic native Messages wire shape is not exercised by the E2E fake //// provider, so these tests guard exact paid-mode encoding without credentials. +import albedo/composition/sdk_c_support import albedo_bytes/digest import albedo_ext_claude/fast import albedo_ext_claude/wire @@ -109,8 +110,9 @@ pub fn count_body_is_the_prompt_in_claudes_encoding_without_generation_test() -> assert !string.contains(text, "\"speed\"") } -@external(erlang, "albedo_sdk_c_test_support", "home") -fn with_home(run: fn(String) -> Nil) -> Nil +fn with_home(run: fn(String) -> Nil) -> Nil { + sdk_c_support.home(run) +} /// Anthropic's count endpoint refuses uploaded files, so a request with an /// image the account has uploaded is not counted at all; the same image not diff --git a/apps/albedo/test/albedo/composition/codex_images_test.gleam b/apps/albedo/test/albedo/composition/codex_images_test.gleam new file mode 100644 index 000000000..e66157846 --- /dev/null +++ b/apps/albedo/test/albedo/composition/codex_images_test.gleam @@ -0,0 +1,57 @@ +//// The credential-bearing transport rejects destination confusion before +//// opening a socket. Native calls exercise the boundary even if settings +//// validation is bypassed; no credential store or external provider is +//// involved. + +import albedo_env +import albedo_ext_codex/images +import albedo_protect +import gleam/list +import gleam/option.{None, Some} + +const endpoint = "ALBEDO_TEST_CODEX_IMAGE_ENDPOINT" + +fn rejected(url: String, token: String, account: String) -> Nil { + let assert Error(_) = images.post(url, token, account, "s", "c", "{}") as url + Nil +} + +pub fn credential_destination_test() -> Nil { + let previous = albedo_env.lookup(endpoint) + albedo_protect.finally(destinations, fn() { + case previous { + Some(value) -> albedo_env.set(endpoint, value) + None -> albedo_env.unset(endpoint) + } + }) +} + +fn destinations() -> Nil { + albedo_env.unset(endpoint) + list.each( + [ + "https://example.invalid/backend-api/codex/images/generations", + "http://127.0.0.1:1/images/generations", + "https://chatgpt.com@127.0.0.1/backend-api/codex/images/generations", + "https://chatgpt.com:444/backend-api/codex/images/generations", + "https://chatgpt.com/backend-api/codex/images/generations?other=1", + "https://chatgpt.com/backend-api/codex/images/generations#other", + "https://chatgpt.com/other/images/generations", + ], + rejected(_, "private-token", "private-account"), + ) + let url = "https://chatgpt.com/backend-api/codex/images/generations" + albedo_env.set(endpoint, "http://127.0.0.1:1") + rejected(url, "private-token", "image-fixture-account") + rejected(url, "image-fixture-access", "private-account") + list.each( + [ + "https://example.invalid", "http://127.0.0.1:1?x=1", + "http://user@127.0.0.1:1", "http://127.0.0.1:1#x", + ], + fn(value) { + albedo_env.set(endpoint, value) + rejected(url, "image-fixture-access", "image-fixture-account") + }, + ) +} diff --git a/apps/albedo/test/albedo/composition/extension_digests_test.gleam b/apps/albedo/test/albedo/composition/extension_digests_test.gleam index 0e540c959..239b71f70 100644 --- a/apps/albedo/test/albedo/composition/extension_digests_test.gleam +++ b/apps/albedo/test/albedo/composition/extension_digests_test.gleam @@ -7,6 +7,7 @@ //// The seeds cover empty input, Unicode text, leading zero bytes, and signed //// 64-bit overflow. albedo_bytes tests the digests and ids they build on. +import albedo/composition/sdk_c_support import albedo_ext_antigravity/wire as antigravity_wire import albedo_ext_proxy/extension as proxy import albedo_ext_webhooks/ledger as webhooks @@ -85,5 +86,6 @@ pub fn credential_text_reads_only_string_fields_test() -> Nil { decode.run(credential, lenient) |> should.equal(Ok(#("sk-1", ""))) } -@external(erlang, "albedo_sdk_c_test_support", "webhook_headers") -pub fn non_binary_webhook_headers_are_false_test() -> Nil +pub fn non_binary_webhook_headers_are_false_test() -> Nil { + sdk_c_support.webhook_headers() +} diff --git a/apps/albedo/test/albedo/composition/sdk_c_support.gleam b/apps/albedo/test/albedo/composition/sdk_c_support.gleam new file mode 100644 index 000000000..b6cd773ec --- /dev/null +++ b/apps/albedo/test/albedo/composition/sdk_c_support.gleam @@ -0,0 +1,120 @@ +//// Fixtures shared by the extension SDK tests: a fresh VM per time zone, a +//// scratch home, file modes, and the cache and header cases that need +//// files or values a typed caller cannot make. + +import albedo_ext_bedrock/profiles +import albedo_ext_codex/catalog +import albedo_ext_webhooks/ledger +import albedo_file +import albedo_file/info as file_info +import albedo_ports/subprocess +import albedo_protect +import gleam/bit_array +import gleam/dynamic.{type Dynamic} +import gleam/erlang/charlist.{type Charlist} +import gleam/int +import gleam/list +import gleam/option.{None, Some} +import gleam/string + +@external(erlang, "code", "get_path") +fn code_path() -> List(Charlist) + +@external(erlang, "file", "make_symlink") +fn make_symlink(existing: String, new: String) -> Dynamic + +@external(erlang, "file", "read_link") +fn read_link(path: String) -> Result(Charlist, Dynamic) + +@external(erlang, "file", "del_dir_r") +fn delete_tree(path: String) -> Dynamic + +@external(erlang, "file", "make_dir") +fn make_dir(path: String) -> Dynamic + +/// A value of any type where the callee's type says otherwise, as an +/// untyped caller could pass it. +@external(erlang, "gleam@function", "identity") +fn coerce(value: a) -> b + +/// Runs `sdk_calendar_test.` in a fresh VM under time zone +/// `zone`: libc caches TZ, so each zone needs its own VM. +pub fn zone(zone: String, function: String) -> Nil { + let assert Ok(erl) = subprocess.on_path("erl") + let path = + list.flat_map(code_path(), fn(dir) { ["-pa", charlist.to_string(dir)] }) + let #(status, output) = + subprocess.run_with_environment( + erl, + list.flatten([ + ["+S", "2", "-noshell"], + path, + [ + "-eval", + "'albedo@composition@sdk_calendar_test':" <> function <> "(), halt().", + ], + ]), + None, + Some(15_000), + [#("TZ", zone)], + ) + assert status == 0 as { "calendar fixture failed: " <> output } +} + +/// Runs `run` with a fresh directory, removed afterwards. +pub fn home(run: fn(String) -> Nil) -> Nil { + let path = "/tmp/albedo-sdk-c-" <> int.to_string(int.random(1_000_000_000)) + let _ = make_dir(path) + albedo_protect.finally(fn() { run(path) }, fn() { delete_tree(path) }) +} + +/// The permission bits of `path`. +pub fn mode(path: String) -> Int { + let assert Ok(info) = file_info.read(path) + int.bitwise_and(info.mode, 0o777) +} + +/// A symlink loop makes reading fail even as root. Renaming a new cache over +/// the symlink would still succeed, so a failed read must prevent the write. +pub fn unreadable_cache(home: String) -> Nil { + let path = home <> "/bedrock-inference-profiles.json" + let _ = make_symlink(path, path) + profiles.save(home, "new", "model") + let assert Ok(target) = read_link(path) + assert charlist.to_string(target) == path +} + +/// Headers an untyped caller can pass where a text is expected. +pub fn webhook_headers() -> Nil { + list.each( + [coerce(Nil), coerce([]), coerce(dynamic.properties([])), coerce(12)], + fn(header) { + assert !ledger.verify(<<>>, header, "", "") + }, + ) +} + +/// The models cache written where an older release, reading the home as +/// Latin-1, put it, is found at the home's real path. +pub fn codex_legacy(home: String) -> Nil { + let canonical = home <> "/é" + // Each byte of the UTF-8 path read as its own character. + let legacy = + bit_array.from_string(canonical) + |> bytes + |> list.filter_map(string.utf_codepoint) + |> string.from_utf_codepoints + let name = "codex-models.json" + let saved = <<"{\"clientVersion\":\"fixture\",\"accounts\":{}}">> + albedo_file.ensure_parent(legacy <> "/" <> name) + let assert Ok(Nil) = albedo_file.write_private(legacy <> "/" <> name, saved) + assert catalog.listed(canonical) == [] + assert albedo_file.read(canonical <> "/" <> name) == Ok(saved) +} + +fn bytes(data: BitArray) -> List(Int) { + case data { + <> -> [byte, ..bytes(rest)] + _ -> [] + } +} diff --git a/apps/albedo/test/albedo/composition/sdk_calendar_test.gleam b/apps/albedo/test/albedo/composition/sdk_calendar_test.gleam index 550cf5c89..29c3454ac 100644 --- a/apps/albedo/test/albedo/composition/sdk_calendar_test.gleam +++ b/apps/albedo/test/albedo/composition/sdk_calendar_test.gleam @@ -1,13 +1,15 @@ //// Calendar and stamp edge cases need fixed instants and separate timezone VMs. //// These bytes appear in cached memory prefixes and message metadata. +import albedo/composition/sdk_c_support import albedo_clock import albedo_ext_discord/ingest import albedo_lcm/graph import gleam/option.{None, Some} -@external(erlang, "albedo_sdk_c_test_support", "zone") -fn zone(name: String, function: String) -> Nil +fn zone(name: String, function: String) -> Nil { + sdk_c_support.zone(name, function) +} pub fn stamps_match_native_timezone_vectors_test() -> Nil { zone("America/New_York", "new_york") diff --git a/apps/albedo/test/albedo/observation/albedo_stalls_test.erl b/apps/albedo/test/albedo/observation/albedo_stalls_test.erl deleted file mode 100644 index 036353dc2..000000000 --- a/apps/albedo/test/albedo/observation/albedo_stalls_test.erl +++ /dev/null @@ -1,98 +0,0 @@ -%% The VM's one system monitor cannot be driven through the HTTP API: this -%% proves a stall names its labelled process and a burst stays bounded. --module(albedo_stalls_test). --include_lib("eunit/include/eunit.hrl"). - -names_the_process_with_a_large_heap_test() -> - Previous = erlang:system_monitor(), - Parent = self(), - %% Only the fixture's heap passes this bound; long schedules and - %% collections and busy ports are off, and the budget is unbounded, so - %% other tests' events on a loaded machine cannot crowd the fixture out. - Monitor = start(#{ - large_heap => 3000000, - long_gc => 3600000, - long_schedule => 3600000, - busy_port => false, - max_lines => 1000000, - report => fun(Line) -> - Parent ! {stall, unicode:characters_to_list(Line)}, - nil - end - }), - try - spawn(fun() -> - proc_lib:set_label({albedo_session, <<"stalled-fixture">>}), - Big = lists:seq(1, 2000000), - erlang:garbage_collect(), - _ = length(Big) - end), - Line = await(<<"stalled-fixture">>), - ?assertMatch({_, _}, binary:match(list_to_binary(Line), <<"large_heap">>)) - after - exit(Monitor, kill), - restore(Previous) - end. - -%% Lines are tagged with this monitor's ref: the module's tests share one -%% process, so the first test's monitor may still have lines in its mailbox. -a_burst_is_limited_to_the_window_budget_test() -> - Previous = erlang:system_monitor(), - Parent = self(), - Ref = make_ref(), - Monitor = start(#{ - large_heap => 10000, - window_ms => 1000, - report => fun(Line) -> - Parent ! {Ref, unicode:characters_to_list(Line)}, - nil - end - }), - try - [ - spawn(fun() -> - _ = length(lists:seq(1, 200000)), - erlang:garbage_collect() - end) - || _ <- lists:seq(1, 60) - ], - ?assert(until_left_out(Ref, 0) =< 10) - after - exit(Monitor, kill), - restore(Previous) - end. - -%% Other tests' processes are heard too; skip lines that name someone else. -await(Needle) -> - receive - {stall, Line} -> - case binary:match(list_to_binary(Line), Needle) of - nomatch -> await(Needle); - _ -> Line - end - after 10000 -> error(no_stall_reported) - end. - -%% The lines a window reported, up to the count it left out as it closed. -until_left_out(Ref, N) -> - receive - {Ref, Line} -> - case string:find(Line, "left out") of - nomatch -> until_left_out(Ref, N + 1); - _ -> N - end - end. - -%% An unregistered monitor: the stalls defaults with these fields replaced. -start(Overrides) -> - {options, LongGc, LongSchedule, LargeHeap, BusyPort, MaxLines, WindowMs, Report, _} = - 'albedo@observation@stalls':defaults(), - Get = fun(Key, Default) -> maps:get(Key, Overrides, Default) end, - 'albedo@observation@stalls':start( - {options, Get(long_gc, LongGc), Get(long_schedule, LongSchedule), - Get(large_heap, LargeHeap), Get(busy_port, BusyPort), Get(max_lines, MaxLines), - Get(window_ms, WindowMs), Get(report, Report), none} - ). - -restore(undefined) -> erlang:system_monitor(undefined); -restore({Pid, Options}) -> erlang:system_monitor(Pid, Options). diff --git a/apps/albedo/test/albedo/observation/stalls_test.gleam b/apps/albedo/test/albedo/observation/stalls_test.gleam new file mode 100644 index 000000000..65b3bae6e --- /dev/null +++ b/apps/albedo/test/albedo/observation/stalls_test.gleam @@ -0,0 +1,99 @@ +//// The VM's one system monitor cannot be driven through the HTTP API: this +//// proves a stall names its labelled process and a burst stays bounded. + +import albedo/observation/stalls +import albedo_process +import albedo_protect +import gleam/dynamic.{type Dynamic} +import gleam/erlang/process.{type Subject} +import gleam/list +import gleam/option.{None} +import gleam/string + +/// The VM's system monitor before a test, so it can be put back. +@external(erlang, "erlang", "system_monitor") +fn current_monitor() -> Dynamic + +/// Puts back what `current_monitor` read: `undefined` or `{Pid, Options}`. +@external(erlang, "erlang", "system_monitor") +fn restore(previous: Dynamic) -> Dynamic + +@external(erlang, "erlang", "garbage_collect") +fn garbage_collect() -> Bool + +fn with_monitor(options: stalls.Options, body: fn() -> a) -> a { + let previous = current_monitor() + let monitor = stalls.start(options) + albedo_protect.finally(body, fn() { + process.kill(monitor) + let _ = restore(previous) + Nil + }) +} + +/// The first line naming `needle`; other tests' processes are heard too. +fn await(lines: Subject(String), needle: String) -> String { + let assert Ok(line) = process.receive(lines, 10_000) as "no stall reported" + case string.contains(line, needle) { + True -> line + False -> await(lines, needle) + } +} + +pub fn names_the_process_with_a_large_heap_test() -> Nil { + let lines = process.new_subject() + // Only the fixture's heap passes this bound; long schedules and + // collections and busy ports are off, and the budget is unbounded, so + // other tests' events on a loaded machine cannot crowd the fixture out. + let options = + stalls.Options( + ..stalls.defaults(), + large_heap: 3_000_000, + long_gc: 3_600_000, + long_schedule: 3_600_000, + busy_port: False, + max_lines: 1_000_000, + report: process.send(lines, _), + name: None, + ) + use <- with_monitor(options) + process.spawn_unlinked(fn() { + albedo_process.label("albedo_session", "stalled-fixture") + let big = list.repeat(0, 2_000_000) + let _ = garbage_collect() + let _ = list.length(big) + Nil + }) + assert string.contains(await(lines, "stalled-fixture"), "large_heap") +} + +/// The lines a window reported, up to the one counting what it left out. +fn until_left_out(lines: Subject(String), count: Int) -> Int { + let assert Ok(line) = process.receive(lines, 10_000) + as "the window never closed" + case string.contains(line, "left out") { + True -> count + False -> until_left_out(lines, count + 1) + } +} + +pub fn a_burst_is_limited_to_the_window_budget_test() -> Nil { + let lines = process.new_subject() + let options = + stalls.Options( + ..stalls.defaults(), + large_heap: 10_000, + window_ms: 1000, + report: process.send(lines, _), + name: None, + ) + use <- with_monitor(options) + list.each(list.repeat(Nil, 60), fn(_) { + process.spawn_unlinked(fn() { + let _ = list.length(list.repeat(0, 200_000)) + let _ = garbage_collect() + Nil + }) + }) + assert until_left_out(lines, 0) <= 10 +} diff --git a/apps/albedo/test/albedo/runtime/albedo_runtime_ownership_test_support.erl b/apps/albedo/test/albedo/runtime/albedo_runtime_ownership_test_support.erl deleted file mode 100644 index c11da855e..000000000 --- a/apps/albedo/test/albedo/runtime/albedo_runtime_ownership_test_support.erl +++ /dev/null @@ -1,522 +0,0 @@ -%% Deterministic fault placement for runtime ownership regressions. Every -%% function either holds a real process at a gate the test controls or reads -%% a fact from a live process; none of them injects runtime messages or -%% rewrites production modules. --module(albedo_runtime_ownership_test_support). --include_lib("albedo/include/albedo@runtime@state_State.hrl"). --include_lib("albedo/include/albedo@runtime@state_Runtime.hrl"). - --export([ - cleanup_anchor_bound/0, - teardown_during_cancel/0, - await_cancelled/1, - await_cleanup_credits/2, - runtime_state/1, - await_deferred/2, - await_stopped/2, - await_shutdown/1, - new_gate/0, - await_gate/1, - submitted_count/1, - admission_barrier/1, - suspend/1, - resume/1, - kernel_pid/1, - rebind_caller/1, - release_and_await_finished/3, - unknown_spare_budget/0, - gate_spare/2, - with_runtime_cleanup/3 -]). - -%% A suspended process keeps its mailbox, so a worker blocked on it stays -%% blocked until the test resumes it. Suspension is the gate; the test -%% releases it explicitly on every path. -suspend(Pid) -> - true = erlang:suspend_process(Pid), - nil. - -resume(Pid) -> - try erlang:resume_process(Pid) of - _ -> nil - catch - error:badarg -> nil - end. - -%% The kernel handle inside a runtime Session is the kernel's port owner. -kernel_pid(Session) -> - element(4, Session). - -%% The apply worker is the process whose rebind call waits in the suspended -%% kernel driver's mailbox as {albedo_kernel, driver.Rebind(Reply, Host)}. -%% Nothing else sends that call, so the mailbox -%% names the worker without guessing from spawn order. -rebind_caller(Kernel) -> - await_rebind(Kernel, erlang:monotonic_time(millisecond) + 15000). - -await_rebind(Kernel, Deadline) -> - {messages, Messages} = process_info(Kernel, messages), - case [From || {albedo_kernel, {rebind, {subject, From, _}, _Host}} <- Messages] of - [Caller | _] -> - Caller; - [] -> - case erlang:monotonic_time(millisecond) < Deadline of - true -> - receive - after 5 -> ok - end, - await_rebind(Kernel, Deadline); - false -> - error(rebind_call_did_not_arrive) - end - end. - -%% Trace identifies the exact worker's result without consuming the suspended -%% runtime's mailbox. Its presence, not worker readiness, establishes this race. -release_and_await_finished(Worker, Runtime, Release) -> - %% Only the worker's send flag is traced: a call trace pattern is - %% VM-wide, and a parallel copy of this test turning it off would lose - %% this one's barrier. - erlang:trace(Worker, true, [send, {tracer, self()}]), - try - Release(), - Message = - receive - {trace, Worker, send, {_, {finished, _, _, _}} = Finished, Runtime} -> Finished - after 15000 -> error(worker_result_not_sent) - end, - %% The trace may arrive before the message is enqueued. The runtime - %% is suspended, so once the result is in its mailbox it stays there. - await_queued(Runtime, Message, erlang:monotonic_time(millisecond) + 15000) - after - erlang:trace(Worker, false, [send]) - end. - -await_queued(Runtime, Message, Deadline) -> - {messages, Messages} = process_info(Runtime, messages), - case lists:member(Message, Messages) of - true -> - nil; - false -> - case erlang:monotonic_time(millisecond) < Deadline of - true -> - receive - after 1 -> await_queued(Runtime, Message, Deadline) - end; - false -> - error(worker_result_send_did_not_finish) - end - end. - -%% The real runtime admits a real monitored work item. Only interpreter -%% allocation is gated; the surrogate custodian has the existing runtime lifetime. -unknown_spare_budget() -> - Boot = 'albedo@runtime@boot', - Copy = albedo_spare_budget_boot, - Beam = code:which(Boot), - Path = filename:join([ - filename:dirname(filename:dirname(Beam)), - "_gleam_artefacts", - atom_to_list(Boot) ++ ".abstr" - ]), - {ok, Bytes} = file:read_file(Path), - {ok, Copy, Binary} = compile:forms( - spare_patch(binary_to_term(Bytes), Copy), - [binary, export_all, nowarn_export_all] - ), - {module, Copy} = code:load_binary(Copy, "spare-budget-test", Binary), - Runtime = albedo_spare_budget_runtime, - RuntimeSource = 'albedo@runtime', - RuntimeBeam = code:which(RuntimeSource), - RuntimePath = filename:join([ - filename:dirname(filename:dirname(RuntimeBeam)), - "_gleam_artefacts", - atom_to_list(RuntimeSource) ++ ".abstr" - ]), - {ok, RuntimeBytes} = file:read_file(RuntimePath), - RuntimeForms = runtime_spare_patch(binary_to_term(RuntimeBytes), Runtime, Copy), - {ok, Runtime, RuntimeBinary} = compile:forms( - RuntimeForms, - [binary, export_all, nowarn_export_all] - ), - {module, Runtime} = code:load_binary(Runtime, "spare-budget-runtime-test", RuntimeBinary), - {ok, Host} = Runtime:start_with_config(<<":memory:">>, {config, [], []}), - {ok, Owner} = 'gleam@erlang@process':subject_owner(Host#runtime.subject), - unlink(Owner), - persistent_term:put({?MODULE, spare_controller}, self()), - erlang:trace_pattern({Copy, spare_abandoned, 2}, [{'_', [], [{return_trace}]}], [local]), - erlang:trace_pattern({Copy, spare_ready, 3}, [{'_', [], [{return_trace}]}], [local]), - erlang:trace(Owner, true, [call, {tracer, self()}]), - try - Runtime:want_spares(Host), - {Worker, Custodian} = - receive - {spare_allocated, Pid, Resource} -> {Pid, Resource} - after 5000 -> error(spare_not_allocated) - end, - Running = sys:get_state(Owner), - [Ticket] = maps:keys(Running#state.warming), - kill_process(Worker), - State = settled_spare_state(Owner, Copy, Ticket), - 1 = State#state.unconfirmed_spares, - 0 = map_size(State#state.warming), - true = is_process_alive(Custodian), - 'gleam@erlang@process':send(Host#runtime.subject, want_spares), - 'gleam@erlang@process':send(Host#runtime.subject, fill_spares), - AfterRefill = sys:get_state(Owner), - 1 = AfterRefill#state.unconfirmed_spares, - 0 = map_size(AfterRefill#state.warming), - [] = AfterRefill#state.spares, - Runtime:stop(Host), - await_process(Custodian), - nil - after - try - Runtime:stop(Host) - catch - _:_ -> ok - end, - kill_process(Owner), - persistent_term:erase({?MODULE, spare_controller}), - erlang:trace_pattern({Copy, spare_abandoned, 2}, false, [local]), - erlang:trace_pattern({Copy, spare_ready, 3}, false, [local]), - code:delete(Runtime), - code:purge(Runtime), - code:delete(Copy), - code:purge(Copy) - end. - -gate_spare(Runtime, _Modules) -> - Parent = self(), - Custodian = spawn(fun() -> - Monitor = monitor(process, Runtime), - Parent ! {custodian_ready, self()}, - receive - {'DOWN', Monitor, process, Runtime, _} -> ok - end - end), - receive - {custodian_ready, Custodian} -> ok - end, - persistent_term:get({?MODULE, spare_controller}) ! {spare_allocated, self(), Custodian}, - receive - continue -> {ok, {spare, Custodian, atomics:new(1, []), #{}, fun(_) -> {ok, nil} end}} - end. - -settled_spare_state(Owner, Boot, Ticket) -> - Function = - receive - {trace, Owner, call, {Boot, spare_abandoned, [_, Ticket]}} -> {spare_abandoned, 2}; - {trace, Owner, call, {Boot, spare_ready, [_, Ticket, _]}} -> {spare_ready, 3} - after 5000 -> error(dead_worker_not_settled) - end, - {Name, Arity} = Function, - receive - {trace, Owner, return_from, {Boot, Name, Arity}, State} -> State - after 5000 -> error(spare_settlement_did_not_return) - end. - -kill_process(Pid) -> - exit(Pid, kill), - await_process(Pid). -await_process(Pid) -> - Monitor = monitor(process, Pid), - receive - {'DOWN', Monitor, process, Pid, _} -> ok - after 5000 -> error({process_survived, Pid}) - end. - -spare_patch({attribute, L, module, _}, Copy) -> - {attribute, L, module, Copy}; -spare_patch({remote, L, {atom, A, 'albedo@kernel'}, {atom, B, start_spare}}, _) -> - {remote, L, {atom, A, ?MODULE}, {atom, B, gate_spare}}; -spare_patch(Tuple, Copy) when is_tuple(Tuple) -> - list_to_tuple([spare_patch(Value, Copy) || Value <- tuple_to_list(Tuple)]); -spare_patch(List, Copy) when is_list(List) -> [spare_patch(Value, Copy) || Value <- List]; -spare_patch(Value, _) -> - Value. - -runtime_spare_patch({attribute, L, module, _}, Runtime, _) -> - {attribute, L, module, Runtime}; -runtime_spare_patch({remote, L, {atom, A, 'albedo@runtime@boot'}, Function}, _, Boot) -> - {remote, L, {atom, A, Boot}, Function}; -runtime_spare_patch({function, L, spare_target, 0, _}, _, _) -> - {function, L, spare_target, 0, [{clause, L, [], [], [{integer, L, 1}]}]}; -runtime_spare_patch(Tuple, Runtime, Boot) when is_tuple(Tuple) -> - list_to_tuple([runtime_spare_patch(Value, Runtime, Boot) || Value <- tuple_to_list(Tuple)]); -runtime_spare_patch(List, Runtime, Boot) when is_list(List) -> - [runtime_spare_patch(Value, Runtime, Boot) || Value <- List]; -runtime_spare_patch(Value, _, _) -> - Value. - -with_runtime_cleanup(Runtime, Workspace, Run) -> - try - Run() - after - kill_process(Runtime), - albedo_runtime_test_support:cleanup_workspace(Workspace) - end. - -runtime_state(Owner) -> sys:get_state(Owner). - -%% Reusable latch: callbacks announce arrival through the existing Note subject -%% and wait in their own mailbox. The test owns only the release address. -new_gate() -> - Parent = self(), - Pid = spawn(fun() -> - Watch = monitor(process, Parent), - Inbox = 'gleam@erlang@process':new_subject(), - Parent ! {gate_ready, self(), Inbox}, - gate_loop(Inbox, Watch, false, []) - end), - receive - {gate_ready, Pid, Inbox} -> Inbox - end. - -gate_loop(Inbox, Watch, Open, Waiters) -> - Tag = element(3, Inbox), - receive - {Tag, {wait, Pid, Ref}} -> - case Open of - true -> - Pid ! {Ref, released}, - gate_loop(Inbox, Watch, Open, Waiters); - false -> - gate_loop(Inbox, Watch, Open, [{Pid, Ref} | Waiters]) - end; - {Tag, nil} -> - [Pid ! {Ref, released} || {Pid, Ref} <- Waiters], - gate_loop(Inbox, Watch, true, []); - {'DOWN', Watch, process, _, _} -> - ok - end. - -await_gate(Inbox) -> - Ref = make_ref(), - Monitor = monitor(process, element(2, Inbox)), - 'gleam@erlang@process':send(Inbox, {wait, self(), Ref}), - receive - {Ref, released} -> - demonitor(Monitor, [flush]), - nil; - {'DOWN', Monitor, process, _, _} -> - error(gate_owner_stopped) - after 20000 -> error(gate_not_released) - end. - -submitted_count(Owner) -> - {messages, Messages} = process_info(Owner, messages), - length([ok || {_, {submitted, _, _}} <- Messages]). - -%% The call barrier runs after a cancellation notification from the same pool. -%% It establishes that the runtime processed it, without a scheduling sleep. -admission_barrier(Host) -> - _ = 'albedo@runtime':admission_snapshot(Host), - nil. - -%% Resource death precedes the stop worker's result. Wait for the runtime to -%% settle that result before checking which compositions it still retains. -await_stopped(Host, Id) -> - {ok, Owner} = 'gleam@erlang@process':subject_owner(Host#runtime.subject), - await_stopped_state(Owner, Id, erlang:monotonic_time(millisecond) + 5000). -await_stopped_state(Owner, Id, Deadline) -> - State = sys:get_state(Owner), - case maps:is_key(Id, State#state.stopping) of - false -> - nil; - true -> - case erlang:monotonic_time(millisecond) < Deadline of - true -> - receive - after 1 -> ok - end, - await_stopped_state(Owner, Id, Deadline); - false -> - error({stop_not_settled, Id}) - end - end. - -await_shutdown(Host) -> - {ok, Owner} = 'gleam@erlang@process':subject_owner(Host#runtime.subject), - await_shutdown_state(Owner, erlang:monotonic_time(millisecond) + 5000). -await_shutdown_state(Owner, Deadline) -> - State = sys:get_state(Owner), - case State#state.shutdown of - {some, _} -> - nil; - none -> - case erlang:monotonic_time(millisecond) < Deadline of - true -> await_shutdown_state(Owner, Deadline); - false -> error(shutdown_not_admitted) - end - end. - -await_deferred(Host, Id) -> - {ok, Owner} = 'gleam@erlang@process':subject_owner(Host#runtime.subject), - await_deferred_state(Owner, Id, erlang:monotonic_time(millisecond) + 5000). -await_deferred_state(Owner, Id, Deadline) -> - State = sys:get_state(Owner), - case maps:is_key(Id, State#state.deferred) of - true -> - nil; - false -> - case erlang:monotonic_time(millisecond) < Deadline of - true -> await_deferred_state(Owner, Id, Deadline); - false -> error(deferred_request_not_admitted) - end - end. - -%% Direct ingress must remain bounded even when a runtime cannot drain cleanup. -%% This isolates the reservation invariant from scheduler progress. -cleanup_anchor_bound() -> - Process = 'gleam@erlang@process', - Parent = self(), - Runtime = spawn(fun() -> - Parent ! {test_subject, Process:new_subject()}, - reservation_mailbox(Parent) - end), - Subject = - receive - {test_subject, S} -> S - after 5000 -> error(no_subject) - end, - Pool = 'albedo@runtime@admission':start( - Subject, fun(T, M) -> {submitted, T, M} end, fun(T) -> - {cancel, T} - end - ), - try - Accepted = [ - Ticket - || _ <- lists:seq(1, 512), - {ok, Ticket} <- [ - 'albedo@runtime@admission':submit( - Pool, preparation, <<"anchor">>, fun(_) -> prepare end, fun(_) -> nil end - ) - ], - begin - 'albedo@runtime@admission':required(Pool, <<"anchor">>, reset, fun() -> - reset - end), - 'albedo@runtime@admission':cancel(Ticket), - 'albedo@runtime@admission':release(Ticket), - true - end - ], - Stats = 'albedo@runtime@admission':stats(Pool), - true = length(Accepted) > 0 andalso length(Accepted) < 512, - true = maps:get(<<"owned_reserved">>, Stats) =< length(Accepted), - true = maps:get(<<"public_reserved">>, Stats) =:= length(Accepted), - lists:foreach( - fun(_) -> - receive - {owned_cleanup, Cleanup} -> - 'albedo@runtime@admission':complete(Cleanup, fun() -> nil end) - after 5000 -> error(cleanup_not_forwarded) - end - end, - Accepted - ), - {ok, New} = 'albedo@runtime@admission':submit( - Pool, preparation, <<"after-cleanup">>, fun(_) -> prepare end, fun(_) -> nil end - ), - 'albedo@runtime@admission':cancel(New), - 'albedo@runtime@admission':release(New), - nil - after - exit(Runtime, kill), - await_process('albedo@runtime@admission':owner(Pool)) - end. - -%% The failure callback is a deterministic gate between claiming cancellation -%% and its remaining bookkeeping. Owner teardown must not escape as badarg. -teardown_during_cancel() -> - Process = 'gleam@erlang@process', - Parent = self(), - Runtime = spawn(fun() -> - Parent ! {test_subject, Process:new_subject()}, - receive - stop -> ok - end - end), - Subject = - receive - {test_subject, S} -> S - after 5000 -> error(no_subject) - end, - Pool = 'albedo@runtime@admission':start( - Subject, fun(T, M) -> {submitted, T, M} end, fun(T) -> - {cancel, T} - end - ), - {ok, Ticket} = 'albedo@runtime@admission':submit( - Pool, preparation, <<"teardown">>, fun(_) -> prepare end, fun(_) -> - Parent ! {cancel_entered, self()}, - receive - release -> nil - end - end - ), - Caller = spawn(fun() -> - Parent ! - {cancel_result, catch_result(fun() -> 'albedo@runtime@admission':cancel(Ticket) end)} - end), - try - receive - {cancel_entered, Caller} -> ok - after 5000 -> error(cancel_not_entered) - end, - Owner = 'albedo@runtime@admission':owner(Pool), - exit(Owner, kill), - await_process(Owner), - Caller ! release, - receive - {cancel_result, nil} -> nil; - {cancel_result, Other} -> error({cancel_failed, Other}) - after 5000 -> error(cancel_not_returned) - end - after - exit(Caller, kill), - exit(Runtime, kill) - end. - -catch_result(Run) -> - try - Run() - catch - Class:Reason -> {Class, Reason} - end. - -await_cancelled(Pool) -> - await_stat(Pool, cancelled, fun(N) -> N > 0 end, erlang:monotonic_time(millisecond) + 5000). -await_cleanup_credits(Pool, Count) -> - await_stat( - Pool, cleanup_credits, fun(N) -> N =:= Count end, erlang:monotonic_time(millisecond) + 5000 - ). -await_stat(Pool, Field, Ready, Deadline) -> - Value = maps:get(atom_to_binary(Field), 'albedo@runtime@admission':stats(Pool)), - case Ready(Value) of - true -> - nil; - false -> - case erlang:monotonic_time(millisecond) < Deadline of - true -> - receive - after 1 -> ok - end, - await_stat(Pool, Field, Ready, Deadline); - false -> - error({admission_stat_not_reached, Field, Value}) - end - end. - -reservation_mailbox(Parent) -> - receive - {_, {submitted, Ticket, reset}} -> - Parent ! {owned_cleanup, Ticket}, - reservation_mailbox(Parent); - stop -> - ok; - _ -> - reservation_mailbox(Parent) - end. diff --git a/apps/albedo/test/albedo/runtime/ownership_support.gleam b/apps/albedo/test/albedo/runtime/ownership_support.gleam new file mode 100644 index 000000000..e0de7f794 --- /dev/null +++ b/apps/albedo/test/albedo/runtime/ownership_support.gleam @@ -0,0 +1,600 @@ +//// Deterministic fault placement for runtime ownership regressions. Every +//// function either holds a real process at a gate the test controls or reads +//// a fact from a live process; none of them injects runtime messages or +//// rewrites production modules. +//// +//// Messages read from another process's mailbox are matched by their Gleam +//// type, so a change to that type recompiles this module with it. + +import albedo/composition/extensions +import albedo/kernel as python +import albedo/kernel/driver +import albedo/kernel/spare +import albedo/runtime +import albedo/runtime/admission +import albedo/runtime/state as runtime_state +import albedo_clock +import albedo_protect +import gleam/dict +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/erlang/atom.{type Atom} +import gleam/erlang/process.{type Pid, type Subject} +import gleam/list +import gleam/option +import gleam/result + +// Bindings. + +@external(erlang, "erlang", "suspend_process") +fn suspend_process(pid: Pid) -> Bool + +@external(erlang, "erlang", "resume_process") +fn resume_process(pid: Pid) -> Bool + +@external(erlang, "erlang", "process_info") +fn process_info(pid: Pid, item: Atom) -> #(Atom, List(Dynamic)) + +@external(erlang, "erlang", "trace") +fn trace(pid: Pid, on: Bool, flags: List(Dynamic)) -> Int + +@external(erlang, "sys", "get_state") +fn get_state(pid: Pid) -> runtime_state.State + +@external(erlang, "atomics", "new") +fn atomics_new(size: Int, options: List(Nil)) -> spare.Atomics + +@external(erlang, "albedo_runtime_test_support", "cleanup_workspace") +fn cleanup_workspace(path: String) -> Nil + +/// A value read from a mailbox, as the type its sender used. +@external(erlang, "gleam@function", "identity") +fn coerce(value: a) -> b + +// Suspension. + +/// A suspended process keeps its mailbox, so a worker blocked on it stays +/// blocked until the test resumes it. Suspension is the gate; the test +/// releases it explicitly on every path. +pub fn suspend(pid: Pid) -> Nil { + let assert True = suspend_process(pid) + Nil +} + +pub fn resume(pid: Pid) -> Nil { + let _ = albedo_protect.rescue(fn() { resume_process(pid) }) + Nil +} + +/// The kernel handle inside a runtime Session is the kernel's driver. +pub fn kernel_pid(session: runtime.Session) -> Pid { + session.kernel +} + +// Mailboxes. + +fn messages(pid: Pid) -> List(Dynamic) { + process_info(pid, atom.create("messages")).1 +} + +/// The `#(tag, message)` a subject delivered, when `value` is one. +fn delivered(value: Dynamic) -> Result(#(Dynamic, Dynamic), Nil) { + decode.run(value, { + use tag <- decode.field(0, decode.dynamic) + use message <- decode.field(1, decode.dynamic) + decode.success(#(tag, message)) + }) + |> result.replace_error(Nil) +} + +/// Polls `check` every few milliseconds until it holds, for at most +/// `budget_ms`. +fn eventually( + check: fn() -> Result(a, Nil), + budget_ms: Int, + what: String, +) -> a { + let deadline = albedo_clock.monotonic_ms() + budget_ms + poll(check, deadline, what) +} + +fn poll(check: fn() -> Result(a, Nil), deadline: Int, what: String) -> a { + case check() { + Ok(value) -> value + Error(Nil) -> + case albedo_clock.monotonic_ms() < deadline { + True -> { + process.sleep(2) + poll(check, deadline, what) + } + False -> panic as what + } + } +} + +/// The apply worker is the process whose rebind call waits in the +/// suspended kernel driver's mailbox. Nothing else sends that call, so the +/// mailbox names the worker without guessing from spawn order. +pub fn rebind_caller(kernel: Pid) -> Pid { + let tag = atom.to_dynamic(atom.create("albedo_kernel")) + use <- eventually(_, 15_000, "the rebind call did not arrive") + messages(kernel) + |> list.find_map(fn(message) { + case delivered(message) { + Ok(#(sent_to, request)) if sent_to == tag -> + case coerce(request) { + driver.Rebind(reply:, ..) -> process.subject_owner(reply) + _ -> Error(Nil) + } + _ -> Error(Nil) + } + }) +} + +/// Trace identifies the exact worker's result without consuming the +/// suspended runtime's mailbox. Its presence, not worker readiness, +/// establishes this race. +pub fn release_and_await_finished( + worker: Pid, + runtime: Pid, + release: fn() -> Nil, +) -> Nil { + // Only the worker's send flag is traced: a call trace pattern is VM-wide, + // and a parallel copy of this test turning it off would lose this one's + // barrier. + let flags = [ + atom.to_dynamic(atom.create("send")), + coerce(#(atom.create("tracer"), process.self())), + ] + let _ = trace(worker, True, flags) + use <- albedo_protect.finally(after: fn() { + trace(worker, False, [atom.to_dynamic(atom.create("send"))]) + }) + release() + let sent = + process.new_selector() + |> process.select_record(atom.create("trace"), 4, fn(trace) { + decode.run(trace, { + use from <- decode.field(1, decode.dynamic) + use kind <- decode.field(2, atom.decoder()) + use message <- decode.field(3, decode.dynamic) + use to <- decode.field(4, decode.dynamic) + decode.success(#(from, atom.to_string(kind), message, to)) + }) + }) + let finished = await_finished(sent, worker, runtime) + // The trace may arrive before the message is enqueued. The runtime is + // suspended, so once the result is in its mailbox it stays there. + use <- eventually(_, 15_000, "the worker's result never reached the runtime") + case list.contains(messages(runtime), finished) { + True -> Ok(Nil) + False -> Error(Nil) + } +} + +fn await_finished( + sent: process.Selector(Result(#(Dynamic, String, Dynamic, Dynamic), _)), + worker: Pid, + runtime: Pid, +) -> Dynamic { + let assert Ok(Ok(#(from, kind, message, to))) = + process.selector_receive(sent, 15_000) + as "the worker's result was not sent" + let finished = case delivered(message) { + Ok(#(_, inner)) -> + case coerce(inner) { + runtime_state.Finished(..) -> True + _ -> False + } + Error(Nil) -> False + } + case + from == coerce(worker) + && kind == "send" + && to == coerce(runtime) + && finished + { + True -> message + False -> await_finished(sent, worker, runtime) + } +} + +pub fn with_runtime_cleanup( + runtime: Pid, + workspace: String, + run: fn() -> a, +) -> a { + albedo_protect.finally(run, fn() { + kill_process(runtime) + cleanup_workspace(workspace) + }) +} + +pub fn runtime_state(owner: Pid) -> runtime_state.State { + get_state(owner) +} + +fn runtime_owner(host: runtime.Runtime) -> Pid { + let assert Ok(owner) = process.subject_owner(host.subject) + owner +} + +pub fn submitted_count(owner: Pid) -> Int { + messages(owner) + |> list.count(fn(message) { + case delivered(message) { + Ok(#(_, inner)) -> + case coerce(inner) { + runtime_state.Submitted(..) -> True + _ -> False + } + Error(Nil) -> False + } + }) +} + +/// The call barrier runs after a cancellation notification from the same +/// pool. It establishes that the runtime processed it, without a sleep. +pub fn admission_barrier(host: runtime.Runtime) -> Nil { + let _ = runtime.admission_snapshot(host) + Nil +} + +/// Resource death precedes the stop worker's result. Wait for the runtime +/// to settle that result before checking what it still retains. +pub fn await_stopped(host: runtime.Runtime, id: String) -> Nil { + let owner = runtime_owner(host) + use <- eventually(_, 5000, "the stop was not settled") + case dict.has_key(get_state(owner).stopping, id) { + False -> Ok(Nil) + True -> Error(Nil) + } +} + +pub fn await_shutdown(host: runtime.Runtime) -> Nil { + let owner = runtime_owner(host) + use <- eventually(_, 5000, "the shutdown was not admitted") + case get_state(owner).shutdown { + option.Some(_) -> Ok(Nil) + option.None -> Error(Nil) + } +} + +pub fn await_deferred(host: runtime.Runtime, id: String) -> Nil { + let owner = runtime_owner(host) + use <- eventually(_, 5000, "the deferred request was not admitted") + case dict.has_key(get_state(owner).deferred, id) { + True -> Ok(Nil) + False -> Error(Nil) + } +} + +pub fn await_cancelled(pool: admission.Pool) -> Nil { + await_stat(pool, "cancelled", fn(count) { count > 0 }) +} + +pub fn await_cleanup_credits(pool: admission.Pool, count: Int) -> Nil { + await_stat(pool, "cleanup_credits", fn(credits) { credits == count }) +} + +fn await_stat( + pool: admission.Pool, + field: String, + ready: fn(Int) -> Bool, +) -> Nil { + use <- eventually(_, 5000, "admission stat " <> field <> " not reached") + case dict.get(admission.stats(pool), field) { + Ok(value) -> + case ready(value) { + True -> Ok(Nil) + False -> Error(Nil) + } + Error(Nil) -> Error(Nil) + } +} + +// Gates. + +type Gate { + Wait(reply: Subject(Nil)) +} + +/// What a gate hears: a wait, its release, or its test's end. +type GateEvent { + Waited(reply: Subject(Nil)) + Released + OwnerGone +} + +fn gate_waits(owner: Pid) -> Subject(Gate) { + process.unsafely_create_subject( + owner, + atom.to_dynamic(atom.create("albedo_test_gate")), + ) +} + +/// A reusable latch: callbacks wait on it until the test sends `Nil` to the +/// gate, after which every wait returns at once. +pub fn new_gate() -> Subject(Nil) { + let parent = process.self() + let ready = process.new_subject() + process.spawn_unlinked(fn() { + let release = process.new_subject() + process.send(ready, release) + let watch = process.monitor(parent) + gate_loop( + process.new_selector() + |> process.select_map(release, fn(_) { Released }) + |> process.select_map(gate_waits(process.self()), fn(wait) { + Waited(wait.reply) + }) + |> process.select_specific_monitor(watch, fn(_) { OwnerGone }), + False, + [], + ) + }) + let assert Ok(release) = process.receive(ready, 5000) + release +} + +fn gate_loop( + events: process.Selector(GateEvent), + open: Bool, + waiting: List(Subject(Nil)), +) -> Nil { + case process.selector_receive_forever(events) { + Waited(reply) if open -> { + process.send(reply, Nil) + gate_loop(events, open, waiting) + } + Waited(reply) -> gate_loop(events, open, [reply, ..waiting]) + Released -> { + list.each(waiting, process.send(_, Nil)) + gate_loop(events, True, []) + } + OwnerGone -> Nil + } +} + +pub fn await_gate(gate: Subject(Nil)) -> Nil { + let assert Ok(owner) = process.subject_owner(gate) + let reply = process.new_subject() + let monitor = process.monitor(owner) + process.send(gate_waits(owner), Wait(reply)) + let outcome = + process.new_selector() + |> process.select_map(reply, fn(_) { Ok(Nil) }) + |> process.select_specific_monitor(monitor, fn(_) { Error(Nil) }) + |> process.selector_receive(20_000) + process.demonitor_process(monitor) + case outcome { + Ok(Ok(Nil)) -> Nil + Ok(Error(Nil)) -> panic as "the gate's owner stopped" + Error(Nil) -> panic as "the gate was not released" + } +} + +fn kill_process(pid: Pid) -> Nil { + process.kill(pid) + await_process(pid) +} + +fn await_process(pid: Pid) -> Nil { + let monitor = process.monitor(pid) + let assert Ok(Nil) = + process.new_selector() + |> process.select_specific_monitor(monitor, fn(_) { Nil }) + |> process.selector_receive(5000) + as "a process survived" + Nil +} + +// An unknown spare allocation. + +type SpareEvent { + SpareAllocated(worker: Pid, custodian: Pid) +} + +/// A spare whose worker the test holds at the gate after its custodian +/// exists, so killing the worker leaves an allocation of unknown outcome. +fn gated_spare( + events: Subject(SpareEvent), +) -> fn(Pid, List(String)) -> Result(spare.Spare, python.Error) { + fn(runtime: Pid, _modules: List(String)) { + let ready = process.new_subject() + let custodian = + process.spawn_unlinked(fn() { + let monitor = process.monitor(runtime) + process.send(ready, Nil) + let _ = + process.new_selector() + |> process.select_specific_monitor(monitor, fn(_) { Nil }) + |> process.selector_receive_forever + Nil + }) + let assert Ok(Nil) = process.receive(ready, 5000) + process.send(events, SpareAllocated(process.self(), custodian)) + // Held here until the test kills this worker. + process.sleep_forever() + Ok( + spare.Spare(custodian, atomics_new(1, []), dynamic.nil(), fn(_) { + Ok(Nil) + }), + ) + } +} + +/// A warmup whose worker dies after allocating its custodian: the runtime +/// keeps the spare's budget as unconfirmed, does not count it warming, and +/// still stops with its custodian. +pub fn unknown_spare_budget() -> Nil { + let events = process.new_subject() + let assert Ok(host) = + runtime.start_with_options( + ":memory:", + extensions.Config([], []), + runtime.Options( + ..runtime.default_options(), + spares: 1, + start_spare: gated_spare(events), + ), + ) + let owner = runtime_owner(host) + use <- albedo_protect.finally(after: fn() { + let _ = albedo_protect.rescue(fn() { runtime.stop(host) }) + process.kill(owner) + }) + runtime.want_spares(host) + let assert Ok(SpareAllocated(worker, custodian)) = + process.receive(events, 5000) + as "no spare was allocated" + let assert [_] = dict.keys(get_state(owner).warming) + kill_process(worker) + let settled = { + use <- eventually(_, 5000, "the dead worker was not settled") + let state = get_state(owner) + case dict.is_empty(state.warming) { + True -> Ok(state) + False -> Error(Nil) + } + } + assert settled.unconfirmed_spares == 1 + assert process.is_alive(custodian) + process.send(host.subject, runtime_state.WantSpares) + process.send(host.subject, runtime_state.FillSpares) + let after = get_state(owner) + assert after.unconfirmed_spares == 1 + assert dict.is_empty(after.warming) + assert after.spares == [] + runtime.stop(host) + await_process(custodian) +} + +// Admission cleanup. + +/// The messages a stand-in runtime receives from its admission pool. +type Fake { + Submitted(admission.Ticket, Fake) + Cancelled(admission.Ticket) + Prepare + ResetCleanup +} + +fn fake_runtime(parent: Subject(admission.Ticket)) -> #(Pid, Subject(Fake)) { + let ready = process.new_subject() + let pid = + process.spawn_unlinked(fn() { + let inbox = process.new_subject() + process.send(ready, inbox) + fake_loop(inbox, parent) + }) + let assert Ok(inbox) = process.receive(ready, 5000) + #(pid, inbox) +} + +fn fake_loop(inbox: Subject(Fake), parent: Subject(admission.Ticket)) -> Nil { + case process.receive_forever(inbox) { + Submitted(ticket, ResetCleanup) -> process.send(parent, ticket) + _ -> Nil + } + fake_loop(inbox, parent) +} + +fn fake_pool(inbox: Subject(Fake)) -> admission.Pool { + admission.start(inbox, Submitted, Cancelled) +} + +/// Direct ingress must remain bounded even when a runtime cannot drain +/// cleanup. This isolates the reservation invariant from scheduler +/// progress. +pub fn cleanup_anchor_bound() -> Nil { + let cleanups = process.new_subject() + let #(runtime, inbox) = fake_runtime(cleanups) + let pool = fake_pool(inbox) + use <- albedo_protect.finally(after: fn() { + process.kill(runtime) + await_process(admission.owner(pool)) + }) + let accepted = + list.repeat(Nil, 512) + |> list.filter_map(fn(_) { + admission.submit( + pool, + admission.Preparation, + "anchor", + fn(_) { Prepare }, + fn(_) { Nil }, + ) + |> result.map(fn(ticket) { + admission.required(pool, "anchor", admission.Reset, fn() { + ResetCleanup + }) + admission.cancel(ticket) + admission.release(ticket) + ticket + }) + |> result.replace_error(Nil) + }) + let count = list.length(accepted) + let stats = admission.stats(pool) + assert count > 0 && count < 512 + assert result.unwrap(dict.get(stats, "owned_reserved"), 0) <= count + assert dict.get(stats, "public_reserved") == Ok(count) + list.each(accepted, fn(_) { + let assert Ok(cleanup) = process.receive(cleanups, 5000) + as "a cleanup was not forwarded" + admission.complete(cleanup, fn() { Nil }) + }) + let assert Ok(next) = + admission.submit( + pool, + admission.Preparation, + "after-cleanup", + fn(_) { Prepare }, + fn(_) { Nil }, + ) + admission.cancel(next) + admission.release(next) +} + +/// The failure callback is a deterministic gate between claiming +/// cancellation and its remaining bookkeeping. Owner teardown must not +/// escape as badarg. +pub fn teardown_during_cancel() -> Nil { + let #(runtime, inbox) = fake_runtime(process.new_subject()) + let pool = fake_pool(inbox) + let entered = process.new_subject() + let assert Ok(ticket) = + admission.submit( + pool, + admission.Preparation, + "teardown", + fn(_) { Prepare }, + fn(_) { + let gate = process.new_subject() + process.send(entered, gate) + let assert Ok(Nil) = process.receive(gate, 10_000) + Nil + }, + ) + let results = process.new_subject() + let caller = + process.spawn_unlinked(fn() { + process.send( + results, + albedo_protect.rescue(fn() { admission.cancel(ticket) }), + ) + }) + use <- albedo_protect.finally(after: fn() { + process.kill(caller) + process.kill(runtime) + }) + let assert Ok(gate) = process.receive(entered, 5000) + as "the cancellation was not entered" + let owner = admission.owner(pool) + kill_process(owner) + process.send(gate, Nil) + let assert Ok(Ok(Nil)) = process.receive(results, 5000) + as "the cancellation failed or did not return" + Nil +} diff --git a/apps/albedo/test/albedo/runtime/runtime_ownership_test.gleam b/apps/albedo/test/albedo/runtime/runtime_ownership_test.gleam index 9a5e75522..c74bbf4af 100644 --- a/apps/albedo/test/albedo/runtime/runtime_ownership_test.gleam +++ b/apps/albedo/test/albedo/runtime/runtime_ownership_test.gleam @@ -14,6 +14,7 @@ import albedo/runtime import albedo/runtime/admission import albedo/runtime/boot import albedo/runtime/kernels +import albedo/runtime/ownership_support import albedo/runtime/state as runtime_state import albedo/session/session_fixture import albedo_protect @@ -39,39 +40,49 @@ fn temporary_workspace() -> String @external(erlang, "albedo_runtime_test_support", "cleanup_workspace") fn cleanup_workspace(path: String) -> Nil -@external(erlang, "albedo_runtime_ownership_test_support", "suspend") -fn suspend(pid: Pid) -> Nil +fn suspend(pid: Pid) -> Nil { + ownership_support.suspend(pid) +} -@external(erlang, "albedo_runtime_ownership_test_support", "resume") -fn resume(pid: Pid) -> Nil +fn resume(pid: Pid) -> Nil { + ownership_support.resume(pid) +} -@external(erlang, "albedo_runtime_ownership_test_support", "kernel_pid") -fn kernel_pid(session: runtime.Session) -> Pid +fn kernel_pid(session: runtime.Session) -> Pid { + ownership_support.kernel_pid(session) +} -@external(erlang, "albedo_runtime_ownership_test_support", "rebind_caller") -fn rebind_caller(kernel: Pid) -> Pid +fn rebind_caller(kernel: Pid) -> Pid { + ownership_support.rebind_caller(kernel) +} -@external(erlang, "albedo_runtime_ownership_test_support", "release_and_await_finished") fn release_and_await_finished( worker: Pid, runtime: Pid, release: fn() -> Nil, -) -> Nil +) -> Nil { + ownership_support.release_and_await_finished(worker, runtime, release) +} -@external(erlang, "albedo_runtime_ownership_test_support", "with_runtime_cleanup") -fn with_runtime_cleanup(runtime: Pid, workspace: String, run: fn() -> a) -> a +fn with_runtime_cleanup(runtime: Pid, workspace: String, run: fn() -> a) -> a { + ownership_support.with_runtime_cleanup(runtime, workspace, run) +} -@external(erlang, "albedo_runtime_ownership_test_support", "new_gate") -fn new_gate() -> Subject(Nil) +fn new_gate() -> Subject(Nil) { + ownership_support.new_gate() +} -@external(erlang, "albedo_runtime_ownership_test_support", "await_gate") -fn await_gate(gate: Subject(Nil)) -> Nil +fn await_gate(gate: Subject(Nil)) -> Nil { + ownership_support.await_gate(gate) +} -@external(erlang, "albedo_runtime_ownership_test_support", "submitted_count") -fn submitted_count(owner: Pid) -> Int +fn submitted_count(owner: Pid) -> Int { + ownership_support.submitted_count(owner) +} -@external(erlang, "albedo_runtime_ownership_test_support", "admission_barrier") -fn admission_barrier(host: runtime.Runtime) -> Nil +fn admission_barrier(host: runtime.Runtime) -> Nil { + ownership_support.admission_barrier(host) +} /// What a preparation reports to the test: the resource process an owned /// plugin started, the preparation process that started it, and each time a @@ -638,15 +649,17 @@ pub fn release_reset_reopen_forget_and_stop_close_at_the_right_time_test() -> Ni cleanup_workspace(workspace) } -@external(erlang, "albedo_runtime_ownership_test_support", "unknown_spare_budget") -fn unknown_spare_budget() -> Nil +fn unknown_spare_budget() -> Nil { + ownership_support.unknown_spare_budget() +} pub fn an_unknown_spare_allocation_retains_budget_without_blocking_stop_test() -> Nil { unknown_spare_budget() } -@external(erlang, "albedo_runtime_ownership_test_support", "runtime_state") -fn read_runtime_state(owner: Pid) -> runtime_state.State +fn read_runtime_state(owner: Pid) -> runtime_state.State { + ownership_support.runtime_state(owner) +} /// Different generations can retire resources for the same session. The /// session cleanup map has one entry, but every monitored stop consumes a @@ -708,17 +721,21 @@ pub fn concurrent_retirements_of_one_session_keep_the_stop_bound_test() -> Nil { /// The real runtime is suspended, so none of its queue checks can run. /// Producer reservations must still refuse a burst and settle every callback. -@external(erlang, "albedo_runtime_ownership_test_support", "cleanup_anchor_bound") -pub fn cleanup_intents_retain_their_bounded_preparation_slots_test() -> Nil +pub fn cleanup_intents_retain_their_bounded_preparation_slots_test() -> Nil { + ownership_support.cleanup_anchor_bound() +} -@external(erlang, "albedo_runtime_ownership_test_support", "teardown_during_cancel") -pub fn owner_teardown_during_cancellation_does_not_crash_its_caller_test() -> Nil +pub fn owner_teardown_during_cancellation_does_not_crash_its_caller_test() -> Nil { + ownership_support.teardown_during_cancel() +} -@external(erlang, "albedo_runtime_ownership_test_support", "await_cancelled") -fn await_cancelled(pool: admission.Pool) -> Nil +fn await_cancelled(pool: admission.Pool) -> Nil { + ownership_support.await_cancelled(pool) +} -@external(erlang, "albedo_runtime_ownership_test_support", "await_cleanup_credits") -fn await_cleanup_credits(pool: admission.Pool, count: Int) -> Nil +fn await_cleanup_credits(pool: admission.Pool, count: Int) -> Nil { + ownership_support.await_cleanup_credits(pool, count) +} pub fn relay_requester_death_withdraws_without_runtime_probe_traffic_test() -> Nil { let workspace = temporary_workspace() @@ -980,8 +997,9 @@ pub fn runtime_death_answers_accepted_preparation_once_test() -> Nil { process.send(release, Nil) } -@external(erlang, "albedo_runtime_ownership_test_support", "await_stopped") -fn await_stopped(host: runtime.Runtime, id: String) -> Nil +fn await_stopped(host: runtime.Runtime, id: String) -> Nil { + ownership_support.await_stopped(host, id) +} pub fn saturated_preparation_ingress_does_not_drop_owned_cleanup_test() -> Nil { let workspace = temporary_workspace() @@ -1041,8 +1059,9 @@ pub fn observations_progress_while_all_preparation_workers_are_gated_test() -> N runtime.stop(host) } -@external(erlang, "albedo_runtime_ownership_test_support", "await_shutdown") -fn await_shutdown(host: runtime.Runtime) -> Nil +fn await_shutdown(host: runtime.Runtime) -> Nil { + ownership_support.await_shutdown(host) +} pub fn shutdown_with_queued_preparations_settles_every_request_once_test() -> Nil { let workspace = temporary_workspace() @@ -1094,8 +1113,9 @@ pub fn oversized_callback_is_refused_without_retaining_a_ticket_test() -> Nil { runtime.stop(host) } -@external(erlang, "albedo_runtime_ownership_test_support", "await_deferred") -fn await_deferred(host: runtime.Runtime, id: String) -> Nil +fn await_deferred(host: runtime.Runtime, id: String) -> Nil { + ownership_support.await_deferred(host, id) +} pub fn a_dead_requesters_deferred_reload_never_prepares_again_test() -> Nil { let workspace = temporary_workspace() diff --git a/apps/albedo/test/albedo/runtime/spare_quiet_test.gleam b/apps/albedo/test/albedo/runtime/spare_quiet_test.gleam index 789127b2d..a60154a3b 100644 --- a/apps/albedo/test/albedo/runtime/spare_quiet_test.gleam +++ b/apps/albedo/test/albedo/runtime/spare_quiet_test.gleam @@ -11,6 +11,7 @@ import albedo/composition/extensions import albedo/runtime import albedo/runtime/state as runtime_state +import albedo_property import gleam/erlang/process.{type Subject} type Clock { @@ -50,7 +51,9 @@ fn spare_ready(host: runtime.Runtime, tries: Int) -> Bool { } } -pub fn spares_stay_while_wakes_come_and_go_once_they_stop_test() -> Nil { +/// A real spare boots here, which can outlast eunit's default limit. +pub fn spares_stay_while_wakes_come_and_go_once_they_stop_test_() -> albedo_property.Timed { + use <- albedo_property.within(60) let time = clock() let assert Ok(host) = runtime.start_with_options( diff --git a/apps/albedo/test/albedo/session/albedo_daemon_request_test.erl b/apps/albedo/test/albedo/session/albedo_daemon_request_test.erl deleted file mode 100644 index 48d21da83..000000000 --- a/apps/albedo/test/albedo/session/albedo_daemon_request_test.erl +++ /dev/null @@ -1,94 +0,0 @@ -%% Exact exception classification cannot be asserted through HTTP: application -%% panics and disappearing actor handles must have different failure behavior. --module(albedo_daemon_request_test). --include_lib("eunit/include/eunit.hrl"). - -closed_actor_calls_are_unavailable_test() -> - lists:foreach( - fun(Message) -> - Reason = #{ - module => <<"gleam/erlang/process">>, - function => <<"perform_call">>, - message => Message - }, - ?assertMatch( - {error, Message}, - 'albedo@http@request_guard':http_request(fun() -> - erlang:error(Reason) - end) - ) - end, - [ - <<"callee exited: ProcessDown(..., Normal)">>, - <<"Callee subject had no owner">>, - <<"callee did not send reply before timeout">> - ] - ). - -closed_calls_name_albedos_frames_test() -> - Message = <<"Callee subject had no owner">>, - Reason = #{ - module => <<"gleam/erlang/process">>, - function => <<"perform_call">>, - message => Message - }, - Stack = [ - {'gleam@erlang@process', perform_call, 3, []}, - {'albedo_sdk@store', write, 2, []}, - {'albedo_protect', rescue, 1, []}, - {'albedo@session', run, 1, []}, - {'albedo_ext_demo@feature', go, 1, []}, - {'albedo@http@request_guard', http_request, 1, []}, - {?MODULE, caller, 0, []} - ], - ?assertEqual( - {error, - <>}, - 'albedo@http@request_guard':http_request(fun() -> - erlang:raise(error, Reason, Stack) - end) - ). - -unrelated_errors_keep_their_reason_test() -> - Reasons = [ - #{ - module => <<"application">>, - function => <<"perform_call">>, - message => <<"callee exited: unrelated application error">> - }, - #{ - module => <<"gleam/erlang/process">>, - function => <<"perform_call">>, - message => <<"callee did not send reply before timeout: application error">> - }, - #{ - module => <<"gleam/erlang/process">>, - function => <<"application_call">>, - message => <<"callee did not send reply before timeout">> - }, - application_bug - ], - lists:foreach( - fun(Reason) -> - ?assertException( - error, - Reason, - 'albedo@http@request_guard':http_request(fun() -> - erlang:error(Reason) - end) - ) - end, - Reasons - ), - ?assertException( - throw, - application_bug, - 'albedo@http@request_guard':http_request(fun() -> - throw(application_bug) - end) - ). - -ordinary_responses_pass_through_test() -> - ?assertEqual({ok, response}, 'albedo@http@request_guard':http_request(fun() -> response end)). diff --git a/apps/albedo/test/albedo/session/albedo_running_test.erl b/apps/albedo/test/albedo/session/albedo_running_test.erl deleted file mode 100644 index 11e533bd0..000000000 --- a/apps/albedo/test/albedo/session/albedo_running_test.erl +++ /dev/null @@ -1,107 +0,0 @@ -%% E2E cannot hold an old owner's cleanup behind a replacement publication. -%% Control owner publications and suspend the real progress monitor to verify -%% reads remain safe even before queued death cleanup runs. --module(albedo_running_test). --include_lib("eunit/include/eunit.hrl"). --define(REGISTRY, 'albedo_process@registry'). - -old_owner_cleanup_preserves_replacement_test() -> - Session = make_ref(), - {Previous, PreviousWatcher} = owner(Session), - {Replacement, ReplacementWatcher} = owner(Session), - try - Previous ! {idle, self()}, - receive - {idle, Previous} -> ok - after 5000 -> error(idle_stalled) - end, - ?assertEqual([{Session, Replacement}], ets:lookup(albedo_running, Session)), - nil = 'albedo@observation@bus_queues':forget(Session, Previous), - ?assert('albedo@observation@bus_queues':running(Session)), - stop(Previous), - wait_for_exit(PreviousWatcher), - ?assertEqual([{Session, Replacement}], ets:lookup(albedo_running, Session)), - ?assertMatch( - {ok, {Replacement, _}}, - ?REGISTRY:lookup(?REGISTRY:new(albedo_session_progress), Session) - ) - after - stop(Previous), - stop(Replacement), - wait_for_exit(PreviousWatcher), - wait_for_exit(ReplacementWatcher) - end, - ?assertEqual([], ets:lookup(albedo_running, Session)). - -dead_owner_reads_idle_before_monitor_removes_record_test() -> - Session = make_ref(), - {Owner, Watcher} = owner(Session), - true = erlang:suspend_process(Watcher), - try - ?assert('albedo@observation@bus_queues':running(Session)), - stop(Owner), - ?assertEqual([{Session, Owner}], ets:lookup(albedo_running, Session)), - ?assertNot('albedo@observation@bus_queues':running(Session)) - after - erlang:resume_process(Watcher), - stop(Owner), - wait_for_exit(Watcher) - end, - ?assertEqual([], ets:lookup(albedo_running, Session)), - ?assertEqual({error, nil}, ?REGISTRY:lookup(?REGISTRY:new(albedo_session_progress), Session)). - -owner(Session) -> - %% Initialise detached tables before tracing, leaving only the progress - %% monitor as a spawned child of the registering owner. - nil = ?REGISTRY:register(?REGISTRY:new(albedo_running), warmup, self()), - nil = ?REGISTRY:forget(?REGISTRY:new(albedo_running), warmup), - nil = ?REGISTRY:register(?REGISTRY:new(albedo_session_progress), warmup, self()), - nil = ?REGISTRY:forget(?REGISTRY:new(albedo_session_progress), warmup), - Parent = self(), - Owner = spawn(fun() -> - receive - start -> ok - end, - nil = 'albedo@observation@bus_queues':register_owner(Session, self(), fun(_) -> nil end), - nil = 'albedo@observation@bus_queues':mark_running(Session, true), - Parent ! {ready, self()}, - owner_loop(Session) - end), - erlang:trace(Owner, true, [procs, {tracer, Parent}]), - Owner ! start, - Watcher = - receive - {trace, Owner, spawn, Child, _} -> Child - after 5000 -> error(progress_monitor_missing) - end, - receive - {ready, Owner} -> ok - after 5000 -> error(owner_start_stalled) - end, - erlang:trace(Owner, false, [procs]), - {Owner, Watcher}. - -owner_loop(Session) -> - receive - {idle, Parent} -> - nil = 'albedo@observation@bus_queues':mark_running(Session, false), - Parent ! {idle, self()}, - owner_loop(Session); - stop -> - ok - end. - -stop(Pid) -> - Monitor = monitor(process, Pid), - Pid ! stop, - receive - {'DOWN', Monitor, process, Pid, _} -> ok - after 5000 -> error({owner_stop_stalled, Pid}) - end. - -wait_for_exit(Pid) -> - Monitor = monitor(process, Pid), - receive - {'DOWN', Monitor, process, Pid, _} -> ok - after 5000 -> error({monitor_cleanup_stalled, Pid}) - end. diff --git a/apps/albedo/test/albedo/session/daemon_request_test.gleam b/apps/albedo/test/albedo/session/daemon_request_test.gleam new file mode 100644 index 000000000..285ba75a7 --- /dev/null +++ b/apps/albedo/test/albedo/session/daemon_request_test.gleam @@ -0,0 +1,131 @@ +//// Exact exception classification cannot be asserted through HTTP: +//// application panics and disappearing actor handles must have different +//// failure behavior. + +import albedo/http/request_guard +import albedo_protect +import gleam/dynamic.{type Dynamic} +import gleam/erlang/atom.{type Atom} +import gleam/list +import gleam/string + +@external(erlang, "erlang", "error") +fn error(reason: Dynamic) -> a + +@external(erlang, "erlang", "raise") +fn raise(class: Atom, reason: Dynamic, stack: List(Frame)) -> a + +@external(erlang, "erlang", "throw") +fn throw(reason: Dynamic) -> a + +/// One `{Module, Function, Arity, Location}` stack frame. +type Frame = + #(Atom, Atom, Int, List(Nil)) + +fn properties(map: List(#(String, Dynamic))) -> Dynamic { + dynamic.properties( + list.map(map, fn(entry) { + #(atom.to_dynamic(atom.create(entry.0)), entry.1) + }), + ) +} + +/// A failed call the way `gleam/erlang/process` raises one: a map keyed by +/// atoms, as Gleam's panics are. +fn closed(module: String, function: String, message: String) -> Dynamic { + properties([ + #("module", dynamic.string(module)), + #("function", dynamic.string(function)), + #("message", dynamic.string(message)), + ]) +} + +pub fn closed_actor_calls_are_unavailable_test() -> Nil { + list.each( + [ + "callee exited: ProcessDown(..., Normal)", + "Callee subject had no owner", + "callee did not send reply before timeout", + ], + fn(message) { + let assert Error(answer) = + request_guard.http_request(fn() { + error(closed("gleam/erlang/process", "perform_call", message)) + }) + // This test is albedo code too, so the answer names its frames. + assert string.starts_with( + answer, + message <> " in albedo@session@daemon_request_test:", + ) + }, + ) +} + +pub fn closed_calls_name_albedos_frames_test() -> Nil { + let message = "Callee subject had no owner" + let frame = fn(module, function, arity) { + #(atom.create(module), atom.create(function), arity, []) + } + let stack = [ + frame("gleam@erlang@process", "perform_call", 3), + frame("albedo_sdk@store", "write", 2), + frame("albedo_protect", "rescue", 1), + frame("albedo@session", "run", 1), + frame("albedo_ext_demo@feature", "go", 1), + frame("albedo@http@request_guard", "http_request", 1), + frame("test_caller", "caller", 0), + ] + assert request_guard.http_request(fn() { + raise( + atom.create("error"), + closed("gleam/erlang/process", "perform_call", message), + stack, + ) + }) + == Error( + message + <> " in albedo_sdk@store:write < albedo@session:run" + <> " < albedo_ext_demo@feature:go", + ) +} + +pub fn unrelated_errors_keep_their_reason_test() -> Nil { + let reasons = [ + closed( + "application", + "perform_call", + "callee exited: unrelated application error", + ), + closed( + "gleam/erlang/process", + "perform_call", + "callee did not send reply before timeout: application error", + ), + closed( + "gleam/erlang/process", + "application_call", + "callee did not send reply before timeout", + ), + atom.to_dynamic(atom.create("application_bug")), + ] + list.each(reasons, fn(reason) { + let assert Error(crash) = + albedo_protect.rescue(fn() { + request_guard.http_request(fn() { error(reason) }) + }) + assert crash.class == atom.create("error") + assert crash.reason == reason + }) + let assert Error(crash) = + albedo_protect.rescue(fn() { + request_guard.http_request(fn() { + throw(atom.to_dynamic(atom.create("application_bug"))) + }) + }) + assert crash.class == atom.create("throw") + assert crash.reason == atom.to_dynamic(atom.create("application_bug")) +} + +pub fn ordinary_responses_pass_through_test() -> Nil { + assert request_guard.http_request(fn() { "response" }) == Ok("response") +} diff --git a/apps/albedo/test/albedo/session/running_test.gleam b/apps/albedo/test/albedo/session/running_test.gleam new file mode 100644 index 000000000..5b37bb5d2 --- /dev/null +++ b/apps/albedo/test/albedo/session/running_test.gleam @@ -0,0 +1,167 @@ +//// E2E cannot hold an old owner's cleanup behind a replacement publication. +//// Control owner publications and suspend the real progress monitor to +//// verify reads remain safe even before queued death cleanup runs. + +import albedo/observation/bus_queues +import albedo_process/registry.{type Registry} +import albedo_protect +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/erlang/atom.{type Atom} +import gleam/erlang/process.{type Pid, type Subject} +import gleam/int + +type Command { + Start + Idle(reply: Subject(Nil)) + Stop +} + +@external(erlang, "erlang", "trace") +fn trace(pid: Pid, on: Bool, flags: List(Dynamic)) -> Int + +@external(erlang, "erlang", "suspend_process") +fn suspend(pid: Pid) -> Bool + +@external(erlang, "erlang", "resume_process") +fn resume(pid: Pid) -> Bool + +@external(erlang, "ets", "lookup") +fn ets_lookup(table: Atom, key: String) -> List(#(String, Pid)) + +fn running_rows(session: String) -> List(#(String, Pid)) { + ets_lookup(atom.create("albedo_running"), session) +} + +fn progress() -> Registry(String, #(Pid, Dynamic)) { + registry.new(atom.create("albedo_session_progress")) +} + +/// An owner of `session` that marks it running, and the progress monitor +/// registering it spawned. +fn owner(session: String) -> #(Pid, Subject(Command), Pid) { + // Initialise detached tables before tracing, leaving only the progress + // monitor as a spawned child of the registering owner. + let running = registry.new(atom.create("albedo_running")) + registry.register(running, "warmup", process.self()) + registry.forget(running, "warmup") + registry.register(progress(), "warmup", #(process.self(), dynamic.nil())) + registry.forget(progress(), "warmup") + let mailbox = process.new_subject() + let ready = process.new_subject() + let pid = + process.spawn_unlinked(fn() { + let commands = process.new_subject() + process.send(mailbox, commands) + let assert Ok(Start) = process.receive(commands, 5000) + bus_queues.register_owner(session, process.self(), fn(_) { Nil }) + bus_queues.mark_running(session, True) + process.send(ready, Nil) + owner_loop(session, commands) + }) + let assert Ok(commands) = process.receive(mailbox, 5000) + let _ = + trace(pid, True, [ + atom.to_dynamic(atom.create("procs")), + to_dynamic(#(atom.create("tracer"), process.self())), + ]) + process.send(commands, Start) + let spawned = + process.new_selector() + |> process.select_record(atom.create("trace"), 4, fn(message) { + decode.run(message, { + use kind <- decode.field(2, atom.decoder()) + use child <- decode.field(3, decode.dynamic) + decode.success(#(atom.to_string(kind), child)) + }) + }) + let assert Ok(Ok(#("spawn", child))) = process.selector_receive(spawned, 5000) + as "the progress monitor was not spawned" + let assert Ok(Nil) = process.receive(ready, 5000) + let _ = trace(pid, False, [atom.to_dynamic(atom.create("procs"))]) + #(pid, commands, unsafe_pid(child)) +} + +@external(erlang, "gleam@function", "identity") +fn unsafe_pid(value: Dynamic) -> Pid + +@external(erlang, "gleam@function", "identity") +fn to_dynamic(value: a) -> Dynamic + +fn owner_loop(session: String, commands: Subject(Command)) -> Nil { + case process.receive_forever(commands) { + Idle(reply) -> { + bus_queues.mark_running(session, False) + process.send(reply, Nil) + owner_loop(session, commands) + } + Start -> owner_loop(session, commands) + Stop -> Nil + } +} + +fn await_down(pid: Pid) -> Nil { + let monitor = process.monitor(pid) + let assert Ok(Nil) = + process.new_selector() + |> process.select_specific_monitor(monitor, fn(_) { Nil }) + |> process.selector_receive(5000) + as "a process did not exit" + Nil +} + +fn stop(owner: #(Pid, Subject(Command), Pid)) -> Nil { + process.send(owner.1, Stop) + await_down(owner.0) +} + +fn unique() -> String { + "running-" <> int.to_string(int.random(1_000_000_000)) +} + +pub fn old_owner_cleanup_preserves_replacement_test() -> Nil { + let session = unique() + let previous = owner(session) + let replacement = owner(session) + albedo_protect.finally( + fn() { + let idle = process.new_subject() + process.send(previous.1, Idle(idle)) + let assert Ok(Nil) = process.receive(idle, 5000) + assert running_rows(session) == [#(session, replacement.0)] + bus_queues.forget(session, previous.0) + assert bus_queues.running(session) + stop(previous) + await_down(previous.2) + assert running_rows(session) == [#(session, replacement.0)] + let assert Ok(#(published, _)) = registry.lookup(progress(), session) + assert published == replacement.0 + }, + fn() { + stop(replacement) + await_down(replacement.2) + }, + ) + assert running_rows(session) == [] +} + +pub fn dead_owner_reads_idle_before_monitor_removes_record_test() -> Nil { + let session = unique() + let held = owner(session) + let watcher = held.2 + let _ = suspend(watcher) + albedo_protect.finally( + fn() { + assert bus_queues.running(session) + stop(held) + assert running_rows(session) == [#(session, held.0)] + assert !bus_queues.running(session) + }, + fn() { + let _ = resume(watcher) + await_down(watcher) + }, + ) + assert running_rows(session) == [] + assert registry.lookup(progress(), session) == Error(Nil) +} diff --git a/apps/albedo/test/albedo/session/turn_lifecycle_test.gleam b/apps/albedo/test/albedo/session/turn_lifecycle_test.gleam index 0c1f5ae08..15a7e5ce3 100644 --- a/apps/albedo/test/albedo/session/turn_lifecycle_test.gleam +++ b/apps/albedo/test/albedo/session/turn_lifecycle_test.gleam @@ -9,6 +9,7 @@ //// versions with their inspection probes are not needed. import albedo/runtime +import albedo/runtime/ownership_support import albedo/session import albedo/support/turn_harness as h import albedo_model as types @@ -18,11 +19,13 @@ import gleam/list import gleam/option.{None} import gleam/string -@external(erlang, "albedo_runtime_ownership_test_support", "suspend") -fn suspend(pid: Pid) -> Nil +fn suspend(pid: Pid) -> Nil { + ownership_support.suspend(pid) +} -@external(erlang, "albedo_runtime_ownership_test_support", "resume") -fn resume(pid: Pid) -> Nil +fn resume(pid: Pid) -> Nil { + ownership_support.resume(pid) +} @external(erlang, "albedo_turn_lifecycle_test_support", "queue_length") fn queue_length(pid: Pid) -> Int diff --git a/apps/albedo/test/albedo/storage/albedo_attachment_storage_test.erl b/apps/albedo/test/albedo/storage/albedo_attachment_storage_test.erl deleted file mode 100644 index 6bc0c6d9f..000000000 --- a/apps/albedo/test/albedo/storage/albedo_attachment_storage_test.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% A Python kernel can hold a file open while concurrent input admissions -%% publish the same path. HTTP E2E cannot pause that OS reader deterministically; -%% this descriptor invariant catches in-place truncation without a timing race. --module(albedo_attachment_storage_test). --include_lib("eunit/include/eunit.hrl"). - -replacement_keeps_open_readers_on_complete_snapshot_test() -> - Dir = filename:join( - os:getenv("TMPDIR", "/tmp"), - "albedo-attachment-storage-" ++ os:getpid() ++ "-" ++ - integer_to_list(erlang:unique_integer([positive])) - ), - Path = unicode:characters_to_binary(filename:join(Dir, "attachment.txt")), - {ok, nil} = 'albedo@attachments@pastes':save(Path, <<"original bytes">>), - {ok, Reader} = file:open(Path, [read, binary, raw]), - try - ?assertEqual({ok, nil}, 'albedo@attachments@pastes':save(Path, <<"replacement bytes">>)), - ?assertEqual({ok, <<"replacement bytes">>}, file:read_file(Path)), - ?assertEqual({ok, <<"original bytes">>}, file:read(Reader, 64)) - after - file:close(Reader), - file:del_dir_r(Dir) - end. diff --git a/apps/albedo/test/albedo/storage/attachment_storage_test.gleam b/apps/albedo/test/albedo/storage/attachment_storage_test.gleam new file mode 100644 index 000000000..9b5ab5ae3 --- /dev/null +++ b/apps/albedo/test/albedo/storage/attachment_storage_test.gleam @@ -0,0 +1,45 @@ +//// A Python kernel can hold a file open while concurrent input admissions +//// publish the same path. HTTP E2E cannot pause that OS reader +//// deterministically; this descriptor invariant catches in-place truncation +//// without a timing race. + +import albedo/attachments/pastes +import albedo_file +import gleam/dynamic.{type Dynamic} +import gleam/erlang/atom.{type Atom} +import gleam/int + +type Mode { + Read + Binary + Raw +} + +@external(erlang, "file", "open") +fn open(path: String, modes: List(Mode)) -> Result(Dynamic, Dynamic) + +@external(erlang, "file", "read") +fn read(device: Dynamic, size: Int) -> Result(BitArray, Dynamic) + +@external(erlang, "file", "close") +fn close(device: Dynamic) -> Atom + +@external(erlang, "file", "del_dir_r") +fn delete_tree(path: String) -> Dynamic + +pub fn replacement_keeps_open_readers_on_complete_snapshot_test() -> Nil { + let dir = + "/tmp/albedo-attachment-storage-" + <> int.to_string(int.random(1_000_000_000)) + let path = dir <> "/attachment.txt" + let assert Ok(Nil) = pastes.save(path, <<"original bytes">>) + let assert Ok(reader) = open(path, [Read, Binary, Raw]) + let replaced = pastes.save(path, <<"replacement bytes">>) + let published = albedo_file.read(path) + let kept = read(reader, 64) + let _ = close(reader) + let _ = delete_tree(dir) + assert replaced == Ok(Nil) + assert published == Ok(<<"replacement bytes">>) + assert kept == Ok(<<"original bytes">>) +} diff --git a/apps/albedo/test/albedo/transfer/albedo_transfers_test.erl b/apps/albedo/test/albedo/transfer/albedo_transfers_test.erl deleted file mode 100644 index 3b2f2e006..000000000 --- a/apps/albedo/test/albedo/transfer/albedo_transfers_test.erl +++ /dev/null @@ -1,46 +0,0 @@ -%% An import's worker is one process per transfer, so a wake that lands while -%% it is still on its last step cannot be seen by E2E without holding that step. --module(albedo_transfers_test). --include_lib("eunit/include/eunit.hrl"). - -a_wake_during_the_last_step_runs_the_work_again_test() -> - Parent = self(), - Key = list_to_binary(integer_to_list(erlang:unique_integer([positive]))), - Work = fun() -> - Parent ! {step, self()}, - receive - release -> ok - end - end, - ?assert('albedo@transfer@transfer_files':run_once(Key, Work)), - First = - receive - {step, Pid} -> Pid - after 5000 -> error(no_first_step) - end, - %% The state a wake wrote is not read by a step already past its read. - ?assertNot('albedo@transfer@transfer_files':run_once(Key, Work)), - Monitor = erlang:monitor(process, First), - First ! release, - Second = - receive - {step, Again} -> Again - after 5000 -> error(wake_lost) - end, - Second ! release, - receive - {'DOWN', Monitor, process, First, _} -> ok - after 5000 -> error(no_exit) - end, - wait_unregistered(Key, 50). - -wait_unregistered(_, 0) -> - error(still_registered); -wait_unregistered(Key, N) -> - case global:whereis_name({albedo_transfer, Key}) of - undefined -> - ok; - _ -> - timer:sleep(20), - wait_unregistered(Key, N - 1) - end. diff --git a/apps/albedo/test/albedo/transfer/transfers_test.gleam b/apps/albedo/test/albedo/transfer/transfers_test.gleam new file mode 100644 index 000000000..c03cba69b --- /dev/null +++ b/apps/albedo/test/albedo/transfer/transfers_test.gleam @@ -0,0 +1,53 @@ +//// An import's worker is one process per transfer, so a wake that lands +//// while it is still on its last step cannot be seen by E2E without +//// holding that step. + +import albedo/transfer/transfer_files +import gleam/dynamic.{type Dynamic} +import gleam/erlang/atom.{type Atom} +import gleam/erlang/process.{type Pid, type Subject} +import gleam/int + +@external(erlang, "global", "whereis_name") +fn global_whereis(name: #(Atom, String)) -> Dynamic + +fn registered(key: String) -> Bool { + global_whereis(#(atom.create("albedo_transfer"), key)) + != atom.to_dynamic(atom.create("undefined")) +} + +fn wait_unregistered(key: String, tries: Int) -> Bool { + case registered(key), tries { + False, _ -> True + True, 0 -> False + True, _ -> { + process.sleep(20) + wait_unregistered(key, tries - 1) + } + } +} + +pub fn a_wake_during_the_last_step_runs_the_work_again_test() -> Nil { + let steps: Subject(#(Pid, Subject(Nil))) = process.new_subject() + let key = int.to_string(int.random(1_000_000_000)) + let work = fn() { + let release = process.new_subject() + process.send(steps, #(process.self(), release)) + let assert Ok(Nil) = process.receive(release, 10_000) + Nil + } + assert transfer_files.run_once(key, work) + let assert Ok(#(first, release_first)) = process.receive(steps, 5000) + // The state a wake wrote is not read by a step already past its read. + assert !transfer_files.run_once(key, work) + let monitor = process.monitor(first) + process.send(release_first, Nil) + let assert Ok(#(_, release_second)) = process.receive(steps, 5000) + as "the wake was lost" + process.send(release_second, Nil) + let assert Ok(Nil) = + process.new_selector() + |> process.select_specific_monitor(monitor, fn(_) { Nil }) + |> process.selector_receive(5000) + assert wait_unregistered(key, 50) +} diff --git a/robot-docs/contributing.md b/robot-docs/contributing.md index 4c629fb21..3d40ca197 100644 --- a/robot-docs/contributing.md +++ b/robot-docs/contributing.md @@ -48,6 +48,15 @@ and encode JSON at the wire boundary. Do not encode an observation to JSON and parse it again to add fields. See [`command.StateOp`](../packages/albedo_sdk/src/albedo_sdk/command.gleam). +Tests follow the same rule. Write a test, or a test support module, in Gleam, +with `@external` bindings for the OTP calls it needs. Do not `-include` a +generated Gleam record header in Erlang, and do not build or match a Gleam value +as a positional tuple there. `gleam build` does not recompile an Erlang file +when only the header it includes changes, so after a record change the test runs +a stale module and fails with `badrecord`. A Gleam module that reads another +process's mailbox coerces each message to its Gleam type and matches the +constructor, so the compiler keeps it in step with the type. + Carry a refusal as a typed value from the place that decides it. Daemon operations return a [`Refusal`](../apps/albedo/src/albedo/refusal.gleam) variant, and `refusal.failure` is the only place that chooses its HTTP status, diff --git a/robot-docs/runtime.md b/robot-docs/runtime.md index 156ab82eb..b07ed3e81 100644 --- a/robot-docs/runtime.md +++ b/robot-docs/runtime.md @@ -27,7 +27,7 @@ The synchronous `open_session` waits up to 180 seconds and returns A boot worker opens the kernel through the state's `open_kernel`, `kernels.open_with_spare` in the daemon. [`runtime.start_with_options`](../apps/albedo/src/albedo/runtime.gleam) takes -another, a spare count, and a monotonic clock in place of +another, a spare count, a spare starter, and a monotonic clock in place of `runtime.default_options()`. A test can hold a boot, fail it, or hand back a kernel of its own, as [kernel_open_test](../apps/albedo/test/albedo/runtime/kernel_open_test.gleam) -- knotmirror 0.0.1