FrankenTerm

Algorithm & Data Structure Catalog

874 words4 min read6 subsectionsFrom the README at ft 0.15.21

On this page6
Throughput-critical primitivesSearch and retrievalConcurrency & cancellationStatistical / probabilisticGraphs and orderingSpecialized data structures

This section catalogs every non-trivial algorithm or data structure the project uses, why it was chosen, and where to read more.

Throughput-critical primitives

Algorithm Where Why this one
Aho-Corasick (multi-pattern) patterns.rs scan trigger O(n) in chunk length regardless of pattern count; the right tool for exact-substring multi-pattern matching.
Bloom filter (FNV-1a seeded) patterns.rs prefilter Rejects 80–95% of chunks in O(k) per chunk where k is small. The false-positive rate is tunable; we tune for "reject when possible, but never miss."
SIMD newline / ANSI density scan simd_scan.rs, feeding BOCPD features One linear pass per chunk gives us both newline count and ANSI escape density (TUI-vs-text output) at near-zero extra cost.
zstd compression byte_compression.rs, warm scrollback tiers 5:1 to 10:1 ratios typical on terminal output; high compression ratio with low decompression cost.
FNV-1a (64-bit non-crypto hash) Content fingerprinting One byte per cycle; deterministic across platforms; ideal for real-time dedup decisions where SHA-256 is too expensive.
SHA-256 Audit trail, attestation bundle, content addressing Cryptographic strength is required where the hash is a security primitive (audit row signing, attestation verification, idempotency keys).
XOR filter Search dedup Approximately 1.23 × n × fingerprint_bytes, which is more compact than Bloom at equivalent FP rates. Static (built once from a known set), which fits the dedup case where the known-hash set changes infrequently.

Search and retrieval

Algorithm Where Why this one
SQLite FTS5 Storage (lexical index) Bundled with rusqlite (no system dep); BM25-like ranking; reliable on commodity hardware.
Tantivy frankenterm-core-tantivy Richer scoring + faster ranked queries when relevance matters more than raw matching. The crate exists, but its index is not populated on the production path.
FNV-1a hash embeddings search/ semantic lane Deterministic, model-free and cheap enough to embed every segment at write time; fastembed/ONNX models are not on the production path.
Reciprocal Rank Fusion (RRF) search/ hybrid mode score(doc) = sum 1/(k + rank) with k=60 (canonical). Robust to rank-vs-score scale differences across backends.

Concurrency & cancellation

Algorithm Where Why this one
Cx cancellation tokens (asupersync) Workspace-wide Structured concurrency primitive that propagates cancel signals through the call graph. Replaces ad-hoc Arc<AtomicBool> patterns and tokio's CancellationToken — see Engineering Discipline for the ban.
Semaphore-guarded pools runtime_async::Semaphore, mux connection pool Each acquire returns a guard that holds a permit; dropping the guard releases. Prevents pool starvation when operations fail.
Circuit breaker (Closed → Open → Half-Open → Closed) mux pool, web/SSE, distributed connector Stops retry storms after sustained failure; configurable cooldown periods; status snapshot exposed via telemetry.
Exponential backoff with jitter retry layer Uniform ±10% by default; per-use-case policies (mux CLI: 3/100 ms, DB writes: 5/50 ms, webhooks: 5/1 s). Cancellation does not count as a circuit-breaker failure (ft-gc4hz).
Atomic CAS quiescence gauges wait.rs, watchdog Composable activity tracker; multiple watchers can wait for system idle without blocking each other.

Statistical / probabilistic

Algorithm Where Why this one
BOCPD (Bayesian Online Change-Point Detection) Pattern engine novel-failure detector Detects statistical regime changes without a-priori failure templates. Catches what regex doesn't.
EWMA estimator (NaN-sanitized) disk_pressure.rs, telemetry Smooth running average with configurable alpha. The NaN-sanitization closure (ft-fiuu6) ensures bad inputs can't poison the estimator.
T-Digest (NaN-aware) quantile_sketch, latency telemetry Online quantile estimation in bounded memory. Returns NaN for NaN input (not silent 0) per the substrate-audit closure.
Empirical Bernstein CI bench_stats Concentration-of-measure inequality with rejection of non-finite range. Used in bench result statistical gating.
Hoeffding inequality bench statistics, ML monitoring Sample-size derivation: how many samples do we need to bound error with high confidence?
Conformal SLO bands renderer SLO catalog, perf-gate Distribution-free prediction intervals. Future round-3 elevation (ft-tf6g3.30).
SPRT (Sequential Probability Ratio Test) ft-perf-gate substrate Stop testing as soon as the decision is statistically clear. Round-3 elevation (ft-tf6g3.30).
Reservoir sampling telemetry retention Bounded-memory uniform sampling over an unbounded stream.

Graphs and ordering

Algorithm Where Why this one
Dijkstra, Bellman-Ford, Floyd-Warshall Agent routing, dependency analysis Three different complexity points; pick the right one based on graph properties (sparse vs dense, negative edges, all-pairs vs single-source).
Topological sort + cycle detection Mission/tx step ordering, dependency-aware ready-set computation Catches dependency cycles before execution. Aligned with bv --robot-insights cycle detection.
Causal DAG construction Replay subsystem Decision graph with provenance edges; enables diff between two execution traces.
Min-plus algebra (network calculus) Latency analysis Formal worst-case delay and backlog bounds on the capture pipeline. The Lindley/min-plus bound artifact is at docs/attestations/perf/lindley-bounds.json.

Specialized data structures

Structure Where Why this one
Adaptive Radix Tree (ART) adaptive_radix_tree.rs Memory-efficient prefix-keyed structure; outperforms B-tree for string keys with shared prefixes.
Van Emde Boas (interface) van_emde_boas.rs Bounded-universe integer set with O(1) insert/remove/min/max and word-scan successor/predecessor; substrate for time-bucketed event indexing.
Wavelet tree wavelet_tree.rs O(log σ) rank/quantile and O(log n · log σ) select over byte sequences; substrate for scrollback byte-distribution analysis.
Binomial heap binomial_heap.rs Worst-case O(log n) insert/extract-min; arena-allocated, so meld copies the donor arena (O(m)) — substrate for single-queue priority scheduling.
Compact bitset compact_bitset.rs Dense membership representation; faster than HashSet<u32> for small universes.
Bimap bimap.rs Bidirectional HashMap; substrate for pane-id ↔ session-id style mappings.
Consistent hash consistent_hash.rs Stable load distribution across shards (mux sharding); minimizes shuffle when a shard joins/leaves.
Union-find union_find.rs Disjoint-set partition tracking; the error-clustering engine merges MinHash clusters with a module-local equivalent.
Bounded edit distance bounded_edit_distance.rs Levenshtein with an early-bail bound (Ukkonen banded DP); used by output compression for line-similarity checks.
Work-stealing deque work_stealing_deque.rs Single-producer multi-consumer queue (mutex-backed with try-lock steal; safe-Rust Chase-Lev interface); scheduling substrate for worker pools.