fix(control-plane): give the container document its own shape

container-runtime-policies seeded and validated config.ContainerConfig directly,
the last resource in the registry whose document was the internal config struct
(archie-core-1171). encoding/json fell back to that struct's Go field names --
Image, MaxConcurrency, LegacyEnabled, Profiles -- the only Go-cased keys the Web
UI still rendered, and case-insensitive matching let a lowercase misspelling
("maxconcurrency") decode as the field while "max_concurrency" was read back
half-applied.

Define the document here instead: containerRuntimePolicies with explicit
snake_case tags and agentProfile at the profile nesting level, the same shape
092194cd gave the channel document. The two durations stay config.Duration,
which already writes the string the file accepts; this leak was the keys only.
The mapping to config.ContainerConfig is one function the validator and the
runtime layering share.

Reading a legacy document is deliberate, so it stays strict about everything
else: DecodeRenamingLegacyKeys renames the seven Go-cased keys an existing store
holds (and the four at the profile level), drops LegacyEnabled -- the removed
containers.enabled switch, which had no runtime consumer and no current
counterpart -- and keeps DisallowUnknownFields, because swallowing an unknown
key decodes as unset and an unset image is a broken worker. A misspelling is
refused.

normalizeContainerPolicies, through the Definition.Normalize hook the channel
document already uses, rewrites a legacy document into the current shape on
write, so a stored document converges the next time it is saved. The layering
keeps its profile semantics -- a document that omits profiles (one stored before
they existed) inherits the file's, one that carries them replaces the file's --
and now checks both spellings of the key.

docs/development/control-plane.md's 'adding a database-owned field' still
instructed the untagged practice this class of issue removes; it now names the
wire-shape rule, the legacy-key tolerance and the Normalize hook instead.
This commit is contained in:
sam committed 2026-09-26 20:18:38 +10:00
1 parent 0254fdaf8d
commit b381ff52b3
8 files changed
+387 -43

No files matched your search

