ruleix

package module
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 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.
  • Optional per-worker Local caches for workloads with query locality.
  • 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}
	var matches []string
	index.Search(query, &matches)
	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

Search appends matches to the supplied slice and returns whether that call found at least one match. Reset the slice when previous results are not needed:

var matches []string
index.Search(query, &matches)

matches = matches[:0]
index.Search(nextQuery, &matches)

An Index is immutable and its Search method is safe for concurrent use.

Choosing Index or Local

Use Index.Search for independent queries, simple concurrency, and controlled scratch-memory retention. Use a Local when one worker repeatedly searches related values and can benefit from cached intermediate and exact results.

local := index.Local()
defer local.Close()

for query := range queries {
	matches = matches[:0]
	local.Search(query, &matches)
}

A Local is not safe for concurrent use; create one per goroutine. It is the explicit memory-for-speed path and may retain wide cached results. Always call Close so its state can be cleared and reused. A closed Local cannot be used again.

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 and unsampled Local contexts use the plain search tree. 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,
	}
	var matches []string
	index.Search(query, &matches)
	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]) Local

func (ix *Index[C, ID]) Local() *Local[C, ID]

Local returns a search context that caches every materialized intermediate bitmap result for its lifetime. It can eliminate repeated work across an arbitrarily large query working set at the cost of retaining every distinct cached query value and result until Close. Use Index.Search for one-off queries that should not retain per-query state.

A Local is not safe for concurrent use. Create one per goroutine:

local := index.Local()
var matches []ID
for value := range values {
	local.Search(value, &matches)
}

Call Close when the context is no longer needed so its internal resources can be reused. The Index remains immutable and may be shared by all of those goroutines.

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)
	}

	// Local caches intermediate bitmaps between calls. Keep it in one goroutine.
	local := index.Local()
	defer local.Close()
	var matches []string
	for _, region := range []int{20, 30} {
		matches = matches[:0]
		local.Search(constraint{store: pointer(10), region: pointer(region)}, &matches)
		fmt.Println(matches)
	}

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

func (*Index[C, ID]) Search

func (ix *Index[C, ID]) Search(value C, dst *[]ID) bool

Search appends the unique IDs of every stored rule matching value to dst, reports whether this call found any matches, and updates the slice through its pointer if append allocates a larger backing array. Existing elements in dst do not affect the reported result. Results preserve first-insertion order. Search panics when dst is nil.

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 Local

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

Local is a search context that keeps per-node cached results between calls. It must not be used concurrently by multiple goroutines.

func (*Local[C, ID]) Close

func (local *Local[C, ID]) Close()

Close releases cached search results and returns the internal context to the originating Index for reuse. Empty per-node cache structures and learned All child orders remain with that recyclable context, while all query and result state is reset so its next Local lifetime starts cold. A closed Local must not be used again. Repeated calls to Close are safe.

func (*Local[C, ID]) Search

func (local *Local[C, ID]) Search(value C, dst *[]ID) bool

Search appends matching IDs to dst while reusing this Local's cached state and reports whether this call found any matches. Existing elements in dst do not affect the reported result. Search panics when dst is nil.

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 repeated searches with a local cache.
Command local_search demonstrates repeated searches with a local cache.
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