From 8eed5b24708efa15658826336c3049d934e5cc00 Mon Sep 17 00:00:00 2001 From: Zhe Li Date: Sun, 12 Jul 2026 23:58:50 +0200 Subject: [PATCH 1/3] fix(localnet): restore requires a prior up; never create a volume out of band MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RunRestore loaded a pg_dumpall stream into _postgres via a throwaway `docker run -v :...`. When the target instance had never been `up`, that `docker run` CREATED the volume out of band, with no `com.docker.compose.*` labels. A later `up` adopts it (the "volume ... already exists but was not created by Docker Compose" warning), and `docker compose down --volumes` (used by `down` and `remove --force`) refuses to delete a volume Compose did not create — so the volume is stranded. This is the root cause behind the M1-RMV-001 e2e failure ("FAIL step 3b: volumes remain after remove"). Require the target instance to already be registered (it was `up`, so Compose owns the volume) before restoring; refuse otherwise and tell the user to run `localnet up ` first. Applies to cross-name restore too. This keeps the "never create a volume outside Compose" invariant. The precondition is enforced via the registry (a proxy for "the Compose-owned volume exists"). A stricter Docker volume-ownership label check is deferred and documented in docs/limitations.md. Tests: seed a stopped instance in the round-trip, cross-name, and content-SHA restore tests; add TestRestore_RefusesUnknownInstance. --- docs/limitations.md | 37 +++++++++++++ internal/localnet/snapshot/snapshot.go | 57 +++++++++++++-------- internal/localnet/snapshot/snapshot_test.go | 30 +++++++++-- 3 files changed, 99 insertions(+), 25 deletions(-) diff --git a/docs/limitations.md b/docs/limitations.md index 146c7d8f..5fae67a0 100644 --- a/docs/limitations.md +++ b/docs/limitations.md @@ -95,6 +95,43 @@ resolved. snapshot in its error so the stuck service + state are visible without re-running anything. +## Snapshot restore + +- **`restore` requires the target instance to already exist (was `up` + at least once).** A restore loads a `pg_dumpall` stream into the + instance's EXISTING Postgres volume via a throwaway loader container. + That volume is only a Docker-Compose-owned volume after an `up` + created it. Restoring into a never-`up` instance would force the + loader's `docker run -v :...` to CREATE the volume out of band — + producing a volume Compose does not own. `docker compose down + --volumes` (used by `localnet down` and `localnet remove --force`) + only removes volumes Compose itself created, so such an orphan volume + survives teardown and is silently adopted (with a "volume … already + exists but was not created by Docker Compose" warning) on the next + `up`. To keep the "never create a volume outside Compose" invariant, + restore now refuses when the instance is not registered and tells the + user to run `localnet up ` first. This also applies to + cross-name restore: the target name must have been `up` too. + *Workaround:* run `localnet up ` (or `up ` for a + cross-name restore) before `localnet restore`. + +- **The restore precondition is enforced via the registry, not a Docker + volume-ownership check (known gap).** The guard checks that a registry + record exists for the target instance, which is a PROXY for "the + Compose-owned volume exists". `up` writes `state.json` early (at + "creating" time, before the volume is guaranteed to exist), so a + crashed/half-finished `up` can leave a registry entry with no volume — + in which case restore would still proceed and the loader would + re-create the volume out of band, reintroducing the orphan. The + robust check is to verify the volume carries Compose's ownership + labels (`com.docker.compose.project=canton-` and + `com.docker.compose.volume=postgres`) via a label-filtered + `docker volume ls` — a bare `docker volume inspect ` is NOT + sufficient because a detached `docker run -v` volume exists under the + same name yet lacks those labels. That label-based volume-ownership + check is intentionally deferred for now; the registry gate covers the + common case. Tracked as a follow-up. + ## Platform parity - **Homebrew formula targets macOS arm64 and Linux x86_64 only.** diff --git a/internal/localnet/snapshot/snapshot.go b/internal/localnet/snapshot/snapshot.go index 6fb3c354..f5385658 100644 --- a/internal/localnet/snapshot/snapshot.go +++ b/internal/localnet/snapshot/snapshot.go @@ -456,27 +456,40 @@ func RunRestore(ctx context.Context, out io.Writer, errw io.Writer, name, src st fmt.Sprintf("schema %d · %d database(s) · captured %s", meta.SchemaVersion, meta.Database.DatabaseCount, meta.CreatedAt), "")) - // Distinguish ErrNotFound (legitimate "no existing instance") from - // every other error so a permission/parse failure can't be mistaken - // for "fresh restore". + // The instance must already be registered — restore loads a dump into + // the instance's EXISTING Postgres volume, and that volume only exists + // (as a Docker-Compose-owned volume) after at least one `up`. Restoring + // into a never-`up` instance would force the loader to create the volume + // out of band (`docker run -v :...`), producing a volume Compose + // does not own — which `down --volumes` / `remove --force` then refuse + // to reclaim, stranding it. So require a prior `up` and never create a + // volume here. (Includes cross-name restore: the target name must have + // been `up` too.) See docs/limitations.md "Restore requires a prior up". + // + // Distinguish ErrNotFound from every other error so a permission/parse + // failure can't be mistaken for "not registered". existing, rerr := registry.Read(name) if rerr != nil && !errors.Is(rerr, registry.ErrNotFound) { _, _ = fmt.Fprintf(errw, "read existing registry state for %q: %s\n", name, rerr) return localnet.ExitRuntimeFailure } - if existing != nil { - if existing.Status == registry.StatusRunning { - _, _ = fmt.Fprintf(errw, - "instance %q is running — run `localnet down %s` first\n", name, name) - return localnet.ExitUserError - } - if existing.SpliceVersion != meta.SpliceVersion && !force { - _, _ = fmt.Fprintf(errw, - "Splice version mismatch: existing instance is %s, snapshot is %s. "+ - "Pass --force to override.\n", - existing.SpliceVersion, meta.SpliceVersion) - return localnet.ExitUserError - } + if existing == nil { + _, _ = fmt.Fprintf(errw, + "instance %q not found — restore loads into an existing instance's "+ + "data volume. Run `localnet up %s` first, then restore.\n", name, name) + return localnet.ExitUserError + } + if existing.Status == registry.StatusRunning { + _, _ = fmt.Fprintf(errw, + "instance %q is running — run `localnet down %s` first\n", name, name) + return localnet.ExitUserError + } + if existing.SpliceVersion != meta.SpliceVersion && !force { + _, _ = fmt.Fprintf(errw, + "Splice version mismatch: existing instance is %s, snapshot is %s. "+ + "Pass --force to override.\n", + existing.SpliceVersion, meta.SpliceVersion) + return localnet.ExitUserError } // Build the registry record we'll commit only after a successful @@ -784,11 +797,13 @@ func (dockerPgArchiver) RestoreInto(ctx context.Context, image, volume, user str // Clear any leftover from a previous interrupted restore. _ = exec.CommandContext(ctx, "docker", "rm", "-f", tmpName).Run() - // Throwaway Postgres on the target volume. HOST_AUTH_METHOD=trust - // makes the (only) case where the volume is empty — restore into a - // never-started instance — initialise without a password and accept - // the local psql connection; for an already-initialised volume the - // env is ignored. + // Throwaway Postgres on the target volume. RunRestore guarantees the + // volume already exists (Compose created it on a prior `up`), so this + // never brings a volume into being out of band. HOST_AUTH_METHOD=trust + // is kept as a belt-and-braces: if the volume's data dir is somehow + // uninitialised, Postgres initialises without a password and accepts + // the local psql connection; for an already-initialised volume (the + // normal case) the env is ignored. if err := exec.CommandContext(ctx, "docker", "run", "-d", "--name", tmpName, "-v", volume+":"+pgDataDir, "-e", "POSTGRES_USER="+user, diff --git a/internal/localnet/snapshot/snapshot_test.go b/internal/localnet/snapshot/snapshot_test.go index 124442ec..cd3db560 100644 --- a/internal/localnet/snapshot/snapshot_test.go +++ b/internal/localnet/snapshot/snapshot_test.go @@ -148,11 +148,11 @@ func TestSnapshot_RoundTrip(t *testing.T) { t.Errorf("snapshot must quiesce+resume writers: quiesced=%v resumed=%v", faSnap.Quiesced, faSnap.Resumed) } - // Restore into a FRESH registry root with no prior `demo`. + // Restore into a FRESH registry root. Restore requires the target + // instance to already exist (it was `up`, so its Compose volume + // exists) — so seed a STOPPED `demo` before restoring. t.Setenv("CANTON_DEVKIT_REGISTRY", t.TempDir()) - if _, err := registry.Read("demo"); !errors.Is(err, registry.ErrNotFound) { - t.Fatalf("setup: registry should be empty, got %v", err) - } + seedInstance(t, "demo", "0.6.4", registry.StatusStopped) fa2 := &FakeArchiver{} installFake(t, fa2) out.Reset() @@ -283,6 +283,22 @@ func TestRestore_RefusesRunningInstance(t *testing.T) { } } +func TestRestore_RefusesUnknownInstance(t *testing.T) { + t.Setenv("CANTON_DEVKIT_REGISTRY", t.TempDir()) // empty registry — no instance + installFake(t, &FakeArchiver{}) + dst := filepath.Join(t.TempDir(), "a.tgz") + dump := []byte("dump") + writeArchive(t, dst, validHeader("ghost", "0.6.4", dump), stateFor(t, "ghost", "0.6.4"), dump) + + var out, errBuf bytes.Buffer + if code := RunRestore(context.Background(), &out, &errBuf, "ghost", dst, false); code != localnet.ExitUserError { + t.Fatalf("code=%d want ExitUserError (instance never up)", code) + } + if !strings.Contains(errBuf.String(), "not found") || !strings.Contains(errBuf.String(), "localnet up") { + t.Errorf("expected 'not found / run localnet up first', stderr=%q", errBuf.String()) + } +} + func TestRestore_RefusesSpliceVersionMismatch(t *testing.T) { t.Setenv("CANTON_DEVKIT_REGISTRY", t.TempDir()) seedInstance(t, "demo", "0.6.3", registry.StatusStopped) // existing is 0.6.3 @@ -322,6 +338,7 @@ func TestRestore_RefusesIfContainersRunning(t *testing.T) { func TestRestore_VerifiesContentSHA(t *testing.T) { t.Setenv("CANTON_DEVKIT_REGISTRY", t.TempDir()) + seedInstance(t, "demo", "0.6.4", registry.StatusStopped) installFake(t, &FakeArchiver{}) dst := filepath.Join(t.TempDir(), "tamper.tgz") dump := []byte("the real dump bytes") @@ -350,7 +367,12 @@ func TestRestore_CrossNameRewritesProject(t *testing.T) { t.Fatalf("snapshot code=%d stderr=%q", code, errBuf.String()) } + // Cross-name restore still requires the TARGET name to already exist + // (it was `up`, so `canton-clone_postgres` exists). Seed a stopped + // `clone`; the embedded snapshot name stays `demo`, so the rename + // warning still fires below. t.Setenv("CANTON_DEVKIT_REGISTRY", t.TempDir()) + seedInstance(t, "clone", "0.6.4", registry.StatusStopped) fa2 := &FakeArchiver{} installFake(t, fa2) out.Reset() From e378abf9b87d827bd77e828fcc28fd1600c702fe Mon Sep 17 00:00:00 2001 From: Zhe Li Date: Mon, 13 Jul 2026 00:15:29 +0200 Subject: [PATCH 2/3] test(e2e): M1-SNP-001 uses `down` (not `remove`) before restore MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Restore now loads into the instance's EXISTING Compose-owned Postgres volume and refuses to create one out of band. The snapshot/restore test tore the instance down with `remove` (which reclaims the volume), then restored — which the new contract correctly rejects with "instance not found — run localnet up first". Switch the teardown to `down`, which preserves the volume, so restore has a Compose-owned volume to load into. --- scripts/e2e/m1-snp-001.sh | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/scripts/e2e/m1-snp-001.sh b/scripts/e2e/m1-snp-001.sh index e5720429..27666f13 100755 --- a/scripts/e2e/m1-snp-001.sh +++ b/scripts/e2e/m1-snp-001.sh @@ -19,7 +19,12 @@ run_test() { [ -f "$SNAPSHOT_PATH" ] && [ -s "$SNAPSHOT_PATH" ] \ || { echo "FAIL step 1: snapshot file missing or empty" >&2; return 1; } - e2e_cleanup_instance e2e-test-default + # Tear down with `down` (NOT `remove`): restore loads a dump into the + # instance's EXISTING Compose-owned Postgres volume, so the volume must + # survive. `remove` reclaims volumes and would leave restore with nothing + # to load into (restore refuses to create a volume out of band). + cli down e2e-test-default \ + || { echo "FAIL step 2: down before restore failed" >&2; return 1; } cli restore e2e-test-default --from "$SNAPSHOT_PATH" \ || { echo "FAIL step 3: restore command failed" >&2; return 1; } From f81a73d8c28450e1949ce083b3de4272afa09bab Mon Sep 17 00:00:00 2001 From: Zhe Li Date: Mon, 13 Jul 2026 08:54:54 +0200 Subject: [PATCH 3/3] test(e2e): M1-UP-003 precleans e2e-version-test before up The test brings up a fresh `e2e-version-test` but had no precondition cleanup, so a leftover instance from a prior/aborted run caused step 1 to abort with "instance already running". Add a best-effort `e2e_cleanup_instance` before `up`, matching the self-defending pattern used by other lifecycle tests. Cleanup lives in the test's precondition (not teardown) because M1-LST-001 depends on e2e-version-test staying up. --- scripts/e2e/m1-up-003.sh | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/scripts/e2e/m1-up-003.sh b/scripts/e2e/m1-up-003.sh index 86e2a27b..a62ffa93 100755 --- a/scripts/e2e/m1-up-003.sh +++ b/scripts/e2e/m1-up-003.sh @@ -11,6 +11,11 @@ e2e_require_docker TEST_ID="M1-UP-003" run_test() { + # Precondition: this test brings up a fresh e2e-version-test. Clear any + # instance left running by a prior/aborted run so `up` does not abort with + # "instance already running". Best-effort; failures here are non-fatal. + e2e_cleanup_instance e2e-version-test + echo " Starting e2e-version-test with --version $SPLICE_VERSION (may take 3-5 minutes)..." timed 600 "$CDK" localnet up e2e-version-test --version "$SPLICE_VERSION" \ || { echo "FAIL step 1: up --version exited $?" >&2; return 1; }