Merge origin/main (v1.44.1) into local main

This commit is contained in:
sam committed 2026-09-30 02:39:21 +10:00
commit cadbc6d1ca
17 files changed
+1056 -45

No files matched your search

+160 -30
View File
@@ -3,6 +3,8 @@ package controlplane
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -73,14 +75,47 @@ type SeedSkip struct {
Err error
}
// ImportConfig seeds every control-plane resource that has no stored value yet
// from the file config, and reports the version of every kind it left alone.
// The audit identity every seed writes under. It is a constant rather than a
// literal at each call site because a later boot reads it back: it is how a
// stored value is told apart from one an operator replaced (seedWroteNewest),
// and a writer whose identity its own reader cannot name cannot make that
// distinction at all.
const (
seedActor = "system:migration"
seedSource = "legacy-config"
)
// ImportConfig brings every control-plane resource up to date with the value
// this build seeds for it, and reports the version each kind is left at.
//
// A seed the resource's own validator refuses is SKIPPED and returned in skipped,
// not fatal. Nothing is written for that kind, so it stays ABSENT and the file
// document's value stays the one in effect (Client.RuntimeConfig leaves an absent
// kind alone), with the fix still in the file. The seed is retried on the next
// start of this process, so correcting config.toml re-seeds it.
// For a kind the store does not hold, that is the seed itself. For a kind it
// does hold, the stored value wins and the seed writes nothing -- with one
// exception, because the two ways a kind gets its content are not symmetric:
//
// - A kind derived from the file config is seeded once and then owned by the
// store. Editing config.toml does not reach a database that holds a value
// for it, which is the whole point of the file being only a seed.
// - A kind whose document the build ships (the ones that set Definition.Defaults,
// the same set the catalog offers as "restore shipped") is not derived from
// operator input at all, so a stored copy is a copy of an older build's
// document and nothing else. A value like that is brought up to date, or a
// State Store upgraded under a running deployment keeps serving the previous
// release's document forever. For workflow-definitions that is not a stale
// setting but an outage: the collection validates as one document, so a
// stored step type this build no longer has fails every task's pin, whatever
// workflow the task names.
//
// A refreshed kind keeps its history: the value it replaced stays a revision in
// resource_history. What is replaced is only the seed's own work -- a
// definition set an operator replaced is theirs and is left alone, on the boot
// that finds it and on every boot after.
//
// A seed the resource's own validator refuses is SKIPPED and returned in
// skipped, not fatal. Nothing is written for that kind, so it stays ABSENT and
// the file document's value stays the one in effect (Client.RuntimeConfig
// leaves an absent kind alone), with the fix still in the file. The seed is
// retried on the next start of this process, so correcting config.toml re-seeds
// it.
// docs/prds/runtime-control-plane.md, "Bootstrap, migration, and recovery":
// after migration, settings in TOML are ignored and cannot block State Store
// startup -- and this import runs on the State Store's startup path. Fail closed
@@ -91,35 +126,130 @@ func (s *Server) ImportConfig(ctx context.Context, cfg config.Config) (map[strin
versions := make(map[string]int64, len(s.ordered))
var skipped []SeedSkip
for _, definition := range s.ordered {
resource, err := s.store.Resource(ctx, definition.Kind)
if err == nil {
versions[definition.Kind] = resource.Version
continue
}
if !errors.Is(err, storecontract.ErrResourceNotFound) {
version, err := s.seedKind(ctx, definition, cfg)
var refusal *seedRefusal
switch {
case errors.As(err, &refusal):
skipped = append(skipped, SeedSkip{Kind: definition.Kind, Err: refusal.err})
case err != nil:
return nil, nil, err
default:
versions[definition.Kind] = version
}
value, err := definition.seededValue(cfg)
if err != nil {
// Skipped and reported, not fatal: nothing is written, so the kind
// stays absent and the file document's value is the one in effect,
// while the process that would RUN the value still fails closed on
// it (boot.runtimeConfig validates the effective document).
// seededValue wraps a seed's encode and validation failures together,
// which is why both take this path: the alternative is a second seed
// implementation here to tell them apart.
skipped = append(skipped, SeedSkip{Kind: definition.Kind, Err: err})
continue
}
resource, err = s.store.PutResource(ctx, storecontract.ResourceWrite{Kind: definition.Kind, Value: value, Actor: "system:migration", Source: "legacy-config", RequestID: "import:" + definition.Kind, ExpectedVersion: 0, At: time.Now().UTC()})
if err != nil {
return nil, nil, fmt.Errorf("seed %s: %w", definition.Kind, err)
}
versions[definition.Kind] = resource.Version
}
return versions, skipped, nil
}
// seedRefusal is the seed's own validation refusing the value this build
// derived. It is an error because it is one -- there is nothing to write -- and a
// distinct type because ImportConfig answers it by reporting the kind rather
// than failing the boot (see ImportConfig on why a bad seed is not fatal).
type seedRefusal struct{ err error }
func (r *seedRefusal) Error() string { return r.err.Error() }
func (r *seedRefusal) Unwrap() error { return r.err }
// seedKind seeds one kind if the store holds nothing for it, refreshes a
// shipped document the seed itself wrote, and otherwise leaves the stored value
// alone, returning the version the kind is left at. A *seedRefusal means the
// value this build derived is not one the resource's validator accepts, and
// nothing was written.
func (s *Server) seedKind(ctx context.Context, definition Definition, cfg config.Config) (int64, error) {
stored, storedErr := s.store.Resource(ctx, definition.Kind)
absent := errors.Is(storedErr, storecontract.ErrResourceNotFound)
if storedErr != nil && !absent {
return 0, storedErr
}
value, err := definition.seededValue(cfg)
if err != nil {
// Skipped and reported, not fatal: nothing is written, so the kind
// stays absent and the file document's value is the one in effect,
// while the process that would RUN the value still fails closed on
// it (boot.runtimeConfig validates the effective document).
// seededValue wraps a seed's encode and validation failures together,
// which is why both take this path: the alternative is a second seed
// implementation here to tell them apart.
return 0, &seedRefusal{err: err}
}
if !absent && bytes.Equal(stored.Value, value) {
// The store already holds what this build seeds. Comparing the values
// rather than re-writing them is what keeps a boot from adding a
// revision for a document that did not change.
return stored.Version, nil
}
if !absent {
refresh, err := s.shippedValueIsStale(ctx, definition)
if err != nil {
return 0, err
}
if !refresh {
return stored.Version, nil
}
}
write := storecontract.ResourceWrite{
Kind: definition.Kind, Value: value,
Actor: seedActor, Source: seedSource,
RequestID: seedRequestID(definition.Kind, value),
ExpectedVersion: expectedVersion(stored, absent), At: time.Now().UTC(),
}
resource, err := s.store.PutResource(ctx, write)
if err != nil {
return 0, fmt.Errorf("seed %s: %w", definition.Kind, err)
}
return resource.Version, nil
}
// expectedVersion is the optimistic-concurrency guard a seed writes under: the
// revision it is replacing, or nothing at all for a kind that has none.
func expectedVersion(stored storecontract.Resource, absent bool) int64 {
if absent {
return 0
}
return stored.Version
}
// shippedValueIsStale reports whether a stored value is the build's to replace:
// the kind ships a document of its own (Defaults is set exactly for those, and
// a file-derived seed never overwrites a stored value) and the revision the
// seed itself wrote is the newest one. A newer revision carrying any other
// identity is an operator's replacement, and an operator's replacement is not
// the seed's to undo.
func (s *Server) shippedValueIsStale(ctx context.Context, definition Definition) (bool, error) {
if definition.Defaults == nil {
return false, nil
}
return s.seedWroteNewest(ctx, definition.Kind)
}
// seedWroteNewest reports whether the newest revision of kind was written by a
// seed. It reads the ledger rather than the current row because the ledger is
// what records who wrote a value, and the row does not.
func (s *Server) seedWroteNewest(ctx context.Context, kind string) (bool, error) {
history, err := s.store.ResourceHistory(ctx, kind, 1)
if err != nil {
return false, fmt.Errorf("read %s history: %w", kind, err)
}
if len(history) == 0 {
return false, nil
}
return history[0].Actor == seedActor && history[0].Source == seedSource, nil
}
// seedRequestID is the idempotency key a seed writes under. It is derived from
// the value rather than from the kind alone, because the key is spent the
// moment it is in the ledger (resource_history's UNIQUE (kind, request_id), and
// PutResource answers a known key from that ledger): a key derived from the
// kind makes every later value a replay of the first one ever written, which is
// how a document that changed in the build never reached a database the seed
// had already written. Deriving it from the value keeps the write idempotent --
// the same document twice is still one revision -- without making the second
// document impossible.
func seedRequestID(kind string, value []byte) string {
sum := sha256.Sum256(value)
return "import:" + kind + ":" + hex.EncodeToString(sum[:])
}
// seededValue is the value the State Store writes for a kind it does not hold
// yet: the definition's seed derived from cfg, run through the same Decode a
// write applies. ImportConfig stores it; the offline config layering reads it
+319
View File
@@ -0,0 +1,319 @@
package controlplane
import (
"bytes"
"encoding/json"
"errors"
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
)
// retiredStepType names a step type no registry declares. A stored collection
// carrying one is what a database seeded by an earlier release holds once a
// built-in workflow's step vocabulary changes under it.
const retiredStepType = "legacy.retired-step"
// staleWorkflowDefinitions is a stored workflow-definitions value this build
// refuses. ValidateDefinitionCollection validates the collection as one
// document, which is what makes one stale entry fail every task's pin, whatever
// workflow that task names.
//
// It is encoded directly rather than through encodeWorkflowDefinitions, because
// that runs the validator a write applies: the point of the fixture is the
// document an earlier release wrote, which this build's write path would refuse
// (the validator cannot bless the value whose rejection is the bug reported).
func staleWorkflowDefinitions(t *testing.T) []byte {
t.Helper()
value, err := json.Marshal(workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{
{ID: "legacy", YAML: "id: legacy\nsteps:\n - type: " + retiredStepType + "\n"},
}})
if err != nil {
t.Fatalf("encode the stale definitions: %v", err)
}
if _, err := workflow.DecodeDefinitionCollection(value, testSteps(t).Registry()); err == nil {
t.Fatal("the stored value under test decodes; it is not the stale state this test is about")
}
return value
}
// writeSeeded writes value as the revision an earlier release's seed left
// behind: the seed's own audit identity, and the seed's own request ID for that
// value. The producer supplies both -- the value is the only thing substituted
// -- so a test does not restate a key or an identity it would then be pinning.
func writeSeeded(t *testing.T, resources *pgstore.TaskDB, kind string, value []byte) storecontract.Resource {
t.Helper()
if current, err := resources.Resource(t.Context(), kind); err == nil {
t.Fatalf("%s already holds version %d; a seeded fixture writes the first revision", kind, current.Version)
} else if !errors.Is(err, storecontract.ErrResourceNotFound) {
t.Fatalf("read %s: %v", kind, err)
}
seeded, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
Kind: kind, Value: value, ExpectedVersion: 0,
Actor: seedActor, Source: seedSource, RequestID: seedRequestID(kind, value),
})
if err != nil {
t.Fatalf("write the seeded %s revision: %v", kind, err)
}
return seeded
}
// replaceAsOperator replaces a kind the way the dashboard does: a write carrying
// the operator's attribution, which is what marks the value as theirs.
func replaceAsOperator(t *testing.T, resources *pgstore.TaskDB, kind string, value []byte, expected int64) storecontract.Resource {
t.Helper()
replaced, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
Kind: kind, Value: value, ExpectedVersion: expected,
Actor: "operator", Source: "archie-ui", RequestID: "operator-replace-" + kind,
})
if err != nil {
t.Fatalf("replace %s: %v", kind, err)
}
return replaced
}
// TestImportConfigRefreshesAStaleShippedValue is defect 1 of #1233. A seed was
// consulted only for a kind the store did not hold, so a document that changed
// in the build never reached a database an earlier release seeded -- and for
// workflow-definitions that is not a stale setting but an outage, because the
// collection validates as one document and a step type this build no longer has
// fails every task's pin.
func TestImportConfigRefreshesAStaleShippedValue(t *testing.T) {
t.Parallel()
resources := pgstore.Open(t)
defer resources.Close()
server := testServer(t, resources)
// The state under test is "the seed's own document, one release old" -- the
// state the issue reports -- rather than "a value somebody else wrote",
// which is the distinction the refresh turns on.
seeded := writeSeeded(t, resources, WorkflowDefinitionsKind, staleWorkflowDefinitions(t))
versions, _, err := server.ImportConfig(t.Context(), config.Config{})
if err != nil {
t.Fatalf("ImportConfig: %v", err)
}
refreshed, err := resources.Resource(t.Context(), WorkflowDefinitionsKind)
if err != nil {
t.Fatal(err)
}
if refreshed.Version <= seeded.Version {
t.Fatalf("%s is still at version %d: the stale seed value was not replaced", WorkflowDefinitionsKind, refreshed.Version)
}
definitions, err := workflow.DecodeDefinitionCollection(refreshed.Value, testSteps(t).Registry())
if err != nil {
t.Fatalf("the stored workflow definitions still do not decode, so no task can pin: %v", err)
}
if len(definitions.Definitions) != len(workflow.ShippedDefinitions().Definitions) {
t.Fatalf("stored definitions = %d, want the shipped %d", len(definitions.Definitions), len(workflow.ShippedDefinitions().Definitions))
}
if versions[WorkflowDefinitionsKind] != refreshed.Version {
t.Fatalf("the import reported version %d, want the version the store holds, %d", versions[WorkflowDefinitionsKind], refreshed.Version)
}
// A refresh is a write like any other: what it replaced stays a revision, so
// the value the previous release shipped is still readable.
history, err := resources.ResourceHistory(t.Context(), WorkflowDefinitionsKind, 0)
if err != nil {
t.Fatal(err)
}
if len(history) != 2 || !bytes.Equal(history[1].Value, staleWorkflowDefinitions(t)) {
t.Fatalf("history = %+v, want the replaced value kept as a revision", history)
}
}
// TestImportConfigLeavesASeededValueAloneOnceItMatches pins the other half of the
// refresh: a boot that finds the value it would write writes nothing. A seed that
// re-wrote its own document on every start would add a revision per boot, and the
// revision an operator reads as "what I am running" would move for no reason.
func TestImportConfigLeavesASeededValueAloneOnceItMatches(t *testing.T) {
t.Parallel()
resources := pgstore.Open(t)
defer resources.Close()
server := testServer(t, resources)
for attempt := 1; attempt <= 2; attempt++ {
if _, _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
t.Fatalf("ImportConfig %d: %v", attempt, err)
}
stored, err := resources.Resource(t.Context(), WorkflowDefinitionsKind)
if err != nil {
t.Fatal(err)
}
if stored.Version != 1 {
t.Fatalf("after %d seed(s) %s is at version %d, want the one revision", attempt, WorkflowDefinitionsKind, stored.Version)
}
}
}
// TestImportConfigKeepsAStoredValueThatIsNotTheSeeds pins the half the refresh
// must not break. The seed writes a value it produced itself; a value it did not
// produce is somebody's, and two kinds of somebody are covered here:
//
// - an operator's replacement, which the seed must leave alone on the boot
// that finds it and on every boot after -- a refresh that consulted the
// store's copy rather than the ledger would take the value back the moment
// it had written it once;
// - a kind derived from the file config, where the file is only a seed by
// design, so a changed config.toml does not reach a database that holds a
// value for it.
func TestImportConfigKeepsAStoredValueThatIsNotTheSeeds(t *testing.T) {
t.Parallel()
tests := []struct {
name string
kind string
// settle leaves the store holding the value the imports must not touch,
// and returns that value.
settle func(t *testing.T, resources *pgstore.TaskDB) []byte
// cfg is the file config the imports run with. For the file-derived
// case it names a different value from the one that was seeded.
cfg func() config.Config
// verify checks the stored value after the imports, given the value
// settle left behind.
verify func(t *testing.T, got, want []byte)
}{
{
name: "an operator's replacement, whose shipped document also moved on",
kind: WorkflowDefinitionsKind,
cfg: func() config.Config { return config.Config{} },
settle: func(t *testing.T, resources *pgstore.TaskDB) []byte {
t.Helper()
// The seed wrote a document this build refuses, and the operator
// then replaced it. The stored value is therefore neither the
// seed's nor the one this build ships, which is exactly the
// state a refresh keyed on authorship has to leave alone.
seeded := writeSeeded(t, resources, WorkflowDefinitionsKind, staleWorkflowDefinitions(t))
value, err := encodeWorkflowDefinitions(workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{
{ID: "operator-only", YAML: "id: operator-only\nsteps:\n - type: bootstrap.apply\n"},
}}, testSteps(t).Registry())
if err != nil {
t.Fatal(err)
}
return replaceAsOperator(t, resources, WorkflowDefinitionsKind, value, seeded.Version).Value
},
verify: func(t *testing.T, got, want []byte) {
t.Helper()
definitions, err := workflow.DecodeDefinitionCollection(got, testSteps(t).Registry())
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, want) || len(definitions.Definitions) != 1 || definitions.Definitions[0].ID != "operator-only" {
t.Fatalf("stored value = %s, want the operator's replacement kept", got)
}
},
},
{
name: "a value derived from the file config, whose config.toml changed",
kind: RepositoryPoliciesKind,
cfg: func() config.Config {
cfg := validConfigForValidation()
cfg.Repos = []config.Repo{{Owner: "acme", Name: "widget"}}
return cfg
},
settle: func(t *testing.T, resources *pgstore.TaskDB) []byte {
t.Helper()
resolved := validConfigForValidation()
resolved.Repos = []config.Repo{{Owner: "acme", Name: "app"}}
if _, _, err := testServer(t, resources).ImportConfig(t.Context(), resolved); err != nil {
t.Fatal(err)
}
stored, err := resources.Resource(t.Context(), RepositoryPoliciesKind)
if err != nil {
t.Fatal(err)
}
return stored.Value
},
verify: func(t *testing.T, got, want []byte) {
t.Helper()
if !bytes.Equal(got, want) {
t.Fatalf("stored repository policies = %s, want the seeded %s: the file is a seed, not the owner", got, want)
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
resources := pgstore.Open(t)
defer resources.Close()
server := testServer(t, resources)
want := tt.settle(t, resources)
before, err := resources.Resource(t.Context(), tt.kind)
if err != nil {
t.Fatal(err)
}
for attempt := 1; attempt <= 2; attempt++ {
versions, _, err := server.ImportConfig(t.Context(), tt.cfg())
if err != nil {
t.Fatalf("ImportConfig %d: %v", attempt, err)
}
after, err := resources.Resource(t.Context(), tt.kind)
if err != nil {
t.Fatal(err)
}
if after.Version != before.Version {
t.Fatalf("import %d moved %s from version %d to %d: the stored value is not the seed's to replace",
attempt, tt.kind, before.Version, after.Version)
}
if versions[tt.kind] != before.Version {
t.Fatalf("import %d reported version %d for %s, want the stored %d", attempt, versions[tt.kind], tt.kind, before.Version)
}
tt.verify(t, after.Value, want)
}
})
}
}
// TestImportConfigRecreatesAKindAnOperatorRemoved is defect 2 of #1233: the
// documented recovery -- remove the resource, restart -- wrote nothing. The seed's
// request ID is in resource_history, that ledger outlives the row it describes,
// and a write whose request ID is already in the ledger is answered as a replay,
// so the seed reported a version for a kind that was not there and left it absent.
func TestImportConfigRecreatesAKindAnOperatorRemoved(t *testing.T) {
t.Parallel()
resources := pgstore.Open(t)
defer resources.Close()
server := testServer(t, resources)
if _, _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
t.Fatal(err)
}
seeded, err := resources.Resource(t.Context(), WorkflowDefinitionsKind)
if err != nil {
t.Fatal(err)
}
history, err := resources.ResourceHistory(t.Context(), WorkflowDefinitionsKind, 0)
if err != nil {
t.Fatal(err)
}
if len(history) != 1 {
t.Fatalf("seed revisions = %d, want the one the removal leaves behind", len(history))
}
if _, err := resources.Pool.Exec(t.Context(), `DELETE FROM resources WHERE kind = $1`, WorkflowDefinitionsKind); err != nil {
t.Fatalf("remove the resource: %v", err)
}
if _, err := resources.Resource(t.Context(), WorkflowDefinitionsKind); !errors.Is(err, storecontract.ErrResourceNotFound) {
t.Fatalf("resource after the removal = %v, want ErrResourceNotFound", err)
}
if _, _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
t.Fatalf("ImportConfig after the removal: %v", err)
}
restored, err := resources.Resource(t.Context(), WorkflowDefinitionsKind)
if err != nil {
t.Fatalf("the removed %s was not re-seeded: %v", WorkflowDefinitionsKind, err)
}
if restored.Version != seeded.Version || !bytes.Equal(restored.Value, seeded.Value) {
t.Fatalf("re-seeded %s = version %d, want the seed back at version %d", WorkflowDefinitionsKind, restored.Version, seeded.Version)
}
if _, err := workflow.DecodeDefinitionCollection(restored.Value, testSteps(t).Registry()); err != nil {
t.Fatalf("the re-seeded workflow definitions do not decode: %v", err)
}
}
@@ -28,7 +28,10 @@ type executionSettingsDocument struct {
}
// ImportWorkflowExecutionSettings preserves the focused bootstrap API for callers
// that do not own the complete legacy configuration document.
// that do not own the complete legacy configuration document. It is the same
// producer rule as ImportConfig, at this narrower entry point: a kind the store
// holds is left alone, and a kind it does not hold is seeded under the one seed
// identity (see seedActor and seedRequestID).
func (s *Server) ImportWorkflowExecutionSettings(ctx context.Context, settings workflow.ExecutionSettings) (int64, error) {
resource, err := s.store.Resource(ctx, WorkflowExecutionSettingsKind)
if err == nil {
@@ -45,7 +48,7 @@ func (s *Server) ImportWorkflowExecutionSettings(ctx context.Context, settings w
if err != nil {
return 0, err
}
resource, err = s.store.PutResource(ctx, storecontract.ResourceWrite{Kind: WorkflowExecutionSettingsKind, Value: value, Actor: "system:migration", Source: "legacy-config", RequestID: "import:" + WorkflowExecutionSettingsKind, ExpectedVersion: 0, At: time.Now().UTC()})
resource, err = s.store.PutResource(ctx, storecontract.ResourceWrite{Kind: WorkflowExecutionSettingsKind, Value: value, Actor: seedActor, Source: seedSource, RequestID: seedRequestID(WorkflowExecutionSettingsKind, value), ExpectedVersion: 0, At: time.Now().UTC()})
return resource.Version, err
}
+45 -4
View File
@@ -1842,11 +1842,33 @@ func (d *Daemon) publicationGrant(ctx context.Context, task *workflow.Task) (str
return grant, revoke, true
}
// pinWorkflowDefinition puts the task's workflow definition pin in the state
// the worker's compile requires before it runs a dispatch: a stored definition
// that names the workflow the task row names
// (agentworker.CompilePinnedWorkflow).
//
// A pin that is present, hash-valid and id-consistent is reused unchanged, so
// the definition an operator had active when the task was pinned survives every
// later dispatch even after the active definition moved on. Anything else -- no
// pin, or a pin naming a workflow this task no longer runs -- is resolved again
// from the active collection for the workflow the task names.
//
// The re-pin is what makes the waiting_human -> approved requeue dispatchable:
// RequeueTask writes the new workflow column and leaves the previous run's
// definition pinned, so the requeued row carries the two half-state values the
// worker refuses to run. Resolving here, at the write, is where the row
// becomes valid; a consumer that repaired it would only be tolerating a state
// this producer is responsible for.
//
// An already-pinned definition is deliberately NOT refreshed to the operator's
// current active one: a run's definition is pinned once, so a mid-flight
// change to a definition never alters work already in progress.
func (d *Daemon) pinWorkflowDefinition(ctx context.Context, task *workflow.Task) error {
if task.WorkflowDefinitionYAML != "" {
if workflow.DigestDefinition(task.WorkflowDefinitionYAML) != task.WorkflowDefinitionDigest {
return fmt.Errorf("stored workflow definition digest mismatch")
}
pinned, ok, err := pinnedDefinitionID(task)
if err != nil {
return err
}
if ok && pinned == task.Workflow {
return nil
}
d.runActionPlaybooks(ctx, task)
@@ -1860,6 +1882,25 @@ func (d *Daemon) pinWorkflowDefinition(ctx context.Context, task *workflow.Task)
return d.pinWorkflowFromCollection(ctx, task, collection, version)
}
// pinnedDefinitionID reports the workflow a task's stored definition pin names,
// with ok false for a task carrying no pin. It enforces what this package owns
// about a stored pin: the YAML hashes to the digest recorded beside it, and it
// declares an id at all. A pin failing either is a row an operator has to
// resolve, not one to silently overwrite.
func pinnedDefinitionID(task *workflow.Task) (string, bool, error) {
if task.WorkflowDefinitionYAML == "" {
return "", false, nil
}
if workflow.DigestDefinition(task.WorkflowDefinitionYAML) != task.WorkflowDefinitionDigest {
return "", false, fmt.Errorf("stored workflow definition digest mismatch")
}
id, err := workflow.DefinitionID(task.WorkflowDefinitionYAML)
if err != nil {
return "", false, fmt.Errorf("stored workflow definition: %w", err)
}
return id, true, nil
}
// runActionPlaybooks runs the action playbooks matching a task that is about
// to be pinned, which happens once per task (docs/prds/action-playbook-run.md).
// A run never affects routing and its failure never fails the task. A task
+246
View File
@@ -2,6 +2,8 @@ package daemon
import (
"context"
"log/slog"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/workflow"
@@ -46,3 +48,247 @@ func TestWorkflowDefinitionPinSurvivesActiveOverride(t *testing.T) {
t.Fatal("persisted workflow digest does not identify the pinned YAML")
}
}
// TestPinWorkflowDefinitionRepinsWhenTheTaskNamesAnotherWorkflow covers the
// waiting_human -> approved requeue: RequeueTask writes the new workflow name
// and leaves the previous run's definition pinned, so the requeued row carries
// a workflow column and a stored definition that disagree.
//
// Those two are what the worker's compile refuses at dispatch
// (agentworker.CompilePinnedWorkflow: "pinned workflow definition does not
// match task identity"), so a pin that names a different workflow than the
// task is a dispatch that can never run, and the daemon -- the producer that
// wrote the pin -- re-pins it from the collection the task's workflow is
// resolved out of. A pin that is present, digest-valid AND id-consistent stays
// a strict no-op, so an operator's newer active definition does not overwrite
// a task's existing pin on the next dispatch.
func TestPinWorkflowDefinitionRepinsWhenTheTaskNamesAnotherWorkflow(t *testing.T) {
const (
pinnedVersion = 4
activeVersion = 9
)
feasibilityPin := "id: feasibility\nsteps:\n - type: feasibility.assess\n"
customPin := "id: custom\nsteps:\n - type: bootstrap.apply\n"
// The active collection is the one the daemon resolves a named workflow
// out of. Its "custom" entry is deliberately different YAML from customPin:
// that is the operator's newer active definition, and the only way to tell
// a reuse from a re-pin is that a reused pin keeps the older YAML.
active := &workflowDefinitionsStub{
collection: workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{
{ID: "feasibility", YAML: feasibilityPin},
{ID: "implement", YAML: "id: implement\nsteps:\n - type: implement.prepare\n"},
{ID: "custom", YAML: "id: custom\nsteps:\n - type: bootstrap.prepare\n"},
}},
version: activeVersion,
}
tests := []struct {
name string
// taskWorkflow is the row's workflow column: what the requeue wrote,
// and the workflow the pinned definition must end up naming.
taskWorkflow string
// pinnedYAML is the definition the row carries into the dispatch --
// for a requeue, the workflow the task ran before its workflow column
// changed.
pinnedYAML string
// shipped pins from the shipped definitions, the way a daemon with no
// definitions provider does.
shipped bool
wantWorkflow string
wantYAML string
wantVersion int64
}{
{
name: "a requeue onto another workflow is re-pinned from the active collection",
taskWorkflow: "implement",
pinnedYAML: feasibilityPin,
wantWorkflow: "implement",
wantYAML: "id: implement\nsteps:\n - type: implement.prepare\n",
wantVersion: activeVersion,
},
{
name: "a daemon with no definitions provider re-pins from the shipped set",
taskWorkflow: "implement",
pinnedYAML: feasibilityPin,
shipped: true,
wantWorkflow: "implement",
wantVersion: 0,
},
{
name: "an id-consistent pin is reused, so an active override does not displace it",
taskWorkflow: "custom",
pinnedYAML: customPin,
wantWorkflow: "custom",
wantYAML: customPin,
wantVersion: pinnedVersion,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
wantYAML := tt.wantYAML
if tt.shipped {
entry, ok := workflow.ShippedDefinitions().DefinitionByID(tt.wantWorkflow)
if !ok {
t.Fatalf("shipped definitions have no %q", tt.wantWorkflow)
}
wantYAML = entry.YAML
}
resources := pgstore.Open(t)
defer resources.Close()
task, err := resources.EnqueueChatTask(t.Context(), "acme", "widget", tt.name, "", tt.taskWorkflow, "operator", nil)
if err != nil {
t.Fatal(err)
}
// RequeueTask sets status, workflow and park_reason, and never
// touches the workflow_definition_* columns, so this is the row a
// requeue hands to the next dispatch: the new workflow name over
// the previous run's definition.
task.WorkflowDefinitionYAML = tt.pinnedYAML
task.WorkflowDefinitionDigest = workflow.DigestDefinition(tt.pinnedYAML)
task.WorkflowDefinitionVersion = pinnedVersion
if err := resources.Update(t.Context(), task); err != nil {
t.Fatal(err)
}
d := &Daemon{Store: resources, Log: slog.New(slog.DiscardHandler)}
if !tt.shipped {
d.WorkflowDefinitions = active
}
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
t.Fatalf("pinWorkflowDefinition: %v", err)
}
if task.Workflow != tt.wantWorkflow || task.WorkflowDefinitionYAML != wantYAML || task.WorkflowDefinitionVersion != tt.wantVersion {
t.Fatalf("pin = (%q, version %d, %q),\nwant (%q, version %d, %q)",
task.Workflow, task.WorkflowDefinitionVersion, task.WorkflowDefinitionYAML,
tt.wantWorkflow, tt.wantVersion, wantYAML)
}
stored, err := resources.TaskByID(t.Context(), task.ID)
if err != nil {
t.Fatal(err)
}
if stored.Workflow != tt.wantWorkflow || stored.WorkflowDefinitionYAML != wantYAML || stored.WorkflowDefinitionVersion != tt.wantVersion {
t.Fatalf("persisted pin = (%q, version %d, %q),\nwant (%q, version %d, %q)",
stored.Workflow, stored.WorkflowDefinitionVersion, stored.WorkflowDefinitionYAML,
tt.wantWorkflow, tt.wantVersion, wantYAML)
}
requirePinMatchesTaskIdentity(t, stored)
})
}
}
// TestApproveRequeueRepinsTheWorkflowDefinition reproduces the operator-visible
// defect end to end through the real store writes: a task runs feasibility,
// parks waiting_human with the feasibility definition pinned, and the approval
// requeue moves it to the implement workflow. RequeueTask sets status, workflow
// and park_reason and leaves the workflow_definition_* columns, so the next
// dispatch met an id mismatch and the worker's compile parked the task again --
// identically on every further approval, leaving decline the only working
// action.
//
// What the task row must satisfy before that dispatch is the worker's own
// precondition (agentworker.CompilePinnedWorkflow), asserted here through
// requirePinMatchesTaskIdentity.
func TestApproveRequeueRepinsTheWorkflowDefinition(t *testing.T) {
resources := pgstore.Open(t)
defer resources.Close()
if _, err := resources.EnqueueChatTask(t.Context(), "acme", "widget", "feature request", "", "feasibility", "operator", nil); err != nil {
t.Fatal(err)
}
claim, err := resources.ClaimNext(t.Context())
if err != nil || claim == nil {
t.Fatalf("claim: (%v, %v)", claim, err)
}
// The run pins the feasibility definition and parks for the human decision.
provider := &workflowDefinitionsStub{collection: workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{
{ID: "feasibility", YAML: "id: feasibility\nsteps:\n - type: feasibility.assess\n"},
{ID: "implement", YAML: "id: implement\nsteps:\n - type: implement.prepare\n"},
}}, version: 2}
d := &Daemon{Store: resources, Log: slog.New(slog.DiscardHandler), WorkflowDefinitions: provider}
if err := d.pinWorkflowDefinition(t.Context(), claim); err != nil {
t.Fatal(err)
}
if err := resources.Transition(t.Context(), claim.ID, "running", "waiting_human", "PRD delivered, awaiting go/no-go"); err != nil {
t.Fatal(err)
}
// The operator approves: the same write taskactions.Service.apply performs.
if err := resources.Requeue(t.Context(), claim.ID, "waiting_human", "implement"); err != nil {
t.Fatal(err)
}
requeued, err := resources.TaskByID(t.Context(), claim.ID)
if err != nil {
t.Fatal(err)
}
if requeued.Workflow != "implement" {
t.Fatalf("requeued workflow = %q, want implement", requeued.Workflow)
}
if got, err := workflow.DefinitionID(requeued.WorkflowDefinitionYAML); err != nil || got != "feasibility" {
t.Fatalf("the requeue changed the stored pin to (%q, %v); this test only means anything while the pin is still the previous workflow's", got, err)
}
// The next dispatch re-pins before the worker's compile sees the row.
if err := d.pinWorkflowDefinition(t.Context(), requeued); err != nil {
t.Fatal(err)
}
stored, err := resources.TaskByID(t.Context(), requeued.ID)
if err != nil {
t.Fatal(err)
}
requirePinMatchesTaskIdentity(t, stored)
}
// TestPinWorkflowDefinitionRefusesATamperedPin keeps the digest half of the
// guard intact: a stored definition that does not hash to the digest recorded
// with it is a corrupt row, and repairing it here would silently run a
// definition nobody wrote. It is refused, and the row is left for an operator.
func TestPinWorkflowDefinitionRefusesATamperedPin(t *testing.T) {
resources := pgstore.Open(t)
defer resources.Close()
task, err := resources.EnqueueChatTask(t.Context(), "acme", "widget", "tampered", "", "implement", "operator", nil)
if err != nil {
t.Fatal(err)
}
task.WorkflowDefinitionYAML = "id: implement\nsteps:\n - type: implement.prepare\n"
task.WorkflowDefinitionDigest = workflow.DigestDefinition("id: implement\nsteps:\n - type: implement.build\n")
if err := resources.Update(t.Context(), task); err != nil {
t.Fatal(err)
}
d := &Daemon{Store: resources, Log: slog.New(slog.DiscardHandler), WorkflowDefinitions: &workflowDefinitionsStub{
collection: workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{
{ID: "implement", YAML: "id: implement\nsteps:\n - type: implement.prepare\n"},
}},
version: 3,
}}
err = d.pinWorkflowDefinition(t.Context(), task)
if err == nil || !strings.Contains(err.Error(), "digest mismatch") {
t.Fatalf("pinWorkflowDefinition error = %v, want a digest mismatch refusal", err)
}
if task.WorkflowDefinitionVersion != 0 {
t.Fatalf("refused pin wrote version %d; a refused pin must leave the row alone", task.WorkflowDefinitionVersion)
}
}
// requirePinMatchesTaskIdentity holds a persisted pin to the invariant the
// worker's compile enforces before it runs a dispatch
// (agentworker.CompilePinnedWorkflow): the pinned definition compiles against
// the process vocabulary, names the workflow the task row names, and hashes to
// the digest stored beside it. A producer that leaves a pin failing this is
// the defect that parks a requeued task forever.
func requirePinMatchesTaskIdentity(t *testing.T, stored *workflow.Task) {
t.Helper()
compiled, err := workflow.ParseAndCompile(stored.WorkflowDefinitionYAML, workflow.BuiltinStepRegistry())
if err != nil {
t.Fatalf("pinned definition does not compile: %v", err)
}
if compiled.Name != stored.Workflow {
t.Fatalf("pinned definition names %q, the task row names %q: the worker's compile refuses this pair", compiled.Name, stored.Workflow)
}
if got := workflow.DigestDefinition(stored.WorkflowDefinitionYAML); got != stored.WorkflowDefinitionDigest {
t.Fatalf("pinned definition digest = %s, the row records %s", got, stored.WorkflowDefinitionDigest)
}
}
+22
View File
@@ -105,6 +105,28 @@ func DigestDefinition(src string) string {
return hex.EncodeToString(sum[:])
}
// DefinitionID returns the workflow id a definition declares without compiling
// it. It is the identity half of DigestDefinition, for the readers that hold
// only stored YAML: a pin's id and the task's workflow column have to agree
// before a dispatch runs, and DigestDefinition cannot answer that.
//
// It reads the single declared id and ignores the rest, so it neither needs a
// step registry nor rejects a definition written against a vocabulary the
// caller does not have. ParseDefinition stays the validator; this is only the
// name.
func DefinitionID(src string) (string, error) {
var declared struct {
ID string `yaml:"id"`
}
if err := yaml.Unmarshal([]byte(src), &declared); err != nil {
return "", fmt.Errorf("parse workflow YAML: %w", err)
}
if strings.TrimSpace(declared.ID) == "" {
return "", fmt.Errorf("workflow id is required")
}
return declared.ID, nil
}
// WorkflowDefinitionEntry and WorkflowDefinitionCollection are defined in
// package task so dashboards can decode the stored projection without linking
// the engine. Validation and compilation stay here.
@@ -33,6 +33,58 @@ func TestParseDefinitionAllowsRepeatingAnOperation(t *testing.T) {
}
}
// TestDefinitionIDReadsTheDeclaredWorkflowName covers the identity a stored
// definition carries: DefinitionID answers "which workflow is this" for a
// reader holding only YAML, without a step registry and without rejecting a
// definition written against a vocabulary this process does not have (which is
// why a daemon cannot answer it by compiling).
func TestDefinitionIDReadsTheDeclaredWorkflowName(t *testing.T) {
tests := []struct {
name string
src string
want string
err string
}{
{
name: "the shipped feasibility definition names itself",
src: "id: feasibility\nsteps:\n - type: feasibility.assess\n",
want: "feasibility",
},
{
name: "an unregistered step type is still an answerable id",
src: "id: operator-local\nsteps:\n - type: plugin.step\n",
want: "operator-local",
},
{
name: "a definition with no id is refused",
src: "steps:\n - type: feasibility.assess\n",
err: "id is required",
},
{
name: "malformed YAML is refused",
src: "id: [unterminated\n",
err: "parse workflow YAML",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := DefinitionID(tt.src)
if tt.err != "" {
if err == nil || !strings.Contains(err.Error(), tt.err) {
t.Fatalf("DefinitionID() error = %v, want %q", err, tt.err)
}
return
}
if err != nil {
t.Fatalf("DefinitionID: %v", err)
}
if got != tt.want {
t.Fatalf("DefinitionID() = %q, want %q", got, tt.want)
}
})
}
}
func TestShippedDefinitionsEmitDeclaredInputsForPRReview(t *testing.T) {
entry, ok := ShippedDefinitions().DefinitionByID("pr-review")
if !ok {
@@ -108,6 +108,43 @@ func (q *Queries) LockResourceWrite(ctx context.Context, hashtextextended string
return err
}
const reinsertResource = `-- name: ReinsertResource :one
INSERT INTO resources (kind, value, version, updated_at)
VALUES ($1, $2, $3, $4)
RETURNING kind, value, version, updated_at, org_id
`
type ReinsertResourceParams struct {
Kind string
Value []byte
Version int64
UpdatedAt time.Time
}
// Re-creates the current row for a revision resource_history already records.
// The ledger outlives the row it describes, so a resource an operator removed
// still has its revisions; putting one back needs the row re-created without a
// second ledger entry, which idx_resource_history_kind_request would refuse.
// The revision is the ledger's, not a fresh one: this is the row that write
// produced, restored.
func (q *Queries) ReinsertResource(ctx context.Context, arg ReinsertResourceParams) (Resource, error) {
row := q.db.QueryRow(ctx, reinsertResource,
arg.Kind,
arg.Value,
arg.Version,
arg.UpdatedAt,
)
var i Resource
err := row.Scan(
&i.Kind,
&i.Value,
&i.Version,
&i.UpdatedAt,
&i.OrgID,
)
return i, err
}
const resourceByKind = `-- name: ResourceByKind :one
SELECT kind, value, version, updated_at, org_id FROM resources WHERE kind = $1
`
@@ -13,6 +13,17 @@ SELECT kind, value, version, actor, source, request_id, expected_version,
FROM resource_history
WHERE kind = $1 AND request_id = $2;
-- name: ReinsertResource :one
-- Re-creates the current row for a revision resource_history already records.
-- The ledger outlives the row it describes, so a resource an operator removed
-- still has its revisions; putting one back needs the row re-created without a
-- second ledger entry, which idx_resource_history_kind_request would refuse.
-- The revision is the ledger's, not a fresh one: this is the row that write
-- produced, restored.
INSERT INTO resources (kind, value, version, updated_at)
VALUES ($1, $2, $3, $4)
RETURNING kind, value, version, updated_at, org_id;
-- name: ResourceHistory :many
SELECT kind, value, version, actor, source, request_id, expected_version,
current_version, at
+42 -4
View File
@@ -78,6 +78,17 @@ func (s *Resources) Audit(ctx context.Context, table string, keys []string, limi
return entries, nil
}
// PutResource applies one control-plane resource write.
//
// It is idempotent per request ID: a write whose (kind, request_id) is already
// in resource_history returns that revision instead of writing a second one, so a
// retry that reached the store twice is still one revision. The ledger is what
// carries the key -- resource_history outlives the row it describes -- so a
// replay of a revision whose resource an operator removed re-creates that row
// rather than answering with a revision the store no longer holds. The
// alternative is a write that reports a version for a kind that is absent: the
// caller cannot tell the difference, and a kind can stay gone while every
// process believes it holds a value.
func (s *Resources) PutResource(ctx context.Context, write storecontract.ResourceWrite) (_ storecontract.Resource, retErr error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
@@ -91,10 +102,11 @@ func (s *Resources) PutResource(ctx context.Context, write storecontract.Resourc
if existing, err := queries.ResourceByRequest(ctx, postgresdb.ResourceByRequestParams{
Kind: write.Kind, RequestID: write.RequestID,
}); err == nil {
return resourceFromAudit(
existing.Kind, existing.Value, existing.Version, existing.Actor, existing.Source,
existing.RequestID, existing.ExpectedVersion, existing.CurrentVersion, existing.At,
), nil
resource, err := s.replayedResource(ctx, queries, tx, existing)
if err != nil {
return storecontract.Resource{}, err
}
return resource, nil
} else if !errors.Is(err, pgx.ErrNoRows) {
return storecontract.Resource{}, err
}
@@ -150,6 +162,32 @@ func (s *Resources) PutResource(ctx context.Context, write storecontract.Resourc
), nil
}
// replayedResource answers a write whose request ID resource_history already
// holds. The ledger's revision is the answer and a replay writes nothing, with
// one repair: when the resource that revision describes is no longer the current
// row, the row is re-created from it. That is the state an operator removing a
// resource leaves behind, and without the repair the store answers with a
// revision it does not hold, so the caller reads a version for a kind that is
// absent and the kind stays absent.
func (s *Resources) replayedResource(ctx context.Context, queries *postgresdb.Queries, tx pgx.Tx, existing postgresdb.ResourceByRequestRow) (storecontract.Resource, error) {
if _, err := queries.ResourceByKind(ctx, existing.Kind); errors.Is(err, pgx.ErrNoRows) {
if _, err := queries.ReinsertResource(ctx, postgresdb.ReinsertResourceParams{
Kind: existing.Kind, Value: existing.Value, Version: existing.Version, UpdatedAt: existing.At,
}); err != nil {
return storecontract.Resource{}, err
}
if err := tx.Commit(ctx); err != nil {
return storecontract.Resource{}, err
}
} else if err != nil {
return storecontract.Resource{}, err
}
return resourceFromAudit(
existing.Kind, existing.Value, existing.Version, existing.Actor, existing.Source,
existing.RequestID, existing.ExpectedVersion, existing.CurrentVersion, existing.At,
), nil
}
func resourceFromCurrent(resource postgresdb.Resource) storecontract.Resource {
return storecontract.Resource{
Kind: resource.Kind, Value: resource.Value, Version: resource.Version, At: resource.UpdatedAt,
@@ -267,6 +267,70 @@ func TestResourceWritesPreserveOptimisticAndIdempotentSemantics(t *testing.T) {
}
}
// A write is idempotent per request ID, and the ledger holding those IDs
// outlives the row it describes. So a replay whose resource is gone must
// re-create it: answering with the ledger's revision alone reports a version for
// a kind the store does not hold, and a caller cannot tell that apart from a
// resource that is there. An operator removing a resource and restarting the
// process that seeds it is the shape this repairs.
func TestResourceReplayRecreatesARemovedResource(t *testing.T) {
pool, _ := migrated(t)
resources := NewResources(pool)
at := time.Date(2026, 9, 27, 9, 0, 0, 0, time.UTC)
write := storecontract.ResourceWrite{
Kind: "workflow-definitions", Value: []byte(`{"definitions":[]}`), Actor: "system:migration",
Source: "legacy-config", RequestID: "import:workflow-definitions", ExpectedVersion: 0, At: at,
}
seeded, err := resources.PutResource(t.Context(), write)
if err != nil {
t.Fatalf("seed PutResource: %v", err)
}
if _, err := pool.Exec(t.Context(), `DELETE FROM resources WHERE kind = $1`, write.Kind); err != nil {
t.Fatalf("remove the resource: %v", err)
}
if _, err := resources.Resource(t.Context(), write.Kind); !errors.Is(err, storecontract.ErrResourceNotFound) {
t.Fatalf("resource after the removal = %v, want ErrResourceNotFound", err)
}
replayed, err := resources.PutResource(t.Context(), write)
if err != nil {
t.Fatalf("replay PutResource: %v", err)
}
if replayed.Version != seeded.Version || string(replayed.Value) != string(seeded.Value) {
t.Fatalf("replay = %+v, want the revision the ledger records, %+v", replayed, seeded)
}
live, err := resources.Resource(t.Context(), write.Kind)
if err != nil {
t.Fatalf("the replay did not re-create the resource: %v", err)
}
if live.Version != seeded.Version || string(live.Value) != string(seeded.Value) {
t.Fatalf("live resource after the replay = %+v, want the restored %+v", live, seeded)
}
// The repair re-creates the row the write produced; it does not append a
// second ledger entry, which idx_resource_history_kind_request would refuse.
history, err := resources.ResourceHistory(t.Context(), write.Kind, 0)
if err != nil {
t.Fatalf("ResourceHistory: %v", err)
}
if len(history) != 1 {
t.Fatalf("history after the replay = %d revisions, want the one the write made", len(history))
}
// A resource the store still holds is answered from the ledger, unchanged:
// the idempotent replay the index exists for.
again, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
Kind: write.Kind, Value: []byte(`{"definitions":[{"id":"different"}]}`), Actor: "other",
Source: "retry", RequestID: write.RequestID, ExpectedVersion: 0, At: at.Add(time.Minute),
})
if err != nil {
t.Fatalf("second replay: %v", err)
}
if again.Version != seeded.Version || string(again.Value) != string(seeded.Value) {
t.Fatalf("second replay = %+v, want the original %+v", again, seeded)
}
}
// 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