diff --git a/docs/data/generated/dev-docs.json b/docs/data/generated/dev-docs.json index b45385b4f..aed952775 100644 --- a/docs/data/generated/dev-docs.json +++ b/docs/data/generated/dev-docs.json @@ -118,7 +118,7 @@ "url": "/dev/development/control-plane/", "title": "Control plane and settings", "section": "Development", - "body": "# Control plane and settings\n\nAuthority: `docs/architecture/configuration.md`. The wiring matrix, the\ndecoded-but-unwired ledger and the three shapes an unwired field takes are in\n`.agents/skills/archie-config-and-flags`.\n\nA field that parses is not a field that works. Before adding one, name the code\nthat reads it and the path the value takes to get there.\n\n## Decide what kind of setting it is\n\n- **Bootstrap-only** (read once at process start: `database_url`, `state_dir`,\n `work_dir`). It stays in the file, is checked by `validateBootstrap` in\n `internal/infrastructure/configuration/validate.go`, and the runtime overlay\n refuses changes to it.\n- **Database-owned** (repository policies, scheduling, tools, plugins,\n channels, containers). The file only seeds it. Once the State Store holds the\n control-plane resource, the stored document is layered over the file\n (`controlplane.Client.RuntimeConfig`) and the file key stops mattering. It is\n checked by `validateDatabaseOwned` and by the resource's validator.\n- **Worker-carried.** A value the agent container needs travels in\n `config.TaskConfig` (`Config.ForTask`) or on `taskrun.Request`. Never pass it\n as an environment variable the daemon did not already define, and never carry\n a secret this way.\n\n## Adding a database-owned field\n\n1. Add it to the struct the resource's `Document` names in\n `internal/app/controlplane/operational_settings.go`. The resource's JSON\n schema and the dashboard's Advanced settings editor are generated from that\n type, so no UI work is needed for the editor itself.\n2. Stored documents use Go field names as keys (`Image`, `MaxConcurrency`).\n Give the field no `json` tag unless its neighbours have one.\n3. A map or a nested struct needs its layering checked. `json.Unmarshal`\n merges into an existing map, so a stored map would add to the file's rather\n than replace it. A field the stored document omits keeps the file's value\n (a document stored before the field existed). Add a case to\n `internal/app/controlplane/runtime_config_test.go` for both.\n4. Validate it in one function both sides call, and add a case to\n `TestResourceValidatorsRejectWhatEffectiveValidationRejects` in\n `validators_agree_test.go`, so the file and the resource cannot disagree.\n5. Decide whether it reloads: it does only if every consumer re-reads it from\n `config.Holder`. The allowlist is `internal/app/archied/reload.go`; anything\n not on it requires a restart.\n6. If the settings page shows it as a plain field, add it to\n `internal/webui/config_schema.go` and the view in `api_config.go`.\n7. A generic catalog resource (`replace` command, not domain-managed, no\n query service) is watched **once per archie-ui process** by `webui.RunLive`,\n then published to every browser through `/api/stream`. Do not add an\n EventSource per resource to a settings store or a gRPC Watch per HTTP client.\n The control-plane server polls `Resource` every 250ms per upstream Watch;\n verify watch count is independent of client count and that late clients get\n the hub's current value (`internal/webui/live_hub_test.go`, real server over\n bufconn). Reopens resume after the last delivered version and charge failed\n attempts; accepting a gRPC stream does not establish its health.\n\n## Every new field\n\n- Test through the layering: build the effective config the way boot does,\n not by setting the field on the consumer.\n- Add a commented example to `config.example.toml`. Touch `deployments/*.toml`\n only when a profile there needs a value different from the default.\n- Update the wiring matrix in `.agents/skills/archie-config-and-flags`.\n- Secrets are `SecretRef`s resolved through the secret registry. Never inspect\n a resolved value, even in a test.\n- Reject a configuration that sets a field with no consumer rather than\n accepting and ignoring it (per-identity `forge.intake` is the precedent).\n" + "body": "# Control plane and settings\n\nAuthority: `docs/architecture/configuration.md`. The wiring matrix, the\ndecoded-but-unwired ledger and the three shapes an unwired field takes are in\n`.agents/skills/archie-config-and-flags`.\n\nA field that parses is not a field that works. Before adding one, name the code\nthat reads it and the path the value takes to get there.\n\n## Decide what kind of setting it is\n\n- **Bootstrap-only** (read once at process start: `database_url`, `state_dir`,\n `work_dir`). It stays in the file, is checked by `validateBootstrap` in\n `internal/infrastructure/configuration/validate.go`, and the runtime overlay\n refuses changes to it.\n- **Database-owned** (repository policies, scheduling, tools, plugins,\n channels, containers). The file only seeds it. Once the State Store holds the\n control-plane resource, the stored document is layered over the file\n (`controlplane.Client.RuntimeConfig`) and the file key stops mattering. It is\n checked by `validateDatabaseOwned` and by the resource's validator.\n- **Worker-carried.** A value the agent container needs travels in\n `config.TaskConfig` (`Config.ForTask`) or on `taskrun.Request`. Never pass it\n as an environment variable the daemon did not already define, and never carry\n a secret this way.\n\n## Adding a database-owned field\n\n1. Add it to the wire-shape type the resource's `Document` names — a dedicated\n struct in `internal/app/controlplane/` with explicit snake_case json tags\n (`channel_settings.go`, `tool_settings.go`, `container_settings.go` are the\n precedents), never the internal config struct itself. A struct fed straight\n into the document falls back to Go field names (`Window`, `MaxRequests`),\n and a bare `time.Duration` marshals as nanoseconds — both render unusable\n in the Web UI. The resource's JSON schema and the dashboard's Advanced\n settings editor are generated from that type, so no UI work is needed for\n the editor itself.\n2. Map to and from the internal config type at the resource boundary (`Seed`,\n the layering in `runtime_config.go`, and the validator all use the same\n mapping). Durations in the document are a string-marshalling type\n (`config.Duration` or a document-local one), never a bare `time.Duration`.\n3. A document stored before the shape existed carries Go-cased keys. Read them\n with `controlplanerpc.DecodeRenamingLegacyKeys` (an `UnmarshalJSON` on the\n wire type) while keeping `DisallowUnknownFields` — dropping unknown keys\n would decode a misspelling as \"unset\" — and register a `Normalize` on the\n `Definition` that re-encodes the document, so a legacy document converges\n the next time it is written. A map or a nested struct needs its layering\n checked: a stored map replaces the file's, not merges into it, and a field\n the stored document omits keeps the file's value. Add a case to\n `internal/app/controlplane/runtime_config_test.go` for both.\n4. Validate it in one function both sides call, and add a case to\n `TestResourceValidatorsRejectWhatEffectiveValidationRejects` in\n `validators_agree_test.go`, so the file and the resource cannot disagree.\n5. Decide whether it reloads: it does only if every consumer re-reads it from\n `config.Holder`. The allowlist is `internal/app/archied/reload.go`; anything\n not on it requires a restart.\n6. If the settings page shows it as a plain field, add it to\n `internal/webui/config_schema.go` and the view in `api_config.go`.\n7. A generic catalog resource (`replace` command, not domain-managed, no\n query service) is watched **once per archie-ui process** by `webui.RunLive`,\n then published to every browser through `/api/stream`. Do not add an\n EventSource per resource to a settings store or a gRPC Watch per HTTP client.\n The control-plane server polls `Resource` every 250ms per upstream Watch;\n verify watch count is independent of client count and that late clients get\n the hub's current value (`internal/webui/live_hub_test.go`, real server over\n bufconn). Reopens resume after the last delivered version and charge failed\n attempts; accepting a gRPC stream does not establish its health.\n\n## Every new field\n\n- Test through the layering: build the effective config the way boot does,\n not by setting the field on the consumer.\n- Add a commented example to `config.example.toml`. Touch `deployments/*.toml`\n only when a profile there needs a value different from the default.\n- Update the wiring matrix in `.agents/skills/archie-config-and-flags`.\n- Secrets are `SecretRef`s resolved through the secret registry. Never inspect\n a resolved value, even in a test.\n- Reject a configuration that sets a field with no consumer rather than\n accepting and ignoring it (per-identity `forge.intake` is the precedent).\n" }, { "url": "/dev/development/daemon/", diff --git a/docs/development/control-plane.md b/docs/development/control-plane.md index ff6ddc9d2..f5a687dea 100644 --- a/docs/development/control-plane.md +++ b/docs/development/control-plane.md @@ -25,16 +25,27 @@ that reads it and the path the value takes to get there. ## Adding a database-owned field -1. Add it to the struct the resource's `Document` names in - `internal/app/controlplane/operational_settings.go`. The resource's JSON - schema and the dashboard's Advanced settings editor are generated from that - type, so no UI work is needed for the editor itself. -2. Stored documents use Go field names as keys (`Image`, `MaxConcurrency`). - Give the field no `json` tag unless its neighbours have one. -3. A map or a nested struct needs its layering checked. `json.Unmarshal` - merges into an existing map, so a stored map would add to the file's rather - than replace it. A field the stored document omits keeps the file's value - (a document stored before the field existed). Add a case to +1. Add it to the wire-shape type the resource's `Document` names — a dedicated + struct in `internal/app/controlplane/` with explicit snake_case json tags + (`channel_settings.go`, `tool_settings.go`, `container_settings.go` are the + precedents), never the internal config struct itself. A struct fed straight + into the document falls back to Go field names (`Window`, `MaxRequests`), + and a bare `time.Duration` marshals as nanoseconds — both render unusable + in the Web UI. The resource's JSON schema and the dashboard's Advanced + settings editor are generated from that type, so no UI work is needed for + the editor itself. +2. Map to and from the internal config type at the resource boundary (`Seed`, + the layering in `runtime_config.go`, and the validator all use the same + mapping). Durations in the document are a string-marshalling type + (`config.Duration` or a document-local one), never a bare `time.Duration`. +3. A document stored before the shape existed carries Go-cased keys. Read them + with `controlplanerpc.DecodeRenamingLegacyKeys` (an `UnmarshalJSON` on the + wire type) while keeping `DisallowUnknownFields` — dropping unknown keys + would decode a misspelling as "unset" — and register a `Normalize` on the + `Definition` that re-encodes the document, so a legacy document converges + the next time it is written. A map or a nested struct needs its layering + checked: a stored map replaces the file's, not merges into it, and a field + the stored document omits keeps the file's value. Add a case to `internal/app/controlplane/runtime_config_test.go` for both. 4. Validate it in one function both sides call, and add a case to `TestResourceValidatorsRejectWhatEffectiveValidationRejects` in diff --git a/internal/app/archied/gateway.go b/internal/app/archied/gateway.go index 7eb8430fd..825eeb05d 100644 --- a/internal/app/archied/gateway.go +++ b/internal/app/archied/gateway.go @@ -119,8 +119,21 @@ func RunGateway(ctx context.Context, options GatewayOptions) error { if err != nil { return fmt.Errorf("listen for gateway: %w", err) } + return b.serveGatewayListener(ctx, listener, loopback, contract, opts) +} + +// serveGatewayListener is the serving tail of RunGateway: the listener is +// bound, the process declares itself serving, and the chat contract answers +// until ctx ends. +func (b *boot) serveGatewayListener(ctx context.Context, listener net.Listener, loopback bool, contract gateway.ChatContract, opts []grpc.ServerOption) error { defer listener.Close() b.log.Info("archie-gateway running", "addr", listener.Addr().String(), "token_required", !loopback) + // Boot is over and this listener is about to accept: the same fact + // systemd's READY=1 asserts, so the announcement goes out here rather than + // from a second notion of "started" (archie-core-1174). Not later: Serve + // begins accepting the moment it is called, and a unit whose + // TimeoutStartSec expires first would restart a healthy process. + b.announceReady() return serveGateway(ctx, listener, contract, b.chatSessionStore, opts) } diff --git a/internal/app/archied/gateway_test.go b/internal/app/archied/gateway_test.go index a8c4ad1fd..024b815dd 100644 --- a/internal/app/archied/gateway_test.go +++ b/internal/app/archied/gateway_test.go @@ -1,6 +1,20 @@ package archied -import "testing" +import ( + "context" + "log/slog" + "net" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1" + "github.com/samcharles93/archie-core/internal/domain/messaging" + "github.com/samcharles93/archie-core/internal/domain/taskactions" + "github.com/samcharles93/archie-core/internal/taskstate" +) func TestGatewayServerOptsLoopbackIsInsecure(t *testing.T) { opts, loopback, err := gatewayServerOpts("127.0.0.1:8585", "") @@ -36,3 +50,87 @@ func TestGatewayServerOptsMalformedListen(t *testing.T) { t.Fatal("malformed listen address should error") } } + +// stubGatewayContract satisfies messaging.ChatContract with zero values: the +// serve test exercises the listener, the READY announcement and one read RPC, +// not the chat runtime. +type stubGatewayContract struct{} + +func (stubGatewayContract) Snapshot(context.Context) (messaging.ChatSnapshot, error) { + return messaging.ChatSnapshot{}, nil +} + +func (stubGatewayContract) GetSession(context.Context, string) (messaging.SessionContext, bool, error) { + return messaging.SessionContext{}, false, nil +} + +func (stubGatewayContract) RecentMessages(context.Context, string, int) ([]messaging.Message, error) { + return nil, nil +} + +func (stubGatewayContract) RecentTurns(context.Context, string, int) ([]messaging.TurnRecord, error) { + return nil, nil +} + +func (stubGatewayContract) Route(context.Context, messaging.Inbound) (messaging.ChatReply, error) { + return messaging.ChatReply{}, nil +} + +func (stubGatewayContract) Stream(context.Context, messaging.Inbound) (<-chan messaging.ChatEvent, error) { + return nil, nil +} + +func (stubGatewayContract) Cancel(context.Context, string) (messaging.ChatCancellation, error) { + return messaging.ChatCancellation{}, nil +} + +func (stubGatewayContract) SetPersona(context.Context, string, string) (bool, error) { + return false, nil +} + +func (stubGatewayContract) ApplyTaskAction(context.Context, string, int64, taskstate.Action) (messaging.TaskActionResult, error) { + return messaging.TaskActionResult{}, nil +} + +func (stubGatewayContract) ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action) (messaging.TaskActionResult, error) { + return messaging.TaskActionResult{}, nil +} + +// TestGatewayServingAnnouncesReady: archie-gateway run as a Type=notify unit +// must send READY=1 at the moment it declares itself serving, or systemd kills +// a healthy process once TimeoutStartSec expires (archie-core-1174). The +// announcement is judged against the same evidence archied's run loop uses: +// the contract answers over the bound listener, so READY asserts a serving +// process rather than a bound socket. +func TestGatewayServingAnnouncesReady(t *testing.T) { + listener := newNotifyListener(t) + b := &boot{log: slog.New(slog.DiscardHandler)} + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + + ln, err := (&net.ListenConfig{}).Listen(ctx, "tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + + serveCh := make(chan error, 1) + go func() { serveCh <- b.serveGatewayListener(ctx, ln, true, stubGatewayContract{}, nil) }() + + if !listener.waitForState(t, 5*time.Second, readyState) { + t.Fatal("no READY=1 datagram within 5s of the Gateway serving") + } + + conn, err := grpc.NewClient("passthrough:///"+ln.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + if _, err := pb.NewChatServiceClient(conn).Snapshot(t.Context(), &pb.SnapshotRequest{}); err != nil { + t.Fatalf("Snapshot over gRPC: %v", err) + } + + cancel() + if err := <-serveCh; err != nil { + t.Fatalf("serveGatewayListener returned: %v", err) + } +} diff --git a/internal/app/archied/sd_notify.go b/internal/app/archied/sd_notify.go index 1ca5f8154..ea42accec 100644 --- a/internal/app/archied/sd_notify.go +++ b/internal/app/archied/sd_notify.go @@ -95,11 +95,20 @@ func sendNotify(addr, state string) error { } // announceReady tells systemd the daemon has finished starting. It is called at -// the moment the process declares itself serving (runLoop, next to -// healthSurface.markServing), which is the same fact READY=1 asserts: boot is -// over and the run loop is about to take over. +// the moment a process declares itself serving: the daemon's run loop (next to +// healthSurface.markServing), and the serve steps of archie-gateway and +// archie-state-store (archie-core-1174), which have health surfaces of their +// own and would otherwise hang a Type=notify unit until TimeoutStartSec while +// perfectly healthy. func (b *boot) announceReady() { - newNotifier(os.Getenv, b.log).send(readyState) + notifyReady(b.log) +} + +// notifyReady is announceReady without the boot: the Gateway's serving tail +// runs on a boot it owns, but a free helper keeps the announcement one call +// rather than a second notion of "started" on each surface. +func notifyReady(log *slog.Logger) { + newNotifier(os.Getenv, log).send(readyState) } // startWatchdog arms the heartbeat sampler for the daemon's run loop. It does diff --git a/internal/app/archied/sd_notify_test.go b/internal/app/archied/sd_notify_test.go index bd2aedcf2..cf9e460f8 100644 --- a/internal/app/archied/sd_notify_test.go +++ b/internal/app/archied/sd_notify_test.go @@ -17,6 +17,7 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/daemon" "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore" + "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest" ) // notifyRecorder captures every record at every level. The other recording @@ -119,6 +120,28 @@ func countState(states []string, want string) int { return n } +// waitForState reads datagrams until one carries want or the window closes. +// The states drain above collects a window's worth; a boot-path test waiting +// for one state returns as soon as it arrives. +func (l *notifyListener) waitForState(t *testing.T, window time.Duration, want string) bool { + t.Helper() + deadline := time.Now().Add(window) + buf := make([]byte, 1024) + for time.Now().Before(deadline) { + if err := l.conn.SetReadDeadline(time.Now().Add(50 * time.Millisecond)); err != nil { + t.Fatalf("set notify read deadline: %v", err) + } + n, _, err := l.conn.ReadFromUnix(buf) + if err != nil { + continue + } + if string(buf[:n]) == want { + return true + } + } + return false +} + // newNotifyTestBoot builds the composition the notify path reads: a boot whose // config holder supplies the run loop's poll cadence, and a real daemon whose // own poll loop stamps the progress marker the heartbeat sampler samples. @@ -363,3 +386,36 @@ func TestNotifySocketFailureIsNotFatal(t *testing.T) { t.Errorf("an unusable notify socket logged %d errors, want none: %v", len(errs), errs) } } + +// TestStateStoreBootAnnouncesReady: archie-state-store run as a Type=notify +// unit must send READY=1 once its boot is over and it is serving the contract, +// or systemd kills a healthy process once TimeoutStartSec expires +// (archie-core-1174). The real RunStateStore composition drives it, over a +// real State Store database, the way the provider-seeding boot test does. +func TestStateStoreBootAnnouncesReady(t *testing.T) { + listener := newNotifyListener(t) + url := pgtest.URL(t) + path := filepath.Join(t.TempDir(), "config.toml") + body := fmt.Sprintf("bot_user = 'archie'\ndatabase_url = %q\n", url) + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + errCh := make(chan error, 1) + go func() { errCh <- RunStateStore(ctx, StateStoreOptions{Config: path, Listen: "127.0.0.1:0"}) }() + + if !listener.waitForState(t, 15*time.Second, readyState) { + select { + case bootErr := <-errCh: + t.Fatalf("RunStateStore exited before announcing ready: %v", bootErr) + default: + t.Fatal("no READY=1 datagram within 15s of boot") + } + } + + cancel() + if err := <-errCh; err != nil && !errors.Is(err, context.Canceled) { + t.Fatalf("RunStateStore shutdown: %v", err) + } +} diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index 66ae01e8e..0bbfff103 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -146,6 +146,14 @@ func RunStateStore(ctx context.Context, options StateStoreOptions) error { //nol if err := b.startOptionalSurfaces(ctx, options); err != nil { return err } + // Boot is over and every listener this process serves is bound: the gRPC + // contract below and, when -ready-addr asked for one, the readiness HTTP + // surface. systemd's READY=1 asserts the same fact, so the announcement + // goes out here rather than from a second notion of "started" + // (archie-core-1174). Not earlier: a readiness surface that fails to bind + // fails the boot, and READY must not precede it. Not later: Serve begins + // accepting the moment it is called. + b.announceReady() deps := b.stateStoreDeps(grants) deps.ControlPlane = control diff --git a/internal/app/controlplane/container_settings.go b/internal/app/controlplane/container_settings.go new file mode 100644 index 000000000..061331b5f --- /dev/null +++ b/internal/app/controlplane/container_settings.go @@ -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) +} diff --git a/internal/app/controlplane/container_settings_test.go b/internal/app/controlplane/container_settings_test.go new file mode 100644 index 000000000..ceea747fc --- /dev/null +++ b/internal/app/controlplane/container_settings_test.go @@ -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) + } + }) + } +} diff --git a/internal/app/controlplane/model_settings_test.go b/internal/app/controlplane/model_settings_test.go new file mode 100644 index 000000000..41ba5e83a --- /dev/null +++ b/internal/app/controlplane/model_settings_test.go @@ -0,0 +1,53 @@ +package controlplane + +import ( + "strings" + "testing" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/storecontract" + "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore" +) + +// TestImportConfigRefusesAResolvedProviderSnapshot pins the last line of +// defence behind the boot seeding order: resolveProviderSecrets exports each +// key under a process-local ARCHIE_PROVIDER_ env name and clears the +// source reference, so a provider-settings seed built from an already-resolved +// snapshot (archie-core-1000's failure shape) carries no reference a later +// boot could resolve. The seed runs through the same Decode a write applies, +// so the validation refusal makes ImportConfig skip the kind and store +// nothing -- the State Store still starts, the file document stays in force, +// and the skip is reported -- rather than persisting a name that dies with +// the process that minted it. +func TestImportConfigRefusesAResolvedProviderSnapshot(t *testing.T) { + resolved := config.Config{Providers: map[string]config.Provider{ + "openai": {Class: "openai", APIKeyEnv: "ARCHIE_PROVIDER_6986D5A05E1DF674_API_KEY"}, + }} + resources := pgstore.Open(t) + defer resources.Close() + + versions, skipped, err := testServer(t, resources).ImportConfig(t.Context(), resolved) + if err != nil { + t.Fatalf("ImportConfig: %v", err) + } + if _, stored := versions[ProviderSettingsKind]; stored { + t.Errorf("provider-settings imported from a resolved snapshot: version %d", versions[ProviderSettingsKind]) + } + var reported bool + for _, skip := range skipped { + if skip.Kind == ProviderSettingsKind { + reported = true + if !strings.Contains(skip.Err.Error(), "boot-derived") { + t.Errorf("skip error = %v, want the boot-derived-name refusal", skip.Err) + } + } + } + if !reported { + t.Errorf("skipped = %+v, want provider-settings reported", skipped) + } + if _, err := resources.Resource(t.Context(), ProviderSettingsKind); err == nil { + t.Fatal("provider-settings was stored from a resolved snapshot") + } else if !strings.Contains(err.Error(), "not found") { + t.Fatalf("Resource = %v, want %v", err, storecontract.ErrResourceNotFound) + } +} diff --git a/internal/app/controlplane/operational_settings.go b/internal/app/controlplane/operational_settings.go index efd280eb1..ff27aa3b7 100644 --- a/internal/app/controlplane/operational_settings.go +++ b/internal/app/controlplane/operational_settings.go @@ -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() - }) -} diff --git a/internal/app/controlplane/runtime_config.go b/internal/app/controlplane/runtime_config.go index 8857c6850..549f36325 100644 --- a/internal/app/controlplane/runtime_config.go +++ b/internal/app/controlplane/runtime_config.go @@ -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 } diff --git a/internal/app/controlplane/runtime_config_test.go b/internal/app/controlplane/runtime_config_test.go index fac59c5d9..efc59d804 100644 --- a/internal/app/controlplane/runtime_config_test.go +++ b/internal/app/controlplane/runtime_config_test.go @@ -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) @@ -594,8 +594,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{ diff --git a/internal/app/controlplane/validators_agree_test.go b/internal/app/controlplane/validators_agree_test.go index 7b0f75b98..592325ca4 100644 --- a/internal/app/controlplane/validators_agree_test.go +++ b/internal/app/controlplane/validators_agree_test.go @@ -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, }, diff --git a/internal/domain/scheduling/schedule_test.go b/internal/domain/scheduling/schedule_test.go index b9285df0e..86f1a9893 100644 --- a/internal/domain/scheduling/schedule_test.go +++ b/internal/domain/scheduling/schedule_test.go @@ -1,7 +1,9 @@ package scheduling import ( + "encoding/json" "errors" + "fmt" "testing" "time" ) @@ -16,6 +18,43 @@ func zoned(year int, month time.Month, day, hour, minute, sec int) time.Time { return time.Date(year, month, day, hour, minute, sec, 0, testZone) } +// TestScheduleIntervalJSON pins the wire contract the schedules document and +// the jobs table both depend on: the interval writes the human string +// time.ParseDuration reads -- never the nanosecond count that once asked an +// operator to type 1800000000000 for one hour -- and reads both forms, because +// every schedule stored before this shape existed carries a count. +func TestScheduleIntervalJSON(t *testing.T) { + for _, tc := range []struct { + name string + encoded string + want Duration + wantString string + }{ + {name: "the string the document writes", encoded: `"30m"`, want: Duration(30 * time.Minute), wantString: "30m0s"}, + {name: "the nanosecond count a legacy document carries", encoded: `1800000000000`, want: Duration(30 * time.Minute), wantString: "30m0s"}, + } { + t.Run(tc.name, func(t *testing.T) { + var got Duration + if err := json.Unmarshal([]byte(tc.encoded), &got); err != nil { + t.Fatalf("Unmarshal(%s): %v", tc.encoded, err) + } + if got != tc.want { + t.Errorf("Unmarshal(%s) = %v, want %v", tc.encoded, got, tc.want) + } + encoded, err := json.Marshal(got) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + if string(encoded) != fmt.Sprintf("%q", tc.wantString) { + t.Errorf("Marshal(%v) = %s, want %q: the document writes the string, never a count", got, encoded, tc.wantString) + } + }) + } + if err := json.Unmarshal([]byte(`"banana"`), new(Duration)); !errors.Is(err, ErrInvalidSpec) { + t.Errorf("Unmarshal(banana) = %v, want ErrInvalidSpec", err) + } +} + func TestScheduleCronNextRun(t *testing.T) { tests := []struct { name string diff --git a/internal/infrastructure/postgres/statestore_test.go b/internal/infrastructure/postgres/statestore_test.go index 9b4018508..9d79aa045 100644 --- a/internal/infrastructure/postgres/statestore_test.go +++ b/internal/infrastructure/postgres/statestore_test.go @@ -267,6 +267,52 @@ func TestResourceWritesPreserveOptimisticAndIdempotentSemantics(t *testing.T) { } } +// A request ID is idempotent per kind: the store API, the resource_history +// UNIQUE(kind, request_id) index and every production caller treat it as one, +// so a caller that mints one request ID for two different kinds must get two +// writes -- the second kind's own revision -- and not the first kind's history +// row replayed under the second kind's name. +func TestResourceRequestIDIsIdempotentPerKind(t *testing.T) { + resources := resourcesFor(t) + at := time.Date(2026, 9, 26, 12, 0, 0, 0, time.UTC) + first, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{ + Kind: "provider-settings", Value: []byte(`{"v":1}`), Actor: "operator", Source: "import", + RequestID: "shared", ExpectedVersion: 0, At: at, + }) + if err != nil { + t.Fatalf("first PutResource: %v", err) + } + second, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{ + Kind: "scheduling-policy", Value: []byte(`{"v":2}`), Actor: "operator", Source: "import", + RequestID: "shared", ExpectedVersion: 0, At: at, + }) + if err != nil { + t.Fatalf("second PutResource with the same request ID: %v", err) + } + if second.Kind != "scheduling-policy" || string(second.Value) != `{"v":2}` || second.Version != 1 { + t.Fatalf("second write = %+v, want scheduling-policy's own revision, not a replay of %+v", second, first) + } + + replay, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{ + Kind: "scheduling-policy", Value: []byte(`{"v":999}`), Actor: "other", Source: "retry", + RequestID: "shared", ExpectedVersion: 0, At: at.Add(time.Minute), + }) + if err != nil { + t.Fatalf("replay PutResource: %v", err) + } + if replay.Version != second.Version || string(replay.Value) != string(second.Value) || replay.Actor != second.Actor { + t.Fatalf("replay = %+v, want scheduling-policy's original %+v", replay, second) + } + + live, err := resources.Resource(t.Context(), "scheduling-policy") + if err != nil { + t.Fatalf("Resource: %v", err) + } + if live.Version != second.Version || string(live.Value) != string(second.Value) { + t.Fatalf("live scheduling-policy = %+v, want second write %+v", live, second) + } +} + // PostgreSQL admits concurrent writers, unlike SQLite's single writer. The // resource lock keeps the expected-version comparison and audit append one // serialized operation. diff --git a/internal/webui/server.go b/internal/webui/server.go index 7e3e4a80c..ece780979 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -17,6 +17,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/events" + "github.com/samcharles93/archie-core/internal/infrastructure/captureintake" "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/ui" ) @@ -338,7 +339,10 @@ func (s *Server) Handler() http.Handler { top.HandleFunc(loginCallbackRoute, s.handleCallback) } if s.CaptureIntake != nil { - top.Handle(captureIntakeRoute, s.CaptureIntake) + // captureintake.Path is the single spelling of this route: the receiver + // owns the route's semantics, so mounting re-spells nothing and a rename + // there cannot silently unmount here. + top.Handle(captureintake.Path, s.CaptureIntake) } // The chain runs after the credential check and before any handler: the // principal exists only once the credential resolved @@ -347,12 +351,6 @@ func (s *Server) Handler() http.Handler { return top } -// captureIntakeRoute is the bypass-mux route the host process's capture -// receiver mounts on. captureintake.Path is the authority for the route's -// semantics; this literal exists so webui can mount an http.Handler without -// depending on the receiver's concrete package. -const captureIntakeRoute = "POST /webhooks/capture/{source}" - // handleHealthz is a liveness probe for local, unauthenticated callers -- // most notably the update watchdog script, which polls it after restarting // archied to decide whether the new version came up or the update needs to