mirror of
https://github.com/microsoft/regorus.git
synced 2026-08-05 02:16:11 +00:00
RVM compiler & runtime optimizations: caching, instruction fusion, constant hoisting, and correctness fixes (#626)
* perf!: add LRU caches for compiled regex and glob patterns
Add bounded LRU caches for compiled regex and glob patterns used by
Rego builtins, avoiding repeated recompilation of the same patterns
during policy evaluation.
New `cache` feature (included in `full-opa` and `opa-no-std`) backed by
the `lru` crate (no_std compatible) with `spin::Mutex` for thread safety.
- `src/cache.rs`: generic `LruCache<V>` wrapper, global `REGEX_CACHE`
(default capacity 256) and `GLOB_CACHE` (default capacity 128)
- `src/builtins/regex.rs`: all regex builtins route through the cache
- `src/builtins/glob.rs`: glob.match routes through the cache
- Public API: `regorus::cache::{Config, configure, clear}`
Compilation costs avoided per cache hit:
regex 10-55 µs (simple to complex patterns)
glob 10-12 µs
LRU hit ~10 ns
BREAKING CHANGE: new `cache` Cargo feature added to `full-opa` and
`opa-no-std` feature sets; adds `lru` as a dependency.
Signed-off-by: Anand Krishnamoorthi <anakrish@microsoft.com>
* perf(vm): amortize per-instruction memory and time limit checks
Deduplicate per-instruction memory_check calls by hoisting them to the
main dispatch loop, and amortize monotonic_now() syscalls in the
execution timer by checking elapsed time every N instructions instead
of on every tick.
Signed-off-by: Anand Krishnamoorthi <anakrish@microsoft.com>
* fix(vm): correct object membership to check values only, not keys
The Contains instruction for objects was checking both keys and values:
object_fields.contains_key(v) || object_fields.values().any(|v| ...)
Per the Rego specification, `x in obj` tests whether x is a VALUE of
the object, not a key. The two-argument form `k, v in obj` is needed
to access keys. The interpreter already implemented this correctly
(values-only scan), but the RVM had the extra contains_key() check
which would incorrectly return true when the search value happened to
match a key name.
Remove the contains_key() branch so the behavior matches the interpreter
and the Rego spec. Add two regression tests:
- object_membership_checks_values_not_keys: "foo" in {"foo": "bar"}
must be false (key, not a value)
- object_membership_finds_value: "bar" in {"foo": "bar"} must be true
Signed-off-by: Anand Krishnamoorthi <anakrish@microsoft.com>
* perf(compiler): hoist all-constant collection literals to the literal table
When an array, set, or object literal consists entirely of compile-time
constant expressions (numbers, strings, bools, null, and nested constant
collections), the compiler now evaluates them at compile time and emits a
single Load instruction from the literal table instead of generating
per-element instructions at runtime.
Previously, a Rego expression like `x in [1, 2, 3]` would emit
ArrayCreate + three Load + three ArrayAppend instructions, allocating a
new Vec and Rc on every evaluation. With this change, the entire array
is built once during compilation and loaded as a single constant.
This optimization applies to all three collection types:
- Array literals: avoids ArrayCreate + N x (Load + ArrayAppend)
- Set literals: avoids SetCreate + N x (Load + SetAdd)
- Object literals: avoids ObjectCreate + N x (Load + Load + ObjectInsert)
The implementation adds a try_eval_const() helper that recursively
evaluates an AST expression as a constant Value, returning None if any
sub-expression is non-constant. Each compile method for collection
literals attempts the all-constant fast path first and falls through to
the existing instruction-by-instruction codegen otherwise.
Signed-off-by: Anand Krishnamoorthi <anakrish@microsoft.com>
* perf(compiler): fuse Eq + AssertCondition into AssertEq instruction
Add a new `AssertEq { left, right }` instruction that combines equality
comparison and condition assertion into a single operation. This replaces
the previous two-instruction pattern of `Eq { dest, left, right }` followed
by `AssertCondition { condition: dest }`, saving one instruction and one
register per equality assertion.
The fused instruction checks two registers for equality and directly calls
handle_condition with the result, avoiding the intermediate boolean
register entirely. If either operand is undefined or the values differ,
the condition fails and the rule/loop backtracks.
The optimization applies to four destructuring sites:
- EqualityCheck (assignment re-binding with `x = expr; x = expr`)
- EqualityExpr (destructuring against an expression)
- EqualityValue (destructuring against a literal value)
- assert_array_length (array length validation in destructuring)
In soft_assert_mode the compiler still emits the original Eq instruction
since the boolean result register is needed by callers.
Signed-off-by: Anand Krishnamoorthi <anakrish@microsoft.com>
* perf(compiler): fuse Not + AssertCondition into AssertNot instruction
Add a new `AssertNot { operand }` instruction that combines logical
negation and condition assertion into a single operation. This replaces
the previous two-instruction pattern of `Not { dest, operand }` followed
by `AssertCondition { condition: dest }`, saving one instruction and one
register allocation.
The fused instruction checks the operand register and passes the
condition if the value is false or undefined (per Rego semantics where
`not expr` succeeds when the expression has no results or is false),
and fails the condition if the value is true or any non-boolean truthy
value.
This was the only emission site for the Not+AssertCondition pair,
occurring in the compilation of `Literal::NotExpr` statements.
Signed-off-by: Anand Krishnamoorthi <anakrish@microsoft.com>
* perf(vm): early exit for same-value multi-definition rules
When a rule has multiple definitions that all produce the same value
(e.g. implicit true, or identical literal), set early_exit_on_first_success
on RuleInfo so the VM can stop after the first successful definition.
Signed-off-by: Anand Krishnamoorthi <anakrish@microsoft.com>
* feat!: expose cache configuration API to all language bindings
Add `set_cache_config` and `clear_cache` functions to every binding
so callers can tune or reset the global regex/glob pattern caches
introduced in the cache feature.
Bindings updated:
- FFI (C): `regorus_set_cache_config`, `regorus_clear_cache`
- C++ header: free functions `regorus::set_cache_config`, `regorus::clear_cache`
- Python: module-level `set_cache_config(*, regex, glob)`, `clear_cache()`
- Java: static methods on new `CacheConfig` class
- Go: package-level `SetCacheConfig`, `ClearCache`
- Ruby: module functions `Regorus.set_cache_config`, `Regorus.clear_cache`
- WASM: free functions `setCacheConfig`, `clearCache`
- C#: static methods `Engine.SetCacheConfig`, `Engine.ClearCache`
BREAKING CHANGE: Bump SERIALIZATION_VERSION from 4 to 5 due to new
AssertEq and AssertNot instruction variants added in the instruction
fusion commits. Programs serialized with version 5 cannot be loaded
by older versions of regorus.
* fix: address PR review feedback
Cache subsystem:
- Gate REGEX_CACHE and related imports behind #[cfg(feature = "regex")]
so that building with --features cache without regex compiles correctly.
- Gate LruCache struct behind #[cfg(any(feature = "regex", feature = "glob"))].
- Add Config::MAX_CAPACITY (2^16) hard upper bound; clamp values in
configure() to prevent unbounded cache growth.
- Use parking_lot::Mutex for std builds and spin::Mutex for no_std to
avoid CPU spinning under contention in tight regex/glob eval loops.
- Narrow lock scopes in regex/glob builtins: release the mutex before
compiling a pattern, then re-acquire to insert.
Java JNI binding:
- Fix cache config overflow: negative jlong values now saturate to 0
and positive overflow saturates to usize::MAX (then clamped by
MAX_CAPACITY) instead of silently disabling the cache.
- Gate JNI cache config/clear functions behind #[cfg(feature = "cache")].
Compiler:
- Refactor static_value_of_expr to delegate to try_eval_const,
gaining support for negated numbers and constant collections.
- Make try_eval_const pub(in crate::languages::rego::compiler) and
re-export through expressions.rs.
- Handle Expr::UnaryExpr with numeric literals in try_eval_const so
collections containing negated numbers (e.g. [-1, 2]) are hoisted.
VM correctness:
- Fix Not instruction to follow Rego semantics: not expr yields
true when expr is undefined or false, false for any other defined
value (including non-booleans) -- no longer errors on non-boolean
operands.
- Add enforce_memory_check() call at execute_suspendable_entry to
ensure memory limits are checked before the first instruction.
- Update AssertNot listing comment to "exit if any defined truthy
value" to match actual VM behaviour.
- Add doc comment on Not instruction clarifying Rego negation
semantics.
Bindings:
- Fix C++ header indentation for set_cache_config / clear_cache.
- Propagate Cargo.lock parking_lot addition across ffi, java, python,
and wasm binding lockfiles.
Signed-off-by: Anand Krishnamoorthi <anakrish@microsoft.com>
---------
Signed-off-by: Anand Krishnamoorthi <anakrish@microsoft.com>
This commit is contained in:
committed by
GitHub
parent
898643129e
commit
83891d7782
343
tests/rvm/compiler.rs
Normal file
343
tests/rvm/compiler.rs
Normal file
@@ -0,0 +1,343 @@
|
||||
// Copyright (c) Microsoft Corporation.
|
||||
// Licensed under the MIT License.
|
||||
#![cfg(feature = "rvm")]
|
||||
|
||||
use regorus::languages::rego::compiler::Compiler;
|
||||
use regorus::rvm::Instruction;
|
||||
use regorus::{Engine, Rc, Value};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// Compile a single-rule Rego module and return the program.
|
||||
fn compile_rule(module: &str) -> std::sync::Arc<regorus::rvm::program::Program> {
|
||||
let mut engine = Engine::new();
|
||||
engine
|
||||
.add_policy("test.rego".to_string(), module.to_string())
|
||||
.expect("failed to add policy");
|
||||
let compiled = engine
|
||||
.compile_with_entrypoint(&Rc::from("data.test.p"))
|
||||
.expect("failed to compile policy");
|
||||
Compiler::compile_from_policy(&compiled, &["data.test.p"]).expect("failed to compile to RVM")
|
||||
}
|
||||
|
||||
/// Assert that the program's instruction stream contains no collection-create
|
||||
/// instructions (ArrayCreate, SetCreate, ObjectCreate), meaning the collections
|
||||
/// were hoisted into the literal table.
|
||||
fn assert_no_collection_create(program: ®orus::rvm::program::Program) {
|
||||
for (pc, instr) in program.instructions.iter().enumerate() {
|
||||
match instr {
|
||||
Instruction::ArrayCreate { .. } => {
|
||||
panic!("unexpected ArrayCreate at pc={pc}; expected hoisted constant")
|
||||
}
|
||||
Instruction::SetCreate { .. } => {
|
||||
panic!("unexpected SetCreate at pc={pc}; expected hoisted constant")
|
||||
}
|
||||
Instruction::ObjectCreate { .. } => {
|
||||
panic!("unexpected ObjectCreate at pc={pc}; expected hoisted constant")
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Assert the literal table contains a value equal to `expected`.
|
||||
fn assert_literal_exists(program: ®orus::rvm::program::Program, expected: &Value) {
|
||||
assert!(
|
||||
program.literals.iter().any(|v| v == expected),
|
||||
"expected literal {:?} not found in literal table: {:?}",
|
||||
expected,
|
||||
program.literals
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_array_is_hoisted() {
|
||||
let program = compile_rule(
|
||||
r#"
|
||||
package test
|
||||
p := x if { x := [1, 2, 3] }
|
||||
"#,
|
||||
);
|
||||
assert_no_collection_create(&program);
|
||||
assert_literal_exists(&program, &Value::from_json_str("[1, 2, 3]").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_set_is_hoisted() {
|
||||
let program = compile_rule(
|
||||
r#"
|
||||
package test
|
||||
p := x if { x := {1, 2, 3} }
|
||||
"#,
|
||||
);
|
||||
assert_no_collection_create(&program);
|
||||
let expected_set = Value::Set(Rc::new(
|
||||
[1, 2, 3]
|
||||
.into_iter()
|
||||
.map(Value::from)
|
||||
.collect::<BTreeSet<_>>(),
|
||||
));
|
||||
assert_literal_exists(&program, &expected_set);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_object_is_hoisted() {
|
||||
let program = compile_rule(
|
||||
r#"
|
||||
package test
|
||||
p := x if { x := {"a": 1, "b": 2} }
|
||||
"#,
|
||||
);
|
||||
assert_no_collection_create(&program);
|
||||
assert_literal_exists(
|
||||
&program,
|
||||
&Value::from_json_str(r#"{"a": 1, "b": 2}"#).unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_constant_collection_is_hoisted() {
|
||||
let program = compile_rule(
|
||||
r#"
|
||||
package test
|
||||
p := x if { x := [1, [2, 3], {"k": "v"}] }
|
||||
"#,
|
||||
);
|
||||
assert_no_collection_create(&program);
|
||||
assert_literal_exists(
|
||||
&program,
|
||||
&Value::from_json_str(r#"[1, [2, 3], {"k": "v"}]"#).unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_constant_array_is_not_hoisted() {
|
||||
let program = compile_rule(
|
||||
r#"
|
||||
package test
|
||||
p := x if { y := 1; x := [y, 2, 3] }
|
||||
"#,
|
||||
);
|
||||
// This array contains a variable reference, so it must NOT be hoisted.
|
||||
let has_array_create = program
|
||||
.instructions
|
||||
.iter()
|
||||
.any(|i| matches!(i, Instruction::ArrayCreate { .. }));
|
||||
assert!(
|
||||
has_array_create,
|
||||
"non-constant array should use ArrayCreate"
|
||||
);
|
||||
}
|
||||
|
||||
// --- AssertEq fusion tests ---
|
||||
|
||||
/// Count occurrences of a specific instruction pattern in the program.
|
||||
fn count_instructions(
|
||||
program: ®orus::rvm::program::Program,
|
||||
pred: impl Fn(&Instruction) -> bool,
|
||||
) -> usize {
|
||||
program.instructions.iter().filter(|i| pred(i)).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equality_check_emits_assert_eq() {
|
||||
// Assignment `x = 1` followed by `x = 1` triggers EqualityCheck in destructuring.
|
||||
let program = compile_rule(
|
||||
r#"
|
||||
package test
|
||||
p if { x = 1; x = 1 }
|
||||
"#,
|
||||
);
|
||||
let assert_eq_count =
|
||||
count_instructions(&program, |i| matches!(i, Instruction::AssertEq { .. }));
|
||||
assert!(
|
||||
assert_eq_count > 0,
|
||||
"expected AssertEq instruction for equality check"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destructuring_equality_emits_assert_eq() {
|
||||
let program = compile_rule(
|
||||
r#"
|
||||
package test
|
||||
p if { [1, x] := [1, 2] }
|
||||
"#,
|
||||
);
|
||||
let assert_eq_count =
|
||||
count_instructions(&program, |i| matches!(i, Instruction::AssertEq { .. }));
|
||||
assert!(
|
||||
assert_eq_count > 0,
|
||||
"expected AssertEq for destructuring equality"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn not_expr_emits_assert_not() {
|
||||
let program = compile_rule(
|
||||
r#"
|
||||
package test
|
||||
p if { not false }
|
||||
"#,
|
||||
);
|
||||
let assert_not_count =
|
||||
count_instructions(&program, |i| matches!(i, Instruction::AssertNot { .. }));
|
||||
assert!(
|
||||
assert_not_count > 0,
|
||||
"expected AssertNot for `not` expression"
|
||||
);
|
||||
// The Not+AssertCondition pair should be fused — no separate Not instruction.
|
||||
let not_count = count_instructions(&program, |i| matches!(i, Instruction::Not { .. }));
|
||||
assert_eq!(not_count, 0, "Not should be fused into AssertNot");
|
||||
}
|
||||
|
||||
// --- B-11: early_exit_on_first_success flag tests ---
|
||||
|
||||
/// Find a RuleInfo by name suffix (e.g., "check" matches "data.test.check").
|
||||
fn find_rule_info<'a>(
|
||||
program: &'a regorus::rvm::program::Program,
|
||||
name_suffix: &str,
|
||||
) -> &'a regorus::rvm::program::RuleInfo {
|
||||
program
|
||||
.rule_infos
|
||||
.iter()
|
||||
.find(|ri| ri.name.ends_with(name_suffix))
|
||||
.unwrap_or_else(|| panic!("no RuleInfo ending with '{name_suffix}'"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_exit_set_for_implicit_true_multi_def() {
|
||||
let program = compile_rule(
|
||||
r#"
|
||||
package test
|
||||
p if { 1 == 1 }
|
||||
p if { 2 == 2 }
|
||||
"#,
|
||||
);
|
||||
let ri = find_rule_info(&program, ".p");
|
||||
assert!(
|
||||
ri.early_exit_on_first_success,
|
||||
"two implicit-true defs should set early_exit_on_first_success"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_exit_set_for_same_literal_string() {
|
||||
let program = compile_rule(
|
||||
r#"
|
||||
package test
|
||||
p := "ok" if { 1 == 1 }
|
||||
p := "ok" if { 2 == 2 }
|
||||
"#,
|
||||
);
|
||||
let ri = find_rule_info(&program, ".p");
|
||||
assert!(
|
||||
ri.early_exit_on_first_success,
|
||||
"two defs both returning \"ok\" should set early_exit_on_first_success"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_exit_not_set_for_different_literals() {
|
||||
let program = compile_rule(
|
||||
r#"
|
||||
package test
|
||||
p := "a" if { 1 == 1 }
|
||||
p := "b" if { 2 == 2 }
|
||||
"#,
|
||||
);
|
||||
let ri = find_rule_info(&program, ".p");
|
||||
assert!(
|
||||
!ri.early_exit_on_first_success,
|
||||
"defs returning different literals must NOT set early_exit_on_first_success"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_exit_not_set_for_computed_values() {
|
||||
let program = compile_rule(
|
||||
r#"
|
||||
package test
|
||||
p := x if { x := 1 + 1 }
|
||||
p := x if { x := 2 + 0 }
|
||||
"#,
|
||||
);
|
||||
let ri = find_rule_info(&program, ".p");
|
||||
assert!(
|
||||
!ri.early_exit_on_first_success,
|
||||
"computed expressions must NOT set early_exit_on_first_success"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_exit_not_set_for_single_definition() {
|
||||
let program = compile_rule(
|
||||
r#"
|
||||
package test
|
||||
p if { 1 == 1 }
|
||||
"#,
|
||||
);
|
||||
let ri = find_rule_info(&program, ".p");
|
||||
assert!(
|
||||
!ri.early_exit_on_first_success,
|
||||
"single definition should not set early_exit (only ≥2 defs)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_exit_not_set_for_else_with_different_values() {
|
||||
let program = compile_rule(
|
||||
r#"
|
||||
package test
|
||||
p := "a" if { false } else := "b" if { true }
|
||||
p := "a" if { true }
|
||||
"#,
|
||||
);
|
||||
let ri = find_rule_info(&program, ".p");
|
||||
assert!(
|
||||
!ri.early_exit_on_first_success,
|
||||
"else branches with different values must NOT set early_exit_on_first_success"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_exit_set_for_else_with_same_values() {
|
||||
let program = compile_rule(
|
||||
r#"
|
||||
package test
|
||||
p := "x" if { false } else := "x" if { true }
|
||||
p := "x" if { true }
|
||||
"#,
|
||||
);
|
||||
let ri = find_rule_info(&program, ".p");
|
||||
assert!(
|
||||
ri.early_exit_on_first_success,
|
||||
"else branches all returning same literal should set early_exit_on_first_success"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_exit_set_for_implicit_true_function() {
|
||||
let mut engine = Engine::new();
|
||||
engine
|
||||
.add_policy(
|
||||
"test.rego".to_string(),
|
||||
r#"
|
||||
package test
|
||||
check(x) if { x > 0 }
|
||||
check(x) if { x < -10 }
|
||||
p := check(5)
|
||||
"#
|
||||
.to_string(),
|
||||
)
|
||||
.expect("failed to add policy");
|
||||
let compiled = engine
|
||||
.compile_with_entrypoint(&Rc::from("data.test.p"))
|
||||
.expect("failed to compile");
|
||||
let program = Compiler::compile_from_policy(&compiled, &["data.test.p"])
|
||||
.expect("failed to compile to RVM");
|
||||
let ri = find_rule_info(&program, ".check");
|
||||
assert!(
|
||||
ri.early_exit_on_first_success,
|
||||
"implicit-true function with 2 defs should set early_exit_on_first_success"
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
// Copyright (c) Microsoft Corporation.
|
||||
// Licensed under the MIT License.
|
||||
mod compiler;
|
||||
mod rego;
|
||||
|
||||
283
tests/rvm/rego/cases/early_exit_same_value.yaml
Normal file
283
tests/rvm/rego/cases/early_exit_same_value.yaml
Normal file
@@ -0,0 +1,283 @@
|
||||
# B-11: Early exit for same-value multi-definition rules
|
||||
#
|
||||
# When all definitions of a Complete or function rule produce the same
|
||||
# static value, the VM can stop after the first successful definition.
|
||||
# These tests verify correctness: both that the optimization produces
|
||||
# the right result and that edge cases (different values, else branches,
|
||||
# computed expressions) remain correct.
|
||||
|
||||
cases:
|
||||
# ── Implicit-true multi-def function rules ────────────────────────
|
||||
|
||||
- note: implicit_true_two_definitions_first_succeeds
|
||||
description: Two implicit-true definitions; first succeeds → true
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
check(x) if { x > 0 }
|
||||
check(x) if { x < -10 }
|
||||
p := check(5)
|
||||
query: data.test.p
|
||||
want_result: true
|
||||
|
||||
- note: implicit_true_two_definitions_second_succeeds
|
||||
description: Two implicit-true definitions; only second succeeds → true
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
check(x) if { x > 100 }
|
||||
check(x) if { x < 0 }
|
||||
p := check(-5)
|
||||
query: data.test.p
|
||||
want_result: true
|
||||
|
||||
- note: implicit_true_two_definitions_neither_succeeds
|
||||
description: Two implicit-true definitions; neither succeeds → undefined
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
check(x) if { x > 100 }
|
||||
check(x) if { x < -100 }
|
||||
p := check(5)
|
||||
query: data.test.p
|
||||
want_result: "#undefined"
|
||||
|
||||
- note: implicit_true_four_definitions
|
||||
description: Four implicit-true defs (like mountSource_ok); third succeeds
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
validate(x) if { x == "a" }
|
||||
validate(x) if { x == "b" }
|
||||
validate(x) if { x == "c" }
|
||||
validate(x) if { x == "d" }
|
||||
p := validate("c")
|
||||
query: data.test.p
|
||||
want_result: true
|
||||
|
||||
- note: implicit_true_complete_rule_two_defs
|
||||
description: Complete rule with two implicit-true defs
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
allowed if { input.role == "admin" }
|
||||
allowed if { input.role == "superuser" }
|
||||
p := allowed
|
||||
input: {"role": "superuser"}
|
||||
query: data.test.p
|
||||
want_result: true
|
||||
|
||||
# ── Same literal value (non-true) across definitions ───────────────
|
||||
|
||||
- note: same_string_value_two_defs
|
||||
description: Two defs returning same string constant
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
label(x) := "ok" if { x > 0 }
|
||||
label(x) := "ok" if { x == 0 }
|
||||
p := label(0)
|
||||
query: data.test.p
|
||||
want_result: "ok"
|
||||
|
||||
- note: same_number_value_two_defs
|
||||
description: Two defs returning same numeric constant
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
code(x) := 42 if { x == "answer" }
|
||||
code(x) := 42 if { x == "the answer" }
|
||||
p := code("the answer")
|
||||
query: data.test.p
|
||||
want_result: 42
|
||||
|
||||
- note: same_bool_false_two_defs
|
||||
description: Two defs returning explicit false
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
deny(x) := false if { x == "blocked" }
|
||||
deny(x) := false if { x == "banned" }
|
||||
p := deny("banned")
|
||||
query: data.test.p
|
||||
want_result: false
|
||||
|
||||
# ── Different values across definitions (NO early exit) ────────────
|
||||
|
||||
- note: different_string_values_first_succeeds
|
||||
description: Two defs with different strings; first succeeds → its value
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
classify(x) := "positive" if { x > 0 }
|
||||
classify(x) := "non-positive" if { x <= 0 }
|
||||
p := classify(5)
|
||||
query: data.test.p
|
||||
want_result: "positive"
|
||||
|
||||
- note: different_string_values_second_succeeds
|
||||
description: Two defs with different strings; second succeeds → its value
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
classify(x) := "positive" if { x > 0 }
|
||||
classify(x) := "non-positive" if { x <= 0 }
|
||||
p := classify(-3)
|
||||
query: data.test.p
|
||||
want_result: "non-positive"
|
||||
|
||||
# ── Else branches ──────────────────────────────────────────────────
|
||||
|
||||
- note: else_same_value_across_defs
|
||||
description: Two defs, each with else, all branches return same value
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
result := "match" if {
|
||||
input.x > 10
|
||||
}
|
||||
else := "match" if {
|
||||
input.x > 5
|
||||
}
|
||||
result := "match" if {
|
||||
input.y > 10
|
||||
}
|
||||
else := "match" if {
|
||||
input.y > 5
|
||||
}
|
||||
p := result
|
||||
input: {"x": 1, "y": 7}
|
||||
query: data.test.p
|
||||
want_result: "match"
|
||||
|
||||
- note: else_different_values_within_def
|
||||
description: One def with else returning different value → no early exit
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
grade(x) := "A" if {
|
||||
x >= 90
|
||||
}
|
||||
else := "B" if {
|
||||
x >= 80
|
||||
}
|
||||
grade(x) := "C" if { x >= 70; x < 80 }
|
||||
p := grade(85)
|
||||
query: data.test.p
|
||||
want_result: "B"
|
||||
|
||||
- note: else_different_values_within_def_second
|
||||
description: Else chain where second definition fires
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
grade(x) := "A" if {
|
||||
x >= 90
|
||||
}
|
||||
else := "B" if {
|
||||
x >= 80
|
||||
}
|
||||
grade(x) := "C" if { x >= 70; x < 80 }
|
||||
p := grade(75)
|
||||
query: data.test.p
|
||||
want_result: "C"
|
||||
|
||||
# ── Computed (non-literal) values → no early exit ──────────────────
|
||||
|
||||
- note: computed_value_two_defs
|
||||
description: Defs with computed expressions → no early exit, still correct
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
double(x) := x * 2 if { x > 0 }
|
||||
double(x) := x * 2 if { x < 0 }
|
||||
p := double(-3)
|
||||
query: data.test.p
|
||||
want_result: -6
|
||||
|
||||
# ── Single definition (flag doesn't matter) ────────────────────────
|
||||
|
||||
- note: single_definition_implicit_true
|
||||
description: Single implicit-true def — flag not set but works fine
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
ok(x) if { x > 0 }
|
||||
p := ok(5)
|
||||
query: data.test.p
|
||||
want_result: true
|
||||
|
||||
# ── Mixed implicit-true and explicit-true ───────────────────────────
|
||||
|
||||
- note: mixed_implicit_and_explicit_true
|
||||
description: One def has implicit true, another has explicit := true
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
valid(x) if { x > 0 }
|
||||
valid(x) := true if { x == 0 }
|
||||
p := valid(0)
|
||||
query: data.test.p
|
||||
want_result: true
|
||||
|
||||
# ── Default value interaction ──────────────────────────────────────
|
||||
|
||||
- note: implicit_true_with_default
|
||||
description: Multi-def rule with default; no def succeeds → default
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
default allowed := false
|
||||
allowed if { input.role == "admin" }
|
||||
allowed if { input.role == "superuser" }
|
||||
p := allowed
|
||||
input: {"role": "viewer"}
|
||||
query: data.test.p
|
||||
want_result: false
|
||||
|
||||
- note: implicit_true_with_default_succeeds
|
||||
description: Multi-def rule with default; one def succeeds → true
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
default allowed := false
|
||||
allowed if { input.role == "admin" }
|
||||
allowed if { input.role == "superuser" }
|
||||
p := allowed
|
||||
input: {"role": "admin"}
|
||||
query: data.test.p
|
||||
want_result: true
|
||||
|
||||
# ── Nested function calls with early exit ──────────────────────────
|
||||
|
||||
- note: nested_early_exit_functions
|
||||
description: Outer function calls inner multi-def function
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
inner_ok(x) if { x == "a" }
|
||||
inner_ok(x) if { x == "b" }
|
||||
inner_ok(x) if { x == "c" }
|
||||
outer(x, y) if {
|
||||
inner_ok(x)
|
||||
inner_ok(y)
|
||||
}
|
||||
p := outer("a", "c")
|
||||
query: data.test.p
|
||||
want_result: true
|
||||
|
||||
- note: nested_early_exit_functions_fail
|
||||
description: Outer function calls inner multi-def function, inner fails
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
inner_ok(x) if { x == "a" }
|
||||
inner_ok(x) if { x == "b" }
|
||||
inner_ok(x) if { x == "c" }
|
||||
outer(x, y) if {
|
||||
inner_ok(x)
|
||||
inner_ok(y)
|
||||
}
|
||||
p := outer("a", "d")
|
||||
query: data.test.p
|
||||
want_result: "#undefined"
|
||||
@@ -106,3 +106,21 @@ cases:
|
||||
}
|
||||
query: data.test.main
|
||||
want_result: {"username": "alice123", "user_age": 25}
|
||||
|
||||
- note: object_membership_checks_values_not_keys
|
||||
data: {}
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
main := "foo" in {"foo": "bar"}
|
||||
query: data.test.main
|
||||
want_result: false
|
||||
|
||||
- note: object_membership_finds_value
|
||||
data: {}
|
||||
modules:
|
||||
- |
|
||||
package test
|
||||
main := "bar" in {"foo": "bar"}
|
||||
query: data.test.main
|
||||
want_result: true
|
||||
|
||||
@@ -96,15 +96,15 @@ cases:
|
||||
want_error: "#undefined"
|
||||
|
||||
- note: logical_not_int
|
||||
description: NOT with int operand should error
|
||||
example_rego: "!42"
|
||||
description: NOT with non-boolean defined operand should yield false
|
||||
example_rego: "not 42"
|
||||
literals:
|
||||
- 42
|
||||
instructions:
|
||||
- "Load { dest: 0, literal_idx: 0 }"
|
||||
- "Not { dest: 1, operand: 0 }"
|
||||
- "Return { value: 1 }"
|
||||
want_error: "#undefined"
|
||||
want_result: false
|
||||
|
||||
# Invalid indexing operations
|
||||
- note: index_int_with_string_key
|
||||
|
||||
Reference in New Issue
Block a user