← Back to Pull requests

chore(policy-engine): add pure-Rust columnar policy evaluation engine #4795

Closed
unknown closed this pull request without merging on Nov 24, 2026 20:04 UTC
View on GitHub
unknown unknown commented on Nov 17, 2026 20:56 UTC
Author

Change summary

Adds a 100% safe (#![forbid(unsafe_code)]), pure-Rust columnar telemetry policy evaluation engine (otel-arrow-dfe-policy-engine) for OTAP OtapArrowRecords log batches, aligned with OTEP 4738 and open-telemetry/opentelemetry-proto#865 (opentelemetry.proto.policies.v1development).

This PR introduces the otel-arrow-dfe-policy-engine crate (n-gram columnar engine, unit tests, and Criterion benchmark suite in benches/engine.rs) with zero C/C++ build dependencies and zero new third-party crates in Cargo.lock (promoting aho-corasick 1.1.5, already locked in rust/otap-dataflow/Cargo.lock, to a direct workspace dependency and reusing the existing criterion workspace dev-dependency). For the companion evaluation branch containing all four pure-Rust candidate engines, the optional policy-rs / Vectorscan baseline, the cross-engine differential equivalence and negative-control test suite, and the 280-row cross-candidate benchmark matrix, see:

Cross-candidate comparison & benchmark branch: <https://github.com/dashpole/otel-arrow/tree/policy-engine-full-prototype> (BENCHMARK_RESULTS.md, BENCHMARK_RESULTS_RAW.md)

Design overview

1. Predicate deduplication, Arrow SIMD fast paths & single-pass column scanning: Deduplicates identical (LogFieldSelector, Predicate) pairs across policies at compile time in O(1) via AHashMap<CanonicalPredicateKey, usize> (canonicalizing -0.0/+0.0 and wildcard-free Glob into Equals, while rejecting non-finite doubles per #865), evaluates Exists via validity bitmaps and numeric/ID/small-set string predicates via Arrow cmp kernels (with an IEEE-754 chunked loop for Float64Array), memoizes dictionary-encoded string columns (checking both key and value validity), and uses lazy dictionary key pre-filtering plus a 20% selectivity threshold on OTAP attribute tables (LogAttrs, ResourceAttrs, ScopeAttrs).
2. Required n-gram inverted index for contains, glob, and regex: Walks each regex's regex_syntax::hir::Hir (extract_required_ngrams) and glob's literal runs (extract_glob_ngrams) at compile time to extract mandatory contiguous byte literals (len >= 2) into a single AhoCorasick automaton per field. During evaluation, monotonic generation-stamped counters (StringScanScratch) track matched required literals with zero per-row allocations and invoke regex_automata::meta::Regex (RE2-validated AST translated directly to HIR with multi_line(false)) or linear-time matches_glob only after every required literal matches.
3. Dense bitset filter precedence & masked 4-stage transforms: Resolves filter masks via bounded pooled dense bitsets (DenseBitset / BitsetBufferPool) with ACTION_KEEP overriding ACTION_DROP, opt-in short-circuit evaluation (with in-place single-matcher positive and negated allowlist drop fast paths and borrowed BitsetRef / IdFilter), and per-policy PolicyMatchStats. Applies LogTransformPolicy stages globally in spec order (1. Rename -> 2. Add -> 3. Remove -> 4. Redact, sorted by ascending Policy.id, with WriteMode upsert/update-existing guards and RE2 capture-group expansion reusing Captures) via lazy sparse overlay editors (FlatAttrsEditor, BodyEditor, RootStrEditor, RootSevNumEditor) and lazy direct Arrow builders without splitting batches per policy, while skipping decode_transport_optimized_ids() on passthrough and root-only filter/transform paths. Supports nested LogAttribute (path.len() > 1) and BodyField (path.len() >= 1) reads and writes via a zero-dependency raw-slice RFC 8949 CBOR cursor/mutator (preserving untouched siblings byte-for-byte and enforcing MAX_CBOR_DEPTH = 64), with TraceId/SpanId kept immutable per #865.

Benchmarks & comparison against publicly available approaches

Benchmarked on 1,000-row log batches (dict256 = 256 unique bodies / Arrow dictionary; plain = flat StringArray with 1,000 unique bodies) on the same Linux host. The top row was measured directly on this PR (e8d51d036) via cargo bench --locked -p otel-arrow-dfe-policy-engine --bench engine ([profile.bench]: opt-level = 3, lto = "fat", codegen-units = 1). For W1 Mixed, the table reports filter_w1_mixed_dict256_stats (stats = Some(&mut stats)), which disables Keep-all/Drop-all short-circuiting so both Keep and Drop plans run across every row (apples-to-apples with the non-short-circuit baseline runs from the multi-candidate comparison harness at 676c25d73). For a fair comparison against columnar Vectorscan (#4738), the Vectorscan baseline includes fixes to unwrap logs.body StructArray (str), coerce Int32 severity_number, and reuse Vectorscan Scratch across rows:

| Approach | Dependencies | N=10 Mixed (dict256) | N=100 Mixed (dict256) | N=1,000 Mixed (dict256) | N=10,000 Mixed (dict256) | N=1,000 Shared-Prefix Regex (plain) | N=1,000 Char-Class Regex (dict256) | Compile @ N=1,000 Mixed |
| :--- | :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| Pure-Rust N-Gram Columnar (This PR, Criterion, full eval) | Pure Rust (ahash, aho-corasick, regex-automata) | 7.69 M/s (130 us) | 1.89 M/s (529 us) | 1.31 M/s (766 us) | 0.67 M/s (1.50 ms) | 0.48 M/s (2.06 ms) | 5.74 M/s (174 us) | 4.85 ms |
| Pure-Rust N-Gram Columnar (Initial baseline 676c25d73) | Pure Rust (ahash, aho-corasick, regex-automata) | 2.85 M/s (279 us) | 0.79 M/s (1.34 ms) | 0.47 M/s (2.22 ms) | 0.12 M/s (8.82 ms) | 0.37 M/s (2.33 ms) | 2.34 M/s (395 us) | 3.31 ms (622 KiB) |
| OTAP Columnar Vectorscan (#4738, repaired) | C++17 + Boost + CMake (policy-rs, vectorscan-sys) | 8.39 M/s (110 us) | 0.95 M/s (954 us) | 0.11 M/s (8.74 ms) | 0.01 M/s (87.5 ms) | 0.31 M/s (3.43 ms) | 1.78 M/s (550 us) | 985 ms (1,143 KiB) |
| OTAP query-engine OPL (otel-arrow, balanced Or AST)\
| Pure Rust (query-engine, DataFusion) | 2.11 M/s (417 us) | 0.21 M/s (5.02 ms) | 0.06 M/s (16.7 ms) | N/A (AST limit) | N/A | N/A | 88.6 ms (2,232 KiB) |
| policy-rs Row-by-Row (v1.8.2) | C++17 + Boost + CMake (policy-rs, vectorscan-sys) | 0.01 M/s (90.0 ms) | 0.0008 M/s (1.33 s) | N/A (not run; 1.33 s at N=100) | N/A | N/A | N/A | 41.2 ms (@ N=100) |

\Note: Idiomatic OPL text queries parsed via OplParser ran at 2.23 M/s / 391 us at N=10 and 0.33 M/s / 2.80 ms at N=100, hitting a right-recursive Pest parser stack overflow above ~52 unparenthesized or clauses without balanced grouping.

Additional benchmarks in benches/engine.rs (B = 1,000 logs/batch):

  • Short-circuit W1 Mixed (stats = None): 47.7 ns at N=1 (keep-only passthrough), 7.71 M/s (130 us) at N=10, 2.07 M/s (484 us) at N=100, 1.76 M/s (570 us) at N=1,000, and 2.28 M/s (439 us) at N=10,000 (where Keep rules cover all 32 event_name values and skip the Drop plan). Full-eval N=1 (stats = Some) runs at 21.3 M/s (46.9 us).

  • Glob filtering (dict256, Action::Drop): 4.61 M/s (217 us) at N=10 and 0.55 M/s (1.82 ms) at N=1,000.

  • Policy compilation (W1 Mixed): 9.7 us at N=10, 4.85 ms at N=1,000 (up slightly from the 3.31 ms initial baseline due to strict RE2 AST validation, still 203x faster than Vectorscan's 985 ms), and 20.2 ms at N=10,000 (2.6x faster than the 52 ms initial baseline and 924x faster than Vectorscan's 18.7 s).

  • End-to-end transforms (dict256): W4b filter + 4-stage Rename -> Add -> Remove -> Redact runs at 0.74 M/s (1.34 ms) at N=10, 0.22 M/s (4.52 ms) at N=100, and 31.7 K/s (31.6 ms) at N=1,000. Root-only Body regex redaction over encode_transport_optimized() batches (N=10, preserving DELTA IDs) runs at 2.33 M/s (429 us).
  • Key takeaways:

  • 2.1x to 5.9x faster than the initial baseline across W1 Mixed (N=10..10,000): DenseBitset pooling, dictionary memoization, Arrow SIMD cmp kernels, and selectivity-gated attribute scanning cut W1 Mixed latency from 279 us -> 130 us at N=10 (closing most of the gap to Vectorscan's 110 us), 1.34 ms -> 529 us at N=100 (1.8x faster than Vectorscan), 2.22 ms -> 766 us at N=1,000 (11.4x faster than Vectorscan), and 8.82 ms -> 1.50 ms at N=10,000 (58.3x faster than Vectorscan).

  • Fast on regex workloads too: W3 char-class regex (dict256, N=1,000) drops from 395 us -> 174 us (3.2x faster than Vectorscan), and W2 shared-prefix regex (plain, N=1,000) drops from 2.33 ms -> 2.06 ms (1.7x faster than Vectorscan).

  • Keeping policy-engine separate from query-engine OPL (matching the conclusion in #4738): DataFusion OPL is fast for 1 to 3 ad-hoc filters (74 us at N=1), but Or-tree evaluation scales linearly O(N) per batch and lacks native keep-over-drop precedence and 4-stage conditional policy transforms.
  • Alternative pure-Rust designs evaluated

    Before selecting the full-HIR n-gram index, we implemented and benchmarked three other pure-Rust designs (archived on the comparison branch):

  • Single-literal prefix AhoCorasick + RegexAutomata (candidate1_hybrid.rs): Faster on the initial N = 1..100 baseline (74 us at N=1, 928 us at N=100) due to dictionary memoization on logs.body.str, but up to 43.8x slower (102.1 ms vs. 2.33 ms on plain strings at N=1,000) when hundreds of regexes share a common log prefix (ERROR [auth]...), and uses 38x more heap on character-class regexes at N=10,000 (186 MiB vs. 4.85 MiB, because it did not deduplicate identical regexes across policies).

  • Sharded regex_automata::meta::Regex::build_many (candidate2_regex_automata.rs, 128 patterns/shard): Competitive on dict256 at N=1,000 (1.19 ms), but 3.4x to 9.5x slower on high-cardinality plain strings (W2/W3) due to lazy-DFA cache pressure and per-shard fallback scanning after the first hit.

  • Compiled OPL AST (candidate4_opl.rs, query-engine): Still required falling back to a custom evaluator for negated missing attributes, trace_id/span_id hex matching, CBOR map/slice paths, and 4-stage transforms, while scaling O(N) per batch.
  • Related issue

    Relates to #4726, #4718, and #4738

    Validation

    cargo test --locked -p otel-arrow-dfe-policy-engine --lib (66 passed; 0 failed in 0.09s: ACTION_KEEP over ACTION_DROP precedence, opt-in short-circuiting including negated allowlist fast paths and PolicyMatchStats parity, all 9 opentelemetry-proto#865 predicate operators including Glob, strict RE2 AST validation and multi_line(false) $ semantics, 2^53 i64-f64 precision, compile-time validation rules, absent/all-zero trace_id/span_id "" semantics, empty-string body absence, nested CBOR null Exists, dictionary-value validity parity across low/high selectivity and transforms, CanonicalPredicateKey deduplication, DenseBitset pooling bounds, global Rename -> Add -> Remove -> Redact stage ordering across nested LogAttribute and BodyField with MAX_CBOR_DEPTH = 64 and non-OTLP CBOR values, immutable TraceId/SpanId, transport-optimized ID preservation on root-only paths, and OTLP protobuf round-trips)
    cargo check --locked -p otel-arrow-dfe-policy-engine --all-targets and clippy -D warnings (--lib, --tests, and --bench) (passed, 0 warnings)
    cargo bench --locked -p otel-arrow-dfe-policy-engine --bench engine (all 5 benchmark groups executed cleanly on HEAD; numbers reported above)
    rustfmt --edition 2024 --check, python3 tools/sanitycheck.py, and git diff --check (passed)

  • Multi-candidate differential equivalence tests (N=1..100, dict16/dict256/plain), negative-control tests against legacy Vectorscan bugs, and the 280-row benchmark matrix were executed on the comparison branch (676c25d73)
  • User-facing changes

    None (internal library crate not yet wired into a user-facing processor node; chore PR title).

    Follow-ups

    Items identified during review and deferred for follow-up PRs:

  • Async runtime integration: Keep otel-arrow-dfe-policy-engine purely synchronous in this PR and defer cooperative async yielding until the processor node is wired into a full LocalRuntime pipeline, where we can run A/B responsiveness probe benchmarks (yielding enabled vs. disabled) per rust/otap-dataflow/docs/async-best-practices.md and align the yield boundary with #2374.
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: dashpole Review duration: 10028m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #4795"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%