@@ -0,0 +1,149 @@
package controlplane
import (
"encoding/json"
"fmt"
"strings"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
// containerRuntimePolicies is the container-runtime-policies resource document.
// Its shape IS the contract the Web UI edits, so it is defined here with
// explicit snake_case json tags and never handed the internal config.ContainerConfig
// directly: that struct's tags belong to the TOML file format, and when it was
// the document, encoding/json fell back to its Go field names -- "Image",
// "MaxConcurrency", "LegacyEnabled" -- the only Go-cased resource left in the
// registry (archie-core-1171). The two durations are config.Duration, which
// already writes the string the file accepts; the leak was the keys only.
type containerRuntimePolicies struct {
Image string `json:"image"`
MaxConcurrency int `json:"max_concurrency"`
MaxUptime config.Duration `json:"max_uptime"`
VolumeTTL config.Duration `json:"volume_ttl"`
PullPolicy string `json:"pull_policy"`
Network string `json:"network"`
Profiles map[string]agentProfile `json:"profiles,omitempty"`
}
// agentProfile is one named execution environment as the document writes it.
type agentProfile struct {
Image string `json:"image,omitempty"`
Kit []string `json:"kit,omitempty"`
Adapter string `json:"adapter,omitempty"`
Tools []string `json:"tools,omitempty"`
}
// legacyContainerKeys are the Go field names encoding/json fell back to while
// the document was the internal config struct. The decoder's case-insensitive
// fallback compares whole keys, so "MaxConcurrency" never matches
// "max_concurrency"; every store written before the reshape holds these keys,
// so reading them is deliberate and everything else stays strict.
var legacyContainerKeys = map[string]string{
"Image": "image", "MaxConcurrency": "max_concurrency", "MaxUptime": "max_uptime",
"VolumeTTL": "volume_ttl", "PullPolicy": "pull_policy", "Network": "network",
"Profiles": "profiles",
}
// legacyProfileKeys are the same fallback at the profile nesting level.
var legacyProfileKeys = map[string]string{
"Image": "image", "Kit": "kit", "Adapter": "adapter", "Tools": "tools",
}
func (p *agentProfile) UnmarshalJSON(data []byte) error {
type document agentProfile
var decoded document
err := controlplanerpc.DecodeRenamingLegacyKeys(data, legacyProfileKeys, &decoded)
if err != nil {
return err
}
*p = agentProfile(decoded)
return nil
}
func (p *containerRuntimePolicies) UnmarshalJSON(data []byte) error {
type document containerRuntimePolicies
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
// "LegacyEnabled" decoded the removed containers.enabled switch during the
// window in which this resource existed, and stores written then hold it.
// It has no counterpart in the current shape -- it never had a runtime
// consumer -- so it is dropped rather than renamed: the strict decode would
// otherwise refuse a document every deployment of that window stores.
delete(raw, "LegacyEnabled")
encoded, err := json.Marshal(raw)
if err != nil {
return err
}
var decoded document
if err := controlplanerpc.DecodeRenamingLegacyKeys(encoded, legacyContainerKeys, &decoded); err != nil {
return err
}
*p = containerRuntimePolicies(decoded)
return nil
}
// settings maps the document onto the internal config struct the daemon runs.
func (p containerRuntimePolicies) settings() config.ContainerConfig {
out := config.ContainerConfig{
Image: p.Image, MaxConcurrency: p.MaxConcurrency, MaxUptime: p.MaxUptime,
VolumeTTL: p.VolumeTTL, PullPolicy: p.PullPolicy, Network: p.Network,
}
if p.Profiles != nil {
out.Profiles = make(map[string]config.AgentProfile, len(p.Profiles))
for name, profile := range p.Profiles {
out.Profiles[name] = config.AgentProfile{Image: profile.Image, Kit: profile.Kit, Adapter: profile.Adapter, Tools: profile.Tools}
}
}
return out
}
func seedContainerPolicies(cfg config.Config) any {
containers := cfg.Containers
policies := containerRuntimePolicies{
Image: containers.Image, MaxConcurrency: containers.MaxConcurrency, MaxUptime: containers.MaxUptime,
VolumeTTL: containers.VolumeTTL, PullPolicy: containers.PullPolicy, Network: containers.Network,
}
if containers.Profiles != nil {
policies.Profiles = make(map[string]agentProfile, len(containers.Profiles))
for name, profile := range containers.Profiles {
policies.Profiles[name] = agentProfile{Image: profile.Image, Kit: profile.Kit, Adapter: profile.Adapter, Tools: profile.Tools}
}
}
return policies
}
func validateContainers(input []byte) error {
return validateAs(input, func(policies containerRuntimePolicies) error {
settings := policies.settings()
if settings.MaxConcurrency < 0 || settings.MaxUptime < 0 || settings.VolumeTTL < 0 {
return fmt.Errorf("container limits must not be negative")
}
if settings.PullPolicy != "" && settings.PullPolicy != "missing" && settings.PullPolicy != "always" {
return fmt.Errorf("pull_policy must be missing or always")
}
// The image is required for autonomous workflow workers; the same rule
// holds for the stored policies that replace the file's [containers].
if strings.TrimSpace(settings.Image) == "" {
return fmt.Errorf("container image is required for autonomous workflow workers")
}
return settings.ValidateProfiles()
})
}
// normalizeContainerPolicies canonicalizes the stored document: decoding into
// the shape above and re-encoding writes the snake_case keys, dropping the
// Go-cased keys an earlier revision stored. A document that still carries them
// converges the next time it is written; reads tolerate them meanwhile
// (containerRuntimePolicies), so nothing has to be re-saved before it can be
// read again.
func normalizeContainerPolicies(input []byte) ([]byte, error) {
var policies containerRuntimePolicies
if err := json.Unmarshal(input, &policies); err != nil {
return nil, err
}
return json.Marshal(policies)
}
@@ -0,0 +1,183 @@
package controlplane
import (
"encoding/json"
"strings"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/config"
)
// containerPoliciesDefinition returns the registered definition, so a test that
// pins the document's shape also pins its wiring: Seed, Validate and Normalize
// are the three functions the registry actually runs.
func containerPoliciesDefinition(t *testing.T) Definition {
t.Helper()
for _, definition := range operationalDefinitions() {
if definition.Kind == ContainerRuntimePoliciesKind {
return definition
}
}
t.Fatal("container-runtime-policies is not registered")
return Definition{}
}
// TestContainerRuntimePoliciesSeedIsTheDocumentShape pins what an operator sees
// in the Web UI: snake_case keys and durations they can read, matching every
// sibling resource in the registry. The Go-cased keys this replaced are asserted
// absent, because the defect was invisible to a test that only compared decoded
// values -- encoding/json round-trips the wrong spelling perfectly happily.
func TestContainerRuntimePoliciesSeedIsTheDocumentShape(t *testing.T) {
cfg := config.Config{Containers: config.ContainerConfig{
Image: "archie-agent:test", MaxConcurrency: 4,
MaxUptime: config.Duration(2 * time.Hour), VolumeTTL: config.Duration(24 * time.Hour),
PullPolicy: "missing", Network: "bridge",
Profiles: map[string]config.AgentProfile{"net": {Tools: []string{"whois"}}},
}}
encoded, err := json.Marshal(containerPoliciesDefinition(t).Seed(cfg))
if err != nil {
t.Fatalf("marshal seed: %v", err)
}
var document map[string]any
if err := json.Unmarshal(encoded, &document); err != nil {
t.Fatalf("unmarshal seed: %v", err)
}
want := map[string]any{
"image": "archie-agent:test", "max_concurrency": float64(4),
"max_uptime": "2h0m0s", "volume_ttl": "24h0m0s",
"pull_policy": "missing", "network": "bridge",
}
for key, value := range want {
if document[key] != value {
t.Errorf("seed %s = %#v, want %#v", key, document[key], value)
}
}
profiles, ok := document["profiles"].(map[string]any)
if !ok {
t.Fatalf("profiles = %#v, want an object", document["profiles"])
}
net, ok := profiles["net"].(map[string]any)
if !ok || net["tools"] == nil {
t.Fatalf("profiles.net = %#v, want the snake_case tools", profiles["net"])
}
// The Go field names encoding/json fell back to when the document was the
// internal config struct -- at both nesting levels.
for _, legacy := range []string{"Image", "MaxConcurrency", "MaxUptime", "VolumeTTL", "PullPolicy", "Network", "Profiles"} {
if _, present := document[legacy]; present {
t.Errorf("seed carries the Go-cased key %q", legacy)
}
}
for _, legacy := range []string{"Image", "Kit", "Adapter", "Tools"} {
if _, present := net[legacy]; present {
t.Errorf("profiles.net carries the Go-cased key %q", legacy)
}
}
}
// legacyContainerDocument is a document as an earlier revision stored it: the
// Go field names encoding/json fell back to while the document was the internal
// config struct, and LegacyEnabled from the short window in which the removed
// containers.enabled switch still decoded. Every store written before the
// reshape holds a document like this one, so it has to keep working.
const legacyContainerDocument = `{"Image":"archie-agent:test","MaxConcurrency":4,"MaxUptime":"2h0m0s","VolumeTTL":"24h0m0s","PullPolicy":"missing","Network":"bridge","LegacyEnabled":false,"Profiles":{"net":{"Image":"proxy:1","Tools":["whois"]}}}`
// TestContainerRuntimePoliciesReadsADocumentWrittenBeforeTheReshape covers the
// two halves the change needs: a legacy document still validates and still
// reads, and writing it back (Definition.Decode is what every write path runs)
// rewrites it into the current shape. The control plane fails closed, so a
// shape change without this tolerance stops archied starting on a store that
// already holds the old document.
func TestContainerRuntimePoliciesReadsADocumentWrittenBeforeTheReshape(t *testing.T) {
definition := containerPoliciesDefinition(t)
if err := definition.Validate([]byte(legacyContainerDocument)); err != nil {
t.Fatalf("Validate(legacy) = %v, want it accepted: it is what existing stores hold", err)
}
decoded, err := definition.Decode([]byte(legacyContainerDocument))
if err != nil {
t.Fatalf("Decode(legacy) = %v", err)
}
for _, legacy := range []string{`"Image"`, `"MaxConcurrency"`, `"LegacyEnabled"`, `"Profiles"`, `"Tools"`} {
if strings.Contains(string(decoded), legacy) {
t.Fatalf("decoded document = %s, want the canonical keys without %q", decoded, legacy)
}
}
var document struct {
Image string `json:"image"`
MaxConcurrency int `json:"max_concurrency"`
MaxUptime string `json:"max_uptime"`
VolumeTTL string `json:"volume_ttl"`
PullPolicy string `json:"pull_policy"`
Network string `json:"network"`
Profiles map[string]struct {
Image string `json:"image"`
Tools []string `json:"tools"`
} `json:"profiles"`
}
if err := json.Unmarshal(decoded, &document); err != nil {
t.Fatalf("unmarshal decoded document: %v", err)
}
if document.Image != "archie-agent:test" || document.MaxConcurrency != 4 ||
document.MaxUptime != "2h0m0s" || document.VolumeTTL != "24h0m0s" ||
document.PullPolicy != "missing" || document.Network != "bridge" {
t.Errorf("document = %+v, want the legacy values preserved in the current shape", document)
}
if len(document.Profiles) != 1 || document.Profiles["net"].Image != "proxy:1" {
t.Errorf("profiles = %+v, want the legacy values preserved", document.Profiles)
}
}
// TestContainerRuntimePoliciesKeepsDisallowUnknownFields: the legacy tolerance
// renames the keys an existing store holds and nothing else, because swallowing
// an unknown key decodes as "unset" and an unset image is a broken worker. A
// misspelling is refused, at the top level and inside a profile.
func TestContainerRuntimePoliciesKeepsDisallowUnknownFields(t *testing.T) {
for _, document := range []string{
`{"image":"archie-agent:test","maxconcurrency":4}`,
`{"image":"archie-agent:test","profiles":{"net":{"toolz":["whois"]}}}`,
} {
if err := containerPoliciesDefinition(t).Validate([]byte(document)); err == nil {
t.Errorf("Validate(%s) accepted a misspelled key", document)
}
}
}
// TestContainerRuntimePoliciesLayersLegacyDocuments walks the stored forms to
// config.Containers: the snake_case document and the Go-cased one an existing
// store holds. Both have to reach the running config, or a deployment's
// container policies silently stop applying the next time it boots.
func TestContainerRuntimePoliciesLayersLegacyDocuments(t *testing.T) {
for _, tt := range []struct {
name string
stored string
}{
{
name: "the current shape",
stored: `{"image":"archie-agent:test","max_concurrency":4,"max_uptime":"2h0m0s","volume_ttl":"24h0m0s","pull_policy":"missing","network":"bridge","profiles":{"net":{"image":"proxy:1","tools":["whois"]}}}`,
},
{
name: "the Go-cased shape an existing store holds",
stored: legacyContainerDocument,
},
} {
t.Run(tt.name, func(t *testing.T) {
client := NewRPCClient(&runtimeConfigClient{values: map[string]any{
SchedulingPolicyKind: map[string]any{"poll_interval": "2m", "dispatch": map[string]any{"trigger": "assignee"}},
ContainerRuntimePoliciesKind: json.RawMessage(tt.stored),
}})
got, _, err := client.RuntimeConfig(t.Context(), config.Config{})
if err != nil {
t.Fatalf("RuntimeConfig: %v", err)
}
if got.Containers.Image != "archie-agent:test" || got.Containers.MaxConcurrency != 4 ||
got.Containers.MaxUptime != config.Duration(2*time.Hour) || got.Containers.Network != "bridge" {
t.Fatalf("Containers = %+v, want the stored document applied", got.Containers)
}
if len(got.Containers.Profiles) != 1 || got.Containers.Profiles["net"].Image != "proxy:1" {
t.Fatalf("Profiles = %+v, want the stored profiles applied", got.Containers.Profiles)
}
})
}
}
@@ -2,7 +2,6 @@ package controlplane
import (
"fmt"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/config"
@@ -50,7 +49,7 @@ func operationalDefinitions() []Definition {
{Kind: PluginSettingsKind, Title: "Plugin settings", ApplyMode: "restart-required", Document: pluginSettings{}, Seed: func(cfg config.Config) any {
return pluginSettings{cfg.PluginDir, cfg.ModuleDir, cfg.SecretEngineDir, cfg.SkillsDir}
}, Validate: validatePluginSettings},
{Kind: ContainerRuntimePoliciesKind, Title: "Container runtime policies", ApplyMode: "restart-required", Document: config.ContainerConfig{}, Seed: func(cfg config.Config) any { return cfg.Containers }, Validate: validateContainers},
{Kind: ContainerRuntimePoliciesKind, Title: "Container runtime policies", ApplyMode: "restart-required", Document: containerRuntimePolicies{}, Seed: seedContainerPolicies, Validate: validateContainers, Normalize: normalizeContainerPolicies},
}
}
@@ -103,20 +102,3 @@ func validateScheduling(input []byte) error {
return nil
})
}
func validateContainers(input []byte) error {
return validateAs(input, func(settings config.ContainerConfig) error {
if settings.MaxConcurrency < 0 || time.Duration(settings.MaxUptime) < 0 || time.Duration(settings.VolumeTTL) < 0 {
return fmt.Errorf("container limits must not be negative")
}
if settings.PullPolicy != "" && settings.PullPolicy != "missing" && settings.PullPolicy != "always" {
return fmt.Errorf("pull_policy must be missing or always")
}
// The image is required for autonomous workflow workers; the same rule
// holds for the stored policies that replace the file's [containers].
if strings.TrimSpace(settings.Image) == "" {
return fmt.Errorf("container image is required for autonomous workflow workers")
}
return settings.ValidateProfiles()
})
}
+18 -6
View File
@@ -204,18 +204,30 @@ func runtimeToolConfigFrom(ctx context.Context, reader controlplanerpc.ResourceR
return config.Config{}, nil, err
}
if err := layerResource(ctx, reader, versions, ContainerRuntimePoliciesKind, func(value []byte) error {
// A document that omits Profiles (one stored before they existed)
// A document that omits profiles (one stored before they existed)
// inherits the file's. One that carries them replaces the file's:
// json.Unmarshal merges into an existing map, so without clearing it a
// profile deleted from the store would come back from the file.
// the mapping below would otherwise merge into the file's map, so a
// profile deleted from the store would come back from the file. Both
// spellings are checked, because documents written before the document
// had its own shape carry the Go-cased key.
var keys map[string]json.RawMessage
if err := json.Unmarshal(value, &keys); err != nil {
return err
}
if _, stored := keys["Profiles"]; stored {
out.Containers.Profiles = nil
_, carriesProfiles := keys["profiles"]
if !carriesProfiles {
_, carriesProfiles = keys["Profiles"]
}
return json.Unmarshal(value, &out.Containers)
var policies containerRuntimePolicies
if err := json.Unmarshal(value, &policies); err != nil {
return err
}
inherited := out.Containers.Profiles
out.Containers = policies.settings()
if !carriesProfiles {
out.Containers.Profiles = inherited
}
return nil
}); err != nil {
return config.Config{}, nil, err
}
@@ -58,7 +58,7 @@ func TestRuntimeConfigUsesDatabaseResourcesAndPreservesBootstrapOnlySecrets(t *t
SchedulingPolicyKind: map[string]any{"poll_interval": "2m", "max_retries": 7, "dispatch": map[string]any{"trigger": "assignee"}},
ToolSettingsKind: map[string]any{"mcp_servers": []map[string]any{{"name": "docs", "transport": "http", "url": "https://mcp.example.com", "headers_configured": true}}, "policy": map[string]any{}, "web_fetch": map[string]any{}, "minimax": map[string]any{"enabled": false, "credential_configured": false}},
PluginSettingsKind: map[string]any{"plugin_dir": "/plugins", "module_dir": "/modules", "secret_engine_dir": "/secrets", "skills_dir": "/skills"},
ContainerRuntimePoliciesKind: config.ContainerConfig{Image: "archie:next", PullPolicy: "missing"},
ContainerRuntimePoliciesKind: map[string]any{"image": "archie:next", "pull_policy": "missing"},
}})
got, versions, err := client.RuntimeConfig(t.Context(), base)
@@ -420,8 +420,15 @@ func TestRuntimeConfigLayersStoredProfiles(t *testing.T) {
stored map[string]any
want []string
}{
{name: "stored profiles replace the file's", stored: map[string]any{"Image": "agent:2", "Profiles": map[string]any{"net": map[string]any{"Tools": []string{"whois"}}}}, want: []string{"net"}},
{name: "a document without profiles inherits the file's", stored: map[string]any{"Image": "agent:2"}, want: []string{"file-only"}},
{name: "stored profiles replace the file's", stored: map[string]any{"image": "agent:2", "profiles": map[string]any{"net": map[string]any{"tools": []string{"whois"}}}}, want: []string{"net"}},
{
// The Go-cased spelling documents written before the document had its
// own shape carry: the profile it names must still replace the file's.
name: "legacy Go-cased profiles replace the file's",
stored: map[string]any{"Image": "agent:2", "Profiles": map[string]any{"net": map[string]any{"Tools": []string{"whois"}}}},
want: []string{"net"},
},
{name: "a document without profiles inherits the file's", stored: map[string]any{"image": "agent:2"}, want: []string{"file-only"}},
} {
t.Run(tt.name, func(t *testing.T) {
client := NewRPCClient(&runtimeConfigClient{values: map[string]any{
@@ -107,14 +107,14 @@ func TestResourceValidatorsRejectWhatEffectiveValidationRejects(t *testing.T) {
{
name: "valid container runtime policies",
kind: ContainerRuntimePoliciesKind,
value: config.ContainerConfig{Image: "archie-agent:test", PullPolicy: "missing"},
value: containerRuntimePolicies{Image: "archie-agent:test", PullPolicy: "missing"},
mutate: func(cfg *config.Config) {},
wantErr: false,
},
{
name: "container profile with an empty tool name",
kind: ContainerRuntimePoliciesKind,
value: config.ContainerConfig{Image: "archie-agent:test", Profiles: map[string]config.AgentProfile{
value: containerRuntimePolicies{Image: "archie-agent:test", Profiles: map[string]agentProfile{
"net": {Tools: []string{""}},
}},
mutate: func(cfg *config.Config) {
@@ -125,14 +125,14 @@ func TestResourceValidatorsRejectWhatEffectiveValidationRejects(t *testing.T) {
{
name: "container runtime policies without an image",
kind: ContainerRuntimePoliciesKind,
value: config.ContainerConfig{PullPolicy: "missing"},
value: containerRuntimePolicies{PullPolicy: "missing"},
mutate: func(cfg *config.Config) { cfg.Containers.Image = "" },
wantErr: true,
},
{
name: "negative container volume ttl",
kind: ContainerRuntimePoliciesKind,
value: config.ContainerConfig{Image: "archie-agent:test", VolumeTTL: config.Duration(-time.Minute)},
value: containerRuntimePolicies{Image: "archie-agent:test", VolumeTTL: config.Duration(-time.Minute)},
mutate: func(cfg *config.Config) { cfg.Containers.VolumeTTL = config.Duration(-time.Minute) },
wantErr: true,
},