This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
flagd-evaluator is a WebAssembly-based JSON Logic evaluator designed for feature flag evaluation. It's written in Rust and compiled to WASM (~2.4MB optimized binary) to provide consistent evaluation logic across all OpenFeature flagd providers (Java, JavaScript, .NET, Go, Python, PHP, etc.).
Key Purpose: This is the shared evaluation engine used by all in-process flagd providers to ensure uniform behavior across polyglot architectures. See the flagd providers specification for integration details.
# Build for native development/testing
cargo build
# Build optimized WASM (production)
cargo build --target wasm32-unknown-unknown --no-default-features --release --lib
# WASM output location
# target/wasm32-unknown-unknown/release/flagd_evaluator.wasm
# Run all tests
cargo test
# Run specific test file
cargo test --test integration_tests
cargo test --test gherkin_tests
# Run specific test by name
cargo test test_fractional_operator
# Run with output visible
cargo test -- --nocapture# Format code (required before commit)
cargo fmt
# Check formatting without changing files
cargo fmt -- --check
# Lint code (must pass with no warnings)
cargo clippy -- -D warnings- WASM-First: Compiled to WebAssembly for cross-language portability
- No External Dependencies: Single WASM file, no JNI, no JavaScript bindings
- Chicory Compatible: Works with pure Java WASM runtimes (no native code)
- Memory Safe: Explicit alloc/dealloc, no panics, all errors returned as JSON
- Size Optimized: Aggressive compilation flags (
opt-level = "z", LTO, panic = "abort")
src/
├── lib.rs # Main entry point, WASM exports (update_state, evaluate)
├── evaluation.rs # Core flag evaluation logic, context enrichment ($flagd properties)
├── memory.rs # WASM memory management (alloc/dealloc, pointer packing)
├── storage/ # Thread-local flag state storage
├── operators/ # Custom JSON Logic operators
│ ├── fractional.rs # MurmurHash3-based consistent bucketing for A/B testing
│ ├── sem_ver.rs # Semantic version comparison (=, !=, <, <=, >, >=, ^, ~)
│ ├── starts_with.rs # String prefix matching
│ └── ends_with.rs # String suffix matching
├── model/ # Flag configuration data structures
└── validation.rs # JSON Schema validation against flagd schemas
WASM Exports (lib.rs:138-625):
evaluate_logic(rule_ptr, rule_len, data_ptr, data_len) -> u64- Direct JSON Logic evaluationupdate_state(config_ptr, config_len) -> u64- Store flag configuration, returns changed flagsevaluate(flag_key_ptr, flag_key_len, context_ptr, context_len) -> u64- Evaluate stored flagalloc(len) -> *mut u8- Allocate WASM memorydealloc(ptr, len)- Free WASM memoryset_validation_mode(mode) -> u64- Set strict (0) or permissive (1) validation
All functions return packed u64: upper 32 bits = pointer, lower 32 bits = length.
Memory Model: Caller allocates input buffers, callee allocates result buffers. Caller must free all allocations. UTF-8 JSON strings for all inputs/outputs.
Context Enrichment (evaluation.rs): The evaluator automatically injects standard $flagd properties into evaluation context:
$flagd.flagKey- The flag being evaluated$flagd.timestamp- Unix timestamp (seconds) at evaluation timetargetingKey- Defaults to empty string if not provided in context
Custom Operators: All registered via datalogic_rs::Operator trait (operators/mod.rs). See flagd custom operations spec for full details.
Validation: Uses jsonschema crate to validate flag configs against flagd-schemas. Two modes:
- Strict (default): Reject invalid configs
- Permissive: Accept with warnings (for legacy compatibility)
Flag State Management (storage/mod.rs): Thread-local storage for flag configurations. update_state detects and reports changed flags (added, removed, or mutated).
Critical Build Flags (Cargo.toml:46-51):
[profile.release]
opt-level = "z" # Optimize for size
lto = true # Link-time optimization
codegen-units = 1 # Single codegen unit for better optimization
strip = true # Strip symbols
panic = "abort" # Remove panic unwinding infrastructureNo Default Features for WASM: Always build with --no-default-features to exclude unnecessary dependencies from WASM binary.
- Never panic in WASM exports: All errors must be returned as JSON error responses
- Always validate UTF-8: Use
string_from_memory()which returns Result - Pointer lifetime: WASM memory is stable within a single function call but may be reallocated between calls
- Safety comments required: All
unsafeblocks must have// SAFETY:comments explaining why they're safe
JSON Logic Evaluation (lib.rs:173-175):
match logic.evaluate_json(&rule_str, &data_str) {
Ok(result) => EvaluationResponse::success(result),
Err(e) => EvaluationResponse::error(format!("{}", e)),
}Flag Evaluation (evaluation.rs): Returns EvaluationResult with standardized error codes:
FLAG_NOT_FOUND- Flag key not in configurationPARSE_ERROR- JSON parsing or rule evaluation errorTYPE_MISMATCH- Resolved value doesn't match expected typeGENERAL- Other errors
Resolution reasons: STATIC, DEFAULT, TARGETING_MATCH, DISABLED, ERROR, FLAG_NOT_FOUND
Integration Tests (tests/integration_tests.rs): Comprehensive tests covering:
- Basic JSON Logic operations
- All custom operators (fractional, sem_ver, starts_with, ends_with)
- Memory management
- Edge cases and error handling
- State management and flag evaluation
- Type-specific evaluation functions
- Context enrichment ($flagd properties)
Gherkin Tests (tests/gherkin_tests.rs): Specification compliance tests using the official flagd testbed.
When to Run Tests:
- ✅ After making code changes that affect behavior
- ✅ Before creating a PR
- ✅ When explicitly requested by user
- ❌ During initial exploration or code reading
- ❌ When just browsing documentation
Adding a New Custom Operator:
- Create new file in
src/operators/(e.g.,my_operator.rs) - Implement
datalogic_rs::Operatortrait - Register in
src/operators/mod.rsviacreate_evaluator() - Add tests in both unit tests and
tests/integration_tests.rs - Document in README.md under "Custom Operators" section
Modifying Flag Evaluation Logic:
- Primary logic is in
src/evaluation.rs - Context enrichment happens in
evaluate_flag()function - State retrieval uses thread-local storage via
get_flag_state() - Always maintain backward compatibility with flagd provider specification
- Test with targeting rules, disabled flags, and missing flags
Memory Management Changes:
- All WASM-facing functions must use packed u64 returns
- Use
string_to_memory()to allocate and pack results - Use
string_from_memory()to read inputs (handles UTF-8 validation) - Document caller responsibilities in function doc comments
- Test with the Java example in
examples/java/
Make Regular Commits: Commit your changes frequently with clear, descriptive messages. Don't wait until the end of a large feature to commit.
Follow Conventional Commits Format: Use the same format for regular commits as required for PR titles:
<type>(<scope>): <description>
[optional body]
[optional footer]
Examples:
# Feature commits
git commit -m "feat(operators): add new string matching operator"
git commit -m "feat(evaluation): support nested context properties"
# Bug fix commits
git commit -m "fix(memory): correct pointer alignment in alloc function"
git commit -m "fix(fractional): handle empty bucket key correctly"
# Documentation commits
git commit -m "docs: update API examples in README"
git commit -m "docs(operators): clarify sem_ver caret range behavior"
# Refactoring commits
git commit -m "refactor(storage): simplify flag state management"
# Test commits
git commit -m "test(fractional): add edge case for zero-weight buckets"
# Chore commits
git commit -m "chore(deps): update datalogic-rs to 4.1"
git commit -m "chore: remove unused chrono shim"Commit Message Guidelines:
- Use imperative mood ("add feature" not "added feature")
- Keep subject line under 72 characters
- Add body for complex changes explaining why, not what
- Reference issues when relevant:
Closes #123
When to Commit:
- ✅ After completing a logical unit of work
- ✅ Before switching to a different task
- ✅ After fixing a bug
- ✅ After adding tests
- ✅ Before taking a break or ending work session
- ❌ Don't commit broken code (unless marked with WIP)
- ❌ Don't commit commented-out code or debug statements
This project uses Release Please for automated releases:
- PR Titles Must Follow Conventional Commits: The PR title becomes the commit message (squash merge)
- Format:
<type>(<scope>): <description> - Types that trigger releases:
feat:- Minor version bump (new feature)fix:- Patch version bump (bug fix)perf:- Patch version bump (performance improvement)feat!:orBREAKING CHANGE:- Major version bump
- Types for changelog only (no release):
docs:,chore:,test:,ci:,refactor:,style:,build:
PR Title Validation: GitHub workflow (.github/workflows/pr-title.yml) automatically validates format.
Core Production:
datalogic-rs(4.0) - JSON Logic implementationserde,serde_json- JSON serialization (no_std compatible with alloc)boon(0.6) - JSON Schema validationmurmurhash3- Hash function for fractional operatorahash- Hash table implementation (SIMD-disabled for Chicory compatibility)getrandom- Random number generation for WASM
Dev:
cucumber- Gherkin/BDD testingtokio- Async runtime for tests
This WASM module is embedded in multiple language providers. Key integration patterns:
Java (Chicory):
// Load WASM, get exports for alloc/dealloc/evaluate_logic
// Allocate memory for inputs, write UTF-8 JSON
// Call function, unpack u64 result
// Read result from memory, deallocate all memorySee examples/java/FlagdEvaluatorExample.java for complete working example.
General Pattern:
- Load WASM module
- Get function exports (alloc, dealloc, evaluate_logic, update_state, evaluate)
- For each call:
- Allocate memory for inputs using
alloc() - Write UTF-8 encoded JSON strings to WASM memory
- Call evaluation function with pointers and lengths
- Unpack returned u64 (ptr = upper 32 bits, len = lower 32 bits)
- Read result JSON from WASM memory
- Free all allocations using
dealloc()
- Allocate memory for inputs using
Memory Lifecycle: Host application owns all memory allocation/deallocation decisions. WASM module only allocates result memory internally.
In addition to WASM integration, this project provides native Python bindings using PyO3 for better performance and developer experience.
python/
├── src/
│ └── lib.rs # PyO3 bindings (FlagEvaluator class)
├── tests/ # Python test suite (pytest)
├── examples/ # Usage examples
├── benchmarks/ # Performance benchmarks
├── Cargo.toml # PyO3 dependencies
├── pyproject.toml # Maturin build config
└── README.md # Python-specific documentation
Recommended: Using uv (faster)
# Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh
# Set up development environment (installs deps and creates venv)
cd python
uv sync --group dev
source .venv/bin/activate
# Build and install locally
maturin develop
# Run tests
pytest tests/ -v
# Build wheels for distribution
maturin build --releaseAlternative: Using pip
# Install maturin
pip install maturin
# Build and install locally
cd python
maturin develop
# Run tests
pytest tests/ -v
# Build wheels for distribution
maturin build --releaseAPI Design: Pythonic dictionaries instead of JSON strings:
# PyO3 API (native)
evaluator = FlagEvaluator()
evaluator.update_state({"flags": {"myFlag": {...}}})
result = evaluator.evaluate("myFlag", {})
# vs WASM API (for comparison)
config_json = json.dumps({"flags": {"myFlag": {...}}})
update_state_wasm(config_json)
result_json = evaluate_wasm("myFlag", "{}")
result = json.loads(result_json)State Management: Python class with internal state instead of thread-local storage:
evaluator = FlagEvaluator() # Instance-based state
evaluator.update_state(config)
result = evaluator.evaluate_bool("myFlag", {}, False)Error Handling: Native Python exceptions instead of JSON error responses:
try:
result = evaluator.evaluate_bool("nonexistent", {}, False)
except KeyError as e:
print(f"Flag not found: {e}")Native bindings provide 5-10x better performance than WASM:
- No WASM instantiation overhead
- Direct memory sharing (no serialization)
- Native Python exceptions (no JSON parsing)
Python wheels are built automatically for:
- Linux: x86_64, aarch64 (manylinux)
- macOS: x86_64, aarch64 (Apple Silicon)
- Windows: x64
See .github/workflows/python-wheels.yml for the build configuration.
- Flagd Provider Specification: https://github.com/open-feature/flagd/blob/main/docs/reference/specifications/providers.md
- In-Process Resolver: https://github.com/open-feature/flagd/blob/main/docs/reference/specifications/providers.md#in-process-resolver
- Custom Operations Spec: https://flagd.dev/reference/specifications/custom-operations/
- Flag Definitions Schema: https://flagd.dev/reference/flag-definitions/
- JSON Logic: https://jsonlogic.com/
- datalogic-rs: https://github.com/cozylogic/datalogic-rs
- Chicory WASM Runtime: https://github.com/nicknisi/chicory
The .github/copilot-instructions.md file contains extensive context about this project including:
- Architecture and purpose
- WASM function exports and memory management
- Testing guidelines (when to run tests vs when to just read them)
- Custom operators implementation details
- Pull request conventions
- Integration patterns with host languages
Refer to that file for additional context when working on this repository.