Documentation
¶
Overview ¶
Package eval is the Flagnetic evaluator: a pure function of a ruleset document and a context that computes a flag's value and evaluation reason.
It is the reference implementation. The server's remote evaluation and the Go SDK import it, and the SDKs of other languages implement the same algorithm. Every implementation runs the language-agnostic conformance suite in conformance/fixtures at the repository root; a fixture is the contract, this code is one way to meet it. A new operator lands as a fixture first, and every SDK stays red until it passes.
The module has no dependencies outside the standard library, never reads a clock, never performs I/O and never records an exposure: exposure is an explicit SDK call, so being assigned a variation is never mistaken for having seen it.
Use ¶
rs, err := eval.Decode(document)
r := rs.Evaluate(eval.Context{
Units: map[string]string{"user": "u-1001"},
Attributes: map[string]any{"plan": "pro", "app_version": "1.18.0"},
}, "new_checkout")
A decoded Ruleset is immutable and safe for concurrent use.
Algorithm ¶
For one flag and one context:
- An absent flag is error flag_not_found.
- A flag that is off serves its off variation, reason off.
- The first override whose unit type is in the context with an equal unit ID serves its variation, reason override, override_influenced true. Steps 4 and 5 then run in shadow, ignoring the override; when they end in an experiment that includes the unit, the result carries that experiment's detail with override true and the served variation.
- Flag-level prerequisites in order: each evaluates the prerequisite flag with the same context and holds when its reason is neither off nor error and it serves the required variation. The first failure serves the off variation, reason prerequisite_failed, naming that prerequisite. A flag met again on the current prerequisite path is error prerequisite_cycle. An error in a prerequisite is a defect of the ruleset and becomes the dependent flag's error.
- Rules in order, first match wins. A rule's conditions are evaluated in order and it stops at the first false one. A rule serving a variation matches with reason rule. A rollout is skipped when its unit type is absent, serves with reason rollout when the unit's bucket is below the percentage, and otherwise evaluation continues with the next rule. An experiment is skipped when its unit type is absent; when the inclusion bucket is below the traffic allocation, the variation bucket picks a variation against cumulative weights in list order, reason experiment; otherwise evaluation continues.
- No rule matched: the fallthrough variation, reason fallthrough.
- A variation, segment, flag or attribute referenced but missing from the document, a condition that cannot be evaluated, or an experiment serve breaking its invariants (an experiment key, a unit type and both salts present; a traffic allocation within 0 to 10000; at least two weights, none negative, naming distinct variations of the flag and summing to exactly 10000) is error inconsistent_ruleset, only when evaluation reaches it, as a matched rule for a serve.
An operator, condition kind or serve kind this evaluator does not know, typically sent by a server newer than it, is an unsupported rule: Decode reports it per flag through Ruleset.UnsupportedRules, so an SDK can say once that it must be upgraded, and evaluating it is step 7.
override_influenced is true when an override decided the result or any prerequisite sub-evaluation consulted on the way (flag-level or condition, held or failed) was override-influenced. Only what was evaluated counts: a condition after a false one, and a rule after the first match, are never evaluated.
Operators ¶
An absent attribute, null, or a value of the wrong type makes every operator false except not_exists, which is then true. There is no coercion: "5" is not a number. An unparsable semver or date in a context is a value of the wrong type. In a condition value it makes the condition false, and so does one unparsable item of an in or not_in list. Strings compare byte-wise on UTF-8, case-sensitive; numbers are IEEE 754 doubles; regular expressions are RE2 syntax and search anywhere in the string unless anchored. A unit type named as an attribute is a string attribute holding that unit's ID.
Buckets ¶
Bucket is MurmurHash3 x86 32-bit, seed 0, over the UTF-8 bytes of "{salt}.{unit_id}", read unsigned, mod 10000. It equals ClickHouse murmurHash3_32(concat(salt, '.', unit_id)) % 10000.
Index ¶
- Constants
- func Bucket(salt, unitID string) int
- func BucketInput(salt, unitID string) string
- func CheckOperator(typ AttributeType, op string, value any) error
- func Murmur3(data []byte) uint32
- type Attribute
- type AttributeType
- type Condition
- type Construct
- type ConstructKind
- type Context
- type Environment
- type ErrorCode
- type ExperimentDetail
- type Flag
- type Override
- type Prerequisite
- type Reason
- type Result
- type Rule
- type Ruleset
- type Segment
- type Semver
- type Serve
- type Variation
- type Weight
Examples ¶
Constants ¶
const ( ConditionAttribute = "attribute" ConditionInSegment = "in_segment" ConditionNotInSegment = "not_in_segment" ConditionPrerequisite = "prerequisite" )
Condition kinds.
const ( ServeVariation = "variation" ServeRollout = "rollout" ServeExperiment = "experiment" )
Serve kinds.
const Buckets = 10000
Buckets is the number of buckets a unit is hashed into. A percentage in basis points (0–10000) is compared against a bucket directly.
const SchemaVersion = 1
SchemaVersion is the ruleset schema version this evaluator reads.
const ScopeServer = "server"
ScopeServer is the one scope of a ruleset document: the whole configuration of an environment, private segments and overrides included, which only a server SDK holding a server key receives. A client SDK never receives a ruleset; it asks the server to evaluate for it.
Variables ¶
This section is empty.
Functions ¶
func Bucket ¶
Bucket computes the bucket of a unit for a salt:
murmur3_32(utf8("{salt}.{unit_id}"), seed 0) mod 10000
on the unsigned hash, giving 0–9999. A unit is inside percentage p when Bucket < p. The formula matches ClickHouse murmurHash3_32, so any bucket can be recomputed in SQL:
murmurHash3_32(concat(salt, '.', unit_id)) % 10000
Example ¶
package main
import (
"fmt"
"github.com/azverinus/flagnetic/eval"
)
func main() {
// The same as ClickHouse:
// SELECT murmurHash3_32('a3f9c2e17b4d0e58.u_10482') % 10000
fmt.Println(eval.Bucket("a3f9c2e17b4d0e58", "u_10482"))
}
Output: 6884
func BucketInput ¶
BucketInput is the string hashed for a unit's bucket: "{salt}.{unit_id}".
func CheckOperator ¶
func CheckOperator(typ AttributeType, op string, value any) error
CheckOperator returns why this evaluator cannot apply op with value to an attribute of typ, or nil when it can: op must be defined for typ and value must have the JSON type op needs (a string, number, boolean or list as decoded by encoding/json). It is the operator table the server validates conditions against on write. It does not reject what the evaluator treats as a false condition, such as an unparsable semantic version or date in the value.
Types ¶
type Attribute ¶
type Attribute struct {
Key string `json:"key"`
Type AttributeType `json:"type"`
}
Attribute is a declared attribute with its type.
type AttributeType ¶
type AttributeType string
AttributeType is the type of a declared attribute. A unit type used as an attribute in a condition behaves as a string attribute holding the unit ID of that type.
const ( TypeString AttributeType = "string" TypeNumber AttributeType = "number" TypeBoolean AttributeType = "boolean" TypeSemver AttributeType = "semver" TypeDate AttributeType = "date" TypeList AttributeType = "list" )
Attribute types.
type Condition ¶
type Condition struct {
Kind string `json:"kind"`
Attribute string `json:"attribute,omitempty"`
Op string `json:"op,omitempty"`
Value any `json:"value,omitempty"`
Segment string `json:"segment,omitempty"`
Flag string `json:"flag,omitempty"`
Variation string `json:"variation,omitempty"`
}
Condition is one comparison inside a rule or segment: an attribute, an operator and a value; membership in a segment; or a prerequisite.
type Construct ¶
type Construct struct {
Kind ConstructKind `json:"kind"`
Name string `json:"name"`
}
Construct is one operator, condition kind or serve kind of a ruleset that this evaluator does not know.
type ConstructKind ¶
type ConstructKind string
ConstructKind says what an unsupported construct is.
const ( ConstructOperator ConstructKind = "operator" ConstructConditionKind ConstructKind = "condition_kind" ConstructServeKind ConstructKind = "serve_kind" )
Kinds of construct a ruleset may hold that this evaluator does not know.
type Context ¶
type Context struct {
Units map[string]string `json:"units"`
Attributes map[string]any `json:"attributes"`
}
Context is what a flag is evaluated for: unit IDs by unit type, and attributes. A context with no units is valid: attribute rules apply; rollouts, experiments and overrides are skipped. An empty unit ID counts as absent.
Attribute values are JSON-shaped: string, bool, float64 (any Go number or json.Number is accepted), a list of strings ([]string or []any), or for dates an RFC 3339 string, integral Unix epoch milliseconds or a time.Time.
type Environment ¶
Environment identifies the environment a ruleset belongs to. A document without it (a hand-written offline file) is treated as unprotected.
type ExperimentDetail ¶
type ExperimentDetail struct {
Key string `json:"key"`
// Variation is the served variation: the assignment, or the override's
// variation when an override decided the result.
Variation string `json:"variation"`
UnitType string `json:"unit_type"`
UnitID string `json:"unit_id"`
InclusionSalt string `json:"inclusion_salt"`
VariationSalt string `json:"variation_salt"`
InclusionBucket int `json:"inclusion_bucket"`
VariationBucket int `json:"variation_bucket"`
// Override equals the result's OverrideInfluenced; exposures carrying
// it are excluded from analysis.
Override bool `json:"override"`
}
ExperimentDetail is everything an SDK needs to report an exposure: the one shape of experiment detail shared by local and remote evaluation.
type Flag ¶
type Flag struct {
Key string `json:"key"`
Type string `json:"type"`
AutomaticExposure bool `json:"automatic_exposure"`
Variations []Variation `json:"variations,omitempty"`
On bool `json:"on"`
OffVariation string `json:"off_variation,omitempty"`
Fallthrough string `json:"fallthrough,omitempty"`
Prerequisites []Prerequisite `json:"prerequisites,omitempty"`
Overrides []Override `json:"overrides,omitempty"`
Rules []Rule `json:"rules,omitempty"`
}
Flag is one flag with its configuration in the ruleset's environment.
type Override ¶
type Override struct {
UnitType string `json:"unit_type"`
UnitID string `json:"unit_id"`
Variation string `json:"variation"`
}
Override serves a fixed variation to one unit ID of one unit type.
type Prerequisite ¶
Prerequisite requires another flag of the project to evaluate to a variation for the same context.
type Reason ¶
type Reason string
Reason is the evaluation reason of a result. fallback and local_override are produced by SDKs, never by the evaluator.
const ( ReasonOff Reason = "off" ReasonOverride Reason = "override" ReasonRule Reason = "rule" ReasonRollout Reason = "rollout" ReasonExperiment Reason = "experiment" ReasonFallthrough Reason = "fallthrough" ReasonPrerequisiteFailed Reason = "prerequisite_failed" ReasonError Reason = "error" )
Evaluation reasons.
type Result ¶
type Result struct {
// Type is the flag's type. It is empty only when there is no flag to
// read it from: an error with ErrorFlagNotFound.
Type string `json:"type"`
// Value is the served variation's value; absent for errors.
Value json.RawMessage `json:"value,omitempty"`
// Variation is the served variation's key; absent for errors.
Variation string `json:"variation,omitempty"`
Reason Reason `json:"reason"`
// RuleID is the rule that served, for reasons rule, rollout and
// experiment.
RuleID string `json:"rule_id,omitempty"`
// AutomaticExposure is the flag's setting: with it, an SDK emits an
// exposure after every evaluation carrying Experiment, without a
// second call. It travels with every result of a known flag, so the
// result alone says what to do.
AutomaticExposure bool `json:"automatic_exposure"`
// Experiment is present with reason experiment, and with reason
// override when the override's shadow evaluation lands in a running
// experiment that includes the unit.
Experiment *ExperimentDetail `json:"experiment,omitempty"`
// Prerequisite is the flag-level prerequisite that failed, for reason
// prerequisite_failed.
Prerequisite string `json:"prerequisite,omitempty"`
// Bucket is the unit's bucket for reason rollout.
Bucket *int `json:"bucket,omitempty"`
ErrorCode ErrorCode `json:"error_code,omitempty"`
// OverrideInfluenced is true when an override decided the result, or
// any prerequisite sub-evaluation consulted on the way was
// override-influenced, whatever the final reason. Every exposure and
// event derived from the result carries it.
OverrideInfluenced bool `json:"override_influenced"`
}
Result is what evaluating one flag for one context served, and why. Its JSON form is what the conformance fixtures compare, field for field.
func (Result) MarshalJSON ¶
MarshalJSON encodes a result. Type and AutomaticExposure are the flag's, so both are left out when there is no flag to read them from. That is exactly a result ofFlag never stamped, and ErrorFlagNotFound marks it: flag returns that code only for a key its index does not hold, and every result it stamps keeps the flag it was stamped with.
type Rule ¶
type Rule struct {
ID string `json:"id"`
Conditions []Condition `json:"conditions"`
Serve Serve `json:"serve"`
}
Rule is one ordered AND-set of conditions and what it serves.
type Ruleset ¶
type Ruleset struct {
SchemaVersion int `json:"schema_version"`
Version int64 `json:"version"`
Scope string `json:"scope"`
Environment *Environment `json:"environment,omitempty"`
UnitTypes []string `json:"unit_types"`
Attributes []Attribute `json:"attributes"`
Segments []Segment `json:"segments"`
Flags []Flag `json:"flags"`
// contains filtered or unexported fields
}
Ruleset is the complete evaluable configuration of one environment at one moment. Decode it with Decode; the zero value is not usable.
func Decode ¶
Decode reads a ruleset document. It fails only when the document is not a ruleset this evaluator can read: malformed JSON, an unsupported schema_version or a scope other than server. Dangling references, invalid conditions and invalid experiment serves do not fail decoding; Decode finds an invalid experiment serve once, and evaluating a flag that reaches any of them returns reason error with inconsistent_ruleset, so one defective flag never takes the others down.
func (*Ruleset) Evaluate ¶
Evaluate computes one flag for a context. It never reads a clock, never records an exposure and never fails: problems are results with reason error.
Example ¶
package main
import (
"fmt"
"github.com/azverinus/flagnetic/eval"
)
func main() {
rs, err := eval.Decode([]byte(`{
"schema_version": 1, "version": 42, "scope": "server",
"unit_types": ["user"],
"attributes": [{"key": "plan", "type": "string"}, {"key": "app_version", "type": "semver"}],
"flags": [{"key": "new_checkout", "type": "boolean", "on": true,
"variations": [{"key": "true", "value": true}, {"key": "false", "value": false}],
"off_variation": "false", "fallthrough": "false",
"rules": [{"id": "01J9", "conditions": [
{"kind": "attribute", "attribute": "plan", "op": "eq", "value": "pro"},
{"kind": "attribute", "attribute": "app_version", "op": "lt", "value": "1.17.0"}],
"serve": {"kind": "variation", "variation": "true"}}]}]
}`))
if err != nil {
panic(err)
}
r := rs.Evaluate(eval.Context{
Units: map[string]string{"user": "u-1001"},
Attributes: map[string]any{"plan": "pro", "app_version": "1.9.3"},
}, "new_checkout")
fmt.Println(string(r.Value), r.Reason, r.RuleID)
}
Output: true rule 01J9
func (*Ruleset) EvaluateAll ¶
EvaluateAll evaluates every flag of the ruleset for a context, keyed by flag key. Prerequisite results are memoized within the call.
func (*Ruleset) Flag ¶
Flag returns the flag with key, as the document has it, and whether the document has it. SDKs check a flag's type against the one requested.
func (*Ruleset) Protected ¶
Protected reports whether the ruleset belongs to a protected environment. SDKs refuse local overrides there.
func (*Ruleset) UnsupportedRules ¶
UnsupportedRules reports, by flag key, the constructs each flag holds that this evaluator does not know, in document order, each once. A flag holds what its rules hold and what the segments its rules name hold. It is empty for a ruleset this evaluator fully supports.
type Segment ¶
type Segment struct {
Key string `json:"key"`
Private bool `json:"private"`
Conditions []Condition `json:"conditions"`
}
Segment is a reusable, named AND-set of attribute conditions.
type Semver ¶
type Semver struct {
// contains filtered or unexported fields
}
Semver is a parsed semantic version. Build metadata is dropped because it never affects precedence.
func ParseSemver ¶
ParseSemver parses an optional lower-case "v", one to three dot-separated non-negative integers (missing components are 0, so "1.17" equals "1.17.0"), an optional "-" pre-release and an optional "+" build. Numeric components are unbounded and leading zeros are ignored. Pre-release and build identifiers are non-empty runs of [0-9A-Za-z-]. Anything else is not a version and makes a semver condition false.
type Serve ¶
type Serve struct {
Kind string `json:"kind"`
Variation string `json:"variation,omitempty"`
UnitType string `json:"unit_type,omitempty"`
Percentage int `json:"percentage,omitempty"`
Salt string `json:"salt,omitempty"`
Experiment string `json:"experiment,omitempty"`
InclusionSalt string `json:"inclusion_salt,omitempty"`
VariationSalt string `json:"variation_salt,omitempty"`
TrafficAllocation int `json:"traffic_allocation,omitempty"`
Weights []Weight `json:"weights,omitempty"`
}
Serve is what a matching rule serves. Fields apply per kind: variation uses Variation; rollout uses UnitType, Variation, Percentage and Salt; experiment uses Experiment and the running experiment's frozen fields the ruleset materializes next to it.
type Variation ¶
type Variation struct {
Key string `json:"key"`
Value json.RawMessage `json:"value"`
}
Variation is one named value a flag can serve.