From c12043d4511b0f41e7cabfb20ef53dcd8e2aeac3 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Mon, 16 Nov 2026 01:16:44 -0500 Subject: [PATCH] feat(migrations): refuse a home a newer build upgraded past this one An older daemon started on a home a newer one upgraded had no defined behaviour: nothing recorded what the home was upgraded to, and old code could misread data a newer migration moved or rewrote. Every migration now declares a migration.Compatibility. Additive ones (a new table, index, or defaulted column, or a backfill of one) record nothing and never block a rollback. A breaking one records its name in breaking_migrations before it writes: core steps and extension data migrations in their own commit first, extension schema migrations in the same savepoint as their change. The SDK's SchemaMigration and DataMigration gain a name and a compatibility, and migration_names lists an install's declared names. server.main reads that record after the home lock and before anything opens storage. A recorded name this build does not declare (core, kernel, retired core, or any declared extension's) makes it print "This home was upgraded by a newer albedo (); update albedo or restore a backup." and halt with status 78, which the CLI shows from the startup log. Breaking today: image_store, session_prompts, pending_inputs_inbox, cell_images, and coding_lcm_name. Every migration runs at each startup, so the first build with the record backfills it for homes upgraded earlier. Builds from before the record do not check it. Core migrations become a list of named steps, and startup reports every step's rewritten rows as "migration : rows". --- docs/extensions.md | 6 +- robot-docs/README.md | 3 +- robot-docs/contributing.md | 5 + robot-docs/extensions.md | 19 +++ robot-docs/migrations.md | 122 +++++++++++++- robot-docs/plugins.md | 5 +- robot-docs/testing.md | 11 +- robot-docs/workspaces.md | 3 + src/albedo/daemon/lifecycle.gleam | 20 ++- src/albedo/daemon/migrations.gleam | 70 ++++++-- src/albedo/daemon/registry.gleam | 42 +++-- src/albedo/daemon/server.gleam | 15 +- src/albedo/daemon/transfer.gleam | 4 + .../harness/extensions/lcm/extension.gleam | 4 + .../extensions/paperclips/extension.gleam | 13 ++ .../extensions/rolling/extension.gleam | 9 +- .../extensions/schedule/extension.gleam | 8 +- .../harness/extensions/work/extension.gleam | 5 + .../kernel/migrations/cell_images.gleam | 4 + src/albedo/harness/sdk/extension.gleam | 50 +++++- src/albedo/harness/sdk/migration.gleam | 110 ++++++++++++ test/daemon/migration_names_test.gleam | 13 ++ test/e2e/areas.toml | 10 +- test/e2e/downgrade_test.py | 158 ++++++++++++++++++ test/harness/migration_test.gleam | 128 +++++++++++--- 25 files changed, 765 insertions(+), 72 deletions(-) create mode 100644 src/albedo/harness/sdk/migration.gleam create mode 100644 test/daemon/migration_names_test.gleam create mode 100644 test/e2e/downgrade_test.py diff --git a/docs/extensions.md b/docs/extensions.md index bf4d0f5fb..b5f92898c 100644 --- a/docs/extensions.md +++ b/docs/extensions.md @@ -148,8 +148,10 @@ To add a column later, call `storage.add_columns(db, "table", [#(name, type)])` from the initializer, or add a `MigrationPlugin`. A transfer carries every column, and a daemon refuses a segment with a column its own table lacks, so a new column on a carried table also stops moves to older daemons. Bump the -table's transfer version when the rows change meaning. See -[migrations](../robot-docs/migrations.md). +table's transfer version when the rows change meaning. A `MigrationPlugin` names +itself and declares `migration.Additive` or `migration.Breaking`. An older +daemon that lacks a breaking one refuses the home. See +[migrations](../robot-docs/migrations.md#downgrades). ## Add a Python binding diff --git a/robot-docs/README.md b/robot-docs/README.md index 51fa4de69..dea792d7d 100644 --- a/robot-docs/README.md +++ b/robot-docs/README.md @@ -93,6 +93,7 @@ and the [repository agent instructions](../AGENTS.md). - [Testing](testing.md): concurrency, fixtures, and cleanup. - [Gleam checks](gleam-lint.md): lint rules and review profiles. -- [Migrations](migrations.md): storage changes and startup order. +- [Migrations](migrations.md): storage changes, startup order, and the downgrade + refusal. - [Performance](perf.md): measurement commands, metrics, and gates. - [Release](release.md): builds, packages, and smoke tests. diff --git a/robot-docs/contributing.md b/robot-docs/contributing.md index 73ba069c2..83a695332 100644 --- a/robot-docs/contributing.md +++ b/robot-docs/contributing.md @@ -165,6 +165,11 @@ For schema changes, preserve the [foreign-key indexing rule](migrations.md#foreign-key-indexes). Unindexed child lookups can make deletion block the writer. +Decide whether each migration is additive or breaking, and declare it. Prefer an +additive change. A breaking migration makes every older build refuse the home, +so users can roll back only by restoring a backup. Never rename a recorded +migration or drop its name. See [downgrades](migrations.md#downgrades). + ## Preserve client conventions For terminal screens, follow diff --git a/robot-docs/extensions.md b/robot-docs/extensions.md index 00cab9fbf..8411d8d2a 100644 --- a/robot-docs/extensions.md +++ b/robot-docs/extensions.md @@ -507,6 +507,25 @@ extension code: exempt: read them through the typed operations above. The rule also flags a `tables` entry the extension does not create. +### Migrations + +An extension changes its stored data with a `MigrationPlugin`. Both variants of +[`extension.Migration`](../src/albedo/harness/sdk/extension.gleam) take a `name` +and a [`migration.Compatibility`](../src/albedo/harness/sdk/migration.gleam): + +- `SchemaMigration(name, compatibility, apply)` runs on a connection right after + the extension's initialiser, at every startup. Make `apply` idempotent. +- `DataMigration(name, compatibility, run)` runs after core data migrations, + with the extension's handle and the pre-upgrade backup path. It returns the + rows it rewrote. + +Mark a migration `Breaking` when a build without it would misread or lose the +extension's data, for example after a rename or a format rewrite. The host +records a breaking migration's name in the home before it writes, and a build +that does not know the name refuses that home. Prefix the name with the +extension's name, never change it, and keep a breaking migration declared after +it has nothing left to do. See [downgrades](migrations.md#downgrades). + ### Public features own their tables A [public feature](#public-feature-dependencies) runs its SQL under its owner's diff --git a/robot-docs/migrations.md b/robot-docs/migrations.md index 4dd3f9be1..b78ce7e04 100644 --- a/robot-docs/migrations.md +++ b/robot-docs/migrations.md @@ -7,13 +7,15 @@ extension data migrations. ## Startup order -[server.start](../src/albedo/daemon/server.gleam) calls -`registry.prepare_storage` before serving sessions. +[server.main](../src/albedo/daemon/server.gleam) checks the home's +[breaking-migration record](#downgrades) before anything opens storage. Then +`server.start` calls `registry.prepare_storage` before serving sessions. [Core migrations.run](../src/albedo/daemon/migrations.gleam) runs image storage, transcript classification, session profiles, prompts, titles, usage-hour, and waiting-input upgrades in that order. Each result is checked, so an error stops the sequence. The last moves inputs from the retired `pending_inputs` table into -the [inbox](inbox.md). +the [inbox](inbox.md). Startup prints `migration : rows` for each +core, kernel, and extension migration that rewrote rows. After the core upgrades, `prepare_storage` runs the kernel's [`cell_images`](../src/albedo/harness/kernel/migrations/cell_images.gleam) @@ -37,6 +39,118 @@ handles older transcript rows. Inspect each migration's transaction and marker logic before changing its restart behavior. These upgrades do not all share one transaction. +## Downgrades + +A daemon refuses to start on a home that a newer build upgraded with a breaking +migration this build does not know. Additive changes never block a rollback. + +Every migration declares a +[`migration.Compatibility`](../src/albedo/harness/sdk/migration.gleam): + +- `Additive`: a build without the migration still reads the home correctly. A + new table or index, a nullable or defaulted column, or a backfill of one of + those is additive. Nothing is recorded. +- `Breaking`: a build without the migration would misread or lose data. Rows + moved to another table, a column renamed, dropped, or given a new meaning, and + values rewritten into a new format are breaking. + +### Record + +`migration.apply` and `migration.record` write a breaking migration's name to +the `breaking_migrations` table before the migration writes anything. The table +is created on first use. A data migration's record commits in its own +transaction first, so a run interrupted half way is still recorded. An extension +schema migration's record commits in the same transaction as its schema change. +Breaking migrations run at every startup and record themselves each time, so the +insert is idempotent. + +Transfers do not carry `breaking_migrations`. Each daemon records its own +upgrades. + +### Refusal + +`server.main` calls `registry.unknown_migrations` after it takes the home lock +and before `server.start` opens storage. It compares the record with +`registry.known_migrations`: every core and kernel migration name, the retired +core names, and every migration that the build's declared extensions contain, +including quarantined ones. `migration.unknown` opens an existing +`albedo.sqlite` with `mode=rw` and only reads it. A missing file is a new home. + +When a name is unknown, the daemon prints this line to `daemon.log` and halts +with status 78 through `lifecycle.refuse_storage`: + +```text +This home was upgraded by a newer albedo (); update albedo or restore a backup. +``` + +The CLI reports a daemon that exits during startup with the log written since +launch, so `albedo` shows the line. A failure to read the record stops startup +too. + +### Declare a migration + +1. Decide whether the change is additive or breaking. Prefer an additive form, + such as a new column the old one is copied into, when it keeps the change + useful. +2. Give the migration a name that is unique across the daemon. Prefix an + extension's migration with the extension's name. + [`migration_names_test`](../test/daemon/migration_names_test.gleam) checks + uniqueness. +3. Put a core migration in `migrations.steps` with its compatibility. Declare an + extension migration as `extension.SchemaMigration` or + `extension.DataMigration`, each with a name and compatibility. See + [extension migrations](extensions.md#migrations). +4. Put a breaking change in a declared migration. A table initialiser's rewrite + is not recorded. + +Never rename a migration or reuse a name. Once a home records a name, every +later build must know it. When a breaking core step is removed, move its name to +`retired` in [migrations.gleam](../src/albedo/daemon/migrations.gleam). Keep an +extension's breaking migration declared, with a `run` or `apply` that does +nothing. + +### Homes from before the record + +The first build with the record runs every migration at startup, so it records +each breaking migration it knows. Homes it upgraded earlier gain those records +then. Every build with the check knows those names, so the backfill refuses no +build that has the check. + +A build from before the record does not check it. Rolling a home back to such a +build is not refused, even when a later build recorded a breaking migration. The +refusal protects only rollbacks to builds that include it. + +### Classification + +| Migration | Owner | Compatibility | Reason | +| -------------------------------------------------------------------------------------- | ---------- | ------------- | --------------------------------------------------------------------------------------------- | +| `image_store` | core | Breaking | Transcript rows keep references to images moved into `images`. | +| `transcript_classes` | core | Additive | Fills the new `row_class` column and adds indexes over it. | +| `session_profiles` | core | Additive | A new table, filled once and kept by triggers on rows every build writes. | +| `session_prompts` | core | Breaking | Moves the prompt columns out of `sessions` and drops them. | +| `session_titles` | core | Additive | Sets `auto_title_attempted`, which every build with the column reads the same way. | +| `usage_hours` | core | Additive | A new table, filled once and kept by a trigger on rows every build writes. | +| `pending_inputs_inbox` | core | Breaking | Moves waiting inputs out of `pending_inputs`, and later inputs never go there. | +| `cell_images` | kernel | Breaking | Cell outputs keep references to images moved into `images`. | +| `coding_lcm_name` | coding-lcm | Breaking | Renames the `lcm` extension in settings and session choices. | +| `paperclips_title`, `paperclips_reply`, `paperclips_resolution`, `paperclips_revision` | paperclips | Additive | Defaulted columns. | +| `paperclips_scope` | paperclips | Additive | Drops an index that a build which wants it creates again. | +| `work_cwd` | work | Additive | A defaulted column and an index. | +| `rolling_observation` | rolling | Additive | Drops a table that cached each request's observation. An older build creates it again, empty. | +| `schedule_revision` | schedule | Additive | Defaulted columns. | + +Two older rewrites run inside table initialisers and are not recorded. Every +build with the check includes both. +[`mail_kinds`](../src/albedo/daemon/migrations/mail_kinds.gleam) copies the mail +table and rewrites event kinds. The webhooks `filed` upgrade in +[the webhook ledger](../src/albedo/harness/extensions/webhooks/ledger.gleam) +posts inbox letters for deliveries that waited from before the inbox. + +[`downgrade_test.py`](../test/e2e/downgrade_test.py) opens a home this checkout +upgraded with the [reference build](testing.md#mixed-version-moves). It also +starts this checkout on a home that records an unknown breaking migration and +checks the CLI's message and that the database is unchanged. + ## Foreign-key indexes Make each foreign key's child columns the leading columns of an index. For a @@ -63,3 +177,5 @@ described in [test execution](testing.md). - [Durable operation admission](operations.md) - [Test execution](testing.md) - [The detached kernel](kernel.md) +- [Extension migrations](extensions.md#migrations) +- [Moves between versions](workspaces.md#moves-between-versions) diff --git a/robot-docs/plugins.md b/robot-docs/plugins.md index 0110a3c98..df8e6602f 100644 --- a/robot-docs/plugins.md +++ b/robot-docs/plugins.md @@ -114,8 +114,9 @@ The same `Plugin` type declares provider and model catalogs, login, services, startup, migrations, settings, cleanup, state transfer, history and worktree following, and scheduled prompts. `ServicePlugin` defines an admission policy and a body limit for its routes. `MigrationPlugin` distinguishes schema -migrations from data migrations. `CleanPlugin` runs for installed extensions -when a session is deleted, including extensions that are disabled. +migrations from data migrations, and each names itself and declares whether it +is [breaking](extensions.md#migrations). `CleanPlugin` runs for installed +extensions when a session is deleted, including extensions that are disabled. `StartupPlugin` receives an `extension.Startup` with the store, the extension's [storage handle](extensions.md#extension-storage), the daemon's `inbox`, and an `invalidate` callback. The inbox and `invalidate` are diff --git a/robot-docs/testing.md b/robot-docs/testing.md index da5f39b3c..f91f3db0e 100644 --- a/robot-docs/testing.md +++ b/robot-docs/testing.md @@ -116,10 +116,19 @@ Bump the pin when a commit that users run lands, such as one deployed to another host, or when the reference falls back past a transfer protocol change. 1. Set `REFERENCE` to the full commit hash. -2. Run `nix develop -c python3 test/e2e/run.py move_versions_test.py`. +2. Run + `nix develop -c python3 test/e2e/run.py move_versions_test.py downgrade_test.py`. 3. Report a failure of the supported move as an incompatibility between the two builds. Do not loosen an assertion to make it pass. +[`reference_support.py`](../test/e2e/reference_support.py) builds the reference +on first use. Its `run_reference` points a test daemon's next boot at the +reference daemon and CLI. [`downgrade_test.py`](../test/e2e/downgrade_test.py) +uses it to restart a home this checkout upgraded on the reference build, and +checks that the reference reads a session this checkout wrote. A rollback across +a breaking migration is not supported, so bump the pin past each new breaking +migration. See [downgrades](migrations.md#downgrades). + [`areas.toml`](../test/e2e/areas.toml) selects the file for changes to transfer code, adapters, migrations, and the core tables in `conversation.gleam` and `mail.gleam`. A schema change in another owner reaches it only through diff --git a/robot-docs/workspaces.md b/robot-docs/workspaces.md index fdf880411..3e48c228a 100644 --- a/robot-docs/workspaces.md +++ b/robot-docs/workspaces.md @@ -134,6 +134,9 @@ expires nothing there. each refusal code, including a quarantined extension. See [mixed-version moves](testing.md#mixed-version-moves). +Starting an older daemon on a whole home that a newer one upgraded is a +different case. See [downgrades](migrations.md#downgrades). + ## Browsing [`folders.directory`](../src/albedo/daemon/folders.gleam) returns a directory diff --git a/src/albedo/daemon/lifecycle.gleam b/src/albedo/daemon/lifecycle.gleam index ef3b68f63..8fbdcfd9a 100644 --- a/src/albedo/daemon/lifecycle.gleam +++ b/src/albedo/daemon/lifecycle.gleam @@ -76,13 +76,25 @@ fn home_default() -> Result(String, Nil) { /// Report that another daemon or maintenance command holds `home`, tell a /// waiting CLI, and halt with status 75. pub fn refuse_home(home: String) -> Nil { - io.println_error( + refuse( "storage is in use by another albedo daemon or maintenance command for ALBEDO_HOME=" - <> home, + <> home, + 75, ) +} + +/// Report that this build cannot read its home's storage, tell a waiting +/// CLI, and halt with status 78 (EX_CONFIG): a retry fails the same way until +/// albedo is updated or the home restored. +pub fn refuse_storage(message: String) -> Nil { + refuse(message, 78) +} + +fn refuse(message: String, status: Int) -> Nil { + io.println_error(message) standby_flush() - standby_exiting(75) - halt(75) + standby_exiting(status) + halt(status) } /// A loopback port nothing listens on, which the OS just picked. diff --git a/src/albedo/daemon/migrations.gleam b/src/albedo/daemon/migrations.gleam index f15c86b1e..af3d6d869 100644 --- a/src/albedo/daemon/migrations.gleam +++ b/src/albedo/daemon/migrations.gleam @@ -7,21 +7,71 @@ import albedo/daemon/migrations/session_prompts import albedo/daemon/migrations/session_titles import albedo/daemon/migrations/transcript_classes import albedo/daemon/migrations/usage_hours +import albedo/harness/sdk/migration.{type Compatibility, Additive, Breaking} import albedo/harness/sdk/store +import gleam/list import gleam/result +/// One core upgrade: its name, what a build without it makes of its result, +/// and its run, which takes the pre-upgrade backup path and returns the rows +/// it rewrote. +type Step { + Step( + name: String, + compatibility: Compatibility, + run: fn(store.Store, String) -> Result(Int, String), + ) +} + +/// Breaking core migrations whose step was removed. A home may record them, +/// so their names stay known for good. +const retired: List(String) = [] + /// Upgrade image storage, classify transcript rows, note which profiles wrote /// each session's rows, move session prompts to their own table, then move -/// waiting inputs into the inbox. +/// waiting inputs into the inbox. Each step's compatibility says why. +fn steps() -> List(Step) { + [ + // Rows keep references to images moved out of them. + Step("image_store", Breaking, image_store.run), + // A new column, filled, and indexes over it. + Step("transcript_classes", Additive, rowless(transcript_classes.run)), + // A new table, filled, kept by triggers on the rows every build writes. + Step("session_profiles", Additive, rowless(session_profiles.run)), + // The prompt columns leave `sessions` for a table of their own. + Step("session_prompts", Breaking, rowless(session_prompts.run)), + // A flag every build that has the column reads the same way. + Step("session_titles", Additive, rowless(session_titles.run)), + // A new table, filled, kept by a trigger on the rows every build writes. + Step("usage_hours", Additive, rowless(usage_hours.run)), + // Waiting inputs leave `pending_inputs`, and later ones never go there. + Step("pending_inputs_inbox", Breaking, rowless(pending_inputs_inbox.run)), + ] +} + +fn rowless( + run: fn(store.Store) -> Result(Nil, String), +) -> fn(store.Store, String) -> Result(Int, String) { + fn(ledger, _backup) { run(ledger) |> result.replace(0) } +} + +/// Runs every core step in order, recording each breaking one first, and +/// stops at the first failure. Returns the rows each step rewrote. /// Extension upgrades follow via the runtime; this module knows only core /// storage. -pub fn run(ledger: store.Store, backup: String) -> Result(Int, String) { - use moved <- result.try(image_store.run(ledger, backup)) - use _ <- result.try(transcript_classes.run(ledger)) - use _ <- result.try(session_profiles.run(ledger)) - use _ <- result.try(session_prompts.run(ledger)) - use _ <- result.try(session_titles.run(ledger)) - use _ <- result.try(usage_hours.run(ledger)) - use _ <- result.try(pending_inputs_inbox.run(ledger)) - Ok(moved) +pub fn run( + ledger: store.Store, + backup: String, +) -> Result(List(#(String, Int)), String) { + list.try_map(steps(), fn(step) { + migration.apply(ledger, step.name, step.compatibility, fn() { + step.run(ledger, backup) + }) + |> result.map(fn(rows) { #(step.name, rows) }) + }) +} + +/// Every core migration name a home may record, retired ones included. +pub fn names() -> List(String) { + list.append(list.map(steps(), fn(step) { step.name }), retired) } diff --git a/src/albedo/daemon/registry.gleam b/src/albedo/daemon/registry.gleam index 5616ad20d..4233276e4 100644 --- a/src/albedo/daemon/registry.gleam +++ b/src/albedo/daemon/registry.gleam @@ -49,6 +49,7 @@ import albedo/harness/sdk/credentials import albedo/harness/sdk/extension import albedo/harness/sdk/follow import albedo/harness/sdk/history as stored_history +import albedo/harness/sdk/migration import albedo/harness/sdk/oauth import albedo/harness/sdk/profiles as configuration import albedo/harness/sdk/protect @@ -528,6 +529,26 @@ fn workers(state: State) -> List(session.Session) { |> list.filter_map(fn(pair) { option.to_result(pair.1, Nil) }) } +/// The breaking migrations `home` records that this build does not know, +/// read before anything opens its storage. A newer build ran them; this one +/// would misread what they wrote, so the daemon refuses the home instead. +pub fn unknown_migrations( + home: String, + installed: List(extension.Extension), +) -> Result(List(String), String) { + migration.unknown(home <> "/albedo.sqlite", known_migrations(installed)) +} + +/// Every migration this build declares, core, kernel, and `installed` +/// extensions', whether breaking or not. +pub fn known_migrations(installed: List(extension.Extension)) -> List(String) { + list.flatten([ + migrations.names(), + [cell_images.name], + extension.migration_names(installed), + ]) +} + /// Schema and one-time migrations, before any session starts. pub fn prepare_storage( config: Config, @@ -568,7 +589,7 @@ pub fn prepare_storage( <> "/backups/albedo-before-image-store-" <> int.to_string(usage.now()) <> ".sqlite" - use moved <- result.try( + use core <- result.try( startup.measure("core data migrations", fn() { migrations.run(runtime.ledger(host), backup) }), @@ -579,9 +600,15 @@ pub fn prepare_storage( }), ) // The kernel's own data upgrade keeps the name the migrations table records. + // Cell outputs keep references to images moved out of them. use cells <- result.try( startup.measure("kernel data migrations", fn() { - cell_images.run(runtime.ledger(host), backup) + migration.apply( + runtime.ledger(host), + cell_images.name, + migration.Breaking, + fn() { cell_images.run(runtime.ledger(host), backup) }, + ) }), ) use upgraded <- result.try( @@ -589,7 +616,7 @@ pub fn prepare_storage( runtime.migrate(host, backup) }), ) - let upgraded = [#("cell_images", cells), ..upgraded] + let upgraded = list.flatten([core, [#(cell_images.name, cells)], upgraded]) // Before anything reattaches: kernels another daemon booted stay its own. use disowned <- result.try(link.disown(runtime.ledger(host))) use _ <- result.try( @@ -615,15 +642,6 @@ pub fn prepare_storage( <> " kernels of another daemon's home alone", ) } - case moved { - 0 -> Nil - rows -> - io.println( - "image store: moved images out of " - <> int.to_string(rows) - <> " transcript rows", - ) - } case startup.measure("credentials migration", fn() { credentials.migrate(config.home, int.to_string(usage.now())) diff --git a/src/albedo/daemon/server.gleam b/src/albedo/daemon/server.gleam index 14bd2a7f7..90e48074c 100644 --- a/src/albedo/daemon/server.gleam +++ b/src/albedo/daemon/server.gleam @@ -38,10 +38,12 @@ import albedo/daemon/settings import albedo/daemon/stalls import albedo/daemon/transfers import albedo/daemon/webhook_intake +import albedo/harness/extensions import albedo/harness/runtime import albedo/harness/sdk/credentials import albedo/harness/sdk/extension import albedo/harness/sdk/http_api as sdk_http_api +import albedo/harness/sdk/migration import albedo/harness/sdk/oauth_flows import albedo/harness/sdk/profiles as configuration import albedo/harness/sdk/usage_feed @@ -76,6 +78,7 @@ type HttpBoundary { /// Returns the daemon's port and the webhook intake's port. pub fn start( config: Config, + installed: extensions.Config, port: Int, webhook_port: Int, ) -> Result(#(Int, Int), String) { @@ -84,7 +87,7 @@ pub fn start( io.println("startup: opening storage and installing extensions") use host <- result.try( startup.measure("runtime", fn() { - runtime.start(config.home <> "/albedo.sqlite") + runtime.start_with_config(config.home <> "/albedo.sqlite", installed) }) |> result.map_error(fn(error) { case error { @@ -932,10 +935,20 @@ pub fn main() -> Nil { Error(error) -> panic as error.message } startup.measure("preserve code", fn() { boot_code.prepare(home) }) + let installed = startup.measure("extension declarations", extensions.defaults) + // Before anything opens storage: a home a newer build upgraded past what + // this one can read is refused, unwritten. + case registry.unknown_migrations(home, installed.extensions) { + Ok([]) -> Nil + Ok(names) -> lifecycle.refuse_storage(migration.refusal(names)) + Error(reason) -> + panic as { "could not read the migration record: " <> reason } + } // A fixed port gives services such as the proxy a stable base url. let #(port, webhook_port) = case start( config, + installed, setting("ALBEDO_PORT", 0, 0, 65_535), setting("ALBEDO_WEBHOOK_PORT", default_webhook_port(home), 0, 65_535), ) diff --git a/src/albedo/daemon/transfer.gleam b/src/albedo/daemon/transfer.gleam index e88e9336e..7cd51b9dc 100644 --- a/src/albedo/daemon/transfer.gleam +++ b/src/albedo/daemon/transfer.gleam @@ -156,6 +156,10 @@ pub fn adapter() -> transfer.Adapter { "migrations", "daemon-wide markers of upgrades this home applied", ), + transfer.Excluded( + "breaking_migrations", + "upgrades this home ran that older daemons cannot read; the target records its own", + ), transfer.Excluded( "quota_sample", "account quota readings belong to the daemon, not a session", diff --git a/src/albedo/harness/extensions/lcm/extension.gleam b/src/albedo/harness/extensions/lcm/extension.gleam index d73783753..8ccc5ed22 100644 --- a/src/albedo/harness/extensions/lcm/extension.gleam +++ b/src/albedo/harness/extensions/lcm/extension.gleam @@ -4,6 +4,7 @@ import albedo/harness/compaction import albedo/harness/extensions/lcm/core import albedo/harness/extensions/lcm/graph import albedo/harness/sdk/extension as harness_extension +import albedo/harness/sdk/migration import albedo/harness/sdk/settings import albedo/harness/sdk/storage import gleam/result @@ -47,8 +48,11 @@ fn bundle( harness_extension.CleanPlugin(graph.forget_session), // The graph's owner is lcm-memory, which this extension requires. harness_extension.FeaturePlugin(graph.owner()), + // A build that still calls the extension `lcm` finds sessions and + // settings naming one it does not have. harness_extension.MigrationPlugin(harness_extension.DataMigration( "coding_lcm_name", + migration.Breaking, rename_former, )), ], diff --git a/src/albedo/harness/extensions/paperclips/extension.gleam b/src/albedo/harness/extensions/paperclips/extension.gleam index 9e7e86204..f65182d36 100644 --- a/src/albedo/harness/extensions/paperclips/extension.gleam +++ b/src/albedo/harness/extensions/paperclips/extension.gleam @@ -9,6 +9,7 @@ import albedo/harness/sdk/client_api import albedo/harness/sdk/command.{Argument} import albedo/harness/sdk/extension as harness_extension import albedo/harness/sdk/host +import albedo/harness/sdk/migration import albedo/harness/sdk/service as http_service import gleam/http @@ -57,19 +58,31 @@ pub fn extension() -> harness_extension.Extension { 65_536, service.dispatch, )), + // Defaulted columns, and a dropped index a build that still wants it + // creates again: a build without them reads the rows it knows. harness_extension.MigrationPlugin(harness_extension.SchemaMigration( + "paperclips_title", + migration.Additive, title.apply, )), harness_extension.MigrationPlugin(harness_extension.SchemaMigration( + "paperclips_scope", + migration.Additive, scope.apply, )), harness_extension.MigrationPlugin(harness_extension.SchemaMigration( + "paperclips_reply", + migration.Additive, reply.apply, )), harness_extension.MigrationPlugin(harness_extension.SchemaMigration( + "paperclips_resolution", + migration.Additive, resolution.apply, )), harness_extension.MigrationPlugin(harness_extension.SchemaMigration( + "paperclips_revision", + migration.Additive, revision.apply, )), // The route's workspace records where a new vent was filed; the diff --git a/src/albedo/harness/extensions/rolling/extension.gleam b/src/albedo/harness/extensions/rolling/extension.gleam index 87adb8071..678fff50d 100644 --- a/src/albedo/harness/extensions/rolling/extension.gleam +++ b/src/albedo/harness/extensions/rolling/extension.gleam @@ -5,6 +5,7 @@ import albedo/harness/extensions/rolling/migrations/observation import albedo/harness/extensions/rolling/strategy as rolling import albedo/harness/extensions/rolling/transfer import albedo/harness/sdk/extension +import albedo/harness/sdk/migration import albedo/harness/sdk/settings import albedo/harness/sdk/storage @@ -16,7 +17,13 @@ fn bundle(strategy: compaction.Strategy) -> extension.Extension { [ extension.TransferPlugin(transfer.adapter()), extension.CompactionPlugin(strategy), - extension.MigrationPlugin(extension.SchemaMigration(observation.apply)), + // Drops a table that only cached each request's observation; a build + // that still uses it creates it again, empty. + extension.MigrationPlugin(extension.SchemaMigration( + "rolling_observation", + migration.Additive, + observation.apply, + )), extension.CleanPlugin(fn(db, session) { storage.forget_session(db, ["rolling_compaction_state"], session) }), diff --git a/src/albedo/harness/extensions/schedule/extension.gleam b/src/albedo/harness/extensions/schedule/extension.gleam index de2f03363..6fc0430a3 100644 --- a/src/albedo/harness/extensions/schedule/extension.gleam +++ b/src/albedo/harness/extensions/schedule/extension.gleam @@ -3,6 +3,7 @@ import albedo/harness/extensions/schedule/migrations/revision import albedo/harness/sdk/client_api import albedo/harness/sdk/command.{Argument, Command, Data} import albedo/harness/sdk/extension +import albedo/harness/sdk/migration import albedo/harness/sdk/page import albedo/harness/sdk/service as http_service import albedo/harness/sdk/storage @@ -42,7 +43,12 @@ pub fn extension() -> extension.Extension { ), ]), extension.GlancePlugin(service.sidebar, service.resource_url), - extension.MigrationPlugin(extension.SchemaMigration(revision.apply)), + // Defaulted columns: a build without them reads the rows it knows. + extension.MigrationPlugin(extension.SchemaMigration( + "schedule_revision", + migration.Additive, + revision.apply, + )), extension.ServicePlugin(http_service.json(65_536, service.dispatch)), extension.CleanPlugin(fn(db, session) { storage.forget_session(db, ["schedules"], session) diff --git a/src/albedo/harness/extensions/work/extension.gleam b/src/albedo/harness/extensions/work/extension.gleam index a8ee1d623..91afedb8f 100644 --- a/src/albedo/harness/extensions/work/extension.gleam +++ b/src/albedo/harness/extensions/work/extension.gleam @@ -6,6 +6,7 @@ import albedo/harness/sdk/command.{Argument} import albedo/harness/sdk/extension as harness_extension import albedo/harness/sdk/follow import albedo/harness/sdk/host +import albedo/harness/sdk/migration import albedo/harness/sdk/service as http_service import albedo/harness/sdk/storage import gleam/http @@ -62,7 +63,11 @@ pub fn extension() -> harness_extension.Extension { 65_536, service.dispatch, )), + // A defaulted column and an index: a build without them reads the + // rows it knows. harness_extension.MigrationPlugin(harness_extension.SchemaMigration( + "work_cwd", + migration.Additive, cwd.apply, )), harness_extension.CleanPlugin(fn(db, session) { diff --git a/src/albedo/harness/kernel/migrations/cell_images.gleam b/src/albedo/harness/kernel/migrations/cell_images.gleam index 309354efe..9ade47e8b 100644 --- a/src/albedo/harness/kernel/migrations/cell_images.gleam +++ b/src/albedo/harness/kernel/migrations/cell_images.gleam @@ -12,6 +12,10 @@ import gleam/option.{None, Some} import gleam/result import sqlight +/// The name the migrations table records this upgrade's completion under, and +/// its breaking record. +pub const name = "cell_images" + /// Move legacy inline cell screenshots into the shared image store. Each page /// commits independently; an interrupted startup rechecks the remaining rows. pub fn run(storage: store.Store, backup: String) -> Result(Int, String) { diff --git a/src/albedo/harness/sdk/extension.gleam b/src/albedo/harness/sdk/extension.gleam index dc1369297..e18013544 100644 --- a/src/albedo/harness/sdk/extension.gleam +++ b/src/albedo/harness/sdk/extension.gleam @@ -15,6 +15,7 @@ import albedo/harness/sdk/imagegen import albedo/harness/sdk/input import albedo/harness/sdk/key_environment.{type KeyEnvironment} import albedo/harness/sdk/mail +import albedo/harness/sdk/migration import albedo/harness/sdk/model_lists import albedo/harness/sdk/network import albedo/harness/sdk/network_context @@ -727,14 +728,25 @@ pub type McpServers { ) } +/// Every migration has a `name`, unique across the daemon and stable forever: +/// a home records a breaking one under it, and a daemon that finds a name it +/// does not know refuses that home. Prefix it with the extension's name. Keep +/// a breaking migration declared after it has nothing left to do, with a `run` +/// or `apply` that does nothing, so its name stays known. pub type Migration { - /// Applied immediately after the owning extension creates its tables. - SchemaMigration(apply: fn(sqlight.Connection) -> Result(Nil, String)) + /// Applied immediately after the owning extension creates its tables, in + /// the same transaction as its record when it is breaking. + SchemaMigration( + name: String, + compatibility: migration.Compatibility, + apply: fn(sqlight.Connection) -> Result(Nil, String), + ) /// Applied after core data upgrades, with the same pre-upgrade backup path. /// Returns the number of rows rewritten for startup reporting. `run` /// receives the owning extension's storage handle. DataMigration( name: String, + compatibility: migration.Compatibility, run: fn(storage.Storage, String) -> Result(Int, String), ) } @@ -1499,7 +1511,17 @@ fn started( use _ <- result.try(extension.initialise(setup)) list.try_each(extension.plugins, fn(plugin) { case plugin { - MigrationPlugin(SchemaMigration(apply)) -> store.query(ledger, apply) + MigrationPlugin(SchemaMigration(name, compatibility, apply)) -> + store.query(ledger, fn(db) { + use _ <- result.try(case compatibility { + migration.Additive -> Ok(Nil) + migration.Breaking -> migration.record(db, name) + }) + apply(db) + |> result.map_error(fn(error) { + "migration " <> name <> ": " <> error + }) + }) _ -> Ok(Nil) } }) @@ -1646,18 +1668,30 @@ pub fn migrate( ) -> Result(List(#(String, Int)), String) { extension_values(installed, fn(extension, plugin) { case plugin { - MigrationPlugin(DataMigration(name, run)) -> + MigrationPlugin(DataMigration(name, compatibility, run)) -> Ok( - #(name, fn(ledger, backup) { + #(name, compatibility, fn() { run(storage_of(extension, ledger), backup) }), ) _ -> Error(Nil) } }) - |> list.try_map(fn(migration) { - migration.1(ledger, backup) - |> result.map(fn(count) { #(migration.0, count) }) + |> list.try_map(fn(declared) { + let #(name, compatibility, run) = declared + migration.apply(ledger, name, compatibility, run) + |> result.map(fn(count) { #(name, count) }) + }) +} + +/// The name of every migration `installed` declares, schema and data: each +/// breaking one a home may record that this build knows. +pub fn migration_names(installed: List(Extension)) -> List(String) { + extension_values(installed, fn(_, plugin) { + case plugin { + MigrationPlugin(declared) -> Ok(declared.name) + _ -> Error(Nil) + } }) } diff --git a/src/albedo/harness/sdk/migration.gleam b/src/albedo/harness/sdk/migration.gleam new file mode 100644 index 000000000..e336422d0 --- /dev/null +++ b/src/albedo/harness/sdk/migration.gleam @@ -0,0 +1,110 @@ +//// Whether a build without a storage migration can still read a home that +//// ran it, and the home's record of the ones it cannot. +//// +//// Every core, kernel, and extension migration declares a `Compatibility`. +//// A breaking one is recorded in `breaking_migrations` before it writes, so +//// an interrupted run is recorded too. A daemon reads that record before it +//// opens storage and refuses a home that lists a breaking migration it does +//// not know (robot-docs/migrations.md, "Downgrades"). + +import albedo/harness/sdk/file +import albedo/harness/sdk/store +import gleam/dynamic/decode +import gleam/list +import gleam/result +import gleam/string +import gleam/uri +import sqlight + +/// What a build that lacks a migration makes of a home that ran it. +pub type Compatibility { + /// It reads the home correctly: a new table or index, a nullable or + /// defaulted column, or a backfill of one of those. Nothing is recorded, + /// and a rollback is never refused. + Additive + /// It would misread or lose data: rows moved to another table, a column + /// renamed, dropped, or given a new meaning, or values rewritten into a new + /// format. The home records the migration, and a build that does not know + /// its name refuses to start there. + Breaking +} + +/// Runs `run`, first recording `name` when it is breaking. The record +/// commits before `run` writes, so a home a breaking migration only partly +/// rewrote is still refused by a build that lacks it. +pub fn apply( + ledger: store.Store, + name: String, + compatibility: Compatibility, + run: fn() -> Result(a, String), +) -> Result(a, String) { + use _ <- result.try(case compatibility { + Additive -> Ok(Nil) + Breaking -> store.query(ledger, record(_, name)) + }) + run() +} + +/// Records that this home ran breaking migration `name`, creating the record +/// on first use. Idempotent, so a migration that runs at every startup +/// records itself at every startup. +pub fn record(db: sqlight.Connection, name: String) -> Result(Nil, String) { + use _ <- result.try(store.exec( + db, + "CREATE TABLE IF NOT EXISTS breaking_migrations(name TEXT PRIMARY KEY,recorded_at INTEGER NOT NULL)", + )) + store.run( + db, + "INSERT OR IGNORE INTO breaking_migrations(name,recorded_at) VALUES(?,unixepoch())", + [sqlight.text(name)], + ) +} + +/// The breaking migrations `database` records whose names are not in +/// `known`, sorted. It only reads: a missing file is a new home, and +/// `mode=rw` opens an existing file without creating one. +pub fn unknown( + database: String, + known: List(String), +) -> Result(List(String), String) { + case file.is_regular(database) { + False -> Ok([]) + True -> { + use db <- result.try( + sqlight.open("file:" <> uri.percent_encode(database) <> "?mode=rw") + |> result.map_error(fn(error) { error.message }), + ) + let recorded = recorded(db) + let _ = sqlight.close(db) + use recorded <- result.map(recorded) + list.filter(recorded, fn(name) { !list.contains(known, name) }) + } + } +} + +fn recorded(db: sqlight.Connection) -> Result(List(String), String) { + use _ <- result.try(store.exec(db, "PRAGMA busy_timeout=3000")) + use tables <- result.try(store.rows( + db, + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='breaking_migrations'", + [], + decode.success(Nil), + )) + case tables { + [] -> Ok([]) + _ -> + store.rows( + db, + "SELECT name FROM breaking_migrations ORDER BY name", + [], + decode.field(0, decode.string, decode.success), + ) + } +} + +/// What a daemon says when it refuses a home for `names`. +pub fn refusal(names: List(String)) -> String { + "This home was upgraded by a newer albedo (" + <> string.join(names, ", ") + <> "); update albedo or restore a backup." +} diff --git a/test/daemon/migration_names_test.gleam b/test/daemon/migration_names_test.gleam new file mode 100644 index 000000000..62160f183 --- /dev/null +++ b/test/daemon/migration_names_test.gleam @@ -0,0 +1,13 @@ +//// A home records a breaking migration by name alone, and a daemon refuses a +//// name it does not know, so two migrations sharing a name would let a build +//// that ran only one of them open a home the other rewrote. + +import albedo/daemon/registry +import albedo/harness/extensions +import gleam/list +import gleeunit/should + +pub fn every_migration_name_is_declared_once_test() -> Nil { + let names = registry.known_migrations(extensions.declared().extensions) + list.unique(names) |> should.equal(names) +} diff --git a/test/e2e/areas.toml b/test/e2e/areas.toml index d598faa0c..91e1f5fe3 100644 --- a/test/e2e/areas.toml +++ b/test/e2e/areas.toml @@ -19,7 +19,8 @@ "move_checklist_test.py", "move_versions_test.py", ] -"test/reference-daemon.sh" = ["move_versions_test.py"] +"test/reference-daemon.sh" = ["move_versions_test.py", "downgrade_test.py"] +"test/e2e/reference_support.py" = ["move_versions_test.py", "downgrade_test.py"] "test/e2e/_transfer_support.py" = [ "transfer_test.py", "transfer_activation_test.py", @@ -29,6 +30,11 @@ "move_checklist_test.py", "move_versions_test.py", ] +# The breaking-migration record and the startup refusal that reads it. +"src/albedo/harness/sdk/migration.gleam" = [ + "downgrade_test.py", + "migrations_test.py", +] "src/albedo/harness/sdk/subscriptions.gleam" = ["artifacts_test.py"] "src/albedo/harness/extensions/artifacts/**" = ["artifacts_test.py"] "src/albedo/harness/extensions/skills/**" = ["skills_test.py"] @@ -156,6 +162,7 @@ "src/albedo/harness/kernel/migrations/**" = [ "migrations_test.py", "move_versions_test.py", + "downgrade_test.py", ] "src/albedo/harness/kernel/transfer.gleam" = [ "transfer_test.py", @@ -286,6 +293,7 @@ "src/albedo/daemon/migrations*" = [ "migrations_test.py", "move_versions_test.py", + "downgrade_test.py", ] "src/albedo/daemon/**" = [ "daemon_test.py", diff --git a/test/e2e/downgrade_test.py b/test/e2e/downgrade_test.py new file mode 100644 index 000000000..4367f86b3 --- /dev/null +++ b/test/e2e/downgrade_test.py @@ -0,0 +1,158 @@ +"""Starting a daemon on a home another build upgraded. + +A home records each breaking migration it ran. A build that finds one it does +not know refuses the home before it opens storage, and the CLI shows why. An +additive difference never blocks a rollback, so an older build still opens a +home this checkout upgraded (see robot-docs/migrations.md, "Downgrades"). +""" + +import hashlib +import json +import shutil +import sqlite3 +import subprocess +import tempfile +import time +import unittest +import urllib.error +from contextlib import closing + +from harness import Provider, alive, operation_id, peer_daemon, text +from reference_support import run_reference + +PROFILE = "downgrade" +FUTURE = "from_a_newer_build" + + +def body(daemon, path, payload=None, *, method=None, headers=None): + with daemon.api(path, payload, method=method, headers=headers) as response: + return json.load(response) + + +def recorded(database): + with closing(sqlite3.connect(database)) as db: + return [name for (name,) in db.execute("SELECT name FROM breaking_migrations")] + + +def stop(daemon): + """Stops the daemon through its CLI and waits until its process is gone.""" + pid = json.loads((daemon.home / "daemon.json").read_text())["pid"] + daemon.cli("daemon", "--stop") + deadline = time.monotonic() + 15 + while alive(pid): + if time.monotonic() > deadline: + raise AssertionError(f"daemon {pid} outlived daemon --stop") + time.sleep(0.05) + + +def published_record(daemon): + """The daemon record a ready daemon publishes, if any is there.""" + path = daemon.home / "daemon.json" + return path.read_text() if path.exists() else None + + +def snapshot(database): + """The database file's bytes and logical content, with nothing left in a + write-ahead log: what a refused start must leave as it was.""" + with closing(sqlite3.connect(database)) as db: + dump = list(db.iterdump()) + digest = hashlib.sha256(database.read_bytes()).hexdigest() + return digest, dump + + +class Downgrades(unittest.TestCase): + def setUp(self): + self.provider = Provider(lambda _request: text("noted")) + self.addCleanup(self.provider.close) + + def prepare(self, daemon): + config = { + "providers": { + PROFILE: { + "extension": "openai", + "baseUrl": self.provider.url, + "apiKey": "fixture-key", + "model": "fixture-model", + "protocol": "responses", + } + }, + "active": PROFILE, + } + (daemon.home / "config.json").write_text(json.dumps(config)) + + def converse(self, daemon, words): + session = operation_id() + workspace = tempfile.mkdtemp(prefix="downgrade-workspace-") + self.addCleanup(shutil.rmtree, workspace, True) + body( + daemon, + f"/sessions/{session}", + {"kind": "new", "workspace": workspace, "provider_profile": PROFILE}, + method="PUT", + headers={"If-None-Match": "*"}, + ) + daemon.api( + f"/sessions/{session}/inputs/{operation_id()}", + {"kind": "message", "text": words}, + method="PUT", + ).close() + deadline = time.monotonic() + 60 + while not self.said(daemon, session, "noted"): + if time.monotonic() > deadline: + raise AssertionError(f"session {session} never answered") + time.sleep(0.1) + return session + + def said(self, daemon, session, words): + try: + items = body(daemon, f"/sessions/{session}/history")["items"] + except urllib.error.HTTPError as failure: + if failure.code == 503: + return False + raise + return any(words in json.dumps(item) for item in items) + + def test_an_older_build_opens_a_home_this_build_upgraded(self): + daemon = peer_daemon("downgrade-older", self.prepare) + session = self.converse(daemon, "kept across the rollback") + # This build recorded the breaking migrations it ran; the older one + # predates the record, so only the additive part is new to it. + self.assertTrue(recorded(daemon.home / "albedo.sqlite")) + upgraded_by = body(daemon, "/server")["digest"] + + daemon.restart(prepare=lambda: run_reference(daemon)) + + self.assertNotEqual(body(daemon, "/server")["digest"], upgraded_by) + self.assertTrue(self.said(daemon, session, "kept across the rollback")) + self.assertEqual(body(daemon, f"/sessions/{session}")["id"], session) + + def test_a_home_with_an_unknown_breaking_migration_is_refused_unwritten(self): + daemon = peer_daemon("downgrade-refused", self.prepare) + database = daemon.home / "albedo.sqlite" + stop(daemon) + with closing(sqlite3.connect(database)) as db, db: + db.execute( + "INSERT INTO breaking_migrations(name,recorded_at) VALUES(?,0)", + (FUTURE,), + ) + before = snapshot(database) + published = published_record(daemon) + + launch = daemon.start_cli( + "daemon", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True + ) + stdout, stderr = launch.communicate(timeout=60) + + self.assertNotEqual(launch.returncode, 0, stdout + stderr) + self.assertIn( + f"This home was upgraded by a newer albedo ({FUTURE}); " + "update albedo or restore a backup.", + stdout + stderr, + ) + self.assertEqual(snapshot(database), before) + # No daemon came up to replace the stopped one's record. + self.assertEqual(published_record(daemon), published) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/harness/migration_test.gleam b/test/harness/migration_test.gleam index 4310e8ca6..b1d14a219 100644 --- a/test/harness/migration_test.gleam +++ b/test/harness/migration_test.gleam @@ -4,6 +4,8 @@ import albedo/daemon/mail import albedo/harness/sdk/extension +import albedo/harness/sdk/file +import albedo/harness/sdk/migration import albedo/harness/sdk/storage import albedo/harness/sdk/store import gleam/dynamic/decode @@ -20,26 +22,30 @@ pub fn contributed_migrations_keep_their_phases_and_stop_on_failure_test() -> Ni [], [ extension.MigrationPlugin( - extension.SchemaMigration(fn(db) { + extension.SchemaMigration("owner-schema", migration.Additive, fn(db) { store.add_columns(db, "owner", [#("revision", "INTEGER DEFAULT 1")]) }), ), extension.MigrationPlugin( - extension.DataMigration("owner-data", fn(scope, backup) { - let ledger = storage.ledger(scope) - use _ <- result.try(store.read( - ledger, - "SELECT 1 FROM core_ready", - [], - decode.dynamic, - )) - store.write( - ledger, - "INSERT INTO applied(name,backup) VALUES('owner',?)", - [sqlight.text(backup)], - ) - |> result.replace(1) - }), + extension.DataMigration( + "owner-data", + migration.Additive, + fn(scope, backup) { + let ledger = storage.ledger(scope) + use _ <- result.try(store.read( + ledger, + "SELECT 1 FROM core_ready", + [], + decode.dynamic, + )) + store.write( + ledger, + "INSERT INTO applied(name,backup) VALUES('owner',?)", + [sqlight.text(backup)], + ) + |> result.replace(1) + }, + ), ), ], extension.storage_initialise(fn(scope) { @@ -58,15 +64,19 @@ pub fn contributed_migrations_keep_their_phases_and_stop_on_failure_test() -> Ni [], [ extension.MigrationPlugin( - extension.DataMigration("sibling-data", fn(scope, backup) { - let ledger = storage.ledger(scope) - store.write( - ledger, - "INSERT INTO applied(name,backup) VALUES('sibling',?)", - [sqlight.text(backup)], - ) - |> result.replace(1) - }), + extension.DataMigration( + "sibling-data", + migration.Additive, + fn(scope, backup) { + let ledger = storage.ledger(scope) + store.write( + ledger, + "INSERT INTO applied(name,backup) VALUES('sibling',?)", + [sqlight.text(backup)], + ) + |> result.replace(1) + }, + ), ), ], extension.storage_initialise(fn(scope) { @@ -115,3 +125,71 @@ pub fn contributed_migrations_keep_their_phases_and_stop_on_failure_test() -> Ni rows |> should.equal([#("owner", "/backup"), #("sibling", "/backup")]) store.close(ledger) } + +/// A breaking migration commits its record before it writes, so a run that +/// fails half way still leaves the home refused by a build without it. An +/// additive one records nothing. +pub fn breaking_migrations_are_recorded_before_they_write_test() -> Nil { + let path = temporary_database() + let assert Ok(ledger) = store.start(path, "") + let installed = [ + extension.Extension( + "owner", + "", + [], + [ + extension.MigrationPlugin( + extension.SchemaMigration("owner-added", migration.Additive, fn(db) { + store.exec(db, "CREATE TABLE added(id INTEGER)") + }), + ), + extension.MigrationPlugin( + extension.SchemaMigration( + "owner-rewritten", + migration.Breaking, + fn(db) { store.exec(db, "CREATE TABLE rewritten(id INTEGER)") }, + ), + ), + extension.MigrationPlugin( + extension.DataMigration("owner-moved", migration.Breaking, fn(_, _) { + Error("interrupted") + }), + ), + ], + extension.storage_initialise(fn(_) { Ok(Nil) }), + tables: [], + uses: [], + ), + ] + let assert Ok(#(_, [])) = + extension.install( + installed, + [], + [], + extension.Startup( + mail.inbox(), + fn(_, _, _) { Nil }, + extension.unscoped(ledger), + ), + ) + let assert Error(_) = extension.migrate(installed, ledger, "/backup") + store.close(ledger) + migration.unknown(path, extension.migration_names(installed)) + |> should.equal(Ok([])) + migration.unknown(path, ["owner-added"]) + |> should.equal(Ok(["owner-moved", "owner-rewritten"])) + cleanup(path) +} + +/// Reading a new home's record creates no database there. +pub fn a_new_home_records_nothing_and_stays_unwritten_test() -> Nil { + let path = temporary_database() + migration.unknown(path, []) |> should.equal(Ok([])) + file.is_regular(path) |> should.be_false +} + +@external(erlang, "albedo_runtime_test_support", "temporary_database") +fn temporary_database() -> String + +@external(erlang, "albedo_runtime_test_support", "cleanup") +fn cleanup(path: String) -> Nil -- knotmirror 0.0.1