fix(statestore): make validate run boot's gate, and stop backup replacing the database

Two P1 findings from review, both about a claim outrunning the code.

validate answered a different question from boot's. Boot refuses on
configuration.Validate over the file config with every stored resource
layered onto it (internal/app/archied/control_plane.go:27), which is a
stricter check than the write path's per-resource Decode: validateScheduling
never inspects dispatch.trigger and explicitly permits "0s", while boot
rejects an unknown trigger and a non-positive poll interval. A store holding
such a value printed "is a valid store ... N stored resources validate" and
exited 0 while archied exited 1 on it -- a false green pushing an operator
toward the blunt restore instead of the surgical rollback.

validate now runs both layers and reports both, in boot's order:
store.ValidateFile, then the write path's ValidateStored, then the config
gate. The layering itself is now one implementation: controlplane's
runtimeConfigFrom takes a resourceReader, which the gRPC client and a new
Server.StoredRuntimeConfig (reading its own store) both provide, so the
offline check cannot drift from the daemon's. validate takes -config /
-config-overlay (default: the path the serve subcommand uses), because the
question is about the stored values layered onto that document.

backup had no guard against -out naming the database. It renames its
snapshot over the target, so `backup -db F -out F` replaced a database a
serving State Store may still have open and orphaned the WAL of the file it
just unlinked -- the state Restore refuses up front and maintenance.go's own
comment calls unrecoverable. backup now refuses with the same message
Restore uses, which is what makes its exemption from the ownership lock
sound.

Claims corrected where they ran ahead of the code: ValidateStored now says it
is the write path's check and not boot's, the Restore comment no longer
promises "never a mixture" for the sidecars it removes first, the usage text
advertises validate's -config, and the architecture table drops "must be
stopped" for validate (nothing enforces it; read-only opens skip the lock by
design) and states which two layers validate reports.

