chore(policy-engine): add pure-Rust columnar policy evaluation engine #4795
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
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
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
dashpole
Change summary
Adds a 100% safe (
#![forbid(unsafe_code)]), pure-Rust columnar telemetry policy evaluation engine (otel-arrow-dfe-policy-engine) for OTAPOtapArrowRecordslog batches, aligned with OTEP 4738 and open-telemetry/opentelemetry-proto#865 (opentelemetry.proto.policies.v1development).This PR introduces the
otel-arrow-dfe-policy-enginecrate (n-gram columnar engine, unit tests, and Criterion benchmark suite inbenches/engine.rs) with zero C/C++ build dependencies and zero new third-party crates inCargo.lock(promotingaho-corasick 1.1.5, already locked inrust/otap-dataflow/Cargo.lock, to a direct workspace dependency and reusing the existingcriterionworkspace dev-dependency). For the companion evaluation branch containing all four pure-Rust candidate engines, the optionalpolicy-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 inO(1)viaAHashMap<CanonicalPredicateKey, usize>(canonicalizing-0.0/+0.0and wildcard-freeGlobintoEquals, while rejecting non-finite doubles per#865), evaluatesExistsvia validity bitmaps and numeric/ID/small-set string predicates via Arrowcmpkernels (with an IEEE-754 chunked loop forFloat64Array), 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, andregex: Walks each regex'sregex_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 singleAhoCorasickautomaton per field. During evaluation, monotonic generation-stamped counters (StringScanScratch) track matched required literals with zero per-row allocations and invokeregex_automata::meta::Regex(RE2-validated AST translated directly to HIR withmulti_line(false)) or linear-timematches_globonly after every required literal matches.3. Dense bitset filter precedence & masked 4-stage transforms: Resolves filter masks via bounded pooled dense bitsets (
DenseBitset/BitsetBufferPool) withACTION_KEEPoverridingACTION_DROP, opt-in short-circuit evaluation (with in-place single-matcher positive and negated allowlist drop fast paths and borrowedBitsetRef/IdFilter), and per-policyPolicyMatchStats. AppliesLogTransformPolicystages globally in spec order (1. Rename -> 2. Add -> 3. Remove -> 4. Redact, sorted by ascendingPolicy.id, withWriteModeupsert/update-existing guards and RE2 capture-group expansion reusingCaptures) via lazy sparse overlay editors (FlatAttrsEditor,BodyEditor,RootStrEditor,RootSevNumEditor) and lazy direct Arrow builders without splitting batches per policy, while skippingdecode_transport_optimized_ids()on passthrough and root-only filter/transform paths. Supports nestedLogAttribute(path.len() > 1) andBodyField(path.len() >= 1) reads and writes via a zero-dependency raw-slice RFC 8949 CBOR cursor/mutator (preserving untouched siblings byte-for-byte and enforcingMAX_CBOR_DEPTH = 64), withTraceId/SpanIdkept immutable per#865.Benchmarks & comparison against publicly available approaches
Benchmarked on 1,000-row log batches (
dict256= 256 unique bodies / Arrow dictionary;plain= flatStringArraywith 1,000 unique bodies) on the same Linux host. The top row was measured directly on this PR (e8d51d036) viacargo bench --locked -p otel-arrow-dfe-policy-engine --bench engine([profile.bench]:opt-level = 3,lto = "fat",codegen-units = 1). ForW1Mixed, the table reportsfilter_w1_mixed_dict256_stats(stats = Some(&mut stats)), which disablesKeep-all/Drop-all short-circuiting so bothKeepandDropplans run across every row (apples-to-apples with the non-short-circuit baseline runs from the multi-candidate comparison harness at676c25d73). For a fair comparison against columnar Vectorscan (#4738), the Vectorscan baseline includes fixes to unwraplogs.bodyStructArray(str), coerceInt32severity_number, and reuse VectorscanScratchacross rows:| Approach | Dependencies |
N=10Mixed (dict256) |N=100Mixed (dict256) |N=1,000Mixed (dict256) |N=10,000Mixed (dict256) |N=1,000Shared-Prefix Regex (plain) |N=1,000Char-Class Regex (dict256) | Compile @N=1,000Mixed || :--- | :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 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-engineOPL (otel-arrow, balancedOrAST)\ | 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-rsRow-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 satN=100) | N/A | N/A | N/A |41.2 ms(@N=100) |\Note: Idiomatic OPL text queries parsed via
OplParserran at2.23 M/s/391 usatN=10and0.33 M/s/2.80 msatN=100, hitting a right-recursive Pest parser stack overflow above ~52 unparenthesizedorclauses without balanced grouping.Additional benchmarks in
benches/engine.rs(B = 1,000logs/batch):W1Mixed (stats = None):47.7 nsatN=1(keep-only passthrough),7.71 M/s(130 us) atN=10,2.07 M/s(484 us) atN=100,1.76 M/s(570 us) atN=1,000, and2.28 M/s(439 us) atN=10,000(whereKeeprules cover all 32event_namevalues and skip theDropplan). Full-evalN=1(stats = Some) runs at21.3 M/s(46.9 us).Globfiltering (dict256,Action::Drop):4.61 M/s(217 us) atN=10and0.55 M/s(1.82 ms) atN=1,000.W1Mixed):9.7 usatN=10,4.85 msatN=1,000(up slightly from the3.31 msinitial baseline due to strict RE2 AST validation, still 203x faster than Vectorscan's985 ms), and20.2 msatN=10,000(2.6x faster than the52 msinitial baseline and 924x faster than Vectorscan's18.7 s).dict256):W4bfilter + 4-stageRename -> Add -> Remove -> Redactruns at0.74 M/s(1.34 ms) atN=10,0.22 M/s(4.52 ms) atN=100, and31.7 K/s(31.6 ms) atN=1,000. Root-onlyBodyregex redaction overencode_transport_optimized()batches (N=10, preservingDELTAIDs) runs at2.33 M/s(429 us).Key takeaways:
W1Mixed (N=10..10,000):DenseBitsetpooling, dictionary memoization, Arrow SIMDcmpkernels, and selectivity-gated attribute scanning cutW1Mixed latency from279 us -> 130 usatN=10(closing most of the gap to Vectorscan's110 us),1.34 ms -> 529 usatN=100(1.8x faster than Vectorscan),2.22 ms -> 766 usatN=1,000(11.4x faster than Vectorscan), and8.82 ms -> 1.50 msatN=10,000(58.3x faster than Vectorscan).W3char-class regex (dict256,N=1,000) drops from395 us -> 174 us(3.2x faster than Vectorscan), andW2shared-prefix regex (plain,N=1,000) drops from2.33 ms -> 2.06 ms(1.7x faster than Vectorscan).policy-engineseparate fromquery-engineOPL (matching the conclusion in #4738): DataFusion OPL is fast for 1 to 3 ad-hoc filters (74 usatN=1), butOr-tree evaluation scales linearlyO(N)per batch and lacks nativekeep-over-dropprecedence 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):
AhoCorasick+RegexAutomata(candidate1_hybrid.rs): Faster on the initialN = 1..100baseline (74 usatN=1,928 usatN=100) due to dictionary memoization onlogs.body.str, but up to 43.8x slower (102.1 msvs.2.33 mson plain strings atN=1,000) when hundreds of regexes share a common log prefix (ERROR [auth]...), and uses 38x more heap on character-class regexes atN=10,000(186 MiBvs.4.85 MiB, because it did not deduplicate identical regexes across policies).regex_automata::meta::Regex::build_many(candidate2_regex_automata.rs, 128 patterns/shard): Competitive ondict256atN=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.candidate4_opl.rs,query-engine): Still required falling back to a custom evaluator for negated missing attributes,trace_id/span_idhex matching, CBOR map/slice paths, and 4-stage transforms, while scalingO(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 failedin0.09s:ACTION_KEEPoverACTION_DROPprecedence, opt-in short-circuiting including negated allowlist fast paths andPolicyMatchStatsparity, all 9opentelemetry-proto#865predicate operators includingGlob, strict RE2 AST validation andmulti_line(false)$semantics,2^53i64-f64precision, compile-time validation rules, absent/all-zerotrace_id/span_id""semantics, empty-stringbodyabsence, nested CBOR nullExists, dictionary-value validity parity across low/high selectivity and transforms,CanonicalPredicateKeydeduplication,DenseBitsetpooling bounds, globalRename -> Add -> Remove -> Redactstage ordering across nestedLogAttributeandBodyFieldwithMAX_CBOR_DEPTH = 64and non-OTLP CBOR values, immutableTraceId/SpanId, transport-optimized ID preservation on root-only paths, and OTLP protobuf round-trips)cargo check --locked -p otel-arrow-dfe-policy-engine --all-targetsandclippy-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, andgit diff --check(passed)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;
chorePR title).Follow-ups
Items identified during review and deferred for follow-up PRs:
otel-arrow-dfe-policy-enginepurely synchronous in this PR and defer cooperative async yielding until the processor node is wired into a fullLocalRuntimepipeline, where we can run A/B responsiveness probe benchmarks (yielding enabled vs. disabled) perrust/otap-dataflow/docs/async-best-practices.mdand align the yield boundary with #2374.