Regorus

repository·main·Indexed 43 days ago

https://github.com/microsoft/regorus

A high-performance, lightweight Rego (OPA policy language) interpreter written in Rust. Designed for rigorous enforcement of Rego semantics, it supports both standard and no_std environments, including Confidential Computing. It includes C# bindings for executing policies via the Regorus Virtual Machine (RVM) API, support for Azure RBAC conditions, and the ability to compile and evaluate native Azure Policy JSON rule definitions.

Tokens
76.7K
Snippets
193
Records
281
Agent score
53%

What's inside Regorus

  1. Overview of Regorus

    main

    Regorus is a fast, lightweight, and rigorous Rego interpreter written in Rust. It is designed to be cross-platform, no_std compatible, and highly extensible.

    Key features include:

    • Rego Compliance: Defaults to Rego v1 and is mostly compliant with OPA release v1.2.0.
    • Extensibility: Allows implementing custom stateful builtins in Rust via add_extension.
    • Polyglot Support: Provides bindings for C, C++, C#, Golang, Java, Javascript (WASM), Python, and Ruby.
    • Confidential Computing Ready: Supports fine-grained control over components via Cargo features to minimize binary size and attack surface.
  2. Overview of mimalloc features and design

    main

    mimalloc (pronounced "me-malloc") is a high-performance, general-purpose allocator designed for low-latency and large-scale services. Key design features include:

    • Free list sharding & multi-sharding: Reduces fragmentation and contention by using many small free lists per "mimalloc page" and separate lists for thread-local vs. concurrent free operations.
    • Eager page purging: Marks empty pages as unused to the OS to reduce memory pressure.
    • Secure mode: Can be built with guard pages, randomized allocation, and encrypted free lists to protect against heap vulnerabilities (typically incurs a ~10% performance penalty).
    • First-class heaps (v3+): Allows efficient creation of multiple heaps where allocation can occur from any thread, and entire heaps can be destroyed at once.
    • Bounded performance: Provides bounded worst-case allocation times and minimal space overhead (~0.2% metadata).
  3. Performance overview of mimalloc

    main

    mimalloc is a general-purpose memory allocator designed to perform well across a wide range of workloads. In benchmark testing, it has been shown to outperform other leading allocators like jemalloc, tcmalloc, Hoard, and the default glibc allocator, while maintaining a similar memory footprint.

    Key performance characteristics include:

    • Workload Versatility: It aims for consistent performance across diverse benchmarks rather than optimizing for a single specific pattern.
    • Concurrency & Locality: It demonstrates significant speedups in concurrent workloads (e.g., the LeanN theorem prover benchmark) due to better allocation locality.
    • Thread Migration: It handles object migration between threads efficiently (e.g., larsonN and mstressN benchmarks).
    • Asymmetric Workloads: It excels in scenarios where some threads only allocate and others only free (e.g., xmalloc-testN) by using non-contended sharded thread free lists.
    • Cache Efficiency: It is designed to minimize allocator-induced false sharing of cache lines.
  4. RVM Instruction Set Reference Overview

    main

    The Rego Virtual Machine (RVM) instruction set consists of opcodes emitted by the compiler and executed by the RegoVM. Instructions are categorized by their functionality, such as arithmetic, loops, or host interaction.

    Key Concepts

    • Operands: Instructions use registers (rX), literals (litY), parameter indices (pZ), and immediate values.
    • Parameters: Complex metadata is stored in InstructionData. Instructions reference this metadata via an index (pN).
    • Outcomes: Instructions can result in different control flow states, including Continue, Return, Break, or Suspend.
  5. What is included in the RVM memory budget?

    main

    The memory budget tracks additional live bytes during the RVM execution window.

    Included in the budget:

    • Fresh execution-state initialization.
    • Rule evaluation.
    • Allocations retained by the result.
    • (C FFI) Native result JSON serialization and CString allocation.

    Excluded from the budget:

    • Program compilation.
    • Program loading.
    • Data, input, and context loading.
    • (C#) Managed UTF-8 decoding and managed string allocation (these occur after the C FFI execution window has closed).
  6. What is mimalloc secure mode?

    main

    Secure mode is a build configuration enabled via -DMI_SECURE=ON in CMake. It provides several mitigations against memory-based exploits:

    • Guard Pages: Internal mimalloc pages and heap metadata are surrounded by guard pages to prevent buffer overflow exploits from reaching metadata.
    • Encoded Free Lists: Free list pointers are encoded with per-page keys to prevent overwrites and detect heap corruption.
    • Double Free Detection: Automatically detects and ignores double free attempts.
    • Randomization: Free lists are initialized in random order, and allocation between extension and reuse within a page is randomized. Additionally, large heap blocks from the OS are address randomized to mitigate predictable allocation order attacks.
  7. Understand Regorus Benchmark Test Configurations

    main

    The benchmark evaluates performance using four distinct combinations of engine and input strategies to distinguish between engine instantiation overhead and data parsing overhead:

    1. Cloned Engines + Cloned Inputs: Uses pre-instantiated engines and pre-parsed input data.
    2. Cloned Engines + Fresh Inputs: Uses pre-instantiated engines but performs fresh JSON parsing for each input.
    3. Fresh Engines + Cloned Inputs: Uses new engine instances but uses pre-parsed input data.
    4. Fresh Engines + Fresh Inputs: Uses new engine instances and performs fresh JSON parsing for each input.
  8. Understand Instruction Outcomes

    main

    The instruction dispatcher (dispatch.rs) uses the InstructionOutcome enum to control flow:

    • Continue: Normal execution; the instruction pointer (pc) is incremented.
    • Return(Value): Unwinds the current rule or function frame and propagates the Value upward.
    • Break: Used by specific constructs (like RuleReturn or DestructuringSuccess) to exit to the owning frame without returning a specific value.
    • Suspend { reason }: Used exclusively in Suspendable mode to pause execution.
  9. Use Suspendable mode for asynchronous execution

    main

    The Suspendable mode allows the VM to pause execution and yield control back to the host.

    Workflow:

    1. Entry: Call the public API with the VM configured for Suspendable mode. The VM uses run_stackless_from to manage an execution_stack of ExecutionFrame objects.
    2. Suspension: The VM can suspend due to a HostAwait, a breakpoint, or a step. The SuspendReason is recorded, and the last result snapshot is stored.
    3. Resumption: The host calls resume(resume_value) to provide the value needed to continue execution.
    4. Completion: Once the execution_stack is empty, the VM transitions to ExecutionState::Completed { result }.
  10. Analyze Regorus performance bottlenecks

    main

    Based on engine evaluation benchmarks, developers should be aware of the following performance characteristics:

    • Engine Creation Overhead: Creating a 'fresh' engine is a major bottleneck, performing approximately 7-8x slower than using cloned engines.
    • Input Processing: Generating or parsing 'fresh' inputs adds moderate overhead, typically causing a ~27% impact on throughput compared to using cloned/pre-parsed inputs.
    • Thread Contention: While Regorus uses mimalloc as the default allocator to improve multi-threaded scaling and reduce contention, throughput generally degrades as thread counts increase due to inherent contention.
    • Scaling Strategy: For maximum throughput, use a single thread with cloned engines and cloned inputs. For multi-threaded environments, prioritize cloning engines rather than creating them fresh to avoid the heavy creation penalty.
  11. Understand the Regorus execution time limiting model

    main

    Regorus uses a cooperative time-limit check approach rather than a background watchdog thread or a cancellation token model.

    How it works

    Instead of spawning background threads (which would impact no_std compatibility and predictability), Regorus performs periodic checks during the evaluation process. This 'cooperative' approach amortizes the cost of clock reads and avoids the overhead of thread synchronization or async runtime scheduling.

    Key Differences from Cancellation Tokens

    While cancellation tokens are a common pattern, Regorus prioritizes time-based budgets for the following reasons:

    • Enforcement: Time-based budgets are enforced internally by Regorus based on wall-clock time, whereas tokens require the host to decide when to signal cancellation.
    • Simplicity & Predictability: By avoiding background threads/watchdogs, Regorus maintains a simpler architecture suitable for various environments.
    • Performance: Cooperative checks are optimized for microsecond-scale evaluations, avoiding the overhead of frequent timer-thread ticks.