Files
archie/internal/config/holder.go
T
sam f544dd0978 feat(config): SIGHUP-triggered reload with requires-restart warnings
The daemon can now re-read its configuration on SIGHUP (or on a
future in-process trigger) and republish it through the Holder,
closing the first half of issue #348: 'config can change at runtime,
safely, and can't brick the daemon.'

Reload path:
- cmd/archied/reload.go: ReloadController re-runs loader.Resolve on
  the same paths main.go passed at startup (Resolve is pure -- no
  reload state added to the loader). apply is called only with a
  Document that passed validation; a failed reload records the error
  and its timestamp and leaves the running config untouched. That
  Set-not-called-on-error property is the safety core and is pinned
  by TestReloadValidationFailureDoesNotApply.
- SIGHUP listener in main.go runs reloadLoop(ctx, ch, controller, log);
  the loop is extracted as a testable seam (syscall.SIGHUP is Unix-only,
  fine given the Linux target).

PollInterval is genuinely reloadable now, not just re-read:
the three ticker sites (Run, per-identity goroutine, shared
maintenance loop) re-read the interval each tick and Reset the ticker
on change. A reloaded poll_interval takes effect on the next cycle.

Diff-and-warn so an operator never has to read the source to know
whether an edit took effect: changedNonReloadableFields compares the
old and new snapshots against an allowlist of re-read fields
(PollInterval, Repos, DiffCapLines, Budgets, Dispatch, and the
Containers sub-fields VolumeTTL + MaxConcurrency). Anything else that
changed logs Warn 'requires a restart'; a fully-applied reload logs
Info. The allowlist is deliberate: a field added to Config later
defaults to requires-restart, the safe direction.

NATS split-brain closed: containerEnv now hands containers the
endpoint the daemon's own client connected with at startup
(Daemon.ConnectedNATS, captured at construction) instead of the live
config, so a reloaded nats.url cannot point new containers at a
server the daemon is not publishing on. A nats change is therefore
classified requires-restart, and CLAUDE.md's 'hands its own nats.url
verbatim' note is updated to the meaning it now has (same today,
deliberately different after a reload).

Validation guard: poll_interval <= 0 is rejected in validate.go
beside the VolumeTTL guard. applyDefaults fills zero with 60s, so
this fires on an explicit negative -- which would panic
time.NewTicker/Reset at boot and, after the per-iteration reset,
on a SIGHUP mid-run.

Observability: config.ReloadStatus (last_error, last_error_at,
last_reload_at) is recorded by the controller and surfaced in
/api/config via Server.LastReload, so a stale running config is
visible in the dashboard, not just the logs. Rendering waits for the
UI step.

Recovery hatch: --no-config-overlay flag plus ARCHIE_SKIP_CONFIG_OVERLAY=1
(configuration.SkipOverlay), logged at startup. No overlay source
exists yet; the flag is the documented escape hatch the DB overlay
(step 3 of #348) will consult.

webui.Server.ConfigProvenance becomes atomic.Pointer so a reload can
swap it via SetProvenance independently of Cfg; the accepted skew
(new config alongside old provenance) is documented on the field.

Verified: task check clean; -race on daemon, webui, cmd/archied,
config, infrastructure/configuration.
2026-08-10 00:19:46 +10:00

85 lines
3.2 KiB
Go

package config
import "sync"
// Holder publishes a Config snapshot to concurrent readers and lets a
// single writer swap the snapshot atomically.
//
// # Immutability invariant
//
// A published Config is immutable. The only way to update the published
// value is to call Set with a freshly constructed Config; in-place
// mutation of a published Config is a bug. The reason this matters: Get
// returns a value copy, but the copy shares its reference-type fields
// (Models, Providers, Repos, Identities, MCPServers, Extra, etc.) with
// the published snapshot. Mutating a map or slice through that copy
// 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.
//
// # Torn reads across a field group
//
// A single field read inline (d.Cfg.Get().PollInterval) is fine: the
// value is a primitive, and any other reader sees a whole Config
// snapshot too. The risk is reading two or more fields of the same
// snapshot when a Set could land in between, so each field would
// derive from a different published version. When a logical operation
// needs multiple fields, bind the snapshot to a local first:
//
// cfg := d.Cfg.Get()
// if cfg.PollInterval > 0 { ... }
// for _, r := range cfg.Repos { ... }
//
// A single Get per logical operation is the contract; inline single-
// field access is not a smell.
//
// # Loud failures, not silent degradation
//
// Get panics on a nil receiver. A forgotten NewHolder that publishes
// the zero Holder is a programming error and should crash at the first
// consumer, not boot a daemon that runs forever with PollInterval 0
// and empty Repos. Set has always panicked on nil for the same reason;
// the asymmetry was wrong.
//
// # Why a pointer
//
// The zero value of Holder is not usable (the mutex is uninitialised);
// construct one with [NewHolder]. Holder is always passed by pointer
// because the embedded sync.RWMutex is itself a non-copyable type, and
// copying a Daemon that embeds a value Holder triggers go vet copylocks.
type Holder struct {
mu sync.RWMutex
cfg Config
}
// NewHolder returns a Holder preloaded with c.
func NewHolder(c Config) *Holder {
return &Holder{cfg: c}
}
// Get returns the currently published Config. The returned value is a
// shallow copy; the reference-type fields inside it are shared with the
// published snapshot and must not be mutated. Get panics on a nil
// receiver; a forgotten NewHolder is a programming error. See the type
// doc comment.
func (h *Holder) Get() Config {
h.mu.RLock()
defer h.mu.RUnlock()
return h.cfg
}
// Set replaces the published Config with c. The previous snapshot is
// dropped; c becomes the new published value and its reference-type
// fields become shared with all subsequent Get callers. Set panics on
// a nil receiver.
func (h *Holder) Set(c Config) {
h.mu.Lock()
defer h.mu.Unlock()
h.cfg = c
}