From 1bf95f45c04cd82903340cde8bd1a76ac788298b Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 12 Sep 2026 02:59:23 +0000 Subject: [PATCH 1/3] fix(update): resolve releases without a checkout, and fail loudly when it cannot The check adapter resolved available releases with `git -C "$REPO" ls-remote`, where REPO defaulted to $HOME/projects/archie-core. With that checkout absent, moved or renamed, the swallowed error left Available empty for every component -- which FormatSnapshot renders as "Archie is up to date." A failed lookup therefore read as parity: the exact inverse of what an operator needs to know. Resolve releases from the forge API and `git ls-remote` against the remote directly, with no working-tree state and no dependence on a clone existing. When neither source answers, exit non-zero so the /update command reports that it could not check instead of fabricating an up-to-date result. A tagged release is announced whether or not it has a published artifact, and Reference now records which source answered and the artifact state, so an operator is not sent to a tag with nothing to download without being told. This is what hid archied/v1.24.0 from the live host: tagged, never published. The failure tests run the real script through a fake git and curl, so they assert the source-selection logic rather than a stub. Against the previous script all four fail, including the checkout dependency itself. --- internal/releaseupdate/check_script_test.go | 223 ++++++++++++++++++++ scripts/archie-update-check | 163 +++++++++++--- 2 files changed, 353 insertions(+), 33 deletions(-) create mode 100644 internal/releaseupdate/check_script_test.go diff --git a/internal/releaseupdate/check_script_test.go b/internal/releaseupdate/check_script_test.go new file mode 100644 index 000000000..0e3722be3 --- /dev/null +++ b/internal/releaseupdate/check_script_test.go @@ -0,0 +1,223 @@ +package releaseupdate + +import ( + "encoding/json" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// checkRun configures one end-to-end run of archie-update-check. The fake git +// and curl placed on PATH are what make the test exercise the script's real +// source-selection logic rather than the network. +type checkRun struct { + // git is the fake `git` body. Empty leaves git off PATH entirely, which + // is how the API-only path is reached. + git string + // curl is the fake `curl` body. Empty means curl always fails, so the + // git-tag path is reached. + curl string + // binVersion is what the fake archied reports for -version. + binVersion string +} + +func runUpdateCheckScript(t *testing.T, run checkRun) (Snapshot, []string, string, error) { + t.Helper() + root, err := filepath.Abs(filepath.Join("..", "..")) + if err != nil { + t.Fatal(err) + } + work := t.TempDir() + binDir := filepath.Join(work, "bin") + fakeDir := filepath.Join(work, "fake-bin") + callsPath := filepath.Join(work, "calls") + if err := os.MkdirAll(binDir, 0o755); err != nil { + t.Fatal(err) + } + version := run.binVersion + if version == "" { + version = "1.22.0" + } + writeFakeCommand(t, binDir, "archied", `printf 'archied %s\narchie-agent %s\n' "`+version+`" "1.19.9"`) + if run.git != "" { + writeFakeCommand(t, fakeDir, "git", run.git) + } + if run.curl != "" { + writeFakeCommand(t, fakeDir, "curl", run.curl) + } + + cmd := exec.CommandContext(t.Context(), filepath.Join(root, "scripts", "archie-update-check")) + cmd.Env = append( + os.Environ(), + "PATH="+fakeDir+":"+binDir+":"+os.Getenv("PATH"), + "ARCHIE_BIN="+filepath.Join(binDir, "archied"), + "ARCHIE_TEST_CALLS="+callsPath, + // A remote that cannot be reached in this environment: anything the + // script resolves came from a fake, never from the real network. + "ARCHIE_SOURCE_URL=https://example.invalid/archie-core.git", + "ARCHIE_FORGE_API=https://api.example.invalid", + "ARCHIE_FORGE_TIMEOUT=5", + ) + output, err := cmd.Output() + var stderr string + if exitErr, ok := err.(*exec.ExitError); ok { + stderr = string(exitErr.Stderr) + } + var calls []string + if data, readErr := os.ReadFile(callsPath); readErr == nil && len(data) > 0 { + calls = strings.Split(strings.TrimSpace(string(data)), "\n") + } + if err != nil { + return Snapshot{}, calls, stderr, err + } + var snapshot Snapshot + if err := json.Unmarshal(output, &snapshot); err != nil { + t.Fatalf("decode check output %q: %v", output, err) + } + return snapshot, calls, stderr, nil +} + +// The update check must not depend on a local checkout existing. It used to +// resolve tags with `git -C "$REPO" ls-remote`, so a host with no clone -- +// or a clone under a different name -- silently reported no available +// releases, which the /update command then rendered as "Archie is up to +// date." This is the failure test for that: it must resolve from the remote +// alone, and must not shell into any working tree. +func TestUpdateCheckNeedsNoLocalCheckout(t *testing.T) { + snapshot, calls, _, err := runUpdateCheckScript(t, checkRun{ + git: ` +printf '%s\n' "git $*" >> "$ARCHIE_TEST_CALLS" +case "$*" in + *archied/v*) printf '%s\n' refs/tags/archied/v1.22.0 refs/tags/archied/v1.23.0 ;; + *archie/v*) printf '%s\n' refs/tags/archie/v1.21.0 ;; +esac +`, + }) + if err != nil { + t.Fatalf("check failed: %v", err) + } + for _, fragment := range []string{"ls-remote", "example.invalid/archie-core.git"} { + assertCallContains(t, calls, fragment) + } + // -C is how the old script targeted a checkout. Any use of it means the + // checkout dependency came back. + assertCallAbsent(t, calls, "git -C") + assertCallAbsent(t, calls, "clone") + + if got, want := componentAvailable(snapshot, ComponentDaemon), "1.23.0"; got != want { + t.Errorf("daemon available = %q, want %q", got, want) + } + if got, want := componentAvailable(snapshot, ComponentAgent), "1.21.0"; got != want { + t.Errorf("agent available = %q, want %q", got, want) + } +} + +// A source that cannot be reached is a failure to check, not an absence. The +// old script exited 0 with an empty Available for every component, which is +// indistinguishable from "up to date" -- so an unreachable remote, a deleted +// checkout, or a renamed repo all read as parity. It must instead refuse. +func TestUpdateCheckFailsRatherThanReportingParity(t *testing.T) { + _, _, stderr, err := runUpdateCheckScript(t, checkRun{ + git: `printf '%s\n' "git $*" >> "$ARCHIE_TEST_CALLS"; exit 128`, + }) + if err == nil { + t.Fatal("check succeeded with every source unreachable; an empty result reads as \"up to date\"") + } + for _, fragment := range []string{"example.invalid/archie-core.git", "api.example.invalid"} { + if !strings.Contains(stderr, fragment) { + t.Errorf("failure must name the source it could not read (%s); stderr = %q", fragment, stderr) + } + } +} + +// With git unavailable, the forge API is the fallback source. It has to +// resolve the same release the git path would, or a host without git can +// never be told an update exists. +func TestUpdateCheckFallsBackToForgeAPITags(t *testing.T) { + snapshot, _, _, err := runUpdateCheckScript(t, checkRun{ + curl: ` +printf '%s\n' "curl $*" >> "$ARCHIE_TEST_CALLS" +case "$*" in + *"/tags"*) + printf '%s\n' '[{"name":"archied/v1.22.0"},{"name":"archied/v1.24.0"},{"name":"archie/v1.23.0"}]' + ;; + *) exit 22 ;; +esac +`, + }) + if err != nil { + t.Fatalf("check failed: %v", err) + } + if got, want := componentAvailable(snapshot, ComponentDaemon), "1.24.0"; got != want { + t.Errorf("daemon available = %q, want %q", got, want) + } + if got, want := componentAvailable(snapshot, ComponentAgent), "1.23.0"; got != want { + t.Errorf("agent available = %q, want %q", got, want) + } + if ref := componentReference(snapshot, ComponentDaemon); !strings.Contains(ref, "forge-api-tags") { + t.Errorf("daemon reference = %q, want the API source recorded", ref) + } +} + +// A tagged release is announced whether or not it has a published artifact, +// and the Reference says which, so an operator is never sent to a tag with +// nothing to download without being told. +func TestUpdateCheckReportsArtifactState(t *testing.T) { + tests := []struct { + name string + release string + wantState string + }{ + {name: "published with assets", release: `{"assets":[{"name":"zip"},{"name":"SHA256SUMS"}]}`, wantState: "2-assets"}, + {name: "tagged but never published", release: `{"assets":[]}`, wantState: "no-artifact"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + snapshot, _, _, err := runUpdateCheckScript(t, checkRun{ + git: ` +printf '%s\n' "git $*" >> "$ARCHIE_TEST_CALLS" +case "$*" in + *archied/v*) printf '%s\n' refs/tags/archied/v1.24.0 ;; + *archie/v*) printf '%s\n' refs/tags/archie/v1.23.0 ;; +esac +`, + curl: ` +printf '%s\n' "curl $*" >> "$ARCHIE_TEST_CALLS" +case "$*" in + *"/releases/tags/"*) printf '%s\n' '` + tt.release + `' ;; + *) exit 22 ;; +esac +`, + }) + if err != nil { + t.Fatalf("check failed: %v", err) + } + for _, id := range []string{ComponentDaemon, ComponentAgent} { + ref := componentReference(snapshot, id) + if !strings.Contains(ref, tt.wantState) { + t.Errorf("%s reference = %q, want artifact state %q", id, ref, tt.wantState) + } + } + }) + } +} + +func componentAvailable(snapshot Snapshot, id string) string { + for _, component := range snapshot.Components { + if component.ID == id { + return component.Available + } + } + return "" +} + +func componentReference(snapshot Snapshot, id string) string { + for _, component := range snapshot.Components { + if component.ID == id { + return component.Reference + } + } + return "" +} diff --git a/scripts/archie-update-check b/scripts/archie-update-check index 0fd3918c5..f4a828f1e 100755 --- a/scripts/archie-update-check +++ b/scripts/archie-update-check @@ -5,53 +5,148 @@ # via CommandCatalog (internal/releaseupdate/command.go), which never invokes # a shell, so this file must be directly executable. # -# "Installed" is the release the running binary was ACTUALLY built from, -# read via `archied -version` rather than trusted from git or filesystem -# state -- if a prior build/install step silently failed partway, the -# checkout can disagree with what's really running, and -version is the one -# source that cannot be wrong about that. The build stamp carries a -# git-describe suffix when HEAD has moved past the tag (1.7.0-4-g0736708); -# that suffix is stripped for the comparison, because unreleased commits are -# not an available update and would otherwise report one forever. +# "Installed" is the release the running binary was ACTUALLY built from, read +# via `archied -version` rather than trusted from git or filesystem state -- +# if a prior build/install step silently failed partway, the checkout can +# disagree with what's really running, and -version is the one source that +# cannot be wrong about that. The build stamp carries a git-describe suffix +# when HEAD has moved past the tag (1.7.0-4-g0736708); that suffix is +# stripped for the comparison, because unreleased commits are not an +# available update and would otherwise report one forever. # -# "Available" is the newest release tag on the origin remote, via -# ls-remote -- no local fetch or working-tree state required, so this -# script has no side effects and no dependency on the checkout being -# buildable. +# "Available" is the newest release TAG, resolved without any dependency on a +# local checkout. Two independent sources, in order: # -# Component IDs are "daemon" and "agent" -- the same convention -# releaseupdate.ComponentDaemon/ComponentAgent, archie-update-watchdog's -# report, and Service.Enrich (installtype.Type(), an observed archie-agent -# version) all expect. A check command using different IDs still works for -# the raw Installed/Available display, just without that enrichment or -# Report.Verify recognising it after an install. -set -euo pipefail +# 1. the forge API (tags + releases), which also reports whether the tag has +# a PUBLISHED artifact -- the thing an artifact install path downloads; +# 2. `git ls-remote` against the source remote, which needs no API and no +# working tree. +# +# The tag is the authority for "an update exists"; the artifact is reported +# separately in Reference, so a tagged-but-unpublished release is still +# announced (it is installable via the source-build fallback) instead of being +# silently hidden. +# +# A tag source that fails to resolve is a FAILURE TO CHECK, not an absence. +# An empty Available means "this component is at the newest release we could +# resolve", so it must never be the result of a probe that failed. When no +# authoritative source answers at all, this script exits non-zero and the +# /update command says it could not check -- rather than rendering a failed +# lookup as "Archie is up to date". +set -uo pipefail -REPO="${ARCHIE_REPO_DIR:-$HOME/projects/archie-core}" -BIN="${ARCHIE_BIN:-$HOME/.local/bin/archied}" +readonly REPO_SLUG="${ARCHIE_SOURCE_SLUG:-samcharles93/archie-core}" +readonly API_BASE="${ARCHIE_FORGE_API:-https://api.github.com}" +readonly SOURCE_URL="${ARCHIE_SOURCE_URL:-https://github.com/${REPO_SLUG}.git}" +readonly BIN="${ARCHIE_BIN:-$HOME/.local/bin/archied}" +readonly CURL_TIMEOUT="${ARCHIE_FORGE_TIMEOUT:-20}" +readonly TOKEN="${ARCHIE_FORGE_TOKEN:-}" # base 1.7.0-4-g0736708 -> 1.7.0 base() { printf '%s\n' "${1%%-*}"; } +# installed_for reads the version this binary reports for a named component. +# archied stamps both its own version and the runtime version the release was +# cut with, and -version prints one line per component -- so the installed +# runtime is what THIS RELEASE says it was built against, not a stray binary +# on the host. releaseupdate/service.go documents why a host-side archie-agent +# binary cannot answer this: every archie-agent process is task-scoped and +# ephemeral, observed only through a completed taskrun.Response. installed_for() { "$BIN" -version 2>/dev/null | awk -v n="$1" '$1 == n { print $2; exit }' } -latest_tag() { - git -C "$REPO" ls-remote --tags --refs origin "$1/v*" 2>/dev/null | - sed 's|.*refs/tags/||' | sed "s|^$1/v||" | - sort -V | tail -1 +curl_api() { + if [ -n "$TOKEN" ]; then + curl -fsS --max-time "$CURL_TIMEOUT" \ + -H "Authorization: Bearer $TOKEN" \ + -H "Accept: application/vnd.github+json" \ + "$1" 2>/dev/null + else + curl -fsS --max-time "$CURL_TIMEOUT" \ + -H "Accept: application/vnd.github+json" \ + "$1" 2>/dev/null + fi } +# newest_tag_git resolves the newest tag for a component prefix from the git +# remote. No local checkout, no working-tree state, no fetch -- `ls-remote` +# queries the remote directly, so this works on a host that has never cloned +# anything. +newest_tag_git() { + local component="$1" tags + command -v git >/dev/null 2>&1 || return 1 + tags="$(git ls-remote --tags --refs "$SOURCE_URL" "$component/v*" 2>/dev/null)" || return 1 + [ -n "$tags" ] || return 1 + printf '%s\n' "$tags" | sed 's|.*refs/tags/||' | sed "s|^$component/v||" | sort -V | tail -1 +} + +# newest_tag_api is the API equivalent, used when git is unavailable. +newest_tag_api() { + local component="$1" page payload found total + for page in 1 2 3; do + payload="$(curl_api "${API_BASE}/repos/${REPO_SLUG}/tags?per_page=100&page=${page}")" || return 1 + [ -n "$payload" ] || return 1 + found="$(printf '%s\n' "$payload" \ + | grep -o "\"name\":[[:space:]]*\"${component}/v[^\"]*\"" \ + | sed 's|.*"'"${component}"'/v||; s|"$||' | sort -V | tail -1)" + if [ -n "$found" ]; then + printf '%s\n' "$found" + return 0 + fi + total="$(printf '%s\n' "$payload" | grep -c '"name"')" + [ "${total:-0}" -lt 100 ] && break + done + return 1 +} + +# artifact_state reports whether a tagged release is PUBLISHED with assets, +# which decides whether an artifact install can use it or the source-build +# fallback has to. Purely descriptive: a failure here never fabricates a +# state, it reports "unknown-artifact". +artifact_state() { + local tag="$1" payload count + command -v jq >/dev/null 2>&1 || { printf 'unknown-artifact'; return 0; } + payload="$(curl_api "${API_BASE}/repos/${REPO_SLUG}/releases/tags/${tag}")" || { printf 'no-release'; return 0; } + [ -n "$payload" ] || { printf 'no-release'; return 0; } + count="$(printf '%s\n' "$payload" | jq -r '[.assets[] | select(.name != "")] | length' 2>/dev/null)" + case "${count:-}" in + '' | *[!0-9]*) printf 'unknown-artifact' ;; + 0) printf 'no-artifact' ;; + *) printf '%s-assets' "$count" ;; + esac +} + +esc() { printf '%s' "${1:-}" | sed 's/\\/\\\\/g; s/"/\\"/g'; } + daemon_installed="$(base "$(installed_for archied || true)")" agent_installed="$(base "$(installed_for archie-agent || true)")" -daemon_available="$(latest_tag archied || true)" -agent_available="$(latest_tag archie || true)" -# An unreachable remote must not look like "up to date": leaving Available -# empty makes Snapshot.Available() skip the component rather than claim -# parity it never verified. -esc() { printf '%s' "${1:-}" | sed 's/\\/\\\\/g; s/"/\\"/g'; } +daemon_available="$(newest_tag_git archied || true)" +agent_available="$(newest_tag_git archie || true)" +tag_source="git-tags" +if [ -z "$daemon_available" ] && [ -z "$agent_available" ]; then + daemon_available="$(newest_tag_api archied || true)" + agent_available="$(newest_tag_api archie || true)" + tag_source="forge-api-tags" +fi +if [ -z "$daemon_available" ] && [ -z "$agent_available" ]; then + # Neither source answered. Report the failure; do not exit 0 with two empty + # components, which the caller renders as "up to date". + echo "archie-update-check: could not resolve any release tag from ${SOURCE_URL} or ${API_BASE}/repos/${REPO_SLUG}/tags" >&2 + exit 1 +fi + +daemon_artifacts="" +[ -n "$daemon_available" ] && daemon_artifacts="$(artifact_state "archied/v${daemon_available}")" +agent_artifacts="" +[ -n "$agent_available" ] && agent_artifacts="$(artifact_state "archie/v${agent_available}")" + +reference_for() { + local component="$1" version="$2" artifacts="$3" + [ -z "$version" ] && { printf ''; return 0; } + printf '%s artifact=%s (%s)' "$tag_source" "$artifacts" "$component" +} cat < Date: Sat, 12 Sep 2026 02:59:52 +0000 Subject: [PATCH 2/3] test(update): use errors.As in the check adapter harness --- internal/releaseupdate/check_script_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/internal/releaseupdate/check_script_test.go b/internal/releaseupdate/check_script_test.go index 0e3722be3..a2367195c 100644 --- a/internal/releaseupdate/check_script_test.go +++ b/internal/releaseupdate/check_script_test.go @@ -2,6 +2,7 @@ package releaseupdate import ( "encoding/json" + "errors" "os" "os/exec" "path/filepath" @@ -62,7 +63,8 @@ func runUpdateCheckScript(t *testing.T, run checkRun) (Snapshot, []string, strin ) output, err := cmd.Output() var stderr string - if exitErr, ok := err.(*exec.ExitError); ok { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { stderr = string(exitErr.Stderr) } var calls []string From dad9389530fb1bc3cc7ece4e6e2aec067092ce03 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 12 Sep 2026 03:01:58 +0000 Subject: [PATCH 3/3] fix(update): back up the task store the daemon actually uses, or refuse configured_task_db_path() read the top-level db_path and handed that literal file to the watchdog as ARCHIE_TASK_DB_PATH (scripts/archie-update-install). The daemon's task store is not that file: taskDBPath() in internal/app/archied/main.go derives `-tasks.sqlite`, and the configured path is commonly a zero-byte placeholder beside it. The updater therefore backed up an empty file, and a rollback would have restored that empty file over the real database and deleted its -wal/-shm -- destroying the task store the backup exists to protect. That awk also matched db_path in any section. [indexing] owns its own database, so a config listing it before the top-level key handed the watchdog an unrelated database as ARCHIE_TASK_DB_PATH and backed that up instead. Resolve the top-level key only, append the sibling suffix the daemon uses, and refuse the update when the backup cannot be taken. The backup is the only route back from a forward schema migration, so an update that cannot take one must not start; it now runs as pre-flight, ahead of the adapter refresh, so a refusal changes nothing on the host. The tests drive the real script with a config file the harness controls; all three fail against the previous adapter. --- internal/releaseupdate/install_script_test.go | 119 +++++++++++++++++- scripts/archie-update-install | 41 ++++-- 2 files changed, 150 insertions(+), 10 deletions(-) diff --git a/internal/releaseupdate/install_script_test.go b/internal/releaseupdate/install_script_test.go index 03e8bb24f..6c52450f1 100644 --- a/internal/releaseupdate/install_script_test.go +++ b/internal/releaseupdate/install_script_test.go @@ -282,6 +282,15 @@ func runUpdateInstallScript(t *testing.T, environment map[string]string) (Result // returns the parsed result (empty when the run was expected to fail), the // recorded calls, and the combined output. func runUpdateInstall(t *testing.T, environment map[string]string, wantErr bool) (Result, []string, string) { + t.Helper() + return runUpdateInstallWithConfig(t, environment, "[containers]\nimage = 'registry.example/archie-agent:stable'\n", wantErr) +} + +// runUpdateInstallWithConfig is runUpdateInstall with the operator's config +// file under the caller's control. Config-derived behaviour -- which database +// the updater backs up, which image it rebuilds -- is otherwise untestable, +// which is how the task-database backup path came to be wrong. +func runUpdateInstallWithConfig(t *testing.T, environment map[string]string, configBody string, wantErr bool) (Result, []string, string) { t.Helper() ctx := t.Context() @@ -297,7 +306,7 @@ func runUpdateInstall(t *testing.T, environment map[string]string, wantErr bool) if err := os.MkdirAll(binDir, 0o755); err != nil { t.Fatal(err) } - if err := os.WriteFile(configPath, []byte("[containers]\nimage = 'registry.example/archie-agent:stable'\n"), 0o600); err != nil { + if err := os.WriteFile(configPath, []byte(configBody), 0o600); err != nil { t.Fatal(err) } for _, name := range []string{"archied", "archie-agent"} { @@ -359,6 +368,21 @@ printf '%s\n' "install $*" >> "$ARCHIE_TEST_CALLS" writeFakeCommand(t, fakeDir, "cp", ` printf '%s\n' "cp $*" >> "$ARCHIE_TEST_CALLS" /usr/bin/cp "$@" +`) + writeFakeCommand(t, fakeDir, "sqlite3", ` +printf '%s\n' "sqlite3 $*" >> "$ARCHIE_TEST_CALLS" +[ "${ARCHIE_TEST_SQLITE3_FAILS:-}" = "1" ] && exit 1 +# Reproduce ".backup ''" by writing a plausible backup beside the +# source, so the watchdog's existence check behaves as it would in production. +for arg in "$@"; do + case "$arg" in + .backup*) target="$(printf '%s' "$arg" | sed "s/^\.backup[[:space:]]*//; s/^'//; s/'$//")" ;; + esac +done +if [ -n "${target:-}" ]; then + mkdir -p "$(dirname "$target")" + printf 'backup\n' > "$target" +fi `) // The production adapter prepends /usr/local/go/bin. Run an otherwise @@ -662,3 +686,96 @@ func TestUpdateWatchdogCyclesEveryUnitInDependencyOrder(t *testing.T) { } } } + +// The updater must back up the database the daemon actually uses, which is +// `-tasks.sqlite` (taskDBPath in internal/app/archied/main.go), not +// the configured path itself. The configured path may be a zero-byte +// placeholder while the real store sits beside it -- so backing the literal +// value up produces an empty backup, and a rollback then restores that empty +// file over the database and deletes its -wal/-shm. A rollback that destroys +// the task store is worse than no rollback. +func TestUpdateInstallBacksUpTheSiblingTaskDatabase(t *testing.T) { + work := t.TempDir() + configured := filepath.Join(work, "archie.db") + realStore := configured + "-tasks.sqlite" + if err := os.WriteFile(configured, nil, 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(realStore, []byte("real task data"), 0o600); err != nil { + t.Fatal(err) + } + backup := filepath.Join(work, "backup.sqlite") + + _, calls, _ := runUpdateInstallWithConfig(t, map[string]string{ + "ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.22.0", + "ARCHIE_UPDATE_DAEMON_VERSION": "1.23.0", + "ARCHIE_UPDATE_AGENT_PREVIOUS": "1.21.0", + "ARCHIE_TASK_DB_BACKUP": backup, + }, "db_path = \""+configured+"\"\n\n[containers]\nimage = 'registry.example/archie-agent:stable'\n", false) + + assertCallContains(t, calls, "sqlite3", realStore, ".backup") + assertCallContains(t, calls, "systemd-run", "--setenv=ARCHIE_TASK_DB_PATH="+realStore) + // The zero-byte placeholder is not the store, and must never be the thing + // handed to the watchdog as ARCHIE_TASK_DB_PATH. + assertCallAbsent(t, calls, "--setenv=ARCHIE_TASK_DB_PATH="+configured+" ") +} + +// db_path also appears in other sections -- [indexing] owns its own database. +// Reading the first match in the file can select an unrelated database, so the +// value must come from the daemon's own top-level key. +func TestUpdateInstallIgnoresDbPathFromOtherSections(t *testing.T) { + work := t.TempDir() + configured := filepath.Join(work, "archie.db") + realStore := configured + "-tasks.sqlite" + indexStore := filepath.Join(work, "workspace-indexes.db") + for path, content := range map[string]string{realStore: "real task data", indexStore: "index data"} { + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + backup := filepath.Join(work, "backup.sqlite") + + _, calls, _ := runUpdateInstallWithConfig(t, map[string]string{ + "ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.22.0", + "ARCHIE_UPDATE_DAEMON_VERSION": "1.23.0", + "ARCHIE_UPDATE_AGENT_PREVIOUS": "1.21.0", + "ARCHIE_TASK_DB_BACKUP": backup, + }, "db_path = \""+configured+"\"\n\n[indexing]\ndb_path = \""+indexStore+"\"\n\n[containers]\nimage = 'registry.example/archie-agent:stable'\n", false) + + assertCallContains(t, calls, "sqlite3", realStore) + for _, call := range calls { + if strings.Contains(call, "sqlite3") && strings.Contains(call, indexStore) { + t.Errorf("backed up the indexing database %s: %q", indexStore, call) + } + } + assertCallAbsent(t, calls, "--setenv=ARCHIE_TASK_DB_PATH="+indexStore) +} + +// A store that cannot be backed up must fail the update before anything is +// replaced. Installing with no usable rollback is how a failed update becomes +// a destroyed task store. +func TestUpdateInstallRefusesWhenTaskDatabaseCannotBeBackedUp(t *testing.T) { + work := t.TempDir() + configured := filepath.Join(work, "archie.db") + if err := os.WriteFile(configured+"-tasks.sqlite", []byte("data"), 0o600); err != nil { + t.Fatal(err) + } + _, calls, output := runUpdateInstallWithConfig(t, map[string]string{ + "ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.22.0", + "ARCHIE_UPDATE_DAEMON_VERSION": "1.23.0", + "ARCHIE_UPDATE_AGENT_PREVIOUS": "1.21.0", + "ARCHIE_TEST_SQLITE3_FAILS": "1", + }, "db_path = \""+configured+"\"\n\n[containers]\nimage = 'registry.example/archie-agent:stable'\n", true) + + if !strings.Contains(output, "task database") { + t.Errorf("refusal must name the task database; output = %q", output) + } + // Nothing of the release may be placed on the host, and no backup of the + // failure path may be attempted either. + for _, call := range calls { + if strings.Contains(call, "install -m755") && !strings.Contains(call, "/scripts/") { + t.Errorf("refused update still installed %q", call) + } + } + assertCallAbsent(t, calls, "arhied.prev") +} diff --git a/scripts/archie-update-install b/scripts/archie-update-install index da8ce6cfb..0e4972a20 100755 --- a/scripts/archie-update-install +++ b/scripts/archie-update-install @@ -43,9 +43,22 @@ configured_agent_image() { printf '%s' "$image" } +# The task store is `-tasks.sqlite`, not db_path itself: the daemon +# derives it with taskDBPath() in internal/app/archied/main.go, and the +# configured path may be a zero-byte placeholder while the real store sits +# beside it. Backing up the literal value would produce an empty backup, and a +# rollback would then restore that empty file over the database and delete its +# -wal/-shm -- destroying the task store it exists to protect. +# +# Only the top-level key counts. db_path also appears in other sections +# ([indexing] owns its own database), and the first match in the file can +# easily be one of those. configured_task_db_path() { - awk ' - /^[[:space:]]*db_path[[:space:]]*=/ { + local base + base="$(awk ' + BEGIN { top = 1 } + /^[[:space:]]*\[/ { top = 0 } + top && /^[[:space:]]*db_path[[:space:]]*=/ { value = $0 sub(/^[[:space:]]*db_path[[:space:]]*=[[:space:]]*/, "", value) sub(/[[:space:]]*(#.*)?$/, "", value) @@ -53,7 +66,9 @@ configured_task_db_path() { else if (length(value) >= 2 && substr(value, 1, 1) == sprintf("%c", 39) && substr(value, length(value), 1) == sprintf("%c", 39)) print substr(value, 2, length(value) - 2) exit } - ' "$CONFIG_PATH" 2>/dev/null || true + ' "$CONFIG_PATH" 2>/dev/null || true)" + [ -n "$base" ] || return 0 + printf '%s' "$base-tasks.sqlite" } AGENT_IMAGE="${ARCHIE_AGENT_IMAGE:-$(configured_agent_image)}" @@ -163,18 +178,26 @@ if [[ ",$components," == *,daemon,* ]]; then fi fi +# Pre-flight, before any write to the host. The task database backup is the +# watchdog's only route back from a forward schema migration, so an update +# that cannot take one must not start: once binaries are replaced, a failure +# leaves the previous release unable to read the store it just migrated. This +# runs ahead of the adapter refresh below so a refusal changes nothing at all. +if [[ ",$components," == *,daemon,* ]] && [ -n "$TASK_DB_PATH" ] && [ -f "$TASK_DB_PATH" ]; then + echo "==> backing up task database for schema-safe rollback" + mkdir -p "$(dirname "$TASK_DB_BACKUP")" + if ! sqlite3 "$TASK_DB_PATH" ".backup '$TASK_DB_BACKUP'"; then + echo "refusing to install $GW: could not back up the task database at $TASK_DB_PATH, so a failed update could not be rolled back" >&2 + exit 1 + fi +fi + # Refresh adapters from the approved release source. The running shell # continues with this copy; subsequent updates use the current contract. install -m755 "$source_dir/scripts/archie-update-install" "$BIN_DIR/archie-update-install" install -m755 "$source_dir/scripts/archie-update-watchdog" "$BIN_DIR/archie-update-watchdog" install -m755 "$source_dir/scripts/archie-update-check" "$BIN_DIR/archie-update-check" -if [[ ",$components," == *,daemon,* ]] && [ -n "$TASK_DB_PATH" ] && [ -f "$TASK_DB_PATH" ]; then - echo "==> backing up task database for schema-safe rollback" - mkdir -p "$(dirname "$TASK_DB_BACKUP")" - sqlite3 "$TASK_DB_PATH" ".backup '$TASK_DB_BACKUP'" -fi - # built accumulates only the binaries this release actually ships, so an # update to a release predating one of these processes stays buildable. built=""