# How the Quick Rejection Filter Achieves Sub‑Millisecond Performance in Destructive Command Guard

> Discover how the quick rejection filter in Destructive Command Guard achieves sub-millisecond performance using SIMD search span aware matching and selective scanning for rapid command evaluation.

- Repository: [Jeff Emanuel/destructive_command_guard](https://github.com/Dicklesworthstone/destructive_command_guard)
- Tags: performance
- Published: 2026-07-16

---

**The quick rejection filter in Destructive Command Guard combines SIMD‑accelerated substring search, span‑aware keyword matching, and selective fallback scanning to evaluate Bash commands in under a millisecond, discarding over 99 % of safe commands before any heavy regex or AST processing occurs.**

Destructive Command Guard (DCG) must inspect every Bash command proposed by AI assistants to prevent accidental data loss. To maintain interactive latency, the tool implements a **quick rejection filter** that acts as a high‑speed gatekeeper, ensuring the vast majority of benign commands never trigger expensive validation logic.

## SIMD‑Accelerated Substring Search

At the foundation of the filter lies the `memmem` crate, which provides vectorized `Finder` implementations built on the `memchr` SIMD primitives. In [`src/packs/mod.rs`](https://github.com/Dicklesworthstone/destructive_command_guard/blob/main/src/packs/mod.rs) (lines 70‑75), DCG compiles two static finders once at startup:

```rust
static GIT_FINDER: Finder<'static> = Finder::new("git");
static RM_FINDER: Finder<'static> = Finder::new("rm");

```

These finders scan the raw command string for the core keywords `"git"` and `"rm"` in a single pass. Because `memmem::find` operates on raw byte slices, it avoids the overhead of Unicode decoding, string allocation, or regex compilation. This SIMD‑driven approach identifies commands lacking destructive keywords in sub‑microsecond time, immediately returning control for safe commands.

## Span‑Aware Keyword Matching

When the SIMD scan detects a potential keyword, DCG extracts the **executable span**—the first word after any leading whitespace—and performs targeted validation. The function `span_matches_any_keyword` (see [`src/packs/mod.rs`](https://github.com/Dicklesworthstone/destructive_command_guard/blob/main/src/packs/mod.rs), lines 27‑33) iterates over enabled keywords and delegates to `keyword_matches_span`.

This routine first checks whether the keyword contains whitespace. For single‑word keywords, it executes a fast byte‑wise search using `memmem::find` while enforcing word boundaries via `is_word_byte`. This prevents false positives such as matching `"git"` inside `"gitlab"`. For multi‑word keywords like `"git reset --hard"`, the algorithm falls back to `keyword_matches_with_whitespace` (lines 20‑84), which splits the keyword into parts and validates the sequence using a minimal state machine.

All span‑aware checks operate on raw slices, allocate zero memory, and complete in sub‑microsecond time.

## Selective Fallback to Full Scan

Certain edge cases—such as commands containing redirection operators (`>`, `<`) or pipeline symbols (`|`)—require scanning beyond the initial executable span. The helper `should_fallback_to_full_normalized_keyword_scan` (see [`src/packs/mod.rs`](https://github.com/Dicklesworthstone/destructive_command_guard/blob/main/src/packs/mod.rs), lines 35‑52) detects these patterns and triggers a full‑command keyword scan only when necessary.

Because redirection operators are rare in typical AI‑generated commands, this fallback activates infrequently, preserving the overall sub‑millisecond performance profile. When invoked, the full scan still utilizes fast byte‑search algorithms rather than regex, maintaining deterministic latency.

## Implementation Example

The following Rust code demonstrates how these three techniques integrate into the evaluation pipeline:

```rust
use destructive_command_guard::packs::quick_reject;

/// Returns true if the command can be safely ignored by the heavy matcher.
fn fast_filter(command: &str, enabled_keywords: &[&str]) -> bool {
    // 1️⃣ Quick SIMD search for core words.
    if GIT_FINDER.find(command.as_bytes()).is_none()
        && RM_FINDER.find(command.as_bytes()).is_none()
    {
        // No git/rm → definitely safe.
        return true;
    }

    // 2️⃣ Extract the executable span (first word after whitespace).
    let exec_span = command
        .trim_start()
        .split_whitespace()
        .next()
        .unwrap_or_default();

    // 3️⃣ Span‑aware keyword test.
    if span_matches_any_keyword(exec_span, enabled_keywords) {
        // A known destructive keyword appears → need further evaluation.
        return false;
    }

    // 4️⃣ Rare fallback for redirects/pipelines.
    if should_fallback_to_full_normalized_keyword_scan(command) {
        // Scan the whole command (still a fast byte search).
        return !enabled_keywords.iter().any(|kw| keyword_matches_substring(command, kw));
    }

    // No destructive keyword found → quick‑reject passes.
    true
}

```

## Summary

- **SIMD‑accelerated search** uses the `memmem` crate to scan for `"git"` and `"rm"` in raw byte slices without allocation or Unicode overhead.
- **Span‑aware matching** validates keywords against the executable span only, employing word‑boundary checks to eliminate false positives while avoiding regex.
- **Selective fallback** triggers full‑command scans only for commands containing redirection or pipeline operators, ensuring edge cases are handled without compromising average‑case performance.
- **Zero‑allocation design** ensures deterministic latency, processing safe commands in a few hundred microseconds according to the `Dicklesworthstone/destructive_command_guard` source code.

## Frequently Asked Questions

### What makes SIMD acceleration critical for the quick rejection filter?

SIMD instructions allow the `memmem` crate to evaluate multiple bytes simultaneously, reducing the search time for core keywords like `"git"` and `"rm"` from linear byte‑by‑byte inspection to vectorized operations. This reduces the baseline processing cost to sub‑microsecond levels, ensuring the filter never becomes a bottleneck during interactive shell sessions.

### How does span‑aware matching prevent false positives like "gitlab"?

The `keyword_matches_span` function enforces word boundaries using `is_word_byte` checks during the byte‑wise search. When scanning for `"git"`, the algorithm verifies that the match is not preceded or followed by alphanumeric characters, correctly rejecting embedded matches such as `"gitlab"` or `"digital"` while still catching standalone `"git"` commands.

### When does the filter fall back to a full command scan?

The fallback activates when `should_fallback_to_full_normalized_keyword_scan` (lines 35‑52 in [`src/packs/mod.rs`](https://github.com/Dicklesworthstone/destructive_command_guard/blob/main/src/packs/mod.rs)) detects redirection operators (`>`, `<`), pipes (`|`), or other shell metacharacters that might place destructive keywords outside the initial executable span. This occurs rarely in practice, as most AI‑generated commands use simple syntax without complex redirections.

### Which dependencies enable the sub‑millisecond performance?

The [`Cargo.toml`](https://github.com/Dicklesworthstone/destructive_command_guard/blob/main/Cargo.toml) declares `memchr` and `memmem` as core dependencies, providing the SIMD‑optimized substring search primitives. These crates implement platform‑specific vectorized instructions (AVX2, SSE2, or NEON) that process raw byte slices without branching or allocation, delivering the consistent sub‑millisecond latency required for real‑time command evaluation.