diff --git a/agents.md b/agents.md index 1df7a7b10..53e2ff3c4 100644 --- a/agents.md +++ b/agents.md @@ -43,7 +43,7 @@ Test placement (expanded rules in `.agents/skills/writing-tests/SKILL.md`): the ### Private daemons -An experiment, eval or reproduction that needs a second daemon starts it with its own `ALBEDO_HOME` and an `ALBEDO_DAEMON` copy from `test/snapshot-daemon.sh`, and must not leave it running: the CLI starts the daemon detached, so it outlives the command. Set `ALBEDO_PARENT_PID` to the pid of the process that owns the run (the eval script, not the CLI, which exits at once) and the daemon stops when that process does; the e2e harnesses do this for their runners. End the run with `albedo daemon --stop` under the same environment, and check `ps` for daemons whose environment names your home before you report done. +An experiment, eval or reproduction that needs a second daemon starts it with its own `ALBEDO_HOME` and an `ALBEDO_DAEMON` copy from `test/snapshot-daemon.sh`, and must not leave it running: the CLI starts the daemon detached, so it outlives the command. Set `ALBEDO_PARENT_PID` to the pid of the process that owns the run (the eval script, not the CLI, which exits at once) and the daemon stops when that process does; the e2e harnesses do this for their runners. A sealed `ALBEDO_DAEMON` also gets a standby VM after each launch (robot-docs/runtime.md, "standby"): point `ALBEDO_STANDBY_DIR` at a short directory of your own, or set `ALBEDO_STANDBY=0`; it too ends with `ALBEDO_PARENT_PID`. End the run with `albedo daemon --stop` under the same environment, and check `ps` for daemons whose environment names your home before you report done. ### Looking at UI changes diff --git a/cli/internal/localdaemon/detach_other.go b/cli/internal/localdaemon/detach_other.go index 4f7102ab1..dfb1ca372 100644 --- a/cli/internal/localdaemon/detach_other.go +++ b/cli/internal/localdaemon/detach_other.go @@ -4,6 +4,7 @@ package localdaemon import ( "errors" + "net" "os" "os/exec" ) @@ -19,3 +20,7 @@ func tryLauncherLock(*os.File) (bool, error) { return false, errors.New("local daemon launch requires a platform with advisory file locks") } func endpointGone(error) bool { return false } + +func handOver(*exec.Cmd, *os.File) (*net.UnixConn, <-chan error, bool) { return nil, nil, false } + +func startStandby(LocalOptions) {} diff --git a/cli/internal/localdaemon/lifecycle.go b/cli/internal/localdaemon/lifecycle.go index ee6c89226..19462743e 100644 --- a/cli/internal/localdaemon/lifecycle.go +++ b/cli/internal/localdaemon/lifecycle.go @@ -159,6 +159,9 @@ func AttachOrLaunch(ctx context.Context, options LocalOptions, snapshot daemon.C if err != nil && restartingEndpoint(err) { return Launch(ctx, options) } + if err == nil { + startStandby(options) + } return connection, err } @@ -245,7 +248,7 @@ func LocalCommand(ctx context.Context, options LocalOptions, args ...string) (*e for _, entry := range os.Environ() { key, _, _ := strings.Cut(entry, "=") switch key { - case "ALBEDO_API_KEY", "ALBEDO_MODEL", "ALBEDO_BASE_URL", "ALBEDO_PROTOCOL", "ALBEDO_HOME": + case "ALBEDO_API_KEY", "ALBEDO_MODEL", "ALBEDO_BASE_URL", "ALBEDO_PROTOCOL", "ALBEDO_HOME", "ALBEDO_STANDBY_SERVE", "ALBEDO_STANDBY_ENV": default: cmd.Env = append(cmd.Env, entry) } @@ -347,7 +350,16 @@ func Upgrade(parent context.Context, options LocalOptions, approved daemon.Conne return launchLocal(parent, options, &approved) } +// launchLocal leaves a standby for the next launch behind every success. func launchLocal(parent context.Context, options LocalOptions, approved *daemon.ConnectionSnapshot) (*daemon.Connection, error) { + connection, err := launchHome(parent, options, approved) + if err == nil { + startStandby(options) + } + return connection, err +} + +func launchHome(parent context.Context, options LocalOptions, approved *daemon.ConnectionSnapshot) (*daemon.Connection, error) { lockCtx, cancelLock := context.WithTimeout(parent, startupDelay(startupLimit)) defer cancelLock() if err := parent.Err(); err != nil { @@ -445,13 +457,20 @@ func startLocal(parent context.Context, cmd *exec.Cmd, options LocalOptions) (*d logFile.Close() return nil, err } - if err := cmd.Start(); err != nil { + // A standby of this build becomes the daemon; anything else boots cold. + handover, exited, warm := handOver(cmd, logFile) + if warm { + defer handover.Close() + } else if err := cmd.Start(); err != nil { logFile.Close() return nil, err } logFile.Close() - exited := make(chan error, 1) - go func() { exited <- cmd.Wait() }() + if !warm { + started := make(chan error, 1) + go func() { started <- cmd.Wait() }() + exited = started + } contended := false progress := watchStartup(options.HomeDir) progress.logSize = logStart @@ -472,8 +491,7 @@ func startLocal(parent context.Context, cmd *exec.Cmd, options LocalOptions) (*d select { case waitErr := <-exited: exited = nil - var exit *exec.ExitError - if errors.As(waitErr, &exit) && exit.ExitCode() == 75 { + if exitStatus(waitErr) == 75 { contended = true } else { return nil, &LocalError{Kind: StartupFailed, HomeDir: options.HomeDir, Cause: startupExitError(waitErr, logPath, logStart, options.ProjectRoot)} @@ -491,6 +509,27 @@ func startLocal(parent context.Context, cmd *exec.Cmd, options LocalOptions) (*d } } +// standbyExit is a handed-over daemon's end, as its handover socket reports it. +type standbyExit struct{ status int } + +func (e *standbyExit) Error() string { + if e.status < 0 { + return "daemon closed its handover connection" + } + return fmt.Sprintf("exit status %d", e.status) +} + +// exitStatus is a launched daemon's exit status, or -1 when it is unknown. +func exitStatus(err error) int { + if exit, ok := errors.AsType[*exec.ExitError](err); ok { + return exit.ExitCode() + } + if exit, ok := errors.AsType[*standbyExit](err); ok { + return exit.status + } + return -1 +} + func startupWaitError(home, logPath string, contended bool, reason string) error { if contended { return &LocalError{Kind: HomeInUse, HomeDir: home, Cause: fmt.Errorf("home is held by another daemon or maintenance command; wait for it to finish and retry: %w", context.DeadlineExceeded)} diff --git a/cli/internal/localdaemon/standby_unix.go b/cli/internal/localdaemon/standby_unix.go new file mode 100644 index 000000000..2facf4082 --- /dev/null +++ b/cli/internal/localdaemon/standby_unix.go @@ -0,0 +1,233 @@ +//go:build unix + +package localdaemon + +import ( + "bytes" + "context" + "encoding/binary" + "encoding/json" + "errors" + "io" + "io/fs" + "net" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "syscall" + "time" +) + +// A standby answers within this long or the launch goes cold. +const standbySilence = 50 * time.Millisecond + +// standbyBase is the per-user directory standbys advertise in, created 0700, +// or "" when standbys are off or the directory is not this user's alone. The +// mode is the access check: only this user (or root) can reach a socket in it. +func standbyBase() string { + if os.Getenv("ALBEDO_STANDBY") == "0" { + return "" + } + base := os.Getenv("ALBEDO_STANDBY_DIR") + if base == "" { + if runtime := os.Getenv("XDG_RUNTIME_DIR"); runtime != "" { + base = filepath.Join(runtime, "albedo-standby") + } else { + base = filepath.Join(os.TempDir(), "albedo-standby-"+strconv.Itoa(os.Getuid())) + } + } + if err := os.Mkdir(base, 0o700); err != nil && !errors.Is(err, fs.ErrExist) { + return "" + } + info, err := os.Lstat(base) + if err != nil || !info.IsDir() || info.Mode().Perm()&0o077 != 0 { + return "" + } + if stat, ok := info.Sys().(*syscall.Stat_t); !ok || int(stat.Uid) != os.Getuid() { + return "" + } + return base +} + +// sealedDigest is the build seal of the application a daemon executable runs: +// a packaged wrapper's /lib/albedo/albedo, a test snapshot's +// /albedo, or the app around /priv/bin. Unsealed builds have none. +func sealedDigest(executable string) string { + resolved, err := filepath.EvalSymlinks(executable) + if err != nil { + return "" + } + dir := filepath.Dir(resolved) + for _, app := range []string{filepath.Join(dir, "..", "lib", "albedo", "albedo"), filepath.Join(dir, "albedo"), filepath.Dir(filepath.Dir(dir))} { + data, err := os.ReadFile(filepath.Join(app, ".build-digest")) + if err == nil && len(data) == 65 && data[64] == '\n' && strings.Trim(string(data[:64]), "0123456789abcdef") == "" { + return string(data[:64]) + } + } + return "" +} + +type standbyRecord struct { + Pid int `json:"pid"` + Digest string `json:"digest"` + Socket string `json:"socket"` +} + +// liveStandby reads the record a standby of this build wrote and reports +// whether its process still runs. +func liveStandby(base, digest string) (standbyRecord, bool) { + var record standbyRecord + data, err := os.ReadFile(filepath.Join(base, digest[:16]+".json")) + if err != nil || json.Unmarshal(data, &record) != nil || record.Digest != digest || record.Pid <= 0 { + return record, false + } + err = syscall.Kill(record.Pid, 0) + return record, err == nil || errors.Is(err, syscall.EPERM) +} + +func environment(entries []string) map[string]string { + values := make(map[string]string, len(entries)) + for _, entry := range entries { + if key, value, ok := strings.Cut(entry, "="); ok { + values[key] = value + } + } + return values +} + +// handOver gives the home this command would boot to a standby of the same +// build: the environment, working directory and log descriptor the command +// would have started with. It reports false, and nothing has started, when no +// standby answers in time or one refuses. A taken handover reports the +// daemon's exit on the returned channel. +func handOver(cmd *exec.Cmd, log *os.File) (*net.UnixConn, <-chan error, bool) { + digest := sealedDigest(cmd.Path) + if digest == "" { + return nil, nil, false + } + base := standbyBase() + if base == "" { + return nil, nil, false + } + record, alive := liveStandby(base, digest) + if !alive { + return nil, nil, false + } + dialed, err := net.DialTimeout("unix", record.Socket, standbySilence) + if err != nil { + return nil, nil, false + } + conn := dialed.(*net.UnixConn) + if !offer(conn, cmd, digest, log) { + conn.Close() + return nil, nil, false + } + exited := make(chan error, 1) + go func() { + output, _ := io.ReadAll(io.LimitReader(conn, 64)) + status := -1 + if code, ok := strings.CutPrefix(strings.TrimSpace(string(output)), "exit "); ok { + if parsed, err := strconv.Atoi(code); err == nil { + status = parsed + } + } + exited <- &standbyExit{status: status} + }() + return conn, exited, true +} + +func offer(conn *net.UnixConn, cmd *exec.Cmd, digest string, log *os.File) bool { + cwd := cmd.Dir + if cwd == "" { + var err error + if cwd, err = os.Getwd(); err != nil { + return false + } + } + var limit syscall.Rlimit + if syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit) != nil { + return false + } + request, err := json.Marshal(map[string]any{ + "digest": digest, "max_fds": limit.Cur, "cwd": cwd, "env": environment(cmd.Env), + }) + if err != nil { + return false + } + message := binary.BigEndian.AppendUint32(nil, uint32(len(request))) + message = append(message, request...) + if conn.SetDeadline(time.Now().Add(standbySilence)) != nil { + return false + } + // A stream socket may take only part of the message with the descriptor. + sent, _, err := conn.WriteMsgUnix(message, syscall.UnixRights(int(log.Fd())), nil) + if err != nil { + return false + } + if _, err := conn.Write(message[sent:]); err != nil { + return false + } + answer := make([]byte, 0, 128) + buffer := make([]byte, 128) + for !bytes.Contains(answer, []byte("\n")) && len(answer) < 4096 { + n, err := conn.Read(buffer) + if err != nil { + return false + } + answer = append(answer, buffer[:n]...) + } + if string(answer) != "ok\n" { + return false + } + if _, err := conn.Write([]byte("go\n")); err != nil { + return false + } + return conn.SetDeadline(time.Time{}) == nil +} + +// startStandby starts one detached standby for this build unless one runs. +// Its stdout and stderr are a pipe it reads itself (fd 3) and relays to the +// log of whichever daemon it becomes. +func startStandby(options LocalOptions) { + cmd, err := LocalCommand(context.Background(), options) + if err != nil { + return + } + digest := sealedDigest(cmd.Path) + if digest == "" { + return + } + base := standbyBase() + // Its socket, /<16 hex>-.sock, must fit a sockaddr_un. + if base == "" || len(base)+30 > 103 { + return + } + if _, alive := liveStandby(base, digest); alive { + return + } + env := make([]string, 0, len(cmd.Env)+2) + for _, entry := range cmd.Env { + if !strings.HasPrefix(entry, "ALBEDO_HOME=") { + env = append(env, entry) + } + } + launched, err := json.Marshal(environment(env)) + if err != nil { + return + } + cmd.Env = append(env, "ALBEDO_STANDBY_SERVE="+base, "ALBEDO_STANDBY_ENV="+string(launched)) + read, write, err := os.Pipe() + if err != nil { + return + } + defer read.Close() + defer write.Close() + cmd.Stdout, cmd.Stderr, cmd.ExtraFiles = write, write, []*os.File{read} + detach(cmd) + passFileLimit() + if cmd.Start() == nil { + go func() { _ = cmd.Wait() }() + } +} diff --git a/cli/test/e2e/harness_test.go b/cli/test/e2e/harness_test.go index d80a3acd1..d5adc6ae7 100644 --- a/cli/test/e2e/harness_test.go +++ b/cli/test/e2e/harness_test.go @@ -301,6 +301,8 @@ func hermeticEnv(root, home, userHome, scratch, daemonExe, sshBin string) []stri "ALBEDO_IDLE_SECONDS=10", "ALBEDO_KERNEL_GRACE_SECONDS=20", "ALBEDO_PRELOAD=0", + // One daemon serves the whole suite; a standby would only idle. + "ALBEDO_STANDBY=0", // Two schedulers keep a booting test VM from pinning every core. "ERL_FLAGS=+S 2:2 +SDcpu 2:2 +sbwt none +sbwtdcpu none +sbwtdio none", ) diff --git a/priv/ready-modules.txt b/priv/ready-modules.txt new file mode 100644 index 000000000..49eb94d81 --- /dev/null +++ b/priv/ready-modules.txt @@ -0,0 +1,322 @@ +albedo +albedo@@main +albedo@clock +albedo@daemon@acp_attachments +albedo@daemon@configuration +albedo@daemon@conversation +albedo@daemon@core_settings +albedo@daemon@family +albedo@daemon@http_api +albedo@daemon@http_coding +albedo@daemon@images +albedo@daemon@listener +albedo@daemon@mail +albedo@daemon@maintenance +albedo@daemon@migrations +albedo@daemon@migrations@conversation_columns +albedo@daemon@migrations@image_store +albedo@daemon@migrations@mail_kinds +albedo@daemon@migrations@session_profiles +albedo@daemon@migrations@transcript_classes +albedo@daemon@operations +albedo@daemon@quota +albedo@daemon@registry +albedo@daemon@server +albedo@daemon@session_configuration +albedo@daemon@session_preferences +albedo@daemon@session_workspace +albedo@daemon@store +albedo@daemon@store@checkpoint +albedo@daemon@store@readers +albedo@daemon@usage +albedo@daemon@webhook_intake +albedo@harness@command +albedo@harness@compaction +albedo@harness@extension +albedo@harness@extension@selection +albedo@harness@extensions +albedo@harness@extensions@artifacts@ledger +albedo@harness@extensions@cua@extension +albedo@harness@extensions@discord@extension +albedo@harness@extensions@discord@ledger +albedo@harness@extensions@discord@manager +albedo@harness@extensions@exa@extension +albedo@harness@extensions@lcm@extension +albedo@harness@extensions@lcm@graph +albedo@harness@extensions@links@ledger +albedo@harness@extensions@mcp@extension +albedo@harness@extensions@models@extension +albedo@harness@extensions@notes@extension +albedo@harness@extensions@paperclips@ledger +albedo@harness@extensions@paperclips@migrations@reply +albedo@harness@extensions@paperclips@migrations@resolution +albedo@harness@extensions@paperclips@migrations@revision +albedo@harness@extensions@paperclips@migrations@scope +albedo@harness@extensions@paperclips@migrations@title +albedo@harness@extensions@perplexity@search +albedo@harness@extensions@python@cells +albedo@harness@extensions@python@kernel +albedo@harness@extensions@python@link +albedo@harness@extensions@python@migrations@cell_images +albedo@harness@extensions@python@migrations@kernel_links +albedo@harness@extensions@remote@extension +albedo@harness@extensions@rolling@extension +albedo@harness@extensions@rolling@migrations@observation +albedo@harness@extensions@schedule@ledger +albedo@harness@extensions@schedule@migrations@revision +albedo@harness@extensions@skills@loads +albedo@harness@extensions@snapcompact@extension +albedo@harness@extensions@warm@extension +albedo@harness@extensions@webhooks@ledger +albedo@harness@extensions@work@ledger +albedo@harness@extensions@work@migrations@cwd +albedo@harness@links +albedo@harness@protect +albedo@harness@runtime +albedo@harness@runtime@boot +albedo@harness@runtime@state +albedo@harness@settings +albedo@harness@settings@projection +albedo@harness@web_search +albedo@shared +albedo@startup +albedo_account_migration +albedo_acp +albedo_active_output +albedo_agents +albedo_antigravity +albedo_capabilities +albedo_claude_auth +albedo_clock +albedo_code +albedo_credentials +albedo_daemon +albedo_discord +albedo_extension_cache +albedo_extension_settings +albedo_http_api +albedo_inspect +albedo_lock +albedo_mailbox +albedo_openai_auth +albedo_opencode_go +albedo_operations +albedo_protect +albedo_python +albedo_registry +albedo_registry_host +albedo_session +albedo_session_preferences +albedo_settings_http +albedo_settings_lock +albedo_settings_store +albedo_stalls +albedo_standby +albedo_state_expiry +albedo_storage_cli +albedo_wakes +application +application_controller +application_master +atomics +auth +beam_lib +binary +c +calendar +code +code_server +counters +crypto +dist_util +dtls_connection_sup +dtls_listener_sup +dtls_server_session_cache_sup +dtls_server_sup +dtls_sup +edlin +edlin_key +epp +erl_anno +erl_distribution +erl_epmd +erl_eval +erl_features +erl_init +erl_internal +erl_lint +erl_parse +erl_prim_loader +erl_scan +erl_signal_handler +erl_tracer +erlang +erpc +error_handler +error_logger +erts_code_purger +erts_dirty_process_signal_handler +erts_internal +erts_literal_area_collector +erts_trace_cleaner +esqlite3 +esqlite3_nif +ets +exception_ffi +file +file_io_server +file_server +filelib +filename +gb_sets +gb_trees +gen +gen_event +gen_server +gen_statem +gen_tcp +gleam@bit_array +gleam@bool +gleam@bytes_tree +gleam@dict +gleam@dynamic +gleam@dynamic@decode +gleam@erlang@process +gleam@http +gleam@http@request +gleam@http@response +gleam@int +gleam@json +gleam@list +gleam@option +gleam@otp@actor +gleam@otp@factory_supervisor +gleam@otp@static_supervisor +gleam@otp@supervision +gleam@pair +gleam@result +gleam@string +gleam@string_tree +gleam@uri +gleam_erlang_ffi +gleam_json_ffi +gleam_otp_external +gleam_stdlib +glisten +glisten@internal@acceptor +glisten@internal@handler +glisten@internal@listener +glisten@socket@options +glisten@tcp +glisten@transport +glisten_ffi +glisten_tcp_ffi +global +global_group +group +heart +inet +inet_config +inet_db +inet_parse +inet_tcp +inet_tcp_dist +inet_udp +init +io +io_lib +io_lib_format +json +kernel +kernel_config +kernel_refc +lists +logger +logger_backend +logger_config +logger_filters +logger_formatter +logger_h_common +logger_handler_watcher +logger_olp +logger_proxy +logger_server +logger_simple_h +logger_std_h +logger_sup +maps +mist +mist@internal@clock +mist@internal@encoder +mist@internal@handler +mist@internal@http +mist@internal@http@handler +mist_ffi +net_kernel +orddict +ordsets +os +otp_internal +peer +persistent_term +prim_buffer +prim_eval +prim_file +prim_inet +prim_net +prim_socket +prim_tty +prim_tty_sighandler +prim_zip +proc_lib +proplists +queue +rand +raw_file_io +raw_file_io_list +re +rpc +sets +socket_registry +sqlight +sqlight_ffi +ssl_admin_sup +ssl_app +ssl_client_session_cache_db +ssl_config +ssl_connection_sup +ssl_listen_tracker_sup +ssl_logger +ssl_manager +ssl_pem_cache +ssl_pkix_db +ssl_server_session_cache_sup +ssl_sup +ssl_upgrade_server_session_cache_sup +standard_error +string +supervisor +supervisor_bridge +sys +timer +tls_client_ticket_store +tls_connection_sup +tls_server_session_ticket_sup +tls_server_sup +tls_sup +unicode +unicode_util +uri_string +user_drv +user_sup +yamerl_app +yamerl_node_binary +yamerl_node_bool +yamerl_node_float +yamerl_node_int +yamerl_node_map +yamerl_node_null +yamerl_node_seq +yamerl_node_str +yamerl_sup +zlib diff --git a/robot-docs/runtime.md b/robot-docs/runtime.md index c6f29af60..ad60d4e38 100644 --- a/robot-docs/runtime.md +++ b/robot-docs/runtime.md @@ -103,6 +103,59 @@ to match. Polling and HTTP probe budgets remain unchanged. A stalled startup reports the log path and leaves the detached process running; check that log before retrying. A child exit reports its startup log immediately. +## standby + +A sealed build boots from a standby when one is waiting: a VM the CLI started +with the daemon's own launcher and arguments, holding the dependency apps and +the code a ready daemon has loaded (`priv/ready-modules.txt` and +`priv/boot-modules.txt`, both written by `test/manual/record_boot_modules.py`). +It waits in `albedo_standby:wait/0`, which `albedo.main` calls before +`server.main`. Until a CLI hands it a home it opens no storage, binds no TCP +port, holds no lock and writes no `daemon.json`. Nothing it runs before the +handover may read HOME, ALBEDO_HOME or other user settings; loading a module +runs none of its code. + +Standbys live in `ALBEDO_STANDBY_DIR`, else `$XDG_RUNTIME_DIR/albedo-standby`, +else `$TMPDIR/albedo-standby-`. The CLI creates it 0700, and the CLI and +the standby both refuse it when it is not this user's alone; that mode is the +access check, so there is no peer-credential check. Each build has +`.json` (pid, digest, socket), `-.sock`, and +`-.log` with the standby's output before a handover. A +checkout's build has no `.build-digest` and never uses one. + +After a successful launch or attach the CLI starts one standby unless the +record names a live process: `ALBEDO_STANDBY_SERVE` names the directory, +`ALBEDO_STANDBY_ENV` carries the environment it was started with, and its +stdout and stderr are a pipe whose read end it gets as fd 3. It writes its +record before loading; a CLI that arrives meanwhile boots cold. It exits after +`ALBEDO_STANDBY_IDLE` seconds (600) without a handover, and with +`ALBEDO_PARENT_PID` when that is set. `ALBEDO_STANDBY=0` turns standbys off in +the CLI. + +The launching CLI, holding `launcher.lock`, connects within 50 ms and sends a +4-byte length, a JSON request (digest, open-file limit, working directory, +environment) and `daemon.log`'s descriptor (SCM_RIGHTS). The standby removes +its socket and record on accept, so a second CLI boots cold. It refuses, and +exits, when the digest differs, when the CLI's soft `RLIMIT_NOFILE` is not the +VM's `max_fds` (port programs keep the limit the VM started with), when an +`ERL_*` variable differs from its start, or when `ALBEDO_INSPECT` is set and +HOME is not the VM's `-home` (distribution reads its cookie file there). The CLI +then boots cold. Otherwise it rebuilds the environment the launcher would have +made from the CLI's (variables the launcher added stay, a prefix it put on one, +such as a wrapper's PATH, goes on the new value), changes directory, answers +`ok`, and on `go` returns into `server.main`, which runs from `defaults()` as in +a cold boot. The VM keeps the stdio it started with, which port programs +inherit, so a relay copies that pipe to the handed-over log; +`albedo_standby:flush/0` runs before the daemon halts. The CLI holds the +connection until the daemon is ready: its end means the daemon exited, and a +refused home sends `exit 75` first. + +One standby serves one boot: it becomes that daemon, and the CLI starts the +next one after the launch. Boots closer together than a standby takes to load +(the e2e suite's parallel lanes) mostly start cold. An idle standby takes about +41 MB on macOS. It moves a boot's VM start and code loading off the launch, not +off the machine. + ## sealed build identity An immutable application may carry `.build-digest` beside `ebin` and `priv`, diff --git a/src/albedo.gleam b/src/albedo.gleam index ecf3f64f8..8fdef7b4e 100644 --- a/src/albedo.gleam +++ b/src/albedo.gleam @@ -3,7 +3,14 @@ import albedo/daemon/storage_cli pub fn main() -> Nil { case storage_cli.arguments() { - [] -> daemon.main() + [] -> { + standby() + daemon.main() + } arguments -> storage_cli.main(arguments) } } + +/// Returns at once, or, in a standby VM, once a CLI has handed it a home. +@external(erlang, "albedo_standby", "wait") +fn standby() -> Nil diff --git a/src/albedo/daemon/albedo_daemon.erl b/src/albedo/daemon/albedo_daemon.erl index 40c5df47b..3ab0621db 100644 --- a/src/albedo/daemon/albedo_daemon.erl +++ b/src/albedo/daemon/albedo_daemon.erl @@ -24,6 +24,8 @@ defaults() -> refuse_home(Home) -> io:format(standard_error, "storage is in use by another albedo daemon or maintenance command for ALBEDO_HOME=~ts~n", [Home]), + albedo_standby:flush(), + albedo_standby:exiting(75), erlang:halt(75). %% A loopback port nothing listens on, which the OS just picked. @@ -206,6 +208,7 @@ shutdown() -> _ = try supervisor:terminate_child(os_mon_sup, cpu_sup) catch exit:_ -> ok end, _ = [logger_std_h:filesync(Id) || #{id := Id, module := logger_std_h} <- logger:get_handler_config()], + albedo_standby:flush(), erlang:halt(0). %% Keeps the home lock connection reachable; a collected connection closes and diff --git a/src/albedo/daemon/albedo_standby.erl b/src/albedo/daemon/albedo_standby.erl new file mode 100644 index 000000000..cb9ad4c4d --- /dev/null +++ b/src/albedo/daemon/albedo_standby.erl @@ -0,0 +1,409 @@ +%% A standby: a started VM with its dependency apps and code loaded, waiting +%% for a CLI to hand it a home. It holds nothing that depends on HOME or +%% ALBEDO_HOME, opens no storage, binds no port and writes no daemon.json. +%% After the handover it returns and the caller runs the ordinary daemon main. +%% See robot-docs/runtime.md, "standby". +-module(albedo_standby). +-export([wait/0, flush/0, exiting/1]). + +-include_lib("kernel/include/file.hrl"). + +-define(MARK, <<0, "albedo-standby-flush ">>). +-define(TOKEN_BYTES, 32). +-define(DEFAULT_IDLE_SECONDS, 600). +-define(HANDOVER_MS, 5000). + +%% Returns at once unless ALBEDO_STANDBY_SERVE names a standby directory; then +%% returns only after a handover, with the CLI's environment applied. +wait() -> + case os:getenv("ALBEDO_STANDBY_SERVE") of + false -> nil; + Base -> serve(unicode:characters_to_binary(Base)) + end. + +serve(Base) -> + Digest = case sealed_digest() of + {ok, Sealed} -> Sealed; + error -> erlang:halt(0) + end, + Pid = list_to_binary(os:getpid()), + Key = binary:part(Digest, 0, 16), + Paths = #{record => filename:join(Base, <>), + socket => filename:join(Base, <>), + log => filename:join(Base, <>)}, + persistent_term:put({?MODULE, paths}, Paths), + {ok, Log} = file:open(maps:get(log, Paths), [append, raw, binary]), + relay(Log), + Started = os:getenv(), + Launched = launch_environment(), + Watcher = watch_parent(os:getenv("ALBEDO_PARENT_PID")), + owned(Base) orelse leave(), + live_record(maps:get(record, Paths)) andalso leave(), + %% Advertised before loading, so a CLI arriving meanwhile starts no other; + %% it finds no socket yet and boots cold. + ok = write_record(Paths, Digest, Pid), + load_code(), + [erlang:garbage_collect(P) || P <- erlang:processes()], + Listener = listen(maps:get(socket, Paths)), + case socket:accept(Listener, idle_ms()) of + {ok, Connection} -> + _ = socket:close(Listener), + forget(Paths), + handover(Connection, Digest, Started, Launched, Watcher, Log); + {error, _} -> leave() + end. + +sealed_digest() -> + case code:lib_dir(albedo) of + {error, _} -> error; + AppDir -> + case file:read_file(filename:join(AppDir, <<".build-digest">>), [raw]) of + {ok, <>} -> + case albedo_daemon:build_digest() of + Digest -> {ok, Digest}; + _ -> error + end; + _ -> error + end + end. + +%% The environment the CLI started this standby with, before the launcher +%% scripts changed it. +launch_environment() -> + case os:getenv("ALBEDO_STANDBY_ENV") of + false -> leave(); + Encoded -> json:decode(unicode:characters_to_binary(Encoded)) + end. + +%% Only this user reaches the socket: the CLI made the directory 0700, and the +%% standby checks it still is, owned by whoever owns the files it writes. +owned(Base) -> + Probe = maps:get(log, persistent_term:get({?MODULE, paths})), + case {file:read_link_info(Base), file:read_file_info(Probe)} of + {{ok, #file_info{type = directory, mode = Mode, uid = Uid}}, {ok, #file_info{uid = Uid}}} -> + Mode band 8#077 =:= 0; + _ -> false + end. + +%% Another live standby already advertises this build. +live_record(Record) -> + case file:read_file(Record, [raw]) of + {ok, Bytes} -> + try json:decode(Bytes) of + #{<<"pid">> := Other} when is_integer(Other) -> alive(Other); + _ -> false + catch _:_ -> false + end; + _ -> false + end. + +alive(Pid) -> + Port = open_port({spawn_executable, "/bin/sh"}, + [{args, ["-c", "kill -0 " ++ integer_to_list(Pid)]}, exit_status, hide, stderr_to_stdout]), + receive {Port, {exit_status, Status}} -> Status =:= 0 + after 5000 -> false + end. + +%% The modules a ready daemon has loaded and those its post-ready warm loads +%% (both recorded by test/manual/record_boot_modules.py), so the daemon that +%% follows loads almost nothing before ready and ends up with the code a cold +%% one has. Loading runs no module code that could capture the environment. +load_code() -> + Modules = lists:append([manifest(Name) || Name <- ["ready-modules.txt", "boot-modules.txt"]]), + load_batches(lists:usort(Modules)). + +%% Loading everything at once keeps ~30 MB more of the loader's peak; batches +%% of eight take as long. +load_batches([]) -> ok; +load_batches(Modules) -> + {Batch, Rest} = lists:split(min(8, length(Modules)), Modules), + _ = code:ensure_modules_loaded(Batch), + load_batches(Rest). + +manifest(Name) -> + case file:read_file(filename:join(albedo_code:priv_dir(), Name)) of + {ok, Bytes} -> [binary_to_atom(Module) || Module <- binary:split(Bytes, <<"\n">>, [global]), Module =/= <<>>]; + _ -> [] + end. + +listen(Path) -> + _ = file:delete(Path), + {ok, Socket} = socket:open(local, stream, default), + ok = socket:bind(Socket, #{family => local, path => Path}), + ok = socket:listen(Socket, 4), + Socket. + +write_record(Paths, Digest, Pid) -> + Record = maps:get(record, Paths), + Temp = <>, + Body = json:encode(#{pid => binary_to_integer(Pid), digest => Digest, socket => maps:get(socket, Paths)}), + ok = file:write_file(Temp, Body, [raw]), + file:rename(Temp, Record). + +idle_ms() -> + Seconds = case string:to_integer(os:getenv("ALBEDO_STANDBY_IDLE", "")) of + {N, []} when N > 0 -> N; + _ -> ?DEFAULT_IDLE_SECONDS + end, + Seconds * 1000. + +%% The socket and the record go once a CLI connects, so no second CLI can +%% take this standby; the record stays when a newer standby replaced it. +forget(#{record := Record, socket := Socket}) -> + _ = file:delete(Socket), + Own = list_to_integer(os:getpid()), + case file:read_file(Record, [raw]) of + {ok, Bytes} -> + try json:decode(Bytes) of + #{<<"pid">> := Own} -> _ = file:delete(Record); + _ -> ok + catch _:_ -> ok + end; + _ -> ok + end, + ok. + +leave() -> + Paths = persistent_term:get({?MODULE, paths}), + forget(Paths), + _ = file:delete(maps:get(log, Paths)), + erlang:halt(0). + +%% The CLI sends a 4-byte length, a JSON request and its log descriptor. +%% The standby answers `ok` or `refuse `, and starts only after `go`. +handover(Connection, Digest, Started, Launched, Watcher, Log) -> + case receive_request(Connection) of + {ok, Request, Fd} -> + case environment(Request, Digest, Started, Launched) of + {ok, Environment, Cwd} -> + stop_watching(Watcher), + ok = socket:send(Connection, <<"ok\n">>), + case socket:recv(Connection, 3, ?HANDOVER_MS) of + {ok, <<"go\n">>} -> start(Connection, Environment, Cwd, Fd, Log); + _ -> leave() + end; + {refuse, Why} -> + _ = socket:send(Connection, <<"refuse ", Why/binary, "\n">>), + leave() + end; + error -> leave() + end. + +receive_request(Connection) -> + case socket:recvmsg(Connection, 0, 0, [], ?HANDOVER_MS) of + {ok, #{iov := Iov, ctrl := [#{level := socket, type := rights, data := <>}]}} -> + case rest(Connection, iolist_to_binary(Iov)) of + {ok, Body} -> + try {ok, json:decode(Body), Fd} catch _:_ -> error end; + error -> error + end; + _ -> error + end. + +rest(_, <>) -> {ok, Body}; +rest(Connection, Partial) -> + case socket:recv(Connection, 0, ?HANDOVER_MS) of + {ok, More} -> rest(Connection, <>); + _ -> error + end. + +%% What the cold launch would have given the daemon, or why it differs in a +%% way the started VM cannot follow. +environment(#{<<"digest">> := Digest, <<"max_fds">> := Fds, <<"env">> := Given, <<"cwd">> := Cwd}, Digest, Started, Launched) + when is_map(Given), is_binary(Cwd) -> + case {proplists:get_value(max_fds, hd(erlang:system_info(check_io))), inspect_home(Given)} of + {_, false} -> {refuse, <<"inspection needs the VM's -home">>}; + {Fds, true} -> + Current = maps:from_list([list_to_tuple([unicode:characters_to_binary(Part) || Part <- string:split(Entry, "=")]) + || Entry <- Started, string:find(Entry, "=") =/= nomatch]), + merge(Given, Current, Launched, Cwd); + _ -> {refuse, <<"open file limit differs">>} + end; +environment(#{<<"digest">> := _}, _, _, _) -> {refuse, <<"build differs">>}; +environment(_, _, _, _) -> {refuse, <<"malformed request">>}. + +%% The VM fixed its -home argument at start, and distribution reads the +%% cookie file there; inspection must find it under the daemon's own HOME. +inspect_home(#{<<"ALBEDO_INSPECT">> := _} = Given) -> + Home = unicode:characters_to_list(maps:get(<<"HOME">>, Given, <<>>)), + init:get_argument(home) =:= {ok, [[Home]]}; +inspect_home(_) -> true. + +merge(Given, Current, Launched, Cwd) -> + Keys = lists:usort(maps:keys(Given) ++ maps:keys(Current) ++ maps:keys(Launched)), + try {ok, lists:filtermap(fun(Key) -> variable(Key, Given, Current, Launched) end, Keys), Cwd} + catch throw:{refuse, Key} -> {refuse, <<"environment differs: ", Key/binary>>} + end. + +%% Given is the CLI's environment now, Launched the one it started this +%% standby with, and Current what the launcher scripts made of Launched. +variable(<<"ALBEDO_STANDBY_SERVE">>, _, _, _) -> false; +variable(<<"ALBEDO_STANDBY_ENV">>, _, _, _) -> false; +variable(<<"ERL_", _/binary>> = Key, Given, Current, Launched) -> + same(Key, Given, Launched) orelse throw({refuse, Key}), + keep(Key, Current); +variable(Key, _Given, Current, _Launched) + when Key =:= <<"BINDIR">>; Key =:= <<"ROOTDIR">>; Key =:= <<"EMU">>; Key =:= <<"PROGNAME">> -> + keep(Key, Current); +variable(Key, Given, Current, Launched) -> + case {maps:find(Key, Launched), maps:find(Key, Current), maps:find(Key, Given)} of + {{ok, Value}, {ok, Value}, {ok, New}} -> {true, {Key, New}}; + {{ok, Value}, {ok, Value}, error} -> false; + {{ok, Value}, {ok, Changed}, Wanted} -> + Prefix = byte_size(Changed) - byte_size(Value), + case {Prefix > 0 andalso binary:part(Changed, Prefix, byte_size(Value)) =:= Value, Wanted} of + {true, {ok, New}} -> {true, {Key, <<(binary:part(Changed, 0, Prefix))/binary, New/binary>>}}; + _ when Wanted =:= {ok, Value} -> {true, {Key, Changed}}; + _ -> throw({refuse, Key}) + end; + {{ok, _}, error, _} -> false; + {error, {ok, Added}, error} -> {true, {Key, Added}}; + {error, {ok, _}, {ok, _}} -> throw({refuse, Key}); + {error, error, {ok, New}} -> {true, {Key, New}} + end. + +same(Key, Given, Launched) -> maps:find(Key, Given) =:= maps:find(Key, Launched). + +keep(Key, Current) -> + case maps:find(Key, Current) of + {ok, Value} -> {true, {Key, Value}}; + error -> false + end. + +start(Connection, Environment, Cwd, Fd, Log) -> + Wanted = maps:from_list(Environment), + [os:unsetenv(Name) || Entry <- os:getenv(), [Name | _] <- [string:split(Entry, "=")], + not maps:is_key(unicode:characters_to_binary(Name), Wanted)], + [os:putenv(unicode:characters_to_list(Name), unicode:characters_to_list(Value)) || {Name, Value} <- Environment], + _ = file:set_cwd(Cwd), + Sink = open_port({fd, Fd, Fd}, [out, binary]), + relay_to(Sink), + _ = file:close(Log), + _ = file:delete(maps:get(log, persistent_term:get({?MODULE, paths}))), + Holder = spawn(fun() -> hold(Connection) end), + ok = socket:setopt(Connection, {otp, controlling_process}, Holder), + persistent_term:put({?MODULE, connection}, Connection), + nil. + +%% The CLI closes its end once the daemon is ready. +hold(Connection) -> + _ = socket:recv(Connection, 0, infinity), + persistent_term:erase({?MODULE, connection}), + socket:close(Connection). + +%% Tells a CLI still waiting on the handover why the daemon is about to halt, +%% which it cannot learn from a process it did not start. +exiting(Status) -> + case persistent_term:get({?MODULE, connection}, undefined) of + undefined -> nil; + Connection -> _ = socket:send(Connection, <<"exit ", (integer_to_binary(Status))/binary, "\n">>), nil + end. + +%% A test runner's standby ends with the runner. The daemon a handover starts +%% watches the parent of the CLI that handed it over instead. +watch_parent(false) -> none; +watch_parent(Parent) -> + case string:to_integer(Parent) of + {Pid, []} when Pid > 0 -> + Owner = self(), + spawn(fun() -> + Script = "while kill -0 " ++ integer_to_list(Pid) ++ " 2>/dev/null && kill -0 $PPID 2>/dev/null; do sleep 1; done", + Port = open_port({spawn_executable, "/bin/sh"}, [{args, ["-c", Script]}, exit_status, hide]), + receive + {Port, {exit_status, _}} -> leave(); + {stop, Owner} -> + {os_pid, Shell} = erlang:port_info(Port, os_pid), + _ = open_port({spawn_executable, "/bin/sh"}, [{args, ["-c", "kill " ++ integer_to_list(Shell)]}, hide]), + Owner ! {stopped, self()} + end + end); + _ -> none + end. + +stop_watching(none) -> ok; +stop_watching(Watcher) -> + Ref = monitor(process, Watcher), + Watcher ! {stop, self()}, + receive + {stopped, Watcher} -> demonitor(Ref, [flush]), ok; + {'DOWN', Ref, process, Watcher, _} -> ok + end. + +%% The VM's stdout and stderr, and every port program's, are one pipe whose +%% read end the CLI gave the standby as fd 3. Before the handover the relay +%% copies it to the standby's own log; after it, to the CLI's daemon.log. +relay(Log) -> + Owner = self(), + Relay = spawn(fun() -> + register(albedo_standby_relay, self()), + Port = open_port({fd, 3, 3}, [in, binary, eof]), + Owner ! {relaying, self()}, + relay_loop(Port, {file, Log}, <<>>, #{}) + end), + receive {relaying, Relay} -> ok after 5000 -> erlang:halt(0) end. + +relay_to(Sink) -> + Relay = whereis(albedo_standby_relay), + Ref = monitor(process, Relay), + Relay ! {sink, Sink, self(), Ref}, + receive {Ref, ok} -> demonitor(Ref, [flush]), ok after 5000 -> ok end, + port_connect(Sink, Relay), + unlink(Sink). + +relay_loop(Port, Sink, Held, Waiting) -> + receive + {Port, {data, Data}} -> + {Rest, Waiting1} = deliver(<>, Sink, Waiting), + relay_loop(Port, Sink, Rest, Waiting1); + {Port, eof} -> ok; + {sink, New, From, Ref} -> From ! {Ref, ok}, relay_loop(Port, {port, New}, Held, Waiting); + {flush, Token, From} -> relay_loop(Port, Sink, Held, Waiting#{Token => From}) + end. + +%% Writes everything up to a flush mark, answers the mark's waiter and goes on +%% after it. A mark cut by a read boundary is held back for the next read. +deliver(Data, Sink, Waiting) -> + Size = byte_size(?MARK) + ?TOKEN_BYTES + 1, + case binary:match(Data, ?MARK) of + {At, _} when byte_size(Data) - At >= Size -> + write(Sink, binary:part(Data, 0, At)), + <<_:At/binary, _:(byte_size(?MARK))/binary, Token:?TOKEN_BYTES/binary, 0, Rest/binary>> = Data, + {From, Waiting1} = case maps:take(Token, Waiting) of + {Pid, Left} -> {Pid, Left}; + error -> {none, Waiting} + end, + From =/= none andalso (From ! {flushed, Token}), + deliver(Rest, Sink, Waiting1); + {At, _} -> + write(Sink, binary:part(Data, 0, At)), + {binary:part(Data, At, byte_size(Data) - At), Waiting}; + nomatch -> + Keep = partial_mark(Data), + write(Sink, binary:part(Data, 0, byte_size(Data) - Keep)), + {binary:part(Data, byte_size(Data) - Keep, Keep), Waiting} + end. + +%% How many trailing bytes could begin a mark. +partial_mark(Data) -> + Mark = ?MARK, + Lengths = [N || N <- lists:seq(min(byte_size(Mark) - 1, byte_size(Data)), 1, -1), + binary:part(Data, byte_size(Data) - N, N) =:= binary:part(Mark, 0, N)], + case Lengths of + [N | _] -> N; + [] -> 0 + end. + +write({file, Log}, Bytes) -> _ = file:write(Log, Bytes), ok; +write({port, Port}, Bytes) -> port_command(Port, Bytes), ok. + +%% Returns once everything the VM wrote to stdout or stderr before the call +%% has reached the log; the daemon calls it before it halts. +flush() -> + case whereis(albedo_standby_relay) of + undefined -> nil; + Relay -> + Token = binary:encode_hex(crypto:strong_rand_bytes(?TOKEN_BYTES div 2), lowercase), + Relay ! {flush, Token, self()}, + io:put_chars(standard_error, <<(?MARK)/binary, Token/binary, 0>>), + receive {flushed, Token} -> nil after 1000 -> nil end + end. diff --git a/test/e2e/harness.py b/test/e2e/harness.py index 32932cf3c..7c9eb40f5 100644 --- a/test/e2e/harness.py +++ b/test/e2e/harness.py @@ -78,6 +78,10 @@ scratch.claim("e2e") # A test daemon needs two schedulers, and busy-waiting ones make every boot # pin all cores of the machine. TEST_VM_FLAGS = "+S 2:2 +SDcpu 2:2 +sbwt none +sbwtdcpu none +sbwtdio none" +# The standbys this run's CLIs start (robot-docs/runtime.md, "standby") live +# here, never shared with another run, and shutdown() stops them. Short, for +# the socket path limit. +STANDBY_DIR = Path(tempfile.mkdtemp(prefix="albedo-standby-", dir="/tmp")) # Credentials a provider reads from the environment. The daemon must not see # the developer's, or a catalog reload reaches the live provider. PROVIDER_ENVIRONMENT = ("ALIBABA_API_KEY", "DASHSCOPE_API_KEY", "ALIBABA_BASE_URL") @@ -249,6 +253,7 @@ class Daemon: ALBEDO_ROOT=str(ROOT), ALBEDO_NO_BROWSER="1", ALBEDO_PARENT_PID=str(os.getpid()), + ALBEDO_STANDBY_DIR=str(STANDBY_DIR), ERL_FLAGS=TEST_VM_FLAGS, # Test daemons do not need the package-upgrade safety preload; the # daemon preload test removes this opt-out before it boots. @@ -824,9 +829,26 @@ def shutdown(): daemon.kill() for daemon in list(_daemons): daemon.shutdown() + stop_standbys() fake_provider.close() +def stop_standbys(): + """Kill the run's standbys; each would also end with this process.""" + for record in STANDBY_DIR.glob("*.json"): + try: + pid = json.loads(record.read_text())["pid"] + command = subprocess.run( + ["ps", "-o", "command=", "-p", str(pid)], capture_output=True, text=True + ).stdout + # A record of a standby that died unannounced may name a reused pid. + if "albedo@@main" in command: + os.kill(pid, signal.SIGKILL) + except (OSError, ValueError, KeyError): + pass + shutil.rmtree(STANDBY_DIR, ignore_errors=True) + + atexit.register(shutdown) diff --git a/test/e2e/standby_test.py b/test/e2e/standby_test.py new file mode 100644 index 000000000..f1aab80cf --- /dev/null +++ b/test/e2e/standby_test.py @@ -0,0 +1,225 @@ +"""A daemon booted through a standby VM is the daemon a cold boot gives. + +Catches a handover that changes the daemon (its home, storage or log), a CLI +that takes a standby it must not (another build, a refusing or dead one, one +another CLI already took) and a standby that outlives the process that +started it. Only the real CLI, standby and daemon together show these. +""" + +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import tempfile +import threading +import unittest + +import harness +from harness import Albedo, Provider, alive, text, wait_until + + +def snapshot(): + assert harness._executable is not None, "the runner snapshots the daemon first" + return Path(harness._executable).parent + + +def snapshot_digest(): + return (snapshot() / "albedo" / ".build-digest").read_text().strip() + + +class Standbys: + """A private standby directory, so no other test takes this test's standby.""" + + def __init__(self, test): + self.test = test + self.dir = Path(tempfile.mkdtemp(prefix="sb-", dir="/tmp")) + test.addCleanup(self.stop) + + def daemon(self, name, **env): + daemon = harness.Daemon(name) + daemon.env["ALBEDO_STANDBY_DIR"] = str(self.dir) + daemon.env.update(env) + self.test.addCleanup(daemon.shutdown) + return daemon + + def records(self): + records = [] + for path in self.dir.glob("*.json"): + try: + records.append(json.loads(path.read_text())) + except (OSError, ValueError): + pass + return records + + def ready(self, digest=None, other_than=()): + """The live standby of a build once its socket is up.""" + digest = digest or snapshot_digest() + found = {} + + def listening(): + for record in self.records(): + if ( + record["digest"] == digest + and record["pid"] not in other_than + and alive(record["pid"]) + and os.path.exists(record["socket"]) + ): + found.update(record) + return True + return False + + wait_until(listening, 30, "no standby came up") + return found + + def stop(self): + for record in self.records(): + try: + os.kill(record["pid"], signal.SIGKILL) + except ProcessLookupError: + pass + shutil.rmtree(self.dir, ignore_errors=True) + + +def pid(daemon): + return json.loads((daemon.home / "daemon.json").read_text())["pid"] + + +class StandbyTests(unittest.TestCase): + def setUp(self): + self.standbys = Standbys(self) + + def test_a_boot_through_a_standby_keeps_its_sessions_like_a_cold_one(self): + first = self.standbys.daemon("first") + first.boot() + standby = self.standbys.ready() + second = self.standbys.daemon("second") + second.boot() + self.assertEqual(pid(second), standby["pid"]) + self.assertFalse(os.path.exists(standby["socket"])) + record = json.loads((second.home / "daemon.json").read_text()) + self.assertEqual(record["digest"], snapshot_digest()) + # The CLI left the next launch a standby of its own. + self.standbys.ready(other_than={standby["pid"]}) + + provider = Provider(lambda _: text("from the handed-over daemon")) + try: + with harness.on_daemon(second), Albedo(provider) as app: + session = app.session() + app.prompt(session, "hello").close() + app.idle(session) + self.assertTrue(provider.requests) + second.restart() + self.assertIn( + "from the handed-over daemon", json.dumps(app.history(session)) + ) + finally: + provider.close() + self.assertTrue((second.home / "albedo.sqlite").exists()) + log = (second.home / "daemon.log").read_bytes() + self.assertTrue(log) + self.assertNotIn(b"\0", log) + + def test_a_launch_without_a_usable_standby_boots_cold(self): + digest = snapshot_digest() + # A record whose standby died: its pid is gone and nothing listens. + gone = subprocess.Popen(["true"]) + gone.wait() + socket = self.standbys.dir / f"{digest[:16]}-{gone.pid}.sock" + (self.standbys.dir / f"{digest[:16]}.json").write_text( + json.dumps({"pid": gone.pid, "digest": digest, "socket": str(socket)}) + ) + dead = self.standbys.daemon("dead") + dead.boot() + self.assertNotEqual(pid(dead), gone.pid) + standby = self.standbys.ready() + # The VM started with other flags than this CLI asks for: it refuses + # and exits, and the CLI boots cold. + refused = self.standbys.daemon("refused", ERL_AFLAGS="+hms 233") + refused.boot() + self.assertNotEqual(pid(refused), standby["pid"]) + wait_until(lambda: not alive(standby["pid"]), 10, "the refusing standby stayed") + missing = self.standbys.daemon("missing", ALBEDO_STANDBY="0") + missing.boot() + self.assertNotIn( + pid(missing), {record["pid"] for record in self.standbys.records()} + ) + + def test_a_standby_of_another_build_is_never_used(self): + launcher, other = other_build(Path(tempfile.mkdtemp(prefix="build-"))) + self.addCleanup(shutil.rmtree, launcher.parent, True) + first = self.standbys.daemon("other-build", ALBEDO_DAEMON=str(launcher)) + first.boot() + foreign = self.standbys.ready(digest=other) + current = self.standbys.daemon("current") + current.boot() + self.assertNotEqual(pid(current), foreign["pid"]) + self.assertTrue(alive(foreign["pid"])) + self.assertTrue(os.path.exists(foreign["socket"])) + + def test_two_launches_racing_for_one_standby_hand_it_to_one(self): + self.standbys.daemon("first").boot() + standby = self.standbys.ready() + racers = [self.standbys.daemon(f"racer-{n}") for n in range(2)] + failures = [] + + def boot(daemon): + try: + daemon.boot() + except BaseException as error: + failures.append(error) + + threads = [threading.Thread(target=boot, args=(daemon,)) for daemon in racers] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + self.assertEqual(failures, []) + pids = [pid(daemon) for daemon in racers] + self.assertEqual(pids.count(standby["pid"]), 1, pids) + self.assertEqual(len(set(pids)), 2, pids) + + def test_a_standby_ends_with_the_process_that_started_it(self): + parent = subprocess.Popen(["sleep", "120"]) + self.addCleanup(parent.kill) + daemon = self.standbys.daemon("parented", ALBEDO_PARENT_PID=str(parent.pid)) + daemon.boot() + standby = self.standbys.ready() + parent.kill() + parent.wait() + wait_until( + lambda: not alive(standby["pid"]), 15, "the standby outlived its parent" + ) + wait_until( + lambda: not list(self.standbys.dir.iterdir()), + 5, + "the standby left files behind", + ) + + +def other_build(out): + """The test snapshot under another sealed digest: the same code, which the + CLI and its standby must treat as a different build.""" + source = snapshot() + for package in source.iterdir(): + if package.is_dir() and package.name != "albedo": + (out / package.name).symlink_to(package) + albedo = out / "albedo" + albedo.mkdir() + for entry in ("ebin", "priv"): + (albedo / entry).symlink_to((source / "albedo" / entry).resolve()) + digest = "f" * 64 + (albedo / ".build-digest").write_text(digest + "\n") + launcher = out / "albedo-daemon" + launcher.write_text( + "#!/bin/sh\n" + f"exec {harness.ROOT}/priv/bin/albedo-daemon erl -pa {out}/*/ebin " + "-eval 'albedo@@main:run(albedo)' -noshell -extra \"$@\"\n" + ) + launcher.chmod(0o755) + return launcher, digest + + +if __name__ == "__main__": + unittest.main() diff --git a/test/manual/record_boot_modules.py b/test/manual/record_boot_modules.py index ad98dbe48..78d7ba0e0 100644 --- a/test/manual/record_boot_modules.py +++ b/test/manual/record_boot_modules.py @@ -1,7 +1,9 @@ -"""Record modules a first text turn loads for the daemon's background code warm. +"""Record modules a ready daemon has loaded, for standbys, and those a first +text turn loads after that, for the daemon's background code warm. Run with nix develop -c python3 test/manual/record_boot_modules.py. Uses a private -fake-provider daemon, no credentials or Python kernel; writes priv/boot-modules.txt. +fake-provider daemon, no credentials or Python kernel; writes +priv/ready-modules.txt and priv/boot-modules.txt. """ from __future__ import annotations @@ -32,7 +34,8 @@ def loaded(app): def record(protocol): daemon = Daemon("boot-modules") - daemon.env.update(ALBEDO_INSPECT="1", ALBEDO_PRELOAD="0") + # A standby would have loaded more than the boot itself does. + daemon.env.update(ALBEDO_INSPECT="1", ALBEDO_PRELOAD="0", ALBEDO_STANDBY="0") try: daemon.boot() before = loaded( @@ -47,7 +50,7 @@ def record(protocol): session = app.session() app.prompt(session, "hello").close() app.idle(session) - return loaded(app) - before + return before, loaded(app) - before finally: daemon.shutdown() remaining = [ @@ -64,11 +67,17 @@ def record(protocol): def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, default=ROOT / "priv/boot-modules.txt") + parser.add_argument("--ready", type=Path, default=ROOT / "priv/ready-modules.txt") args = parser.parse_args() harness.snapshot_daemon() - modules = sorted(record("chat_completions") | record("responses")) - args.output.write_text("\n".join(modules) + "\n") - print(f"{len(modules)} modules written to {args.output}") + chat_ready, chat_turn = record("chat_completions") + responses_ready, responses_turn = record("responses") + for path, modules in ( + (args.ready, chat_ready | responses_ready), + (args.output, chat_turn | responses_turn), + ): + path.write_text("\n".join(sorted(modules)) + "\n") + print(f"{len(modules)} modules written to {path}") if __name__ == "__main__": diff --git a/test/manual/standby_probe.py b/test/manual/standby_probe.py new file mode 100644 index 000000000..92dd2de4c --- /dev/null +++ b/test/manual/standby_probe.py @@ -0,0 +1,121 @@ +"""Time `albedo daemon` (CLI exec to a ready, attached daemon) on a fresh +home, cold and through a standby, interleaved. + +nix develop -c python3 test/manual/standby_probe.py [repetitions] + +Every daemon and standby is private to the run (its own homes and +ALBEDO_STANDBY_DIR) and stopped before it exits. +""" + +import json +import os +from pathlib import Path +import shutil +import signal +import statistics +import subprocess +import sys +import tempfile +import time + + +def main(): + launcher, cli, output = sys.argv[1:4] + repetitions = int(sys.argv[4]) if len(sys.argv) > 4 else 10 + root = Path(tempfile.mkdtemp(prefix="standby-probe-")) + standbys = Path(tempfile.mkdtemp(prefix="sbp-", dir="/tmp")) + base = { + key: value + for key, value in os.environ.items() + if not key.startswith("ALBEDO_") and key != "ERL_FLAGS" + } + base.update( + ALBEDO_DAEMON=launcher, + ALBEDO_PARENT_PID=str(os.getpid()), + ALBEDO_STANDBY_DIR=str(standbys), + ALBEDO_PRELOAD="0", + ALBEDO_NO_BROWSER="1", + ALBEDO_WEBHOOK_PORT="0", + ) + homes = [] + + def boot(name, **extra): + home = root / name + home.mkdir() + homes.append(home) + (home / "extensions.json").write_text( + json.dumps( + {"models": {"refreshHours": 0, "url": None}, "cacheTtl": {"url": None}} + ) + ) + env = dict(base, ALBEDO_HOME=str(home), **extra) + started = time.monotonic() + subprocess.run( + [cli, "daemon"], env=env, check=True, capture_output=True, timeout=60 + ) + elapsed = time.monotonic() - started + pid = json.loads((home / "daemon.json").read_text())["pid"] + return elapsed * 1000, pid, env + + def stop(env): + subprocess.run( + [cli, "daemon", "--stop"], + env=dict(env, ALBEDO_STANDBY="0"), + capture_output=True, + timeout=60, + ) + + def standby(timeout=30): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + for path in standbys.glob("*.json"): + try: + record = json.loads(path.read_text()) + os.kill(record["pid"], 0) + except (OSError, ValueError, KeyError): + continue + if os.path.exists(record["socket"]): + return record["pid"] + time.sleep(0.02) + raise SystemExit("no standby came up") + + results = {"cold": [], "standby": []} + try: + _, _, env = boot("seed") + stop(env) + for n in range(repetitions): + elapsed, _, env = boot(f"cold-{n}", ALBEDO_STANDBY="0") + results["cold"].append(elapsed) + stop(env) + waiting = standby() + # The standby has nothing left to load once it listens; settle the + # machine the way an idle laptop would be. + time.sleep(0.5) + elapsed, pid, env = boot(f"standby-{n}") + if pid != waiting: + raise SystemExit(f"boot {n} did not take the standby") + results["standby"].append(elapsed) + stop(env) + finally: + for path in standbys.glob("*.json"): + try: + os.kill(json.loads(path.read_text())["pid"], signal.SIGKILL) + except (OSError, ValueError, KeyError): + pass + shutil.rmtree(standbys, ignore_errors=True) + shutil.rmtree(root, ignore_errors=True) + summary = { + kind: { + "median_ms": round(statistics.median(values), 1), + "min_ms": round(min(values), 1), + "max_ms": round(max(values), 1), + "runs": [round(v, 1) for v in values], + } + for kind, values in results.items() + } + Path(output).write_text(json.dumps(summary, indent=2)) + print(json.dumps({kind: value["median_ms"] for kind, value in summary.items()})) + + +if __name__ == "__main__": + main()