ruleix

package module
v0.10.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ruleix

ruleix is a strongly typed, in-memory rule index for Go. It solves the inverse lookup problem: given one concrete value, find every stored rule whose optional constraints match it.

It is useful for pricing, feature flags, promotions, routing, and audience targeting when the same rule schema is searched repeatedly.

SELECT * FROM rules
WHERE (store_id = $1 OR store_id IS NULL)
  AND (region_id = $2 OR region_id IS NULL);

In a stored rule, a missing value acts as a wildcard. Ruleix compiles these rules into an immutable index and combines precomputed candidate sets instead of scanning every rule for every query.

Features

  • Generic, strongly typed API without runtime reflection in search.
  • Equality, exclusion, ordered, interval, and stored-operator filters.
  • Conjunctions with All, including direct access to nested fields.
  • Unique results in first-insertion order.
  • Immutable indexes that support concurrent searches.
  • Batch search with one internally managed cache context per request.
  • Memory-bounded conservative indexes through Lossy.
  • Opt-in build and sampled runtime diagnostics through Inspect.

Ruleix requires Go 1.24 or newer.

Installation

go get github.com/typomaker/ruleix

Quick start

Define one struct type for both stored constraints and concrete queries. Every getter returns (value, ok): ok == false means that the field is missing.

package main

import (
	"cmp"
	"fmt"

	"github.com/typomaker/ruleix"
)

type Constraint struct {
	Country      *string
	MinimumTotal *int
}

func main() {
	schema := ruleix.All(
		ruleix.Include(ruleix.GetterFromPointer(
			func(c Constraint) *string { return c.Country },
		)),
		ruleix.GreaterOrEqual(ruleix.GetterFromPointer(
			func(c Constraint) *int { return c.MinimumTotal },
		), cmp.Compare[int]),
	)

	countryDE, minimum100 := "DE", 100
	constraints := []Constraint{
		{Country: &countryDE, MinimumTotal: &minimum100},
		{Country: &countryDE},
		{},
	}
	ids := []string{"de-orders-over-100", "all-de", "global"}

	index, err := ruleix.New[Constraint, string](schema).Build(
		ruleix.Zip(constraints, ids),
	)
	if err != nil {
		panic(err)
	}

	minimum150 := 150
	query := Constraint{Country: &countryDE, MinimumTotal: &minimum150}
	found := make([][]string, 1)
	index.Search([]Constraint{query}, found)
	matches := found[0]
	fmt.Println(matches)
	// Output: [de-orders-over-100 all-de global]
}

Runnable examples cover multiple columns, repeated local searches, and Between with CompareBy.

Matching semantics

Filter A stored constraint matches when
Include The query value equals the stored value.
Exclude The query value does not equal the stored forbidden value.
GreaterOrEqual The query value is greater than or equal to the stored value.
LessOrEqual The query value is less than or equal to the stored value.
Greater The query value is greater than the stored value.
Less The query value is less than the stored value.
Between The stored interval fully covers the query interval.
CompareBy The comparison operator stored with the constraint evaluates to true.
All Every child rule matches.

For ordinary filters, a missing stored value is a wildcard and matches every concrete query value. A missing query value matches only stored wildcards. Zero values remain concrete when returned with ok == true.

For Exclude, a missing stored value forbids nothing. Between evaluates:

stored.from <= query.from AND query.until <= stored.until

Either stored bound may be a wildcard. CompareBy supports OperatorEQ, OperatorLT, OperatorLTE, OperatorGT, and OperatorGTE. Its query-side operator is ignored; the operator belongs to each stored constraint.

Building an index

New returns a reusable builder. Build consumes an iter.Seq2 of constraints and external IDs. Zip is a convenience for parallel slices and panics when their lengths differ.

builder := ruleix.New[Constraint, string](schema)
index, err := builder.Build(ruleix.Zip(constraints, ids))

Keep the builder when periodically rebuilding the same schema. Each successful call returns an independent immutable index; earlier indexes remain valid. Do not call Build concurrently on the same builder without external synchronization. A failed build does not publish partial state or prevent a later build.

When the same external ID appears more than once, its constraints are combined under that ID. Search returns the ID at most once, ordered by its first insertion.

Searching

Index.Search(conditions, found) appends matches for conditions[i] to found[i], preserving first-insertion ID order. The outer slices must have identical lengths; a mismatch panics before changing any result.

conditions := []Constraint{query, nextQuery}
found := make([][]string, len(conditions))
index.Search(conditions, found)