Tests: TestRecoveryValidateRunsTheGateBootRuns fails on the pre-fix code
("validate accepted a stored policy the daemon refuses to boot with") and
covers a store the State Store never seeded; TestRecoveryBackupRefuses-
TheDatabaseAsItsOwnSnapshot fails on the pre-fix code ("backup over the
database itself succeeded"). The validate-accept test now seeds the store
through ImportConfig and asserts the reported count is non-zero, and the
stored-resource case uses a value both gates refuse instead of one only the
write path does.
This commit is contained in:
sam committed 2026-09-21 22:04:42 +10:00
1 parent b8b477fb32
commit e7e5ddfba5
7 files changed
+310 -54

No files matched your search

+21 -1
View File
@@ -5,10 +5,23 @@ import (
"flag"
"fmt"
"io"
"os"
"path/filepath"
"github.com/samcharles93/archie-core/internal/app/archied"
)
// defaultConfigPath is the configuration the serve path reads by default; the
// offline validate asks what the daemon would boot with, so it reads the same
// one.
func defaultConfigPath() string {
base, err := os.UserConfigDir()
if err != nil {
return ""
}
return filepath.Join(base, "archie", "config.toml")
}
// recoveryUsage is the whole flag surface of the offline recovery commands.
// They are subcommands of this binary rather than a recovery binary of their
// own: offline database maintenance belongs to the process that owns the file
@@ -25,7 +38,8 @@ owns it, while backup takes a consistent snapshot of a serving store.
backup -db FILE -out FILE write a snapshot of the database
restore -db FILE -from FILE replace the database with a snapshot
validate -db FILE check the database the way boot does
validate -db FILE [-config FILE] check the file, its stored settings and the
configuration the daemon would boot with
rollback -db FILE -kind KIND replay an earlier revision of a stored
[-revision N] resource through the ordinary replace
`
@@ -56,6 +70,12 @@ func runRecovery(args []string, stdout, stderr io.Writer) int {
flags.StringVar(&options.From, "from", "", "snapshot file restore reads")
flags.StringVar(&options.Kind, "kind", "", "control-plane resource kind rollback replays")
flags.Int64Var(&options.Revision, "revision", 0, "revision rollback replays (default: the newest one older than the current value)")
// Only validate asks a question about the process rather than the file, so
// only validate takes the configuration the process would boot with.
if command == archied.RecoveryValidate {
flags.StringVar(&options.Config, "config", defaultConfigPath(), "configuration file or directory the daemon boots with")
flags.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory")
}
if err := flags.Parse(args[1:]); err != nil {
return 2
}
+119 -9
View File
@@ -18,6 +18,7 @@ import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
@@ -25,6 +26,7 @@ import (
"github.com/samcharles93/archie-core/internal/app/archied"
"github.com/samcharles93/archie-core/internal/app/controlplane"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/store"
)
@@ -142,6 +144,28 @@ func TestRecoveryBackupRefusesAMissingDatabase(t *testing.T) {
}
}
// backup is the one recovery command allowed to run against a serving store,
// and that exemption is only sound while it never replaces the database. With
// -out naming the database it renames the snapshot over the live file and
// leaves the WAL of the database it just unlinked -- the state the restore path
// refuses up front and the code elsewhere calls unrecoverable.
func TestRecoveryBackupRefusesTheDatabaseAsItsOwnSnapshot(t *testing.T) {
db := filepath.Join(t.TempDir(), "archie.db-tasks.sqlite")
st := openTaskStore(t, db)
seedTask(t, st, "live")
code, _, stderr := runRecoveryCmd(t, "backup", "-db", db, "-out", db)
if code == 0 {
t.Fatal("backup over the database itself succeeded")
}
if !strings.Contains(stderr, "is the database itself") {
t.Errorf("refusal must say the snapshot is the database; stderr = %q", stderr)
}
if got := taskTitles(t, db); len(got) != 1 || got[0] != "live" {
t.Fatalf("refused backup changed the database: tasks = %v", got)
}
}
// Restoring is the forward-migration escape hatch: the previous release
// reads this file, so it must be exactly the snapshot, with the WAL that
// belongs to the replaced database gone rather than replayed over it.
@@ -242,18 +266,68 @@ func TestRecoveryRestoreRefusesTheDatabaseAsItsOwnSnapshot(t *testing.T) {
func TestRecoveryValidateAcceptsAHealthyStore(t *testing.T) {
dir := t.TempDir()
configPath := writeMinimalConfig(t, dir)
db := filepath.Join(dir, "archie.db-tasks.sqlite")
st := openTaskStore(t, db)
seedTask(t, st, "healthy")
seedResource(t, st, controlplane.ModelRoleAssignmentsKind, `{"implement":"anthropic/claude"}`, "seed")
seedStoreResources(t, st, configPath)
code, stdout, stderr := runRecoveryCmd(t, "validate", "-db", db)
code, stdout, stderr := runRecoveryCmd(t, "validate", "-db", db, "-config", configPath)
if code != 0 {
t.Fatalf("validate exited %d: %s", code, stderr)
}
if !strings.Contains(stdout, "schema version") {
t.Errorf("validate must report the schema version it verified; stdout = %q", stdout)
}
// The count is part of what the operator reads, and a check that reports
// "0 stored resources" for a store full of them is worse than no check.
if count := storedResourceCount(t, stdout); count == 0 {
t.Errorf("validate reported no stored resources for a seeded store; stdout = %q", stdout)
}
}
// validate's verdict is only useful if it is the daemon's verdict. Boot refuses
// on configuration.Validate over the file config with every stored resource
// layered onto it (internal/app/archied/control_plane.go), not on the write
// path's own per-resource decode, and the two disagree: the write path accepts
// a scheduling policy boot rejects.
func TestRecoveryValidateRunsTheGateBootRuns(t *testing.T) {
dir := t.TempDir()
configPath := writeMinimalConfig(t, dir)
db := filepath.Join(dir, "archie.db-tasks.sqlite")
seedStoreResources(t, openTaskStore(t, db), configPath)
// The control: a store seeded from this config is one the daemon boots on.
code, _, stderr := runRecoveryCmd(t, "validate", "-db", db, "-config", configPath)
if code != 0 {
t.Fatalf("validate exited %d on a store the daemon starts on: %s", code, stderr)
}
// A hand-edited value, or an older revision of one: the write path's own
// validator never inspects dispatch.trigger, so only the config gate
// catches it, and the daemon exits 1 on it (validateDispatch).
if err := execRaw(t, db, `UPDATE resources SET value='{"poll_interval":"1m","max_retries":3,"dispatch":{"trigger":"bogus"}}' WHERE kind='scheduling-policy'`); err != nil {
t.Fatal(err)
}
code, stdout, stderr := runRecoveryCmd(t, "validate", "-db", db, "-config", configPath)
if code == 0 {
t.Fatalf("validate accepted a stored policy the daemon refuses to boot with; stdout = %q", stdout)
}
if !strings.Contains(stderr, "dispatch.trigger") {
t.Errorf("refusal must name what boot rejects; stderr = %q", stderr)
}
// A store the State Store never seeded: the daemon cannot layer its
// settings from it either, so the offline check must not call it valid.
unseeded := filepath.Join(dir, "unseeded.db-tasks.sqlite")
openTaskStore(t, unseeded)
code, stdout, stderr = runRecoveryCmd(t, "validate", "-db", unseeded, "-config", configPath)
if code == 0 {
t.Fatalf("validate accepted a store with no stored settings; stdout = %q", stdout)
}
if !strings.Contains(stderr, "provider-settings") {
t.Errorf("refusal must name the resource kind boot cannot read; stderr = %q", stderr)
}
}
// validate exists to answer "would archied start against this file". Each case
@@ -318,16 +392,19 @@ func TestRecoveryValidateRefusesWhatTheDaemonRefuses(t *testing.T) {
})
t.Run("stored_resource_that_will_not_validate", func(t *testing.T) {
// The stored settings value that stops archied starting: it can only
// get here by bypassing the write path, which is exactly the state the
// control plane fails closed on and the operator has no path back from.
// A stored value that both gates refuse: the write path stops it at
// Decode (workflow.ExecutionSettings.Validate rejects a negative limit),
// and boot stops on it too -- startWorkflowExecutionSettings decodes the
// same document and exits 1. It can only get here by bypassing the write
// path, which is exactly the state the operator has no path back from.
db := newStore(t)
seedResource(t, openTaskStore(t, db), controlplane.ModelRoleAssignmentsKind, `{"implement":"claude"}`, "hand-edited")
seedResource(t, openTaskStore(t, db), controlplane.WorkflowExecutionSettingsKind,
`{"max_model_tool_steps":-1,"max_runtime_seconds":60,"max_consecutive_gate_failures":3}`, "hand-edited")
code, _, stderr := runRecoveryCmd(t, "validate", "-db", db)
if code == 0 {
t.Fatal("validate accepted a stored resource the write path would refuse")
}
if !strings.Contains(stderr, controlplane.ModelRoleAssignmentsKind) {
if !strings.Contains(stderr, controlplane.WorkflowExecutionSettingsKind) {
t.Errorf("refusal must name the resource kind; stderr = %q", stderr)
}
})
@@ -351,11 +428,14 @@ func TestRecoveryValidateRefusesWhatTheDaemonRefuses(t *testing.T) {
// settings. The serving process creates the table on its next start, so
// refusing this file would send an operator to restore a snapshot for a
// database that would have started perfectly well.
db := newStore(t)
dir := t.TempDir()
configPath := writeMinimalConfig(t, dir)
db := filepath.Join(dir, "archie.db-tasks.sqlite")
openTaskStore(t, db)
if err := execRaw(t, db, `DROP TABLE resources`); err != nil {
t.Fatal(err)
}
code, stdout, stderr := runRecoveryCmd(t, "validate", "-db", db)
code, stdout, stderr := runRecoveryCmd(t, "validate", "-db", db, "-config", configPath)
if code != 0 {
t.Fatalf("validate exited %d: %s", code, stderr)
}
@@ -502,6 +582,36 @@ func TestRecoveryRejectsAnUnknownSubcommand(t *testing.T) {
}
}
// seedStoreResources seeds the store the way the State Store seeds it at boot,
// from the same config file the operator hands validate: the command's verdict
// is about the pair, and a store whose settings never matched the config is a
// state boot does not recognise either.
func seedStoreResources(t *testing.T, st *store.Store, configPath string) {
t.Helper()
doc, err := configuration.New(nil).Resolve(configPath, "")
if err != nil {
t.Fatalf("resolve %s: %v", configPath, err)
}
if _, err := controlplane.NewServer(st).ImportConfig(t.Context(), doc.Config); err != nil {
t.Fatalf("seed store resources: %v", err)
}
}
// storedResourceCount reads the count validate reports out of its summary line.
func storedResourceCount(t *testing.T, stdout string) int {
t.Helper()
before, found := strings.CutSuffix(stdout, " stored resources validate\n")
if !found {
t.Fatalf("no resource count in %q", stdout)
}
fields := strings.Fields(before)
count, err := strconv.Atoi(fields[len(fields)-1])
if err != nil {
t.Fatalf("resource count in %q: %v", stdout, err)
}
return count
}
// seedResource writes one revision of a control-plane resource through the
// store, the way the control plane's replace does. The request ID is derived
// from the label and the revision it produces: the store deduplicates a