Documentation
¶
Overview ¶
Package rules is the rule engine (design/workstreams/dispatcher-core/LLD/rules-engine.md): Engine.Evaluate turns one event and a work item snapshot into the ordered decisions the rule controller applies, with the record of why each rule did or didn't fire.
The package is pure: no I/O, no goroutines and no wall clock. The time comes from the Engine's Clock, the safety rails from the caller's Rails, and everything else from the catalog snapshot, the event and the WorkItemView.
Index ¶
- Constants
- func Allowed() v1alpha1.RailVerdict
- func CouldFire(c *catalog.Catalog, ev v1alpha1.Event, wi WorkItemView) bool
- func Deferred(rail, reason string) v1alpha1.RailVerdict
- func Golden(ev Evaluation) ([]byte, error)
- func ReadsItem(c *catalog.Catalog, ev v1alpha1.Event, wi WorkItemView) bool
- func Suppressed(rail, reason string) v1alpha1.RailVerdict
- type ActionIntent
- type Cancel
- type Change
- type ChangeOp
- type Clock
- type ClockFunc
- type Debounce
- type Decision
- type DeployView
- type Dispatch
- type Effect
- type Engine
- type Evaluation
- type FakeRails
- type Fixture
- type GoldenDecision
- type GoldenEvaluation
- type GoldenMatch
- type Link
- type Match
- type MatchResult
- type Notify
- type PRApproval
- type PRAuthor
- type PRChecks
- type PRView
- type RailTrip
- type Rails
- type RunHarness
- type RunSummary
- type Set
- type Unsupported
- type WorkItemView
Constants ¶
const ( FixtureEvent = "event.json" FixtureWorkItem = "workitem.json" FixtureRails = "rails.json" FixtureExpected = "expected.json" FixtureRendered = "rendered" )
Fixture files (rules-engine LLD §Fixtures). A case is a directory that holds them:
event.json a normalised v1alpha1.Event
workitem.json the WorkItemView before
rails.json optional: the tripped rails (FakeRails); without it every action is allowed
expected.json the golden evaluation (Golden), written by `factory rules test --update`
rendered/ the golden prompts and Template bodies its decisions render, written by
`factory rules test --update` (not read here)
const ( // SectionEvaluation: the event or work item id. SectionEvaluation = "evaluation" // SectionRule: a (RuleSet, rule) candidate and its match result. SectionRule = "rule" // SectionDecision: a decision (an action and its rail verdict), or their order. SectionDecision = "decision" // SectionState: a top-level key of StateAfter. SectionState = "state" )
Change sections: what changed.
const ( KindDispatch = "dispatch" KindSet = "set" KindNotify = "notify" KindCancel = "cancel" KindLink = "link" KindEffect = "effect" KindDebounce = "debounce" KindUnsupported = "unsupported" )
Action kinds (ActionIntent.Kind).
const ( // VerdictAllowed: apply the action. VerdictAllowed = "allowed" // VerdictSuppressed: don't apply it; recorded as suppressed (kill switch, run cap, // active run). VerdictSuppressed = "suppressed" // VerdictDeferred: apply it held back (budget: the Task is created Pending with the // reason). VerdictDeferred = "deferred" // VerdictUnsupported: the engine doesn't support the action (requestApproval in the PoC, // Q18); the rails are not consulted. VerdictUnsupported = "unsupported" )
Verdicts (v1alpha1.RailVerdict.Verdict).
const ( RailKillSwitch = "kill-switch" RailRunCap = "run-cap" RailActiveRun = "active-run" RailBudget = "budget" // RailEngine is the "rail" of an Unsupported decision. RailEngine = "engine" )
Rail names (v1alpha1.RailVerdict.Rail), as in the rules-engine LLD's Rails contract.
Variables ¶
This section is empty.
Functions ¶
func Allowed ¶
func Allowed() v1alpha1.RailVerdict
Allowed is the verdict that lets an action through.
func CouldFire ¶
CouldFire reports whether any rule could fire for ev against wi: some RuleSet in scope (the RuleSet's providers and scope, as Evaluate decides it) has a rule whose on has the event type and whose providers have its source. It reads only the catalog, the event and, for a factory.* event, wi's links, so the rule controller asks it before observing anything.
func Deferred ¶
func Deferred(rail, reason string) v1alpha1.RailVerdict
Deferred is a deferred verdict from rail.
func Golden ¶
func Golden(ev Evaluation) ([]byte, error)
Golden is the content of expected.json for ev: ToGolden, indented, with a final newline.
func ReadsItem ¶
ReadsItem reports whether the where of any rule that could fire for ev reads item. When none does, which rules fire doesn't depend on the work item (its observations included): an evaluation against an unobserved view decides the same.
func Suppressed ¶
func Suppressed(rail, reason string) v1alpha1.RailVerdict
Suppressed is a suppressed verdict from rail.
Types ¶
type ActionIntent ¶
type ActionIntent struct {
Dispatch *Dispatch `json:"dispatch,omitzero"`
Set *Set `json:"set,omitzero"`
Notify *Notify `json:"notify,omitzero"`
Cancel *Cancel `json:"cancel,omitzero"`
Link *Link `json:"link,omitzero"`
Effect *Effect `json:"effect,omitzero"`
Debounce *Debounce `json:"debounce,omitzero"`
// Unsupported is an action the engine accepts but doesn't run (requestApproval, Q18).
Unsupported *Unsupported `json:"unsupported,omitzero"`
}
ActionIntent is one materialised action: every "=CEL" value evaluated, ready for the rule controller to apply. Exactly one member is set.
func (ActionIntent) Kind ¶
func (a ActionIntent) Kind() string
Kind returns the member that is set ("" for none).
func (ActionIntent) String ¶
func (a ActionIntent) String() string
String is a one-line summary for decision records ("dispatch implement → poc").
type Cancel ¶
type Cancel struct {
TaskSpec string `json:"taskSpec"`
}
Cancel cancels the work item's active tasks of a TaskSpec.
type Change ¶
type Change struct {
Section string `json:"section"`
Op ChangeOp `json:"op"`
// Subject is what changed: "<ruleset>/<rule>" for a rule, "<ruleset>/<rule>: <action>"
// for a decision, the key for state, the field for the evaluation.
Subject string `json:"subject"`
// From and To summarise the old and new value (a match result, a rail verdict, a state
// value); empty when there is none or when only Details changed.
From string `json:"from,omitzero"`
To string `json:"to,omitzero"`
// Details are field-level changes ("dispatch.inputs.target: \"pr\" -> \"stack\"").
Details []string `json:"details,omitzero"`
}
Change is one rule-level or decision-level difference between two evaluations of the same case (the golden and now, or the base catalog and the head catalog).
func DiffGolden ¶
func DiffGolden(old, cur GoldenEvaluation) []Change
DiffGolden compares two evaluations of one case, old then new, rule by rule and decision by decision. It returns nil when they are the same.
Rules are paired by (RuleSet, rule). Decisions are paired by (RuleSet, rule, action kind, what the action names: TaskSpec, key, template, ref, op) and occurrence, so a changed input or verdict reads as a change of that decision rather than a removal and an addition; a change of order among the paired decisions is reported once. A decision carries its rule's where inputs, so a change of them is reported on the rule only.
type ChangeOp ¶
type ChangeOp string
ChangeOp is how one rule, decision or state key changed between two evaluations.
type Debounce ¶
type Debounce struct {
// Key is "<rule>/<value of debounce.key>" (the work item id when the rule has no key),
// so two rules never share a key.
Key string `json:"key"`
Until time.Time `json:"until"`
// Then are the rule's materialised actions, in order. Their sets are not in
// Evaluation.StateAfter: they apply when the debounce fires.
Then []ActionIntent `json:"then"`
}
Debounce holds a debounced rule's actions until Until. The controller keeps one pending Debounce per Key and applies Then (after re-checking the rails) at Until; a later match with the same Key while one is pending changes nothing (first wins).
type Decision ¶
type Decision struct {
// RuleSet is the one the rule fired through (its params, its where).
RuleSet string `json:"ruleSet"`
Rule string `json:"rule"`
Action ActionIntent `json:"action"`
// Rail is the rails' verdict: allowed, suppressed{reason} or deferred{reason}.
Rail v1alpha1.RailVerdict `json:"rail"`
// Inputs are the values the where saw (bounded), for the "why" view.
Inputs map[string]any `json:"inputs,omitzero"`
}
Decision is one action to apply, with the RuleSet and rule it came from and the rails' verdict on it.
type DeployView ¶
type DeployView struct {
State string `json:"state,omitzero"`
SHA string `json:"sha,omitzero"`
URL string `json:"url,omitzero"`
ContainsMerge bool `json:"containsMerge,omitzero"`
}
DeployView is a deployment observation (item.deploy).
type Dispatch ¶
type Dispatch struct {
TaskSpec string `json:"taskSpec"`
Queue string `json:"queue"`
// Inputs are the evaluated dispatch inputs, checked against the TaskSpec's declared
// inputs (defaults are not filled in: the controller compiles the Task).
Inputs map[string]any `json:"inputs,omitzero"`
Harness *v1alpha1.HarnessRequest `json:"harness,omitzero"`
Requires *v1alpha1.Requires `json:"requires,omitzero"`
Context []string `json:"context,omitzero"`
Target *v1alpha1.Target `json:"target,omitzero"`
}
Dispatch creates a Task (Pending) in a queue.
type Effect ¶
type Effect struct {
Op v1alpha1.EffectOp `json:"op"`
Target string `json:"target,omitzero"`
Args map[string]any `json:"args,omitzero"`
}
Effect is a direct provider effect.
type Engine ¶
type Engine struct {
Clock Clock
}
Engine evaluates rules. Its zero value is ready: without a Clock, `now` (and debounce deadlines) is the event's time, which keeps fixtures and replays deterministic. An Engine holds no state, so it is safe for concurrent use.
func (*Engine) Evaluate ¶
func (e *Engine) Evaluate(ctx context.Context, c *catalog.Catalog, ev v1alpha1.Event, wi WorkItemView, rails Rails) (Evaluation, error)
Evaluate evaluates ev against the work item wi with the catalog c, judging every decision with rails. It never panics on rule errors: a where that fails is a not-matching candidate with its error recorded, and an action that fails to materialise drops all of that rule's decisions. It returns an error only for a nil catalog or rails, or when ctx is done.
The steps follow the LLD: scope the RuleSets; select the rules whose on and providers match; order the candidates by (priority desc, RuleSet name, rule name); then, for each one, respect final, dedupe on firing per (event, rule), evaluate the where with the RuleSet's params, stage the actions against the state written so far (all or nothing), and commit them through the rails.
type Evaluation ¶
type Evaluation struct {
// Event and WorkItem are the ids of the event and of the work item.
Event string `json:"event"`
WorkItem string `json:"workItem"`
// Matches are every (RuleSet, rule) candidate, in evaluation order, with its result.
Matches []Match `json:"matches"`
// Decisions are the actions to apply, in order.
Decisions []Decision `json:"decisions"`
// StateAfter is the work item's state after every allowed set (a projection: the
// controller writes it).
StateAfter map[string]any `json:"stateAfter"`
}
Evaluation is the result of evaluating one event against one work item: every candidate (RuleSet, rule) with its result, and the ordered decisions the rule controller applies.
func (Evaluation) Records ¶
func (e Evaluation) Records(at time.Time) []v1alpha1.Decision
Records returns the work item's decision records for this evaluation ("why did this happen?"): one per candidate, with the where inputs, the actions and the rail verdicts of a fired rule, and the reason for the others. at is the time the controller applies them.
type FakeRails ¶
type FakeRails struct {
Trips []RailTrip `json:"trips"`
}
FakeRails is a pure Rails for tests and rule fixtures (rails.json): the first trip that matches an action gives its verdict, every other action is allowed. It is read-only, so it is safe for concurrent use.
func (FakeRails) Check ¶
func (f FakeRails) Check(a ActionIntent) v1alpha1.RailVerdict
Check returns the verdict of the first matching trip, or Allowed.
type Fixture ¶
type Fixture struct {
// Name is the case's directory, slash-separated and relative to the fixtures root
// ("poc/train-mock").
Name string
Event v1alpha1.Event
WorkItem WorkItemView
// Rails are the tripped rails of rails.json; nil when the case has none.
Rails *FakeRails
// Expected is the content of expected.json; nil when the case has none yet.
Expected []byte
}
Fixture is one recorded case: an event, the work item before it, the tripped rails and the golden evaluation.
func LoadFixtures ¶
LoadFixtures reads every case under fsys: each directory holding an event.json, at any depth (a case's own subdirectories are not searched). The cases are sorted by name.
func ReadFixture ¶
ReadFixture reads the case in the directory dir of fsys. Unknown JSON fields are errors, so a fixture can't silently drift from the types.
func (Fixture) Evaluate ¶
Evaluate replays the case against the catalog c. It uses an Engine without a Clock, so `now` is the event's time and the result doesn't depend on when it runs.
func (Fixture) RailsOrAllow ¶
RailsOrAllow is the case's rails: its FakeRails, or AllowAll when it has none.
type GoldenDecision ¶
GoldenDecision is a Decision with its inputs redacted to their keys.
type GoldenEvaluation ¶
type GoldenEvaluation struct {
Event string `json:"event"`
WorkItem string `json:"workItem"`
Matches []GoldenMatch `json:"matches"`
Decisions []GoldenDecision `json:"decisions"`
StateAfter map[string]any `json:"stateAfter"`
}
GoldenEvaluation is an Evaluation as expected.json holds it: the where inputs are redacted to their keys, so a golden pins which values a rule read but not the values.
func ParseGolden ¶
func ParseGolden(b []byte) (GoldenEvaluation, error)
ParseGolden decodes an expected.json.
func ToGolden ¶
func ToGolden(ev Evaluation) GoldenEvaluation
ToGolden redacts ev for a golden file.
func (GoldenEvaluation) Marshal ¶
func (g GoldenEvaluation) Marshal() ([]byte, error)
Marshal encodes g as expected.json holds it.
type GoldenMatch ¶
GoldenMatch is a Match with its inputs redacted to their keys.
type Match ¶
type Match struct {
RuleSet string `json:"ruleSet"`
Rule string `json:"rule"`
Priority int `json:"priority,omitzero"`
Result MatchResult `json:"result"`
// FiredVia is the RuleSet the rule fired through (Duplicate only).
FiredVia string `json:"firedVia,omitzero"`
// Action is the failing action ("actions[2].dispatch"; ActionError only).
Action string `json:"action,omitzero"`
// Error is the error message (WhereError and ActionError).
Error string `json:"error,omitzero"`
// Inputs are the values the where saw (bounded), for evaluated candidates.
Inputs map[string]any `json:"inputs,omitzero"`
}
Match is one (RuleSet, rule) candidate and its result.
type MatchResult ¶
type MatchResult string
MatchResult is what happened to one candidate.
const ( // Matched: the where passed and the rule's actions became decisions. Matched MatchResult = "matched" // NotMatched: the where returned false. NotMatched MatchResult = "not-matched" // WhereError: the where failed at runtime (missing key, wrong type, cost limit). The rule // does not match; the error is recorded. WhereError MatchResult = "error" // ActionError: the where passed but an action failed to materialise, so none of the // rule's actions became decisions. The rule still counts as fired (dedupe, final). ActionError MatchResult = "action-error" // SuppressedByFinal: a higher candidate with final: true fired. SuppressedByFinal MatchResult = "suppressed-by-final" // Duplicate: the rule already fired for this event through another RuleSet (FiredVia). Duplicate MatchResult = "duplicate" )
Match results.
type Notify ¶
type Notify struct {
Template string `json:"template"`
To []v1alpha1.Destination `json:"to"`
}
Notify sends a templated message.
type PRApproval ¶
PRApproval is an approving review: by which factory identity (or login), at which commit.
type PRAuthor ¶
type PRAuthor struct {
IsFactory bool `json:"isFactory"`
}
PRAuthor is who opened the PR.
type PRChecks ¶
type PRChecks struct {
State string `json:"state,omitzero"`
Settled bool `json:"settled,omitzero"`
}
PRChecks is the rollup of the PR head's checks.
type PRView ¶
type PRView struct {
Provider string `json:"provider,omitzero"`
Ref string `json:"ref,omitzero"`
Author PRAuthor `json:"author"`
Draft bool `json:"draft"`
Head string `json:"head,omitzero"`
Labels []string `json:"labels,omitzero"`
Checks PRChecks `json:"checks"`
ApprovedBy []PRApproval `json:"approvedBy,omitzero"`
UnresolvedThreads int `json:"unresolvedThreads,omitzero"`
}
PRView is a PR observation (item.pr, item.prs[]).
type RailTrip ¶
type RailTrip struct {
// Rail is the tripped rail (RailKillSwitch, RailRunCap, RailActiveRun, RailBudget). The
// verdict follows the Rails contract: deferred for the budget, suppressed otherwise.
Rail string `json:"rail"`
// Reason is the verdict's reason; it defaults to the rail name.
Reason string `json:"reason,omitzero"`
// Action is the action kind (dispatch, set, notify, cancel, link, effect, debounce).
Action string `json:"action,omitzero"`
// TaskSpec matches dispatch and cancel; Queue matches dispatch; Key matches set.
TaskSpec string `json:"taskSpec,omitzero"`
Queue string `json:"queue,omitzero"`
Key string `json:"key,omitzero"`
}
RailTrip is one tripped rail. Its match fields narrow the actions it applies to; an empty field matches anything.
type Rails ¶
type Rails interface {
Check(a ActionIntent) v1alpha1.RailVerdict
}
Rails judges each decision against the safety rails (design/02-architecture.md §Safety rails): kill switches, budgets, the per-item run cap and the single active run. The rule controller (RT) implements it for one (event, work item); tests use FakeRails.
Check is called once per decision, in order, and must not do I/O on the engine's behalf beyond what the implementation already holds: the engine is pure, so an implementation reads a snapshot taken before Evaluate.
var AllowAll Rails = allowAll{}
AllowAll is Rails that allows every action (e.g. to ask "would any rule match?").
type RunHarness ¶
RunHarness is the harness a run used.
type RunSummary ¶
type RunSummary struct {
ID string `json:"id"`
Spec string `json:"spec"`
Outcome string `json:"outcome,omitzero"`
Status string `json:"status,omitzero"`
Inputs map[string]any `json:"inputs,omitzero"`
Result map[string]any `json:"result,omitzero"`
Agent string `json:"agent,omitzero"`
Harness *RunHarness `json:"harness,omitzero"`
}
RunSummary is one Run as rules see it (run, item.runs[spec][], item.lastRun(spec)).
type Unsupported ¶
type Unsupported struct {
// Action is the action type (requestApproval).
Action string `json:"action"`
Reason string `json:"reason"`
// RequestApproval is what the rule asked for.
RequestApproval *v1alpha1.ApprovalSpec `json:"requestApproval,omitzero"`
}
Unsupported is an action the engine accepts but does not run.
type WorkItemView ¶
type WorkItemView struct {
ID string `json:"id"`
Links []v1alpha1.Link `json:"links,omitzero"`
State map[string]any `json:"state,omitzero"`
// Counters are runs per TaskSpec as stored (e.g. rebuilt from the marker). item.count
// reads the larger of Counters[spec] and len(RunsBySpec[spec]).
Counters map[string]int `json:"counters,omitzero"`
Reporter *v1alpha1.Actor `json:"reporter,omitzero"`
// PR is the primary PR observation, if any; PRs are every linked PR (stacks).
PR *PRView `json:"pr,omitzero"`
PRs []PRView `json:"prs,omitzero"`
// Deploy is the latest deployment observation (item.deploy), if any.
Deploy *DeployView `json:"deploy,omitzero"`
// RunsBySpec are the work item's Run summaries by TaskSpec, oldest first.
RunsBySpec map[string][]RunSummary `json:"runsBySpec,omitzero"`
}
WorkItemView is the read-only snapshot of a work item that the runtime builds (store plus the latest provider observation) before Evaluate. The engine never modifies it.