// Reset each destination before the next request if old results are not needed.
for i := range found {
    found[i] = found[i][:0]
}
index.Search(conditions, found)

For one condition, pass a one-element slice. Search returns true if this call appends at least one match across the batch, and false otherwise, including empty batches. Existing destination contents do not count. Every condition is processed even after a match. Inner destination backing arrays must not overlap.

An Index is immutable and safe for concurrent calls with independent outputs. Each call acquires one private cache context and releases it on return; there is no public Local lifecycle. Related conditions can share postings and checks. See batch search for execution and fallback details and API migration for the breaking change from v0.9.0 and the experimental SearchBatch API.

Memory-bounded indexes

Lossy puts a retained-memory limit around one supported rule or a complete All subtree:

bounded := ruleix.Lossy(
	ruleix.All(
		ruleix.Include(customerID),
		ruleix.GreaterOrEqual(minimumTotal, cmp.Compare[int]),
	),
	ruleix.MemoryLimit(20<<20),
)

The exact representation is retained when it fits. Under pressure, Ruleix selects a coarser conservative representation: search may return false positives but never omit an exact match. MemoryLimit applies to Ruleix's deterministic retained accounting, not transient heap use or process RSS. Build returns an error when no supported representation can satisfy the limit.

See the Lossy index contract for supported value types, nested limits, accounting, and precision behavior.

Diagnostics

Wrap a rule with Inspect to observe the representation selected by Build:

var inspector ruleix.Inspector
observed := ruleix.Inspect(&inspector, bounded)
index, err := ruleix.New[Constraint, string](observed).Build(entries)
snapshot := inspector.Snapshot()

Snapshots describe the latest successful build and low-priority sampled runtime metrics. They are diagnostics, not exact workload accounting. Shared Index searches use the plain search tree unless their internal context is sampled. See the inspection API contract for availability and sampling semantics.

Documentation

Development

go test ./...
go test -race ./...
make lint

Documentation

Overview

Package ruleix implements a strongly typed in-memory rule index.

Example (MultiColumnRules)
package main

import (
	"cmp"
	"fmt"

	"github.com/typomaker/ruleix"
)

func main() {
	type targetingConstraint struct {
		country         *string
		tier            *string
		minimumTotal    *int
		excludedChannel *string
	}

	schema := ruleix.All(
		ruleix.Include(ruleix.GetterFromPointer(func(c targetingConstraint) *string { return c.country })),
		ruleix.Include(ruleix.GetterFromPointer(func(c targetingConstraint) *string { return c.tier })),
		ruleix.GreaterOrEqual(ruleix.GetterFromPointer(func(c targetingConstraint) *int { return c.minimumTotal }), cmp.Compare[int]),
		ruleix.Exclude(ruleix.GetterFromPointer(func(c targetingConstraint) *string { return c.excludedChannel })),
	)

	countryDE := "DE"
	tierGold := "gold"
	minimum100 := 100
	marketplace := "marketplace"
	constraints := []targetingConstraint{
		{
			country:         &countryDE,
			tier:            &tierGold,
			minimumTotal:    &minimum100,
			excludedChannel: &marketplace,
		},
		{country: &countryDE},
		{},
	}
	ids := []string{"gold-de", "all-de", "global"}

	entries := ruleix.Zip(constraints, ids)
	index, err := ruleix.New[targetingConstraint, string](schema).Build(entries)
	if err != nil {
		panic(err)
	}

	minimum150 := 150
	web := "web"
	query := targetingConstraint{
		country:         &countryDE,
		tier:            &tierGold,
		minimumTotal:    &minimum150,
		excludedChannel: &web,
	}
	found := make([][]string, 1)
	index.Search([]targetingConstraint{query}, found)
	matches := found[0]
	fmt.Println(matches)

}
Output:
[gold-de all-de global]

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Zip

func Zip[C any, ID any](constraints []C, ids []ID) iter.Seq2[C, ID]

Zip pairs equally sized constraint and ID slices into a sequence accepted by Builder.Build. It panics when the slice lengths differ. The slices are read when the returned sequence is consumed, not when Zip is called.

Types

type Builder

type Builder[C any, ID comparable] struct {
	// contains filtered or unexported fields
}

Builder constructs immutable indexes from the same Rule schema. A Builder is not safe for concurrent calls to Build; callers that need them must provide their own synchronization. Indexes returned by completed builds are independent and safe for concurrent use.

func New

func New[C any, ID comparable](schema Rule[C]) *Builder[C, ID]

New constructs a Builder from a strongly typed rule schema. New panics when schema is nil.

