From abf1651e5beeeecfef14ca2e85f32294e9c6df74 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 5 Nov 2026 21:25:11 -0500 Subject: [PATCH] move: name every wait in checking, end on an unsupported host, write the ledgers in the boot schema commit --- robot-docs/migrations.md | 2 +- robot-docs/workspaces.md | 8 +++-- src/albedo/daemon/moves.gleam | 49 ++++++++++++++++++++++++++----- src/albedo/daemon/registry.gleam | 7 +++-- src/albedo/daemon/transfers.gleam | 24 +++++++-------- test/e2e/move_checklist_test.py | 20 ++++++++++--- test/e2e/move_test.py | 43 +++++++++++++++++++++++---- 7 files changed, 116 insertions(+), 37 deletions(-) diff --git a/robot-docs/migrations.md b/robot-docs/migrations.md index bc984f908..a8cd04318 100644 --- a/robot-docs/migrations.md +++ b/robot-docs/migrations.md @@ -91,7 +91,7 @@ sessions; session selection and live reload never rerun migrations. rowids. Admission receipts and pending inputs still require globally unique input identities. It then runs its existing domain-local session recovery (missing activity/title from transcript), then creates `sessions_activity`. -2. quota, mail, and family initialise their tables. Mail also ensures its incoming and outgoing conversation indexes after upgrading an older kind constraint. +2. quota, mail, family, transfers and moves initialise their tables. Mail also ensures its incoming and outgoing conversation indexes after upgrading an older kind constraint. On an empty store steps 1 and 2 share one savepoint, so the whole core schema is one commit; each statement there would otherwise commit, and rewrite `sqlite_schema`'s pages, on its own. `transfers.expire` then removes inactive transfer staging older than a week. 3. `migrations.run(ledger, backup)` runs the core `image_store.run`, which first externalizes legacy transcript images, then converts image-table TEXT data to decoded BLOB. It then runs `transcript_classes.run` to classify old diff --git a/robot-docs/workspaces.md b/robot-docs/workspaces.md index 9ce5e1fa9..1748ee7e9 100644 --- a/robot-docs/workspaces.md +++ b/robot-docs/workspaces.md @@ -312,15 +312,17 @@ and web only read its progress. the id is `409 transfer_conflict`, a second move of a session in flight or at its checklist `409 move_in_progress`) is one `moves` row. its driver goes `checking` - (the protocol again, then waits for every session in scope to be at rest, - `reason` naming the one mid-turn), `exporting` (the export, then staging + (connecting over ssh, starting the relay and asking the protocol again, + then waiting for every session in scope to be at rest; `reason` names each + wait, and the session mid-turn), `exporting` (the export, then staging it there with `?workspace=` the destination), `copying` (each segment from where the target's status says it ends, `progress` after every chunk), `activating` (activate, then polling the import until it is `active`; nothing is activated before the target says ready) and `checklist`. `GET /transfers/{id}` reads it. a target out of reach (a laptop asleep, wifi gone) is retried with backoff up to every 30 s for as long - as it takes, `reason` saying so; a step the target fails (a 5xx, a + as it takes, `reason` saying so; a host that can't run albedo's python + (`host_unsupported`) ends the move; a step the target fails (a 5xx, a segment to send again) is retried five times; a refusal ends the move as `failed` with the target's code and detail. a daemon that restarts starts a driver for every unfinished move from its recorded state diff --git a/src/albedo/daemon/moves.gleam b/src/albedo/daemon/moves.gleam index d56186e05..202c16eaf 100644 --- a/src/albedo/daemon/moves.gleam +++ b/src/albedo/daemon/moves.gleam @@ -87,7 +87,7 @@ pub type Preflight { } pub const schema = - "CREATE TABLE IF NOT EXISTS moves(id TEXT PRIMARY KEY,session TEXT NOT NULL,target TEXT NOT NULL,state TEXT NOT NULL CHECK(state IN ('checking','exporting','copying','activating','checklist','active','failed')),reason TEXT,error_code TEXT,error_detail TEXT,bytes_done INTEGER NOT NULL DEFAULT 0,bytes_total INTEGER NOT NULL DEFAULT 0,target_session TEXT,target_home TEXT,lost TEXT NOT NULL DEFAULT '[]',created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS move_occurrences(move TEXT NOT NULL,kind TEXT NOT NULL,origin TEXT NOT NULL,key TEXT NOT NULL,PRIMARY KEY(move,kind,origin,key));" + "CREATE TABLE IF NOT EXISTS moves(id TEXT PRIMARY KEY,session TEXT NOT NULL,target TEXT NOT NULL,state TEXT NOT NULL CHECK(state IN ('checking','exporting','copying','activating','checklist','active','failed')),reason TEXT,error_code TEXT,error_detail TEXT,bytes_done INTEGER NOT NULL DEFAULT 0,bytes_total INTEGER NOT NULL DEFAULT 0,target_session TEXT,target_home TEXT,lost TEXT NOT NULL DEFAULT '[]',created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS move_occurrences(move TEXT NOT NULL,kind TEXT NOT NULL,origin TEXT NOT NULL,key TEXT NOT NULL,PRIMARY KEY(move,kind,origin,key)) WITHOUT ROWID;" /// The moves ledger, and the `moved` column of `sessions`. A move records the /// sessions it carries and when their export began (`since`, ms) as it starts @@ -499,7 +499,15 @@ pub fn preflight( Some(record), _ -> unavailable(refusal(record).detail, None, None, []) None, Error(busy) -> unavailable(busy, None, None, []) None, Ok(sessions) -> - case connect(ssh_target, host, preflight_ssh_ms, preflight_relay_ms) { + case + connect( + ssh_target, + host, + preflight_ssh_ms, + preflight_relay_ms, + unobserved, + ) + { Error(Transport(why)) | Error(Flaky(why)) -> unavailable(why, None, None, sessions) Error(Refused(refusal)) -> @@ -545,17 +553,34 @@ type Trouble { const call_ms = 120_000 +/// The `waiting` of a connect nobody watches. +fn unobserved(_reason: String) -> Nil { + Nil +} + +/// The relay to the daemon on `host`, telling `waiting` what it waits on +/// before each step. A host that can't run albedo's python is refused; one +/// out of reach or needing a sign-in is tried again. fn connect( ssh_target: String, host: String, ssh_ms: Int, relay_ms: Int, + waiting: fn(String) -> Nil, ) -> Result(Relay, Trouble) { + waiting("connecting to " <> host <> " over ssh") use found <- result.try( ssh.ready(ssh_target, ssh_ms) - |> result.map_error(fn(failure) { Transport(ssh.describe(host, failure)) }), + |> result.map_error(fn(failure) { + case failure { + ssh.Unsupported(_) -> + Refused(Refusal("host_unsupported", ssh.describe(host, failure))) + _ -> Transport(ssh.describe(host, failure)) + } + }), ) let commands = found.commands + waiting("starting the relay to the albedo daemon on " <> host) use #(port, hello) <- result.try( open(commands.argv, commands.relay, commands.auth_sock, relay_ms) |> result.map_error(fn(why) { @@ -764,7 +789,7 @@ fn drive(driver: Driver, relay: Option(Relay), attempts: Attempts) -> Nil { let stepped = { use relay <- result.try(case relay { Some(relay) -> Ok(relay) - None -> reach(move) + None -> reach(driver, move) }) advance(driver, move, relay) |> result.map(fn(step) { #(relay, step) }) @@ -824,23 +849,33 @@ fn backoff(attempt: Int) -> Int { } /// The relay to the move's target, checked to speak this daemon's protocol. -fn reach(move: Move) -> Result(Relay, Trouble) { +/// The move's `reason` names each wait on the way. +fn reach(driver: Driver, move: Move) -> Result(Relay, Trouble) { use #(ssh_target, parsed) <- result.try( remote(move.target) |> result.map_error(Refused), ) let host = host_name(parsed) + let waiting = fn(reason) { + let _ = note(driver, Some(reason)) + Nil + } use relay <- result.try(connect( ssh_target, host, ssh.boot_wait_ms, relay_open_ms, + waiting, )) let checked = { + waiting("asking the albedo daemon on " <> host <> " for its protocol") use theirs <- result.try(target_protocol(relay, call_ms)) compatible(host, theirs) |> result.map_error(Refused) } case checked { - Ok(_) -> Ok(relay) + Ok(_) -> { + let _ = note(driver, None) + Ok(relay) + } Error(trouble) -> { close(relay.port) Error(trouble) @@ -1367,7 +1402,7 @@ fn report( use #(ssh_target, parsed) <- result.try(remote(move.target)) let host = host_name(parsed) use relay <- result.try( - connect(ssh_target, host, finish_ssh_ms, finish_relay_ms) + connect(ssh_target, host, finish_ssh_ms, finish_relay_ms, unobserved) |> result.map_error(fn(trouble) { case trouble { Transport(why) | Flaky(why) -> unreachable(why) diff --git a/src/albedo/daemon/registry.gleam b/src/albedo/daemon/registry.gleam index 9dad4f57c..fa4466d87 100644 --- a/src/albedo/daemon/registry.gleam +++ b/src/albedo/daemon/registry.gleam @@ -509,15 +509,16 @@ pub fn prepare_storage( ) use _ <- result.try(quota.initialise(ledger)) use _ <- result.try(mail.initialise(ledger)) - family.initialise(ledger) + use _ <- result.try(family.initialise(ledger)) + use _ <- result.try(transfers.initialise(ledger)) + moves.initialise(ledger) } // Existing transcript recovery keeps its bounded commits and resumes after interruption. use _ <- result.try(case existing { 0 -> store.initialise(ledger, initialise) _ -> initialise() }) - use _ <- result.try(transfers.initialise(ledger, config.home)) - use _ <- result.try(moves.initialise(ledger)) + use _ <- result.try(transfers.expire(ledger, config.home)) let backup = config.home <> "/backups/albedo-before-image-store-" diff --git a/src/albedo/daemon/transfers.gleam b/src/albedo/daemon/transfers.gleam index 1498aa672..a73b79ac7 100644 --- a/src/albedo/daemon/transfers.gleam +++ b/src/albedo/daemon/transfers.gleam @@ -81,19 +81,17 @@ pub const schema = /// What a source delivered after its export, recorded on the target so the /// schedule due scan, webhook intake and discord delivery skip it there. const occurrences_schema = - "CREATE TABLE IF NOT EXISTS transfer_occurrences(kind TEXT NOT NULL CHECK(kind IN ('schedule','webhook','letter')),origin TEXT NOT NULL,key TEXT NOT NULL,transfer TEXT NOT NULL,detail TEXT,PRIMARY KEY(kind,origin,key));" + "CREATE TABLE IF NOT EXISTS transfer_occurrences(kind TEXT NOT NULL CHECK(kind IN ('schedule','webhook','letter')),origin TEXT NOT NULL,key TEXT NOT NULL,transfer TEXT NOT NULL,detail TEXT,PRIMARY KEY(kind,origin,key)) WITHOUT ROWID;" -pub fn initialise(ledger: store.Store, home: String) -> Result(Nil, String) { - use _ <- result.try( - store.query(ledger, fn(db) { - use _ <- result.try(store.exec(db, schema <> occurrences_schema)) - store.add_columns(db, "transfers", [ - #("workspace", "TEXT"), - #("activation", "TEXT"), - ]) - }), - ) - expire(ledger, home) +/// The transfers ledger, created with the core schema; `expire` runs after it. +pub fn initialise(ledger: store.Store) -> Result(Nil, String) { + store.query(ledger, fn(db) { + use _ <- result.try(store.exec(db, schema <> occurrences_schema)) + store.add_columns(db, "transfers", [ + #("workspace", "TEXT"), + #("activation", "TEXT"), + ]) + }) } /// This home's identity, which a manifest names as its origin. @@ -1644,7 +1642,7 @@ fn activation_decoder() -> decode.Decoder(Activation) { } /// Removes inactive transfers untouched for seven days, files then receipt. -fn expire(ledger: store.Store, home: String) -> Result(Nil, String) { +pub fn expire(ledger: store.Store, home: String) -> Result(Nil, String) { let cutoff = clock.system_ms() - expiry_ms use stale <- result.try( store.read( diff --git a/test/e2e/move_checklist_test.py b/test/e2e/move_checklist_test.py index b70f4850a..d80103300 100644 --- a/test/e2e/move_checklist_test.py +++ b/test/e2e/move_checklist_test.py @@ -59,7 +59,14 @@ if [ -e {down} ]; then echo "ssh: connect to host $target port 22: Network is unreachable" >&2 exit 255 fi -exec env -i HOME={home} ALBEDO_HOME="$(cat {hosts}/"$target")" PATH={path} SHELL=/bin/sh /bin/sh -c "$*" +exec env -i HOME={home} ALBEDO_HOME="$(cat {hosts}/"$target")" PATH={path} SHELL={login} /bin/sh -c "$*" +""" + +# The host's login shell. It sources no profile: /etc/profile may replace PATH +# (NixOS's does), dropping the fake host's python3 for the system's or none. +LOGIN_SHELL = """#!/bin/sh +[ "$1" = -l ] && shift +exec /bin/sh "$@" """ OWNER = "100000000000000010" @@ -69,13 +76,14 @@ REFUSED = "arrived after this session moved" def wait_for(predicate, timeout=60, message="condition not met"): + """`message` may be a function, read when the wait gives up.""" deadline = time.monotonic() + timeout while time.monotonic() < deadline: result = predicate() if result: return result time.sleep(0.1) - raise AssertionError(message) + raise AssertionError(message() if callable(message) else message) _fakes: dict[Daemon, FakeDiscord] = {} @@ -132,6 +140,9 @@ class MoveChecklistTests(unittest.TestCase): directory.mkdir(exist_ok=True) os.symlink(shutil.which("python3") or sys.executable, remote / "python3") path = app.daemon.env["PATH"] + login = local / "loginsh" + login.write_text(LOGIN_SHELL) + login.chmod(0o755) ssh = local / "ssh" ssh.write_text( FAKE_SSH.format( @@ -139,6 +150,7 @@ class MoveChecklistTests(unittest.TestCase): hosts=self.hosts, home=self.remote_home, path=shlex.quote(f"{remote}{os.pathsep}{path}"), + login=login, ) ) ssh.chmod(0o755) @@ -245,7 +257,7 @@ class MoveChecklistTests(unittest.TestCase): and move ), 90, - f"the move never reached its checklist: {self.read(transfer)}", + lambda: f"the move never reached its checklist: {self.read(transfer)}", ) self.assertEqual(move["state"], "checklist", move) return transfer, move @@ -408,7 +420,7 @@ class MoveChecklistTests(unittest.TestCase): letters = wait_for( lambda: len(found := bounced()) == 2 and found, 30, - f"the sender was not written back to: {bounced()}", + lambda: f"the sender was not written back to: {bounced()}", ) name = letters[0][1] self.assertTrue(name) diff --git a/test/e2e/move_test.py b/test/e2e/move_test.py index be926320e..44762dc56 100644 --- a/test/e2e/move_test.py +++ b/test/e2e/move_test.py @@ -3,8 +3,9 @@ The source's PATH holds a loopback ssh that runs each command locally with the "remote" host's ALBEDO_HOME set to the peer daemon's home (or to a fake older daemon's), so the relay the move stages and runs over ssh reads that -daemon's daemon.json and calls it, as it would on vassago. A host named -`gone` cannot be reached. A test that creates the `stall` switch holds the +daemon's daemon.json and calls it, as it would on vassago. Its login shell +reads no profile, so the PATH the ssh sets is the host's. A host named `gone` +cannot be reached, and `oldpy` has only python 3.9. A test that creates the `stall` switch holds the relay at the first segment it forwards, so the source daemon can be stopped mid-copy. """ @@ -50,7 +51,16 @@ run= case "$*" in *albedo_transfer_relay*) [ -e {stall} ] && run="python3 {hold}" ;; esac -exec env -i HOME={home} ALBEDO_HOME="$daemon_home" PATH={path} SHELL=/bin/sh $run /bin/sh -c "$*" +path={path} +[ "$target" = oldpy ] && path={oldpy}:$path +exec env -i HOME={home} ALBEDO_HOME="$daemon_home" PATH="$path" SHELL={login} $run /bin/sh -c "$*" +""" + +# The host's login shell. It sources no profile: /etc/profile may replace PATH +# (NixOS's does), dropping the fake host's python3 for the system's or none. +LOGIN_SHELL = """#!/bin/sh +[ "$1" = -l ] && shift +exec /bin/sh "$@" """ # Runs the relay command, passing its frames through until the first segment @@ -108,13 +118,14 @@ def write(path, content): def wait_for(predicate, timeout=60, message="condition not met"): + """`message` may be a function, read when the wait gives up.""" deadline = time.monotonic() + timeout while time.monotonic() < deadline: result = predicate() if result: return result time.sleep(0.1) - raise AssertionError(message) + raise AssertionError(message() if callable(message) else message) # exclusive: sets the daemon's PATH for the loopback ssh, and one test @@ -148,10 +159,14 @@ class MoveTests(unittest.TestCase): directory.mkdir(exist_ok=True) real = shutil.which("python3") or sys.executable os.symlink(real, remote / "python3") + oldpy = root / "oldpy-bin" + oldpy.mkdir() + write(oldpy / "python3", "#!/bin/sh\necho 3.9\n") hold = root / "hold.py" hold.write_text( HOLD.format(stalled=str(self.stalled), release=str(self.release)) ) + write(local / "loginsh", LOGIN_SHELL) path = app.daemon.env["PATH"] write( local / "ssh", @@ -162,6 +177,8 @@ class MoveTests(unittest.TestCase): hold=hold, home=self.remote_home, path=shlex.quote(f"{remote}{os.pathsep}{path}"), + oldpy=oldpy, + login=local / "loginsh", ), ) app.daemon.env["PATH"] = f"{local}{os.pathsep}{path}" @@ -172,7 +189,8 @@ class MoveTests(unittest.TestCase): self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) self.addCleanup(lambda: self.release.touch()) - (self.hosts / "vassago").write_text(str(self.target.home)) + for host in ("vassago", "oldpy"): + (self.hosts / host).write_text(str(self.target.home)) self.destination = Path(tempfile.mkdtemp(prefix="dest-", dir=self.remote_home)) def session(self): @@ -205,7 +223,7 @@ class MoveTests(unittest.TestCase): and move ), timeout, - f"move did not settle: {self.read(transfer)}", + lambda: f"move did not settle: {self.read(transfer)}", ) def exported(self, transfer): @@ -312,6 +330,19 @@ class MoveTests(unittest.TestCase): self.assertEqual(found["target_daemon"]["host"], "gone") self.assertIsNone(found["target_daemon"]["protocol"]) + def test_a_host_too_old_for_albedo_fails_the_move_saying_so(self): + session = self.session() + transfer = operation_id() + self.move(session, transfer, f"oldpy:{self.destination}") + failed = self.settled(transfer) + self.assertEqual(failed["state"], "failed", failed) + self.assertEqual(failed["error"]["code"], "host_unsupported") + self.assertEqual( + failed["error"]["detail"], + "oldpy can't run albedo's kernel: needs python >= 3.11 (found 3.9)", + ) + self.assertEqual(self.exported(transfer), 0) + def test_a_move_resumes_its_copy_after_the_source_daemon_restarts(self): session = self.session() target = f"vassago:{self.destination}" -- knotmirror 0.0.1