diff --git a/cmd/archied/config_update.go b/cmd/archied/config_update.go new file mode 100644 index 000000000..2bce0cf53 --- /dev/null +++ b/cmd/archied/config_update.go @@ -0,0 +1,24 @@ +package main + +import ( + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay" +) + +// applyDottedOverlay decodes dotted-path updates into cfg. yaml cannot +// decode dotted keys ("budgets.max_steps" is not a struct field), so +// the updates are nested into a map first -- the same nesting the +// overlay store's Snapshot performs -- then decoded with the same +// field-level merge the file overlay uses. cfg must be a copy the +// caller owns (a Clone of the published config); it is never decoded +// into a published snapshot directly. +func applyDottedOverlay(cfg *config.Config, updates map[string]any) error { + nested := make(map[string]any) + for key, value := range updates { + if err := overlay.Nest(nested, key, value); err != nil { + return err + } + } + return configuration.ApplyOverlayValues(cfg, nested) +} diff --git a/cmd/archied/config_update_test.go b/cmd/archied/config_update_test.go new file mode 100644 index 000000000..3faf58c69 --- /dev/null +++ b/cmd/archied/config_update_test.go @@ -0,0 +1,34 @@ +package main + +import ( + "testing" + + "github.com/samcharles93/archie-core/internal/config" +) + +// TestApplyDottedOverlayNestsBeforeDecode pins the PATCH-path fix: the +// UI sends dotted keys ("budgets.max_steps") and yaml cannot decode a +// dotted key as a struct field, so the updates must be nested first. A +// regression here silently drops every dotted update while returning 200. +func TestApplyDottedOverlayNestsBeforeDecode(t *testing.T) { + cfg := config.Config{Budgets: config.Budgets{MaxSteps: 10}} + if err := applyDottedOverlay(&cfg, map[string]any{"budgets.max_steps": 20}); err != nil { + t.Fatal(err) + } + if cfg.Budgets.MaxSteps != 20 { + t.Fatalf("MaxSteps = %d, want 20 (dotted key must be nested before decode)", cfg.Budgets.MaxSteps) + } + // A field the update does not name keeps its value. + if cfg.Budgets.MaxTokens != 0 { + t.Errorf("MaxTokens = %d, want 0 (untouched)", cfg.Budgets.MaxTokens) + } +} + +// TestApplyDottedOverlayRejectsEmptyKey pins that a malformed dotted key +// fails instead of silently nesting under a synthetic root. +func TestApplyDottedOverlayRejectsEmptyKey(t *testing.T) { + cfg := config.Config{} + if err := applyDottedOverlay(&cfg, map[string]any{"": 1}); err == nil { + t.Fatal("empty dotted key accepted") + } +} diff --git a/cmd/archied/main.go b/cmd/archied/main.go index bf72855e9..48c94920d 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -19,6 +19,7 @@ import ( "sort" "strconv" "strings" + "sync/atomic" "syscall" "time" @@ -352,22 +353,24 @@ func run() int { // degrade reason into /api/config's reload status so it is visible // where the operator is looking, not only in logs. var overlayStore *overlay.Store - var bootOverlayErr string + var bootOverlayErr atomic.Pointer[string] if !skipOverlay { overlayStore, err = overlay.Open(ctx, configDBPath(doc.Config.DBPath)) if err != nil { - bootOverlayErr = err.Error() + reason := err.Error() + bootOverlayErr.Store(&reason) log.Error("config overlay unavailable; booting on file config alone", "path", configDBPath(doc.Config.DBPath), "err", err) } else { defer overlayStore.Close() if overrides, err := overlayStore.Snapshot(ctx); err != nil { - bootOverlayErr = err.Error() + reason := err.Error() + bootOverlayErr.Store(&reason) log.Error("config overlay unreadable; booting on file config alone", "err", err) } else if len(overrides) > 0 { - next := *doc - applied, err := loader.ApplyOverlay(&next, overrides) + applied, err := loader.ApplyOverlay(doc, overrides) if err != nil { - bootOverlayErr = err.Error() + reason := err.Error() + bootOverlayErr.Store(&reason) log.Error("config overlay rejected by validation; booting on file config alone", "err", err) } else { doc = applied @@ -376,6 +379,8 @@ func run() int { } } cfg := doc.Config + var currentProvenance atomic.Pointer[configuration.Provenance] + currentProvenance.Store(&doc.Provenance) // Re-create the logger now the config is known. Everything above this // point logs to stderr only, which is unavoidable: the log destination is @@ -1033,9 +1038,9 @@ func run() int { // publishConfig publishes a config snapshot and its provenance to // both the daemon and the dashboard (they share one Holder). Reload // and the PATCH path both go through it, so the two can never - // diverge. currentProvenance is the last published provenance chain; - // the PATCH path appends the runtime-overlay origin to it. - currentProvenance := doc.Provenance + // diverge. currentProvenance (an atomic) is the last published + // provenance chain; the PATCH path appends the runtime-overlay + // origin to it. publishConfig := func(cfg config.Config, provenance configuration.Provenance) { d.Cfg.Set(cfg) origins := make([]webui.ConfigOrigin, 0, len(provenance.Origins)) @@ -1060,7 +1065,7 @@ func run() int { // failed to load merges to identity). applyModelCatalog(&doc.Config, catalog) old := d.Cfg.Get() - currentProvenance = doc.Provenance + currentProvenance.Store(&doc.Provenance) publishConfig(doc.Config, doc.Provenance) if fields := changedNonReloadableFields(old, doc.Config); len(fields) > 0 { log.Warn("config reloaded; some changes require a restart", @@ -1077,14 +1082,18 @@ func run() int { // and whether the runtime overlay is in effect at all. web.LastReload = func() config.ReloadStatus { st := reloadController.Status() - st.OverlayUnavailable = bootOverlayErr + if p := bootOverlayErr.Load(); p != nil { + st.OverlayUnavailable = *p + } return st } // PATCH /api/config goes through the same publish path as reload: - // apply to a copy of the published config, validate the materialised - // result, persist to the overlay, then publish. It must never call - // Set directly from the handler -- web.Cfg is the daemon's own Holder. + // apply to a deep copy of the published config, validate the + // materialised result, persist to the overlay, then publish. It must + // never call Set directly from the handler -- web.Cfg is the daemon's + // own Holder -- and it decodes into a Clone so a failed validation + // cannot mutate the published snapshot's shared maps. web.UpdateConfig = func(ctx context.Context, updates map[string]any) error { if overlayStore == nil { return fmt.Errorf("%w: config overlay is disabled (--no-config-overlay or ARCHIE_SKIP_CONFIG_OVERLAY=1)", webui.ErrConfigUpdateUnavailable) @@ -1094,27 +1103,36 @@ func run() int { return fmt.Errorf("%w: config key %s is not runtime-tunable: %s", webui.ErrConfigUpdateInvalid, key, reason) } } - next := d.Cfg.Get() - if err := configuration.ApplyOverlayValues(&next, updates); err != nil { - return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err) + next := d.Cfg.Get().Clone() + if err := applyDottedOverlay(&next, updates); err != nil { + return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err) } if err := configuration.Validate(&next); err != nil { - return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err) + return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err) } for key, value := range updates { data, err := json.Marshal(value) if err != nil { - return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err) + return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err) } if err := overlayStore.Set(ctx, key, string(data), "dashboard"); err != nil { return err } } - prov := configuration.Provenance{Origins: append(append([]configuration.Origin{}, currentProvenance.Origins...), + // Provenance gets the runtime-overlay origin, replacing any prior + // one so the chain does not grow unboundedly across edits. + var kept []configuration.Origin + for _, origin := range currentProvenance.Load().Origins { + if origin.Path == "config_overlay (runtime)" { + continue + } + kept = append(kept, origin) + } + prov := configuration.Provenance{Origins: append(kept, configuration.Origin{Path: "config_overlay (runtime)", Role: configuration.RoleMain, Layer: configuration.LayerOverlay})} - currentProvenance = prov + currentProvenance.Store(&prov) publishConfig(next, prov) - bootOverlayErr = "" // a successful write proves the overlay works again + bootOverlayErr.Store(nil) // a successful write proves the overlay works again log.Info("config updated from dashboard", "keys", len(updates)) return nil } @@ -1141,30 +1159,34 @@ func run() int { // ResetConfig deletes one overlay row and republishes file + remaining // overlay, so a dashboard-created override can be removed without // editing SQL -- and so an operator whose file edit is shadowed by an - // override can recover it with one click. + // override can recover it with one click. The file is resolved and + // the target state validated BEFORE the row is deleted, so a broken + // file cannot leave the store and the running config disagreeing. web.ResetConfig = func(ctx context.Context, key string) error { if overlayStore == nil { return fmt.Errorf("%w: config overlay is disabled", webui.ErrConfigUpdateUnavailable) } + overrides, err := overlayStore.Snapshot(ctx) + if err != nil { + return err + } + delete(overrides, key) // the target overlay state after the reset + doc, err := loader.Resolve(*cfgPath, *overlayPath) + if err != nil { + return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err) + } + if len(overrides) > 0 { + if doc, err = loader.ApplyOverlay(doc, overrides); err != nil { + return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err) + } + } if err := overlayStore.Delete(ctx, key); err != nil { return err } - doc, err := loader.Resolve(*cfgPath, *overlayPath) - if err != nil { - return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err) - } - if overrides, err := overlayStore.Snapshot(ctx); err != nil { - return err - } else if len(overrides) > 0 { - next := *doc - if doc, err = loader.ApplyOverlay(&next, overrides); err != nil { - return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err) - } - } applyModelCatalog(&doc.Config, catalog) - currentProvenance = doc.Provenance + currentProvenance.Store(&doc.Provenance) publishConfig(doc.Config, doc.Provenance) - bootOverlayErr = "" + bootOverlayErr.Store(nil) log.Info("config key reset to file value", "key", key) return nil } diff --git a/cmd/archied/reload.go b/cmd/archied/reload.go index 473dc075b..06c6b315f 100644 --- a/cmd/archied/reload.go +++ b/cmd/archied/reload.go @@ -67,8 +67,9 @@ func (c *ReloadController) Reload() error { return err } if len(values) > 0 { - next := *doc - if doc, err = c.loader.ApplyOverlay(&next, values); err != nil { + // ApplyOverlay never mutates its input: on failure the + // resolved document (and the running config) is untouched. + if doc, err = c.loader.ApplyOverlay(doc, values); err != nil { c.status.Store(&config.ReloadStatus{ LastError: err.Error(), LastErrorAt: time.Now().UTC().Format(time.RFC3339), @@ -160,14 +161,17 @@ var reloadableFields = map[string]bool{ } // reloadableSubFields are sub-fields of structs that are otherwise -// startup-built. VolumeTTL and MaxConcurrency are re-read per cycle -// (cleanupExpiredStorage, drainSQLite/drainNATS); everything else in -// Containers (Image, Enabled, MaxUptime, PullPolicy, Network) is frozen -// in the startup-built container pool. Forge.Host is carried into -// TaskContext by ForTask (display/link building only); the forge client -// itself is startup-built, so Type/Token/TokenEnv stay requires-restart. +// startup-built. VolumeTTL is re-read per cycle in cleanupExpiredStorage; +// everything else in Containers (Image, Enabled, MaxConcurrency, +// MaxUptime, PullPolicy, Network) is frozen in the startup-built +// container pool -- the dispatchers re-read MaxConcurrency but the pool +// captures it at construction (container/pool.go:94,163), so a change +// only partially applies and must warn requires-restart. Forge.Host is +// carried into TaskContext by ForTask (display/link building only); the +// forge client itself is startup-built, so Type/Token/TokenEnv stay +// requires-restart. var reloadableSubFields = map[string]map[string]bool{ - "Containers": {"VolumeTTL": true, "MaxConcurrency": true}, + "Containers": {"VolumeTTL": true}, "Forge": {"Host": true}, } diff --git a/cmd/archied/reload_test.go b/cmd/archied/reload_test.go index efcae7d77..e155330df 100644 --- a/cmd/archied/reload_test.go +++ b/cmd/archied/reload_test.go @@ -230,8 +230,11 @@ func TestChangedNonReloadableFields(t *testing.T) { } c3 := c1 c3.Containers.MaxConcurrency = 4 - if got := changedNonReloadableFields(c1, c3); len(got) != 0 { - t.Fatalf("MaxConcurrency change: got %v, want []", got) + // MaxConcurrency is NOT reloadable: the dispatchers re-read it but the + // startup-built container pool captures it (container/pool.go:94), so + // a change only partially applies and must warn requires-restart. + if got := changedNonReloadableFields(c1, c3); len(got) != 1 || got[0] != "Containers.MaxConcurrency" { + t.Fatalf("MaxConcurrency change: got %v, want [Containers.MaxConcurrency]", got) } c4 := c1 c4.Containers.VolumeTTL = config.Duration(48 * time.Hour) diff --git a/internal/config/clone_test.go b/internal/config/clone_test.go new file mode 100644 index 000000000..e53148bee --- /dev/null +++ b/internal/config/clone_test.go @@ -0,0 +1,74 @@ +package config + +import "testing" + +// TestConfigCloneDeepCopiesReferenceFields pins that Clone returns a +// value sharing no memory with the original: mutating the clone's maps +// and slices must not touch the original. A shallow copy here would +// silently let a failed overlay decode mutate the published snapshot. +func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) { + enabled := true + orig := Config{ + Models: map[string]string{"builder": "m"}, + Repos: []Repo{{Gate: [][]string{{"task", "check"}}, Protect: []string{"p"}}}, + Identities: []IdentityConfig{{ + Models: map[string]string{"planner": "m2"}, + Repos: []Repo{{Gate: [][]string{{"go", "vet"}}}}, + }}, + Dispatch: Dispatch{Labels: map[string]string{"q": "archie:q"}}, + Tools: ToolsConfig{ + MCPServers: []MCPServer{{Headers: map[string]string{"A": "b"}, Args: []string{"x"}}}, + WebFetch: WebFetchConfig{Enabled: &enabled}, + }, + Memory: MemoryConfig{ProviderConfig: map[string]string{"k": "v"}}, + Chat: ChatConfig{Telegram: TelegramConfig{AllowedUserIDs: []int64{1}}}, + Agent: Agent{Env: []string{"HOME"}}, + Extra: map[string]any{"custom": 1}, + } + + got := orig.Clone() + got.Models["builder"] = "changed" + got.Repos[0].Gate[0][0] = "changed" + got.Repos[0].Protect[0] = "changed" + got.Identities[0].Models["planner"] = "changed" + got.Identities[0].Repos[0].Gate[0][0] = "changed" + got.Dispatch.Labels["q"] = "changed" + got.Tools.MCPServers[0].Headers["A"] = "changed" + got.Tools.MCPServers[0].Args[0] = "changed" + got.Memory.ProviderConfig["k"] = "changed" + got.Chat.Telegram.AllowedUserIDs[0] = 99 + got.Agent.Env[0] = "changed" + got.Extra["custom"] = 2 + *got.Tools.WebFetch.Enabled = false + + if orig.Models["builder"] != "m" { + t.Error("Models map is shared") + } + if orig.Repos[0].Gate[0][0] != "task" || orig.Repos[0].Protect[0] != "p" { + t.Error("Repo nested slices are shared") + } + if orig.Identities[0].Models["planner"] != "m2" || orig.Identities[0].Repos[0].Gate[0][0] != "go" { + t.Error("Identity nested fields are shared") + } + if orig.Dispatch.Labels["q"] != "archie:q" { + t.Error("Dispatch.Labels map is shared") + } + if orig.Tools.MCPServers[0].Headers["A"] != "b" || orig.Tools.MCPServers[0].Args[0] != "x" { + t.Error("MCP server fields are shared") + } + if orig.Memory.ProviderConfig["k"] != "v" { + t.Error("Memory.ProviderConfig is shared") + } + if orig.Chat.Telegram.AllowedUserIDs[0] != 1 { + t.Error("Telegram.AllowedUserIDs is shared") + } + if orig.Agent.Env[0] != "HOME" { + t.Error("Agent.Env is shared") + } + if orig.Extra["custom"] != 1 { + t.Error("Extra map is shared") + } + if !*orig.Tools.WebFetch.Enabled { + t.Error("WebFetch.Enabled pointer is shared") + } +} diff --git a/internal/config/config.go b/internal/config/config.go index bdc088795..8f59d3ca9 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -489,6 +489,75 @@ func cloneStringMap(src map[string]string) map[string]string { return dst } +// Clone returns a deep copy of c: every reference-type field (maps, +// slices, and the reference fields nested inside them) is copied, so +// mutating the returned value cannot touch c or anything sharing memory +// with it. It is used before the runtime overlay (or a dashboard PATCH) +// decodes into a snapshot, so a failed or partial decode cannot mutate +// the published config -- Holder.Get returns a shallow copy whose maps +// are shared with the published snapshot. +func (c Config) Clone() Config { + c.Models = cloneStringMap(c.Models) + c.Providers = maps.Clone(c.Providers) + c.Dispatch.Labels = cloneStringMap(c.Dispatch.Labels) + c.Agent.Env = append([]string(nil), c.Agent.Env...) + c.Repos = cloneRepos(c.Repos) + c.Identities = cloneIdentities(c.Identities) + c.Chat.Models = append([]string(nil), c.Chat.Models...) + c.Chat.Telegram.AllowedUserIDs = append([]int64(nil), c.Chat.Telegram.AllowedUserIDs...) + c.Chat.Telegram.UpdateCheckCommand = append([]string(nil), c.Chat.Telegram.UpdateCheckCommand...) + c.Chat.Telegram.UpdateInstallCommand = append([]string(nil), c.Chat.Telegram.UpdateInstallCommand...) + c.Tools.MCPServers = cloneMCPServers(c.Tools.MCPServers) + c.Memory.ProviderConfig = maps.Clone(c.Memory.ProviderConfig) + if c.Tools.WebFetch.Enabled != nil { + v := *c.Tools.WebFetch.Enabled + c.Tools.WebFetch.Enabled = &v + } + c.Extra = maps.Clone(c.Extra) + return c +} + +func cloneRepos(repos []Repo) []Repo { + out := make([]Repo, len(repos)) + for i, r := range repos { + r.Gate = cloneStringSlices(r.Gate) + r.Protect = append([]string(nil), r.Protect...) + r.Preflight = cloneStringSlices(r.Preflight) + out[i] = r + } + return out +} + +func cloneIdentities(ids []IdentityConfig) []IdentityConfig { + out := make([]IdentityConfig, len(ids)) + for i, id := range ids { + id.Models = cloneStringMap(id.Models) + id.Providers = maps.Clone(id.Providers) + id.Dispatch.Labels = cloneStringMap(id.Dispatch.Labels) + id.Repos = cloneRepos(id.Repos) + out[i] = id + } + return out +} + +func cloneMCPServers(servers []MCPServer) []MCPServer { + out := make([]MCPServer, len(servers)) + for i, s := range servers { + s.Args = append([]string(nil), s.Args...) + s.Headers = maps.Clone(s.Headers) + out[i] = s + } + return out +} + +func cloneStringSlices(ss [][]string) [][]string { + out := make([][]string, len(ss)) + for i, s := range ss { + out[i] = append([]string(nil), s...) + } + return out +} + // NATSConfig configures NATS JetStream for task distribution. When URL is // empty the existing SQLite ClaimNext flow is used unchanged. type NATSConfig struct { diff --git a/internal/config/holder.go b/internal/config/holder.go index 1e2210d7e..02f4bece5 100644 --- a/internal/config/holder.go +++ b/internal/config/holder.go @@ -16,11 +16,11 @@ import "sync" // mutates the published snapshot too, and any other reader sees the // mutation outside the protection of the read lock. // -// Reload paths (Loader.Reload, the file watcher, the UI PATCH handler) -// construct a fresh Config and call Set; they never mutate an existing -// one. Decode paths must finish constructing the new Config before Set -// is called; the existing decode.go:80 cfg.Extra[name] = value is fine -// because it runs pre-publish. +// Reload paths (a SIGHUP reload re-calling Loader.Resolve, the UI PATCH +// handler) construct a fresh Config and call Set; they never mutate an +// existing one. Decode paths must finish constructing the new Config +// before Set is called; the existing decode.go:80 cfg.Extra[name] = value +// is fine because it runs pre-publish. // // # Torn reads across a field group // diff --git a/internal/infrastructure/configuration/apply_test.go b/internal/infrastructure/configuration/apply_test.go index 31dcf90c3..dd5aa0e4f 100644 --- a/internal/infrastructure/configuration/apply_test.go +++ b/internal/infrastructure/configuration/apply_test.go @@ -57,10 +57,9 @@ func TestLoaderApplyOverlayLayersDefaultsValidatesAndRecordsProvenance(t *testin t.Errorf("Origins = %+v, want 2 (file + runtime overlay)", applied.Provenance.Origins) } - // An overlay that fails validation aborts; the base document is - // untouched when a copy is passed. - next := *doc - if _, err := l.ApplyOverlay(&next, map[string]any{"agent": map[string]any{"mode": "bogus"}}); err == nil { + // An overlay that fails validation aborts; ApplyOverlay never mutates + // its input, so the base document is untouched even without a copy. + if _, err := l.ApplyOverlay(doc, map[string]any{"agent": map[string]any{"mode": "bogus"}}); err == nil { t.Fatal("invalid overlay accepted") } if doc.Config.Agent.Mode != "inprocess" { diff --git a/internal/infrastructure/configuration/loader.go b/internal/infrastructure/configuration/loader.go index 73cb71a01..93d2e80fe 100644 --- a/internal/infrastructure/configuration/loader.go +++ b/internal/infrastructure/configuration/loader.go @@ -114,22 +114,27 @@ func (l *Loader) Overlay(basePath, overlayPath string) (*Document, error) { } // ApplyOverlay decodes the runtime config overlay (a nested map of -// dotted-path values from the overlay store) into doc with the same -// field-level precedence as a file overlay, records the overlay origin, -// then applies defaults and validates. It is used at boot and on reload -// to layer dashboard-edited overrides over the file config. +// dotted-path values from the overlay store) into a copy of doc with the +// same field-level precedence as a file overlay, records the overlay +// origin, then applies defaults and validates. It is used at boot and on +// reload to layer dashboard-edited overrides over the file config. // -// doc is decoded in place; pass a copy when the base document must -// survive a decode or validation failure (the boot path does). +// ApplyOverlay never mutates its input: the returned Document owns fresh +// copies of the Config and the provenance chain, so a decode or +// validation failure leaves the caller's document (and whatever it was +// published from) exactly as it was. func (l *Loader) ApplyOverlay(doc *Document, overrides map[string]any) (*Document, error) { + next := *doc + next.Config = doc.Config.Clone() + next.Provenance.Origins = append([]Origin(nil), doc.Provenance.Origins...) if len(overrides) == 0 { - return l.finalize(doc) + return l.finalize(&next) } - if err := ApplyOverlayValues(&doc.Config, overrides); err != nil { + if err := ApplyOverlayValues(&next.Config, overrides); err != nil { return nil, err } - doc.Provenance.record(Origin{Path: "config_overlay (runtime)", Role: RoleMain, Layer: LayerOverlay}) - return l.finalize(doc) + next.Provenance.record(Origin{Path: "config_overlay (runtime)", Role: RoleMain, Layer: LayerOverlay}) + return l.finalize(&next) } func (l *Loader) overlayFile(basePath, overlayPath string) (*Document, error) {