func (*Builder[C, ID]) Build

func (b *Builder[C, ID]) Build(entries iter.Seq2[C, ID]) (*Index[C, ID], error)

Build consumes entries and returns an immutable, concurrently searchable Index. Constraints that share an external ID are combined under that ID, which is returned at most once by a search. Build must not be called concurrently on the same Builder; the library deliberately leaves synchronization of builds to the caller. A failed build does not prevent later calls.

type Compare

type Compare[V any] func(a, b V) int

Compare defines an ordering for values used by ordered filters. It returns a negative number when a < b, zero when a == b, and a positive number when a > b. Compare must define a stable, transitive total order for every value supplied during Build and Search. The standard library's cmp.Compare is suitable for ordered types.

type Getter

type Getter[T, V any] func(T) (V, bool)

Getter returns a value and reports whether it is present. A missing value is interpreted as a wildcard by filters. The boolean keeps zero values distinct from missing values without requiring pointers or heap allocations.

func GetterFromPointer

func GetterFromPointer[T, V any](get func(T) *V) Getter[T, V]

GetterFromPointer adapts an old pointer getter during migration. New schemas should return (value, ok) directly to avoid pointers to temporary values.

type Histogram

type Histogram struct {
	Zero, One, TwoToFour, FiveToSixteen, SeventeenTo256, Above256 uint64
}

Histogram groups observed values into stable, allocation-free bins. Each bin includes its lower bound and excludes the next bin's lower bound.

type Index

type Index[C any, ID comparable] struct {
	// contains filtered or unexported fields
}

Index maps query values to the unique IDs of all matching stored constraints. It is immutable after Build and safe for concurrent calls to Search.

func (*Index[C, ID]) Search

func (ix *Index[C, ID]) Search(conditions []C, found [][]ID) bool

Search appends the matches for conditions[i] to found[i], preserving first-insertion ID order and existing destination elements. The outer slices must have equal lengths; a mismatch panics before any result is changed. Search returns whether this call appended any matches. Existing destination contents do not count. Empty batches return false. Each call owns its context. Callers must not concurrently mutate inputs or destinations, and destination backing arrays must not overlap.

Example
package main

import (
	"fmt"

	"github.com/typomaker/ruleix"
)

func main() {
	type constraint struct {
		store  *int
		region *int
	}
	pointer := func(value int) *int { return &value }

	entries := ruleix.Zip(
		[]constraint{
			{},
			{store: pointer(10)},
			{store: pointer(10), region: pointer(20)},
			{store: pointer(10), region: pointer(30)},
		},
		[]string{"global", "store", "region-20", "region-30"},
	)
	index, err := ruleix.New[constraint, string](ruleix.All(
		ruleix.Include(ruleix.GetterFromPointer(func(c constraint) *int { return c.store })),
		ruleix.Include(ruleix.GetterFromPointer(func(c constraint) *int { return c.region })),
	)).Build(entries)
	if err != nil {
		panic(err)
	}

	conditions := []constraint{
		{store: pointer(10), region: pointer(20)},
		{store: pointer(10), region: pointer(30)},
	}
	found := make([][]string, len(conditions))
	index.Search(conditions, found)
	for _, matches := range found {
		fmt.Println(matches)
	}

}
Output:
[global store region-20]
[global store region-30]

type Inspector

type Inspector interface {
	Snapshot() InspectorSnapshot
	// contains filtered or unexported methods
}

Inspector captures immutable views of one rule's compiled representation and accumulated runtime metrics. Inspect selects and assigns the implementation when it decorates a rule.

type InspectorSnapshot

type InspectorSnapshot struct {
	// contains filtered or unexported fields
}

InspectorSnapshot is a coherent view of the build generation selected by one Snapshot call and the runtime counters observed during that call.

func (InspectorSnapshot) Bound

func (s InspectorSnapshot) Bound() bool

Bound reports whether the snapshot belongs to a successful build.

func (InspectorSnapshot) CacheAdmission

func (s InspectorSnapshot) CacheAdmission() uint64

CacheAdmission reports observed cache admissions.

func (InspectorSnapshot) CacheEviction

func (s InspectorSnapshot) CacheEviction() uint64

CacheEviction reports observed cache evictions. Unbounded Local caches do not evict entries, so this compatibility counter remains zero.

func (InspectorSnapshot) CacheExpansion

func (s InspectorSnapshot) CacheExpansion() uint64

CacheExpansion reports observed adaptive cache capacity expansions. Local caches no longer have fixed capacities, so this compatibility counter remains zero.

