Skip to content

feat(selfupdate): rollback to snapshot from the update modal - #152

Merged
frahlg merged 1 commit into
masterfrom
152-rollback-to-snapshot
Apr 20, 2026
Merged

frahlg merged 1 commit into
masterfrom
152-rollback-to-snapshot

Conversation

@frahlg

@frahlg frahlg commented Apr 20, 2026

Copy link
Copy Markdown
Member

Second half of Erik @Xorath's ask — one-click rollback from the UI. Builds on #151 (list + delete). Phase 2 of #140.

Summary

  • New Roll back button on each snapshot row. Warning dialog explains the consequence, then POSTs `/api/version/rollback {snapshot_id}`.
  • Handler: validates the snapshot + its meta, captures a pre-rollback safety snapshot (so operator can roll forward if the restore is worse), calls `TriggerRollback` on the sidecar.
  • Sidecar: accepts `action: "rollback"` on the existing /update endpoint, stops main, `docker cp`s snapshot files into the container's bind mount, starts main again with --force-recreate.
  • UI reuses the existing "updating" overlay skin — new states `restoring` / `restarting` labelled specifically for the rollback action.

Scope: soft rollback only

Image version stays on the currently running tag. Forward-compat generally holds (SQLite is tolerant of added columns). Hard rollback (image-tag swap + state restore) is tracked as #140 Phase 3.

Safety invariants

  • Pre-rollback safety snapshot is always captured — no opt-out. Gives the operator a path forward again if the restored state turns out to be worse.
  • If `docker cp` fails mid-flow, the sidecar still runs `compose up -d` in a `defer`-ish path so the service never stays down.
  • Traversal guard on snapshot id uses the same helper as the delete handler — can't silently drift apart.

Why docker cp

The sidecar's project mount is read-only by design (`${PWD}:${PWD}:ro`). `docker cp` goes through the Docker daemon, which writes to the main container's bind-mounted data dir directly. No compose change required for existing deploys.

Test plan

  • Main API tests — safety snapshot before trigger, validation errors.
  • Sidecar tests — stop/cp/up ordering, missing snapshot, traversal rejection.
  • `make test` + `make e2e` green.
  • Smoke on Pi after the image rolls: open modal → Backup snapshots → Roll back → confirm → watch status banner → verify it lands on the restored state (SoC, config changes you made since).

Follow-ups

🤖 Generated with Claude Code

Second half of Erik @Xorath's request (2026-04-20): a one-click rollback
from the UI, no SSH required. #140 Phase 2.

## Flow

1. Operator clicks *Roll back* on a snapshot row in the update modal.
2. Warning dialog: restores state.db + config.yaml, service restarts,
   any data written since the snapshot is lost. Auto-creates a
   pre-rollback safety snapshot first.
3. Main POSTs /api/version/rollback {snapshot_id}.
4. Main validates the snapshot + meta.json, captures the safety
   snapshot (tagged action=pre-rollback so the UI can tell it apart
   from routine pre-update ones), calls TriggerRollback on the
   selfupdate.Checker.
5. Sidecar receives {action: "rollback", snapshot, files} over the
   Unix socket, runs:
     - compose stop forty-two-watts
     - docker cp <host_snap>/<file> forty-two-watts:/app/data/<file>
       for each listed file
     - compose up -d --force-recreate forty-two-watts
6. UI polls /api/version/update/status — new states "restoring" and
   "restarting" both labelled for the rollback action.

## Why docker cp (not a direct file copy)

Sidecar's project mount is read-only by design (:ro). \`docker cp\` goes
through the Docker daemon, which writes to the main container's
bind-mounted path directly. No compose change required for operators —
the existing v0.31+ docker-compose.yml works as-is.

## Scope — soft rollback only

Image version stays unchanged. Forward-compat holds for small jumps
(SQLite tolerant of extra columns), documented in the warning text.
Hard rollback (image-tag swap) is tracked as #140 Phase 3.

## Safety invariants

- Pre-rollback snapshot is **always** captured; no opt-out. Forward
  roll is the escape hatch if the restored state misbehaves.
- If docker cp fails mid-run, sidecar still calls compose up -d so the
  main container comes back — even with partial restore. Leaving the
  service down would strand the operator.
- Traversal-guard on snapshot id mirrors the delete handler; one
  shared helper (\`containsTraversal\`) so the two can't silently drift.

## Tests

- Main handler:
  - \`TestVersionRollback_CreatesSafetySnapshotBeforeTrigger\` — pre-
    rollback snapshot lands even when sidecar trigger fails.
  - \`TestVersionRollback_ValidatesSnapshotID\` — missing / traversal /
    nonexistent IDs get 400 or 404; never 500.
- Sidecar:
  - \`TestHandleUpdate_RollbackRestoresFiles\` — stop → cp × N → up
    ordering + arg shape.
  - \`TestHandleUpdate_RollbackMissingSnapshot\` — dir missing ⇒
    failed state, no stop attempted.
  - \`TestHandleUpdate_RollbackRejectsTraversal\` — bad snapshot ids
    return 400 before any goroutine.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@frahlg
frahlg merged commit cb3821c into master Apr 20, 2026
1 check passed
@frahlg
frahlg deleted the 152-rollback-to-snapshot branch April 20, 2026 09:12

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0fdcb979c7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

// state turns out to be wrong, this is the forward-rollback point.
info := s.deps.SelfUpdate.Info()
safetyID := ""
if safety, serr := s.createPreUpdateSnapshot("pre-rollback", info.Current, body.SnapshotID); serr != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve rollback target before pruning snapshots

Creating the mandatory pre-rollback safety snapshot here can prune the snapshot the operator just selected. createPreUpdateSnapshot calls pruneSnapshots(..., 5), so when retention is already full and the chosen target is the oldest entry, it gets deleted before TriggerRollback runs, and the sidecar then fails with “snapshot not readable”. This makes rollback fail in a common at-capacity scenario.

Useful? React with 👍 / 👎.

// service back anyway so the operator isn't stranded.
slog.Error("rollback docker cp failed", "file", f, "err", err)
s.writeState(State{State: "failed", Action: base.Action, Snapshot: base.Snapshot, StartedAt: now, UpdatedAt: time.Now(), Message: "docker cp " + f + " failed: " + err.Error()})
_ = s.runner(ctx, s.composeArgs("up", "-d", mainServiceName)...)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restart with a fresh context after rollback copy failure

The recovery compose up call reuses ctx, which is the same timeout-scoped context used for the rollback copy loop. If the copy step fails because that context is canceled/deadline-exceeded (e.g., large snapshot on slow storage), this restart attempt is canceled immediately too, leaving the main service stopped even though the code intends to always bring it back.

Useful? React with 👍 / 👎.

func (s *server) runRollback(snapshotID string, files []string) {
now := time.Now()
base := State{Action: "rollback", Snapshot: snapshotID, StartedAt: now}
s.writeState(State{State: "restoring", Action: base.Action, Snapshot: base.Snapshot, StartedAt: now, UpdatedAt: now, Message: "stopping main service"})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include restoring state in stale/crash recovery handling

Rollback introduces a new in-flight state (restoring), but the stale-state guards still only handle pulling/restarting (in both sidecar crash recovery and API status staleness checks). If the updater dies during this phase, status can remain stuck in restoring indefinitely instead of being promoted to failed, which blocks clear operator feedback for rollback failures.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant