fix(eda): classify actions references by ident/static access counts

Replace the per-form actions select/index special-casing with one AST
visitor that counts actions identifier nodes and statically-resolvable
accesses. resolvable = (identCount == staticCount): any actions read not
consumed by a static access (non-literal index, in operator, size, bare
actions, equality) now fails playbook load instead of slipping through to
a runtime miss.
This commit is contained in:
sam committed 2026-09-22 04:36:28 +10:00
1 parent 753a9f9655
commit c36983d0b1
4 files changed
+192 -152

No files matched your search

+50 -49
View File
@@ -16,7 +16,6 @@
package expr
import (
"fmt"
"sort"
"cel.dev/cel-go/cel"
@@ -67,14 +66,15 @@ func NewEnv() *Env {
// Compile parses and type-checks a playbook expression string against the
// declared context. A syntax error, an unknown root (anything other than
// event/actions), a type error, or a non-literal `actions` index
// (`actions[event.name]`, `actions["a" + "b"]`) is a returned error -- never
// a panic. The returned Program is safe to evaluate concurrently (CEL
// programs are stateless once compiled).
// event/actions), or a type error is a returned error -- never a panic. The
// returned Program is safe to evaluate concurrently (CEL programs are
// stateless once compiled).
//
// This is the reject-at-load entry point: the playbook loader and the lint
// tool call this at load time, so a bad expression drops the playbook with a
// reported error rather than failing at dispatch.
// Compile does not decide whether every `actions` read can be pinned to a
// prior action id at load; that classification is Program.ActionReferences'
// job, and the playbook loader rejects a program whose ActionReferences
// reports unresolvable. The split keeps author-time diagnostics and runtime
// evaluation on the same compiled artifact.
func (e *Env) Compile(src string) (*Program, error) {
ast, issues := e.celEnv.Compile(src)
if issues != nil && issues.Err() != nil {
@@ -84,42 +84,44 @@ func (e *Env) Compile(src string) (*Program, error) {
if err != nil {
return nil, err
}
ids, err := referencedActionIDs(ast)
if err != nil {
return nil, err
}
return &Program{prg: prg, actionIDs: ids}, nil
ids, resolvable := actionReferences(ast)
return &Program{prg: prg, actionIDs: ids, resolvable: resolvable}, nil
}
// referencedActionIDs walks the compiled AST and returns the sorted, de-
// duplicated set of action ids an expression reads from `actions`. Both
// field-selection (`actions.notify`) and literal map-index
// (`actions["notify"]`) forms are collected; `actions` is declared
// map(string,dyn), so CEL type-checking cannot reject an unknown id, and the
// playbook loader compares this set against the ids of prior actions to
// reject unknown references at load (J1 in
// docs/prds/playbook-expression-syntax.md).
// actionReferences walks the compiled AST once and classifies every read of
// the `actions` context root as either a statically-resolvable action id or
// not. The invariant is exhaustive by construction: each read of `actions`
// consumes exactly one `actions` identifier node, so counting identifier
// nodes and counting the reads that match one of the two static access
// shapes (a field selection on the `actions` ident, or a map index whose key
// is a string literal) yields
//
// A non-literal index key (`actions[key]`, `actions[event.name]`,
// `actions["a" + "b"]`) is rejected here with an error: its id cannot be
// resolved statically, so it cannot be checked against declared prior-action
// ids and must not pass the load check as a runtime miss.
func referencedActionIDs(ast *cel.Ast) ([]string, error) {
// resolvable = (identCount == staticCount)
//
// Any other spelling that mentions `actions` contributes an identifier node
// without a matching static access, so it reports unresolvable rather than
// slipping through as a runtime miss. The returned ids are the sorted,
// de-duplicated ids of the static accesses, for the playbook loader's
// unknown-id check.
func actionReferences(ast *cel.Ast) ([]string, bool) {
if ast == nil || ast.NativeRep() == nil {
return nil, nil
return nil, true
}
var identCount, staticCount int
seen := map[string]struct{}{}
var walkErr error
visitor := celast.NewExprVisitor(func(e celast.Expr) {
if walkErr != nil {
return
}
switch e.Kind() {
case celast.IdentKind:
if e.AsIdent() == "actions" {
identCount++
}
case celast.SelectKind:
sel := e.AsSelect()
if isActionsIdent(sel.Operand()) {
seen[sel.FieldName()] = struct{}{}
if !isActionsIdent(sel.Operand()) {
return
}
staticCount++
seen[sel.FieldName()] = struct{}{}
case celast.CallKind:
call := e.AsCall()
if call.FunctionName() != "_[_]" || len(call.Args()) != 2 {
@@ -130,27 +132,23 @@ func referencedActionIDs(ast *cel.Ast) ([]string, error) {
}
key := call.Args()[1]
if key.Kind() != celast.LiteralKind {
walkErr = fmt.Errorf("non-literal actions index key (want a string literal)")
return
}
id, ok := key.AsLiteral().Value().(string)
if !ok {
walkErr = fmt.Errorf("non-literal actions index key (want a string literal)")
return
}
staticCount++
seen[id] = struct{}{}
}
})
celast.PreOrderVisit(ast.NativeRep().Expr(), visitor)
if walkErr != nil {
return nil, walkErr
}
ids := make([]string, 0, len(seen))
for id := range seen {
ids = append(ids, id)
}
sort.Strings(ids)
return ids, nil
return ids, identCount == staticCount
}
// isActionsIdent reports whether e is the `actions` context-root identifier.
@@ -160,20 +158,23 @@ func isActionsIdent(e celast.Expr) bool {
// Program is a compiled, cost-limited playbook expression.
type Program struct {
prg cel.Program
actionIDs []string
prg cel.Program
actionIDs []string
resolvable bool
}
// ReferencedActionIDs returns the sorted, de-duplicated action ids the
// expression reads from `actions` (either `actions.<id>` or
// `actions["<id>"]`). It is empty when the expression reads no prior-action
// result. A non-literal index (`actions[event.name]`) never reaches this
// method: it is rejected at Compile.
func (p *Program) ReferencedActionIDs() []string {
// ActionReferences reports the action ids the expression reads from the
// `actions` context root (sorted, de-duplicated) and whether every `actions`
// read could be statically resolved to one of those ids. ids is empty when
// the expression reads no prior-action result; resolvable is false when the
// expression reads `actions` in any form that cannot be pinned to a prior
// action id at load. The playbook loader rejects a non-resolvable program
// rather than evaluating it as a runtime miss.
func (p *Program) ActionReferences() (ids []string, resolvable bool) {
if p == nil {
return nil
return nil, true
}
return p.actionIDs
return p.actionIDs, p.resolvable
}
// Eval evaluates the program against a dispatch-time context. A missing
+82 -51
View File
@@ -80,77 +80,108 @@ func TestEvalHasMacroPresence(t *testing.T) {
}
}
// TestReferencedActionIDs: a compiled program exposes the action ids its
// expression reads through actions.<id>, sorted and de-duplicated, so the
// playbook loader can reject references to undeclared prior actions.
func TestReferencedActionIDs(t *testing.T) {
// TestActionReferences classifies every read of the `actions` context root:
// a static access (actions.<id> or actions["<id>"]) resolves to its id, and
// any other spelling that mentions actions reports unresolvable.
func TestActionReferences(t *testing.T) {
env := NewEnv()
tests := []struct {
name string
src string
want []string
name string
src string
wantIDs []string
resolvable bool
}{
{
name: "single action reference",
src: `actions.notify.result.delivered == true`,
want: []string{"notify"},
name: "field selection resolves",
src: `actions.a.result.x == true`,
wantIDs: []string{"a"},
resolvable: true,
},
{
name: "no action reference",
src: `event.priority == 3`,
want: nil,
name: "literal map index resolves",
src: `actions["a"].result.x == true`,
wantIDs: []string{"a"},
resolvable: true,
},
{
name: "multiple references deduped and sorted",
src: `actions.b.result == true || actions.a.result == true || actions.b.result2 == true`,
want: []string{"a", "b"},
name: "two static accesses of one id consume two idents",
src: `actions.a.x == actions.a.y`,
wantIDs: []string{"a"},
resolvable: true,
},
{
name: "has macro over action",
src: `has(actions.notify.result.delivered)`,
want: []string{"notify"},
name: "multiple references deduped and sorted",
src: `actions.b.result == true || actions.a.result == true || actions.b.result2 == true`,
wantIDs: []string{"a", "b"},
resolvable: true,
},
{
name: "map index literal reference",
src: `actions["notify"].result.delivered == true`,
want: []string{"notify"},
name: "no actions reference",
src: `event.priority == 3`,
wantIDs: nil,
resolvable: true,
},
{
name: "has macro over static access",
src: `has(actions.notify.result.delivered)`,
wantIDs: []string{"notify"},
resolvable: true,
},
{
name: "event field index key is unresolvable",
src: `actions[event.name].result.x == true`,
wantIDs: nil,
resolvable: false,
},
{
name: "computed string index key is unresolvable",
src: `actions["a" + "b"].result.x == true`,
wantIDs: nil,
resolvable: false,
},
{
name: "in operator on actions is unresolvable",
src: `"notify" in actions`,
wantIDs: nil,
resolvable: false,
},
{
name: "size of actions is unresolvable",
src: `size(actions) > 0`,
wantIDs: nil,
resolvable: false,
},
{
name: "macro receiver actions is unresolvable",
src: `actions.all(k, k == "a")`,
wantIDs: nil,
resolvable: false,
},
{
name: "bare actions is unresolvable",
src: `actions`,
wantIDs: nil,
resolvable: false,
},
{
name: "equality against map literal is unresolvable",
src: `actions == {}`,
wantIDs: nil,
resolvable: false,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
prg, err := env.Compile(tc.src)
if err != nil {
t.Fatalf("Compile: %v", err)
t.Fatalf("Compile(%q): %v", tc.src, err)
}
got := prg.ReferencedActionIDs()
if !slices.Equal(got, tc.want) {
t.Fatalf("ReferencedActionIDs() = %v, want %v", got, tc.want)
ids, resolvable := prg.ActionReferences()
if resolvable != tc.resolvable {
t.Fatalf("ActionReferences(%q) resolvable = %v, want %v", tc.src, resolvable, tc.resolvable)
}
})
}
}
// TestCompileRejectsNonLiteralActionsIndex: an `actions[...]` access whose
// key is not a string literal cannot be resolved statically, so it is a
// Compile-time error rather than a runtime lookup the loader would silently
// skip (J1's unknown-id rule extended to keys that are not literal).
func TestCompileRejectsNonLiteralActionsIndex(t *testing.T) {
env := NewEnv()
tests := []struct {
name string
src string
}{
{name: "event field key", src: `actions[event.name].result.x == true`},
{name: "computed string key", src: `actions["a" + "b"].result.x == true`},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
_, err := env.Compile(tc.src)
if err == nil {
t.Fatalf("Compile(%q) = nil error, want rejection of non-literal actions index", tc.src)
}
if !strings.Contains(err.Error(), "actions") {
t.Errorf("Compile error = %q, want it to name the actions index", err.Error())
if !slices.Equal(ids, tc.wantIDs) {
t.Fatalf("ActionReferences(%q) ids = %v, want %v", tc.src, ids, tc.wantIDs)
}
})
}
+12 -5
View File
@@ -130,19 +130,19 @@ func validateActionIDs(actions []rawAction) error {
return nil
}
// unknownActionReference returns the first action id a compiled `when` reads
// through actions.<id> that is not declared on any action before index idx.
// unknownActionReference returns the first statically-resolved action id a
// compiled `when` reads that is not declared on any action before index idx.
// The comparison is against earlier actions' declared ids (the general rule
// from J1), so it stays correct when the one-action boundary later relaxes;
// today idx is always 0, so any actions.<id> reference is unknown.
func unknownActionReference(raw []rawAction, idx int, prg *expr.Program) (string, bool) {
func unknownActionReference(raw []rawAction, idx int, ids []string) (string, bool) {
declared := make(map[string]struct{}, idx)
for _, prior := range raw[:idx] {
if prior.ID != "" {
declared[prior.ID] = struct{}{}
}
}
for _, id := range prg.ReferencedActionIDs() {
for _, id := range ids {
if _, ok := declared[id]; !ok {
return id, true
}
@@ -259,7 +259,14 @@ func loadOne(dir, path string, env *expr.Env) (*Playbook, error) {
if err != nil {
return nil, fmt.Errorf("playbook %s: when condition: %w", path, err)
}
if id, unknown := unknownActionReference(raw.Actions, 0, prg); unknown {
ids, resolvable := prg.ActionReferences()
if !resolvable {
return nil, fmt.Errorf(
"playbook %s: when condition contains an `actions` reference that cannot be statically resolved to an action id (the `actions` context root must be read as a prior action id)",
path,
)
}
if id, unknown := unknownActionReference(raw.Actions, 0, ids); unknown {
return nil, fmt.Errorf("playbook %s: when condition references unknown action id %q", path, id)
}
action.When = prg
+48 -47
View File
@@ -481,70 +481,71 @@ func TestValidateActionIDs(t *testing.T) {
}
}
// TestLoadWhenReferencesUnknownActionIDFails: a when reading actions.<id>
// (or actions["<id>"]) with no prior action declaring that id is a load
// failure naming the playbook path and the id -- never a runtime miss.
func TestLoadWhenReferencesUnknownActionIDFails(t *testing.T) {
for _, when := range []string{
`actions.notify.result.delivered == true`,
`actions["notify"].result.delivered == true`,
} {
t.Run(when, func(t *testing.T) {
// TestLoadWhenActionsReferenceFails: a when that reads the `actions` context
// root in a form that cannot be pinned to a prior action id at load fails the
// whole load, naming the playbook path (and the id when one statically
// resolves) -- never a runtime miss.
func TestLoadWhenActionsReferenceFails(t *testing.T) {
tests := []struct {
name string
when string
wantID string
}{
{name: "undeclared field selection", when: `actions.a.result.x == true`, wantID: "a"},
{name: "undeclared literal map index", when: `actions["a"].result.x == true`, wantID: "a"},
{name: "non-literal index key", when: `actions[key].result.x == true`},
{name: "in operator on actions", when: `"notify" in actions`},
{name: "size of actions", when: `size(actions) > 0`},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "pb.yaml", "\ntrigger:\n kind: bug\nactions:\n - position: workflow\n workflow: tdd\n when: "+when+"\n")
writeFile(t, dir, "pb.yaml", "\ntrigger:\n kind: bug\nactions:\n - position: workflow\n workflow: tdd\n when: "+tc.when+"\n")
_, err := Load(dir)
if err == nil {
t.Fatal("Load(when referencing undeclared action id) = nil, want load failure")
t.Fatal("Load = nil, want load failure")
}
if !strings.Contains(err.Error(), "pb.yaml") {
t.Errorf("Load error = %q, want the playbook path named", err.Error())
}
if !strings.Contains(err.Error(), "notify") {
t.Errorf("Load error = %q, want the unknown id named", err.Error())
if tc.wantID != "" && !strings.Contains(err.Error(), tc.wantID) {
t.Errorf("Load error = %q, want the unknown id %q named", err.Error(), tc.wantID)
}
})
}
}
// TestLoadWhenNonLiteralActionsIndexFails: an `actions[...]` access whose key
// is not a string literal is rejected at load -- the id cannot be resolved
// statically, so it must not pass the load check and become a runtime miss.
func TestLoadWhenNonLiteralActionsIndexFails(t *testing.T) {
for _, when := range []string{
`actions[key].result.x == true`,
`actions[event.name].result.x == true`,
} {
t.Run(when, func(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "pb.yaml", "\ntrigger:\n kind: bug\nactions:\n - position: workflow\n workflow: tdd\n when: "+when+"\n")
_, err := Load(dir)
if err == nil {
t.Fatal("Load(when with non-literal actions index) = nil, want load failure")
}
if !strings.Contains(err.Error(), "pb.yaml") {
t.Errorf("Load error = %q, want the playbook path named", err.Error())
}
})
}
}
// TestUnknownActionReferenceGeneralRule: the reference check compares against
// the declared ids of earlier actions, so it already behaves correctly when
// the one-action boundary later relaxes (the Load path can only exercise the
// empty-prior set today).
// TestUnknownActionReferenceGeneralRule: the reference check compares the
// statically-resolved ids against the declared ids of earlier actions, so it
// already behaves correctly when the one-action boundary later relaxes (the
// Load path can only exercise the empty-prior set today).
func TestUnknownActionReferenceGeneralRule(t *testing.T) {
prg, err := expr.NewEnv().Compile(`actions.notify.result.delivered == true`)
if err != nil {
t.Fatalf("Compile: %v", err)
env := expr.NewEnv()
compile := func(src string) []string {
t.Helper()
prg, err := env.Compile(src)
if err != nil {
t.Fatalf("Compile(%q): %v", src, err)
}
ids, resolvable := prg.ActionReferences()
if !resolvable {
t.Fatalf("ActionReferences(%q) = resolvable false, want true", src)
}
return ids
}
// notify declared on the prior action: known.
if id, unknown := unknownActionReference([]rawAction{{ID: "notify"}}, 1, prg); unknown {
// a declared on the prior action: known.
if id, unknown := unknownActionReference([]rawAction{{ID: "a"}}, 1, compile(`actions.a.result.delivered == true`)); unknown {
t.Fatalf("unknownActionReference(declared prior) = (%q, true), want known", id)
}
// A different prior id leaves notify unknown.
if id, unknown := unknownActionReference([]rawAction{{ID: "build"}}, 1, prg); !unknown || id != "notify" {
t.Fatalf("unknownActionReference(undeclared) = (%q, %v), want (notify, true)", id, unknown)
// Two static reads of a in one expression consume two actions idents and
// still resolve to the one declared id: known.
if id, unknown := unknownActionReference([]rawAction{{ID: "a"}}, 1, compile(`actions.a.x == actions.a.y`)); unknown {
t.Fatalf("unknownActionReference(two static reads of declared id) = (%q, true), want known", id)
}
// A different prior id leaves b unknown.
if id, unknown := unknownActionReference([]rawAction{{ID: "a"}}, 1, compile(`actions.b.result.delivered == true`)); !unknown || id != "b" {
t.Fatalf("unknownActionReference(undeclared) = (%q, %v), want (b, true)", id, unknown)
}
}