func (InspectorSnapshot) CacheHit

func (s InspectorSnapshot) CacheHit() uint64

CacheHit reports observed cache hits.

func (InspectorSnapshot) CacheMiss

func (s InspectorSnapshot) CacheMiss() uint64

CacheMiss reports observed cache misses.

func (InspectorSnapshot) CandidateCheck

func (s InspectorSnapshot) CandidateCheck() uint64

CandidateCheck reports observed direct internal-ID membership checks.

func (InspectorSnapshot) DistinctValueCount

func (s InspectorSnapshot) DistinctValueCount() (uint64, bool)

DistinctValueCount reports indexed concrete values, excluding wildcards.

func (InspectorSnapshot) EmptyResult

func (s InspectorSnapshot) EmptyResult() uint64

EmptyResult reports observed empty results.

func (InspectorSnapshot) EntryCount

func (s InspectorSnapshot) EntryCount() uint64

EntryCount reports the number of input entries consumed by the build.

func (InspectorSnapshot) FalsePositiveRate

func (s InspectorSnapshot) FalsePositiveRate() (float64, bool)

FalsePositiveRate reports an estimate when one is meaningful.

func (InspectorSnapshot) Granularity

func (s InspectorSnapshot) Granularity() (uint64, bool)

Granularity reports the selected number of quantized key classes.

func (InspectorSnapshot) ItemCount

func (s InspectorSnapshot) ItemCount() (uint64, bool)

ItemCount reports indexed wildcard and concrete posting items.

func (InspectorSnapshot) MemoryLimit

func (s InspectorSnapshot) MemoryLimit() (uint64, bool)

MemoryLimit reports the effective representation byte limit after applying every ancestor policy limit.

func (InspectorSnapshot) MemoryUsage

func (s InspectorSnapshot) MemoryUsage() (uint64, bool)

MemoryUsage reports deterministic accounted representation bytes.

func (InspectorSnapshot) Mode

func (s InspectorSnapshot) Mode() RuleMode

Mode reports the compiled representation mode.

func (InspectorSnapshot) RangePruning

func (s InspectorSnapshot) RangePruning() uint64

RangePruning reports observed early All exits proved by disjoint bitmap ID ranges.

func (InspectorSnapshot) ResultCardinality

func (s InspectorSnapshot) ResultCardinality() Histogram

ResultCardinality reports the captured result-cardinality histogram.

func (InspectorSnapshot) RuleCount

func (s InspectorSnapshot) RuleCount() uint64

RuleCount reports the number of unique external rule IDs in the build.

func (InspectorSnapshot) Strategy

func (s InspectorSnapshot) Strategy() string

Strategy reports the compiled strategy.

type LossyOption

type LossyOption interface {
	// contains filtered or unexported methods
}

LossyOption configures a memory-bounded representation selected during Build. Implementations are sealed so new options can be added without weakening validation of a schema.

func MemoryLimit

func MemoryLimit(bytes uint64) LossyOption

MemoryLimit sets the maximum accounted bytes retained by one Lossy rule.

type Operator

type Operator uint8

Operator identifies a comparison stored in a CompareBy constraint. The comparison is written from the query's perspective: OperatorGTE means query >= stored.

const (
	// OperatorEQ selects query == stored.
	OperatorEQ Operator = iota
	// OperatorLT selects query < stored.
	OperatorLT
	// OperatorLTE selects query <= stored.
	OperatorLTE
	// OperatorGT selects query > stored.
	OperatorGT
	// OperatorGTE selects query >= stored.
	OperatorGTE
)

type Rule

type Rule[T any] interface {
	// contains filtered or unexported methods
}

Rule describes how constraints and query values of T are matched. Construct rules with Include, Exclude, the ordered filters, Between, CompareBy, and All. Its implementation is sealed so an index can rely on all rule invariants.

func All

func All[T any](rules ...Rule[T]) Rule[T]

All combines rules with logical AND: a stored constraint matches only when every child rule matches. All may be nested.

For example, to match both country and customer tier:

ruleix.All(
	ruleix.Include(func(c Constraint) (string, bool) { return c.Country, true }),
	ruleix.Include(func(c Constraint) (string, bool) { return c.Tier, true }),
)

func Between

func Between[T any, V any](from, until Getter[T, V], compare Compare[V]) Rule[T]

Between matches an interval fully covered by a stored interval: stored.from <= query.from AND query.until <= stored.until. Either missing stored bound is a wildcard for that side of the interval; a missing query bound matches only a stored wildcard on the same side.

For example, to find stored validity windows that cover a query window:

