Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions docs/limitations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <vol>:...` 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 <name>` first. This also applies to
cross-name restore: the target name must have been `up` too.
*Workaround:* run `localnet up <name>` (or `up <newname>` 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-<name>` and
`com.docker.compose.volume=postgres`) via a label-filtered
`docker volume ls` — a bare `docker volume inspect <name>` 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.**
Expand Down
57 changes: 36 additions & 21 deletions internal/localnet/snapshot/snapshot.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 <vol>:...`), 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
Expand Down Expand Up @@ -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,
Expand Down
30 changes: 26 additions & 4 deletions internal/localnet/snapshot/snapshot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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()
Expand Down
7 changes: 6 additions & 1 deletion scripts/e2e/m1-snp-001.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down
5 changes: 5 additions & 0 deletions scripts/e2e/m1-up-003.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down
Loading