ruleix.Between(
	func(c Constraint) (time.Time, bool) { return c.ValidFrom, true },
	func(c Constraint) (time.Time, bool) { return c.ValidUntil, true },
	time.Time.Compare,
)

func CompareBy

func CompareBy[T any, V any](
	value Getter[T, V],
	operator Getter[T, Operator],
	compare Compare[V],
) Rule[T]

CompareBy evaluates the operator stored in each inserted rule against the concrete value supplied to Search. The query-side operator is ignored. A missing stored value is a wildcard and its operator is not validated. Build returns an error when a non-wildcard rule has no operator or an unsupported operator.

For example, a stored value with OperatorGTE and value 5 matches a query whose value is 7:

ruleix.CompareBy(
	func(c Constraint) (int, bool) { return c.Orders, true },
	func(c Constraint) (ruleix.Operator, bool) { return c.Operator, true },
	cmp.Compare[int],
)

func Exclude

func Exclude[T any, V comparable](get Getter[T, V]) Rule[T]

Exclude indexes an optional forbidden value. ok == false means no forbidden value. A concrete match excludes the associated result ID even when another stored constraint with that ID matches.

For example, to reject rules whose forbidden channel equals the query channel:

ruleix.Exclude(func(c Constraint) (string, bool) { return c.ExcludedChannel, true })

func Greater

func Greater[T any, V any](get Getter[T, V], compare Compare[V]) Rule[T]

Greater matches query > stored. A missing stored value is a wildcard.

For example, a stored order-count threshold of 5 matches a query count of 6:

ruleix.Greater(
	func(c Constraint) (int, bool) { return c.OrderCountThreshold, true },
	cmp.Compare[int],
)

func GreaterOrEqual

func GreaterOrEqual[T any, V any](get Getter[T, V], compare Compare[V]) Rule[T]

GreaterOrEqual matches query >= stored. A missing stored value is a wildcard.

For example, a stored minimum total of 100 matches a query total of 150:

ruleix.GreaterOrEqual(
	func(c Constraint) (int, bool) { return c.MinimumTotal, true },
	cmp.Compare[int],
)

func Include

func Include[T any, V comparable](get Getter[T, V]) Rule[T]

Include matches a query field when it equals the stored field. A missing stored value is a wildcard and matches every concrete query value; a missing query value matches only stored wildcards.

For example, to match a rule's optional country:

ruleix.Include(func(c Constraint) (string, bool) { return c.Country, true })

func Inspect

func Inspect[T any](dst *Inspector, rule Rule[T]) Rule[T]

Inspect decorates rule with an observational handle. It does not change the compiled search tree or matching semantics. Inspect panics for a nil inspector or rule. Attaching the same inspector more than once in one schema makes Build fail.

func Less

func Less[T any, V any](get Getter[T, V], compare Compare[V]) Rule[T]

Less matches query < stored. A missing stored value is a wildcard.

For example, a stored upper limit of 10 matches a query value of 9:

ruleix.Less(
	func(c Constraint) (int, bool) { return c.UpperLimit, true },
	cmp.Compare[int],
)

func LessOrEqual

func LessOrEqual[T any, V any](get Getter[T, V], compare Compare[V]) Rule[T]

LessOrEqual matches query <= stored. A missing stored value is a wildcard.

For example, a stored maximum total of 200 matches a query total of 150:

ruleix.LessOrEqual(
	func(c Constraint) (int, bool) { return c.MaximumTotal, true },
	cmp.Compare[int],
)

func Lossy

func Lossy[T any](rule Rule[T], options ...LossyOption) Rule[T]

Lossy permits rule to use a conservative approximation when its exact representation does not fit the configured memory limit. Approximate searches can return false positives, but never omit an exact match.

type RuleMode

type RuleMode string

RuleMode describes whether a compiled rule retains exact matching semantics or uses an approximation that may return false positives.

const (
	// RuleModeExact reports a representation with no false positives.
	RuleModeExact RuleMode = "exact"
	// RuleModeLossy reports a conservative representation that may include
	// false positives but never excludes an exact match.
	RuleModeLossy RuleMode = "lossy"
)

Directories

Path Synopsis
examples
between_and_gt command
Package main demonstrates combining Between with a strict greater-than rule.
Package main demonstrates combining Between with a strict greater-than rule.
local_search command
Command local_search demonstrates a batch of related searches.
Command local_search demonstrates a batch of related searches.
multiple_columns command
Package main demonstrates matching rules across several independent columns.
Package main demonstrates matching rules across several independent columns.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL