Merge 'perf/memory: benchmark FTS queries and concurrent transactions' from Pedro Muniz

## Purpose
Add shared FTS query workloads for dhat allocation-stack investigations
and Divan/CodSpeed memory tracking without changing the existing
Criterion profiles.
- Measure query-only cases separately from complete BEGIN
CONCURRENT/query/COMMIT lifecycles, including repeated overlapping
transactions on multiple connections.
- Emit explicit workload-phase events and query-phase heap reports.
- Add a deterministic high-vocabulary corpus, configurable page cache,
and actual stored segment-byte verification before measurement.
- Run FTS workload/CLI tests in CI, with separate fts-queries and fts-
large-index CodSpeed shards. The large case requires at least 256 MiB of
segment data and uses a 200-page cache.
## Measurement limits
Warm dhat runs exclude allocations made during setup and warm-up. Local
Divan does not count Tokio worker-thread allocations; use dhat for
complete concurrent totals. Exceeding the 192 MiB retained-segment
budget does not prove eviction or bounded live memory, and read-only
transactions do not exercise the four-searcher limit across changing
snapshots.
## Validation
- Focused FTS unit tests passed locally (4 tests before the final
additional segment-boundary test).
- Earlier small-corpus harness validation passed before the large-index
extension.
- cargo fmt and git diff --check completed.
- Final local build/test runs were cancelled at pedrocarlo’s request to
run validation in PR CI instead. The optimized large-index measurement
has not completed locally; its minimum-byte assertion and CI results
remain to be verified.

Reviewed-by: Jussi Saurio <jussi.saurio@gmail.com>

Closes #8866
This commit is contained in:
Pedro Muniz
2026-09-09 11:46:53 -03:00
committed by GitHub
12 changed files with 1653 additions and 3 deletions

View File

@@ -26,6 +26,96 @@ The crate is split into a library and binaries. The workload engine lives in
dhat/RSS measurement. Randomized profiles (`read-heavy`, `mixed`) use a fixed
RNG seed (`profile::WORKLOAD_RNG_SEED`) so workloads are identical across runs.
## FTS Query Allocations
The `fts-memory` binary and `perf/memory/codspeed/benches/fts_queries.rs` share
`memory_benchmark::fts`, independently of the existing SQL profile runner.
See `perf/memory/README.md` for commands, corpus details, and measurement limits.
```bash
cargo run -p memory-benchmark --features fts --bin fts-memory -- \
--query common --state warm --documents 10000 --queries 100 \
--dhat-file /tmp/fts-warm.json > /tmp/fts-warm-report.json
python3 perf/memory/analyze-dhat.py /tmp/fts-warm.json --modules --top 20
cargo test -p memory-benchmark-codspeed --features fts --bench fts_queries -- --test
```
Use debug runs for correctness only; use `--profile bench-profile` for optimized
dhat investigations with debug information and no LTO. Query cases are `rare`,
`common`, `and`, `or`, `phrase`, and `ranked`. State `first` requires one query
(the default); `warm` defaults to 100 queries on one persistent connection after
one unmeasured warm-up. The default corpus has 10000 documents; 1000 and 100000
are useful local comparison sizes. WAL and one connection remain the defaults.
For full transaction lifecycles, pass `--mode mvcc --connections 2
--transactions-per-connection 10 --queries-per-transaction 2`. This measures 20
transactions and 40 queries, including `BEGIN CONCURRENT` and `COMMIT`. WAL uses
`BEGIN`. Explicit transaction counts conflict with `--queries`; query counts are
otherwise per connection. All transactions begin before query workers start,
and all workers finish before commits. Connections persist across rounds.
One connection covers repeated transactions; two/four cover overlapping snapshots.
Warm-up runs one complete transaction with one query per connection when explicit
transactions are selected. Reports include completed transaction/query counts and
`max_active_transactions`; heap totals aggregate all connections and scheduling.
`FtsWorkload` emits `setup`, `open`, `warmup`, `run`, `cleanup`, and `done` through
`FtsObserver`. The CLI's `DhatObserver` starts profiling on `run` and stops on
`cleanup`, before connections are dropped. Each transition emits a JSON phase
event to stderr, also saved in the final report's `phases` array. stderr includes
dhat diagnostics; filter phase events with `jq -Rc 'fromjson? | select(.event == "phase")'`.
Elapsed event times include profiler overhead; check exit status for success.
`after_batch` samples live heap after a query per connection or after all commits
in one transaction round. Worker errors are joined before rollback and cleanup.
Setup, database opening, warm-up, and cleanup are excluded. Heap totals, peaks,
retained bytes, and per-query live-byte samples track query-phase allocations,
not caches allocated before profiling. RSS after profiling includes dhat's own
stack/report overhead. JSON goes to stdout and allocation stacks to `--dhat-file`.
The Divan target uses the workspace's CodSpeed-compatible Divan dependency,
without dhat's allocator, and runs in the `fts-queries` memory CI shard. Build
with `cargo codspeed build -m memory -p memory-benchmark-codspeed --features codspeed,fts`
and run with `cargo codspeed run -m memory -p memory-benchmark-codspeed --bench fts_queries`.
Each query has first/warm variants at 1000 and 10000 documents and extra 10/100-query
warm variants at 10000 documents. Names encode `(state, documents, queries)`.
The 24 extra `transactions` cases use 1000 documents, ten transactions per
connection, and two queries per transaction: WAL/one connection and MVCC/one,
two, or four connections for all six query cases. Names encode `(mode,
connections, transactions_per_connection, queries_per_transaction)`. Divan uses
the same `FtsWorkload::prepare` and `run` methods with a no-op observer.
Local builds without the `codspeed` feature install Divan's `AllocProfiler` over
the system allocator. Run `cargo bench --profile bench-profile -p memory-benchmark-codspeed
--features fts --bench fts_queries -- transactions --sample-count 3 --sample-size 1`
for local allocation output. Divan counts only its measured threads, not Tokio
worker threads: multi-connection allocation figures are incomplete. Use the dhat
CLI for process-wide concurrent totals and peaks. `alloc` counts allocation calls;
realloc growth is separate under `grow`. `max alloc` is peak live memory for the
whole measured sequence, not per query.
The existing Criterion memory profiles and their setup-inclusive metrics are unchanged.
For above-cache investigations, use `--documents 20000 --extra-tokens 1024
--cache-pages 200 --min-index-bytes 268435456` with the transaction flags above.
Extra tokens use a fixed seed and do not change query matches. The minimum is
checked against stored FTS chunk bytes, not corpus or database size. Setup uses
the core test-helper backing-row reader, then closes inspection connections.
The JSON `index` reports `segment_bytes`, `segments`, `largest_segment_bytes`,
`page_size`, and `configured_cache_pages`; `corpus` records the three options.
An `event: "index"` stderr record reports sizes before measurement or rejection.
Cache pages must be at least 200; omitted means engine default. Zero extra tokens
and zero minimum preserve the small corpus. A 256 MiB index exceeds the current
192 MiB retained-segment budget, but cached searchers can retain segment data and
live cursors load every visible segment. This is not proof of cache eviction or
a memory ceiling. Read-only transactions do not exercise the four-searcher limit
across changing snapshots. Writer arena (64 MiB) and document flush (1000) limits
apply during setup, outside query profiling. See the README for all caveats.
The matching Divan case is opt-in: `--features fts-stress --bench fts_queries --
oversized_index`, with one/two MVCC connections, three transactions, two queries
per transaction, and one sample. CI builds with `codspeed,fts`, excluding the
large cases at compile time, and runs the smaller cases in `fts-queries`.
The large case took about 18 minutes per configuration under CodSpeed; positional
filters did not isolate Divan cases. Use local Divan or dhat for above-cache runs.
The build job also runs `cargo test -p memory-benchmark --features fts --locked`.
## Running Stack Reports
Use this when investigating stack usage from SQL translation/execution probes.

View File

@@ -47,7 +47,10 @@ jobs:
path: target/codspeed
- name: Build memory benchmarks
run: cargo codspeed build -m memory -p memory-benchmark-codspeed --features codspeed
run: cargo codspeed build -m memory -p memory-benchmark-codspeed --features codspeed,fts
- name: Test FTS memory workload
run: cargo test -p memory-benchmark --features fts --locked
run:
name: "memory benchmarks (${{ matrix.workload }})"
@@ -69,6 +72,7 @@ jobs:
- scan-heavy
- series-blob
- update-churn
- fts-queries
steps:
- uses: actions/checkout@v4
@@ -104,7 +108,12 @@ jobs:
uses: CodSpeedHQ/action@v4.17.0
with:
mode: memory
run: cargo codspeed run -m memory -p memory-benchmark-codspeed --bench memory_profiles "${{ matrix.workload }}"
run: |
if [ "${{ matrix.workload }}" = "fts-queries" ]; then
cargo codspeed run -m memory -p memory-benchmark-codspeed --bench fts_queries
else
cargo codspeed run -m memory -p memory-benchmark-codspeed --bench memory_profiles "${{ matrix.workload }}"
fi
cleanup:
name: Delete temporary benchmark sticky disk

3
Cargo.lock generated
View File

@@ -3740,10 +3740,12 @@ dependencies = [
"serde",
"serde_json",
"stacker",
"tempfile",
"tokio",
"tracing",
"tracing-subscriber",
"turso",
"turso_core",
"turso_parser",
]
@@ -3752,6 +3754,7 @@ name = "memory-benchmark-codspeed"
version = "0.1.0"
dependencies = [
"codspeed-criterion-compat",
"codspeed-divan-compat",
"criterion",
"memory-benchmark",
"tokio",

View File

@@ -13,11 +13,18 @@ path = "src/main.rs"
name = "stack-report"
path = "src/stack_report.rs"
[[bin]]
name = "fts-memory"
path = "src/fts_memory.rs"
required-features = ["fts"]
[features]
stacker = ["turso/stacker"]
fts = ["turso/fts", "dep:tempfile", "dep:turso_core"]
[dependencies]
turso = { path = "../../bindings/rust", default-features = false }
turso_core = { path = "../../core", optional = true, default-features = false, features = ["fs", "fts", "test_helper"] }
turso_parser = { workspace = true }
clap = { workspace = true, features = ["derive"] }
tokio = { workspace = true, default-features = true, features = ["full"] }
@@ -30,3 +37,4 @@ serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
anyhow = { workspace = true }
rand = { workspace = true }
tempfile = { workspace = true, optional = true }

245
perf/memory/README.md Normal file
View File

@@ -0,0 +1,245 @@
# FTS query memory benchmarks
`fts-memory` and the `fts_queries` Divan/CodSpeed target share the corpus and
workload runner in `src/fts.rs`. They use a temporary on-disk database, with WAL
and one connection by default. MVCC and overlapping explicit transactions are
also supported. Existing SQL memory profiles are unchanged.
## Investigate with dhat
```bash
cargo run -p memory-benchmark --features fts --bin fts-memory -- \
--query common --state warm --documents 10000 --queries 100 \
--dhat-file /tmp/fts-common-warm.json > /tmp/fts-common-warm-report.json
python3 perf/memory/analyze-dhat.py /tmp/fts-common-warm.json --modules --top 20
python3 perf/memory/analyze-dhat.py /tmp/fts-common-warm.json --filter tantivy --stacks
python3 perf/memory/analyze-dhat.py /tmp/fts-common-warm.json --sort-by eb --top 20
```
The command above uses a debug build for correctness checks. For representative
allocation investigations, use `cargo run --profile bench-profile` with the same
arguments. This workspace profile enables optimization and debug information
without LTO, preserving more useful allocation stacks. Do not compare debug
allocation numbers with optimized CI results.
Each invocation runs one query case and prints a JSON report to stdout. dhat
writes allocation stacks to `--dhat-file` (default `dhat-heap.json`). Use distinct
paths to preserve reports from multiple runs. The temporary database is removed
when the process exits normally.
| Option | Values / default |
|--------|------------------|
| `--query` | `rare`, `common` (default), `and`, `or`, `phrase`, `ranked` |
| `--state` | `first`, `warm` (default) |
| `--documents` | Positive document count; default 10000; try 1000, 10000, 100000 |
| `--queries` | Queries per connection in autocommit mode; defaults to 1 for first-query runs, 100 for warmed runs |
| `--mode` | `wal` (default), `mvcc` |
| `--connections` | Positive connection count; default 1 |
| `--transactions-per-connection` | Enable explicit transactions and repeat this many per connection; conflicts with `--queries` |
| `--queries-per-transaction` | Queries inside each explicit transaction; default 1; requires `--transactions-per-connection` |
| `--dhat-file` | Output allocation profile path; default `dhat-heap.json` |
Setup inserts the corpus in 500-document transactions, builds the index over
the populated table, and checks that every query plan uses the FTS index method.
Each session reopens the database.
Additional connections share that reopened database handle.
`first` measures exactly one query per connection without warm-up; explicit
transactions must also have a count of one per connection in this state.
`warm` executes the selected query once per connection before measurement,
inside a complete unmeasured transaction when explicit transactions are selected.
Measured work reuses those connections. Neither state claims a cold OS cache.
Both runners include SQL preparation, execution, and draining the result rows.
They accumulate a row count and ID sum, not a result vector. Database opening,
indexing, warm-up, connection destruction, and database cleanup are outside the
measured region. The corpus is synthetic: common terms occur in every document,
rare terms in 1%, and alpha/beta terms in overlapping subsets. The phrase case
distinguishes ordered from reversed words. Ranked queries score alpha/beta
matches and return the best ten.
The JSON report contains total allocation bytes/count, per-query averages,
peak live query bytes, and query bytes retained while the session is still open.
`query_heap` records live tracked bytes after each batch: one query per connection
in autocommit mode, or one complete transaction per connection in explicit mode.
Samples include cumulative completed query and transaction counts. Compare
`--queries 1`, `10`, and `100` at a fixed corpus size to investigate accumulation.
Heap measurement starts after setup and warm-up. These numbers describe only
allocations tracked from that point, not the full live database/cache footprint.
If a pre-existing allocation is resized during measurement, dhat records the
resized allocation. Retained bytes are not automatically leaks: they can be
caches that remain live until the connection closes.
`rss_before_query_bytes` and `rss_after_profiler_bytes` are supporting process
snapshots, not a query peak. The latter includes dhat stack collection and report
generation overhead, which can be large. Use the heap metrics for query analysis.
## Measure concurrent transaction lifecycles
```bash
cargo run -p memory-benchmark --features fts --bin fts-memory -- \
--mode mvcc --connections 2 --query common --documents 1000 \
--transactions-per-connection 10 --queries-per-transaction 2 \
--dhat-file /tmp/fts-transactions.json \
> /tmp/fts-transactions-report.json 2> /tmp/fts-transactions-events.log
```
This measures 20 transactions and 40 FTS queries. Every transaction includes
`BEGIN CONCURRENT`, all its queries, and `COMMIT`. WAL uses `BEGIN` instead.
The original autocommit benchmarks remain separate.
Within each round, the runner begins all transactions and verifies that every
connection is out of autocommit before starting query workers. Query workers
run concurrently; all workers finish before any connection commits. Begin and
commit statements run sequentially across connections, inside measurement.
This guarantees overlapping transactions even when queries complete immediately.
Connections persist across rounds. On a query error, workers are stopped and
joined before active transactions are rolled back.
The report includes actual completed `transactions`, total `queries`, and
`max_active_transactions` observed before query execution. Counts exclude warm-up.
Heap metrics aggregate all connections, including worker scheduling and transaction
overhead; per-query averages therefore include amortized begin/commit costs.
Concurrent allocation order can vary between runs, especially peak live bytes;
compare repeated runs rather than treating one peak as deterministic.
Use one connection to compare repeated transactions without overlap, and two or
four to compare simultaneous snapshot retention. These workloads remain read-only.
## Investigate indexes larger than the caches
The large corpus adds `--extra-tokens` deterministic pseudorandom terms per
document. They enlarge the term dictionaries and postings without changing the
existing query matches. This is a high-vocabulary stress case, not a natural-language
corpus. `--cache-pages` sets the page cache on every measured connection (minimum
200 pages). `--min-index-bytes` rejects an undersized index before profiling.
Defaults are zero extra tokens, the engine's page-cache default, and no size minimum.
```bash
cargo run --profile bench-profile -p memory-benchmark --features fts --bin fts-memory -- \
--documents 20000 --extra-tokens 1024 --cache-pages 200 \
--min-index-bytes 268435456 --mode mvcc --connections 2 \
--query common --transactions-per-connection 3 --queries-per-transaction 2 \
--dhat-file /tmp/fts-large.json > /tmp/fts-large-report.json
```
Setup uses the core `test_helper` backing-row reader to measure actual stored
segment chunk bytes, not database size or source-text size. It reports
`index.segment_bytes`, `segments`, `largest_segment_bytes`, `page_size`, and
`configured_cache_pages`, both in stdout and an `event: "index"` stderr record.
Inspection connections close before measured connections open. This inspection,
including byte checksums, is outside profiling and can take time for large indexes.
The minimum above is 256 MiB, exceeding the current 192 MiB shared retained-segment
budget, the 64 MiB writer arena, and the configured 200-page cache (800 KiB with
4096-byte pages). The writer arena and 1000-document flush threshold apply during
setup, not query measurement. The report's segment count and maximum size distinguish
many small segments from one oversized segment.
An index above 192 MiB does **not** prove query memory is bounded or that every
query reloads the index. The engine retains the newest segment even when it exceeds
the budget, live cursors load all visible segments, and cached searchers may keep
segment data alive. The four-searcher limit counts distinct visible segment/tombstone
sets; repeated read-only transactions do not exercise snapshot churn. Query-string
size/depth limits are validation limits and are not part of this memory workload.
Compare first-query and warmed runs; warm dhat metrics exclude cache allocations
made during warm-up, even when those allocations remain live.
The same large workload is available to Divan/CodSpeed behind a separate feature:
```bash
cargo bench --profile bench-profile -p memory-benchmark-codspeed \
--features fts-stress --bench fts_queries -- oversized_index
```
It runs one and two MVCC connections, three transactions each, two queries per
transaction, with one sample by default. CI builds with `codspeed,fts`, excluding
the large case at compile time. The large case took about 18 minutes per
configuration under CodSpeed, and positional name filters did not isolate it
from the smaller Divan cases. Keep `fts-stress` for explicit local investigations;
the dhat command above remains available for process-wide memory measurements.
The `fts-queries` CI shard runs the smaller cases, and the build job also runs
the FTS workload and CLI tests. Local multi-connection Divan
allocation counts remain incomplete; use dhat for all-thread totals.
## Consume explicit workload phases
`FtsWorkload` owns the transitions, and `DhatObserver` controls the profiler:
```text
setup -> open -> warmup -> run -> cleanup -> done
| |
start dhat stop dhat before dropping connections
```
Each transition emits a JSON object to stderr, for example:
```json
{"event":"phase","phase":"run","elapsed_ms":123}
```
The final stdout report repeats these events in `phases`. Elapsed times include
profiler overhead and are not query timing measurements. `warmup` is emitted even
when `--state first` skips warm-up work. `done` means cleanup finished; check the
process exit status for success. Phase logging and report serialization are
outside the measured region.
stderr also contains dhat diagnostics and, with `cargo run`, build messages.
Extract just phase events without parsing those messages:
```bash
jq -Rc 'fromjson? | select(.event == "phase")' /tmp/fts-transactions-events.log
```
The observer interface also provides `after_batch` for in-process measurement.
It runs after workers finish and, for explicit transactions, after all commits.
Divan uses the same preparation and run methods with a no-op observer; setup
and input destruction remain outside its measured closure.
## Track regressions with Divan and CodSpeed
```bash
cargo test -p memory-benchmark --features fts
cargo test -p memory-benchmark-codspeed --features fts --bench fts_queries -- --test
cargo codspeed build -m memory -p memory-benchmark-codspeed --features codspeed,fts
cargo codspeed run -m memory -p memory-benchmark-codspeed --bench fts_queries
```
The first two commands check correctness without collecting representative
performance numbers. CodSpeed measurement requires its runner; the GitHub
`CodSpeed Memory` workflow includes an `fts-queries` shard. It does not install
the dhat allocator in the Divan executable.
For local allocation output, the target installs Divan's system-backed
`AllocProfiler` when the `codspeed` feature is off:
```bash
cargo bench --profile bench-profile -p memory-benchmark-codspeed \
--features fts --bench fts_queries -- transactions --sample-count 3 --sample-size 1
```
Divan's `alloc` row counts allocation calls; realloc growth is reported separately
under `grow`. Add their bytes for growth-inclusive allocation pressure. `max alloc`
is Divan's peak live bytes/count on the measured thread. These values cover a whole
benchmark sequence, not one query. Divan does not collect allocations on Tokio worker
threads: its figures for two/four connections are incomplete. Use `fts-memory`
with the same configuration for process-wide concurrent heap metrics. Do not
compare partial local Divan numbers with CodSpeed's memory instrument as though
they have the same scope. Single-connection queries run on the measured thread.
Each query case has six configurations, named `(state, documents, queries)`:
first and warmed queries at 1000 and 10000 documents, plus 10-query and 100-query
warmed runs at 10000 documents. CodSpeed reports allocations for the entire
configuration, so divide by its query count for a per-query comparison.
There are also 24 `transactions` cases: every query case at 1000 documents, ten
transactions per connection, and two queries per transaction, using WAL with
one connection or MVCC with one, two, and four connections. Names encode
`(mode, connections, transactions_per_connection, queries_per_transaction)`.
Divan's input generator creates the fixture, opens connections, and performs any
warm-up outside the measured closure. Each input is used for one measured query
or transaction sequence and dropped after measurement. The same boundaries apply
under CodSpeed instrumentation.
Existing Criterion profiles retain their separate harness and measurement rules.

View File

@@ -15,6 +15,8 @@ unexpected_cfgs = { level = "warn", check-cfg = ['cfg(nightly)'] }
[features]
codspeed = []
fts = ["memory-benchmark/fts"]
fts-stress = ["fts"]
[dev-dependencies]
memory-benchmark = { path = ".." }
@@ -22,7 +24,13 @@ tokio = { workspace = true, default-features = true, features = ["full"] }
criterion = { workspace = true }
codspeed-criterion-compat = { workspace = true }
turso_macros = { workspace = true }
divan = { workspace = true }
[[bench]]
name = "memory_profiles"
harness = false
[[bench]]
name = "fts_queries"
harness = false
required-features = ["fts"]

View File

@@ -0,0 +1,139 @@
use divan::{Bencher, black_box};
use memory_benchmark::fts::{
CorpusConfig, Execution, FtsConfig, FtsWorkload, QueryCase, QueryState,
};
use memory_benchmark::workload::JournalMode;
#[cfg(not(feature = "codspeed"))]
#[global_allocator]
static ALLOC: divan::AllocProfiler = divan::AllocProfiler::system();
const CONFIGURATIONS: &[(QueryState, usize, usize)] = &[
(QueryState::First, 1_000, 1),
(QueryState::First, 10_000, 1),
(QueryState::Warm, 1_000, 1),
(QueryState::Warm, 10_000, 1),
(QueryState::Warm, 10_000, 10),
(QueryState::Warm, 10_000, 100),
];
fn main() {
divan::main();
}
macro_rules! query_bench {
($name:ident, $case:ident) => {
#[turso_macros::divan_bench(args = CONFIGURATIONS, sample_size = 1)]
fn $name(bencher: Bencher, configuration: &(QueryState, usize, usize)) {
let &(state, documents, queries) = configuration;
benchmark(bencher, QueryCase::$case, state, documents, queries);
}
};
}
query_bench!(rare, Rare);
query_bench!(common, Common);
query_bench!(and, And);
query_bench!(or, Or);
query_bench!(phrase, Phrase);
query_bench!(ranked, Ranked);
mod transactions {
use super::*;
const CONFIGURATIONS: &[(JournalMode, usize, usize, usize)] = &[
(JournalMode::Wal, 1, 10, 2),
(JournalMode::Mvcc, 1, 10, 2),
(JournalMode::Mvcc, 2, 10, 2),
(JournalMode::Mvcc, 4, 10, 2),
];
macro_rules! transaction_bench {
($name:ident, $case:ident) => {
#[turso_macros::divan_bench(args = CONFIGURATIONS, sample_size = 1)]
fn $name(bencher: Bencher, configuration: &(JournalMode, usize, usize, usize)) {
let &(mode, connections, per_connection, queries_per_transaction) = configuration;
benchmark_workload(
bencher,
FtsConfig {
query: QueryCase::$case,
state: QueryState::Warm,
documents: 1_000,
corpus: CorpusConfig::default(),
mode,
connections,
execution: Execution::Transactions {
per_connection,
queries_per_transaction,
},
},
);
}
};
}
transaction_bench!(rare, Rare);
transaction_bench!(common, Common);
transaction_bench!(and, And);
transaction_bench!(or, Or);
transaction_bench!(phrase, Phrase);
transaction_bench!(ranked, Ranked);
}
#[cfg(feature = "fts-stress")]
#[turso_macros::divan_bench(args = [1, 2], sample_size = 1, sample_count = 1)]
fn oversized_index(bencher: Bencher, connections: usize) {
benchmark_workload(
bencher,
FtsConfig {
query: QueryCase::Common,
state: QueryState::Warm,
documents: 20_000,
corpus: CorpusConfig {
extra_tokens: 1024,
cache_pages: Some(200),
min_index_bytes: 256 * 1024 * 1024,
},
mode: JournalMode::Mvcc,
connections,
execution: Execution::Transactions {
per_connection: 3,
queries_per_transaction: 2,
},
},
);
}
fn benchmark(
bencher: Bencher,
case: QueryCase,
state: QueryState,
documents: usize,
queries: usize,
) {
benchmark_workload(
bencher,
FtsConfig {
query: case,
state,
documents,
corpus: CorpusConfig::default(),
mode: JournalMode::Wal,
connections: 1,
execution: Execution::Queries(queries),
},
);
}
fn benchmark_workload(bencher: Bencher, config: FtsConfig) {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(config.connections)
.enable_all()
.build()
.unwrap();
bencher
.with_inputs(|| rt.block_on(FtsWorkload::prepare(config, &mut ())).unwrap())
.bench_local_refs(|workload| {
black_box(rt.block_on(workload.run(&mut ())).unwrap());
});
}

708
perf/memory/src/fts.rs Normal file
View File

@@ -0,0 +1,708 @@
use anyhow::{Result, ensure};
use clap::ValueEnum;
use rand::{RngCore, SeedableRng, rngs::StdRng};
use serde::Serialize;
use std::fmt::Write;
use std::sync::Arc;
use tempfile::TempDir;
use turso::{Connection, Database};
use turso_core::IO;
use crate::workload::JournalMode;
#[derive(Clone, Copy, Debug, ValueEnum, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum QueryCase {
Rare,
Common,
And,
Or,
Phrase,
Ranked,
}
#[derive(Clone, Copy, Debug, ValueEnum, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum QueryState {
First,
Warm,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum FtsPhase {
Setup,
Open,
Warmup,
Run,
Cleanup,
Done,
}
pub trait FtsObserver {
fn on_phase(&mut self, _phase: FtsPhase) {}
fn on_index(&mut self, _stats: &IndexStats) {}
fn after_batch(&mut self, _progress: &RunResult) {}
}
impl FtsObserver for () {}
#[derive(Clone, Copy, Debug)]
pub enum Execution {
Queries(usize),
Transactions {
per_connection: usize,
queries_per_transaction: usize,
},
}
#[derive(Clone, Copy, Debug)]
pub struct FtsConfig {
pub query: QueryCase,
pub state: QueryState,
pub documents: usize,
pub corpus: CorpusConfig,
pub mode: JournalMode,
pub connections: usize,
pub execution: Execution,
}
#[derive(Clone, Copy, Debug, Default, Serialize)]
pub struct CorpusConfig {
pub extra_tokens: usize,
pub cache_pages: Option<usize>,
pub min_index_bytes: usize,
}
#[derive(Clone, Debug, Serialize)]
pub struct IndexStats {
pub segment_bytes: usize,
pub segments: usize,
pub largest_segment_bytes: usize,
pub page_size: usize,
pub configured_cache_pages: Option<usize>,
}
pub struct FtsWorkload {
sessions: Vec<QuerySession>,
_fixture: FtsFixture,
config: FtsConfig,
}
#[derive(Default, Debug, Serialize)]
pub struct RunResult {
pub queries: usize,
pub transactions: usize,
pub rows: usize,
pub id_sum: i64,
pub max_active_transactions: usize,
}
pub struct FtsFixture {
directory: TempDir,
}
#[derive(Clone)]
pub struct QuerySession {
conn: Connection,
_db: Database,
}
#[derive(Debug, PartialEq, Eq)]
pub struct QueryResult {
pub rows: usize,
pub id_sum: i64,
}
pub async fn run_fts(config: FtsConfig, observer: &mut dyn FtsObserver) -> Result<RunResult> {
let workload = FtsWorkload::prepare(config, observer).await?;
let result = workload.run(observer).await;
workload.finish(observer);
result
}
impl FtsWorkload {
pub async fn prepare(config: FtsConfig, observer: &mut dyn FtsObserver) -> Result<Self> {
config.validate()?;
observer.on_phase(FtsPhase::Setup);
let fixture =
FtsFixture::create_in_mode(config.documents, config.mode, config.corpus).await?;
let stats = fixture.index_stats(config.corpus.cache_pages)?;
observer.on_index(&stats);
ensure!(
stats.segment_bytes >= config.corpus.min_index_bytes,
"index contains {} segment bytes, below requested minimum {}; increase documents or extra tokens",
stats.segment_bytes,
config.corpus.min_index_bytes
);
observer.on_phase(FtsPhase::Open);
let first = fixture.open().await?;
let mut sessions = Vec::with_capacity(config.connections);
for _ in 1..config.connections {
sessions.push(QuerySession {
conn: first._db.connect()?,
_db: first._db.clone(),
});
}
sessions.push(first);
if let Some(pages) = config.corpus.cache_pages {
for session in &sessions {
session
.conn
.pragma_update("cache_size", &pages.to_string())
.await?;
}
}
let workload = Self {
sessions,
_fixture: fixture,
config,
};
observer.on_phase(FtsPhase::Warmup);
if matches!(config.state, QueryState::Warm) {
workload.batch(1).await?;
}
Ok(workload)
}
pub async fn run(&self, observer: &mut dyn FtsObserver) -> Result<RunResult> {
observer.on_phase(FtsPhase::Run);
let mut progress = RunResult::default();
for _ in 0..self.config.execution.batches() {
let batch = self
.batch(self.config.execution.queries_per_batch())
.await?;
progress.queries += batch.queries;
progress.transactions += batch.transactions;
progress.rows += batch.rows;
progress.id_sum += batch.id_sum;
progress.max_active_transactions = progress
.max_active_transactions
.max(batch.max_active_transactions);
observer.after_batch(&progress);
}
Ok(progress)
}
pub fn finish(self, observer: &mut dyn FtsObserver) {
observer.on_phase(FtsPhase::Cleanup);
drop(self);
observer.on_phase(FtsPhase::Done);
}
async fn batch(&self, queries: usize) -> Result<RunResult> {
let transactions = matches!(self.config.execution, Execution::Transactions { .. });
let outcome = async {
let mut active = 0;
if transactions {
let begin = match self.config.mode {
JournalMode::Wal => "BEGIN",
JournalMode::Mvcc => "BEGIN CONCURRENT",
};
for session in &self.sessions {
session.begin(begin).await?;
}
for session in &self.sessions {
active += usize::from(!session.conn.is_autocommit()?);
}
ensure!(
active == self.sessions.len(),
"transactions must overlap before queries start"
);
}
let mut result = self.query_all(queries).await?;
if transactions {
for session in &self.sessions {
session.commit().await?;
ensure!(
session.conn.is_autocommit()?,
"COMMIT must end the transaction"
);
}
result.transactions = self.sessions.len();
result.max_active_transactions = active;
}
Ok(result)
}
.await;
if outcome.is_err() {
for session in &self.sessions {
if !session.conn.is_autocommit()? {
session.conn.execute("ROLLBACK", ()).await?;
}
}
}
outcome
}
async fn query_all(&self, queries: usize) -> Result<RunResult> {
if self.sessions.len() == 1 {
return self.sessions[0]
.query_batch(self.config.query, queries)
.await;
}
let mut workers = tokio::task::JoinSet::new();
for session in &self.sessions {
let session = session.clone();
let case = self.config.query;
workers.spawn(async move { session.query_batch(case, queries).await });
}
let result = async {
let mut result = RunResult::default();
while let Some(worker) = workers.join_next().await {
let batch = worker??;
result.queries += batch.queries;
result.rows += batch.rows;
result.id_sum += batch.id_sum;
}
Ok(result)
}
.await;
if result.is_err() {
workers.shutdown().await;
}
result
}
}
impl FtsConfig {
pub fn validate(&self) -> Result<()> {
ensure!(self.documents > 0, "documents must be positive");
ensure!(
self.corpus
.cache_pages
.is_none_or(|pages| (200..=i32::MAX as usize).contains(&pages)),
"cache pages must be between 200 and i32::MAX"
);
ensure!(self.connections > 0, "connections must be positive");
ensure!(
self.execution.batches() > 0,
"queries or transactions must be positive"
);
ensure!(
self.execution.queries_per_batch() > 0,
"queries per transaction must be positive"
);
ensure!(
!matches!(self.state, QueryState::First)
|| (self.execution.batches() == 1 && self.execution.queries_per_batch() == 1),
"first-query runs require one query per connection; use warm for repeated transactions"
);
self.execution
.batches()
.checked_mul(self.execution.queries_per_batch())
.and_then(|n| n.checked_mul(self.connections))
.ok_or_else(|| anyhow::anyhow!("total query count overflows usize"))?;
Ok(())
}
}
impl Execution {
pub fn batches(self) -> usize {
match self {
Self::Queries(queries) => queries,
Self::Transactions { per_connection, .. } => per_connection,
}
}
fn queries_per_batch(self) -> usize {
match self {
Self::Queries(_) => 1,
Self::Transactions {
queries_per_transaction,
..
} => queries_per_transaction,
}
}
}
impl FtsFixture {
pub async fn create(documents: usize) -> Result<Self> {
Self::create_in_mode(documents, JournalMode::Wal, CorpusConfig::default()).await
}
async fn create_in_mode(
documents: usize,
mode: JournalMode,
corpus: CorpusConfig,
) -> Result<Self> {
ensure!(documents > 0, "documents must be positive");
let fixture = Self {
directory: tempfile::tempdir()?,
};
let session = fixture.open().await?;
let mode = match mode {
JournalMode::Wal => "'wal'",
JournalMode::Mvcc => "'mvcc'",
};
session.conn.pragma_update("journal_mode", mode).await?;
session
.conn
.execute(
"CREATE TABLE docs (id INTEGER PRIMARY KEY, title TEXT, body TEXT)",
(),
)
.await?;
let mut rng = StdRng::seed_from_u64(0x4654_534d);
for start in (0..documents).step_by(500) {
session.conn.execute("BEGIN", ()).await?;
let mut insert = session
.conn
.prepare("INSERT INTO docs VALUES (?1, ?2, ?3)")
.await?;
for id in start..documents.min(start + 500) {
let rare = if id % 100 == 0 { "rare" } else { "plain" };
let alpha = if id % 2 == 0 { "alpha" } else { "gamma" };
let beta = if id % 3 == 0 { "beta" } else { "delta" };
let prefix = if id % 200 == 100 {
"rare common".to_string()
} else {
format!("common {rare}")
};
let mut body = format!("{prefix} {alpha} {beta} search document storage text");
for _ in 0..corpus.extra_tokens {
write!(body, " x{:016x}", rng.next_u64())?;
}
insert
.execute(turso::params![id as i64, format!("document {id:08}"), body])
.await?;
}
session.conn.execute("COMMIT", ()).await?;
}
session
.conn
.execute("CREATE INDEX docs_fts ON docs USING fts (title, body)", ())
.await?;
for case in QueryCase::value_variants() {
session.check_index(*case).await?;
}
Ok(fixture)
}
fn index_stats(&self, cache_pages: Option<usize>) -> Result<IndexStats> {
let io = Arc::new(turso_core::PlatformIO::new()?);
let db = turso_core::Database::open(
io.clone(),
self.directory.path().join("fts.db").to_str().unwrap(),
turso_core::OpenOptions::new(Arc::new(turso_core::SqliteDialect))
.db_opts(turso_core::DatabaseOpts::new().with_index_method(true)),
)?;
let conn = db.connect()?;
conn.execute("BEGIN")?;
conn.execute("SELECT count(*) FROM docs")?;
let mut dumper = turso_core::index_method::fts::FtsBackingRowDumper::new(
&conn,
turso_core::MAIN_DB_ID,
"docs_fts",
)?;
loop {
match dumper.step()? {
turso_core::IOResult::Done(()) => break,
turso_core::IOResult::IO(completions) => {
while !completions.finished() {
io.step()?;
}
}
}
}
let mut sizes = std::collections::BTreeMap::<&str, usize>::new();
let mut segments = 0;
for (path, _, bytes, _) in &dumper.rows {
if let Some(suffix) = path.strip_prefix("fts2/chunk/") {
let (segment, _) = suffix.split_once('/').expect("segment chunk path");
*sizes.entry(segment).or_default() += bytes;
} else if path.starts_with("fts2/seg/") {
segments += 1;
}
}
ensure!(
segments > 0 && sizes.len() == segments,
"missing FTS segment data"
);
let mut page_size = 0;
conn.query("PRAGMA page_size")?
.expect("page size query")
.run_with_row_callback(|row| {
page_size = row.get::<i64>(0)? as usize;
Ok(())
})?;
let stats = IndexStats {
segment_bytes: sizes.values().sum(),
segments,
largest_segment_bytes: *sizes.values().max().unwrap(),
page_size,
configured_cache_pages: cache_pages,
};
drop(dumper);
conn.execute("ROLLBACK")?;
conn.close()?;
Ok(stats)
}
pub async fn session(&self, case: QueryCase, state: QueryState) -> Result<QuerySession> {
let session = self.open().await?;
if matches!(state, QueryState::Warm) {
session.query(case).await?;
}
Ok(session)
}
async fn open(&self) -> Result<QuerySession> {
let path = self.directory.path().join("fts.db");
let db = turso::Builder::new_local(path.to_str().unwrap())
.experimental_index_method(true)
.build()
.await?;
let conn = db.connect()?;
Ok(QuerySession { conn, _db: db })
}
}
impl QuerySession {
async fn begin(&self, sql: &str) -> Result<()> {
self.conn.execute(sql, ()).await?;
Ok(())
}
async fn commit(&self) -> Result<()> {
self.conn.execute("COMMIT", ()).await?;
Ok(())
}
async fn query_batch(&self, case: QueryCase, queries: usize) -> Result<RunResult> {
let mut result = RunResult::default();
for _ in 0..queries {
let query = std::hint::black_box(self.query(case).await?);
result.queries += 1;
result.rows += query.rows;
result.id_sum += query.id_sum;
}
Ok(result)
}
pub async fn query(&self, case: QueryCase) -> Result<QueryResult> {
let mut rows = self.conn.query(case.sql(), ()).await?;
let mut result = QueryResult { rows: 0, id_sum: 0 };
while let Some(row) = rows.next().await? {
result.rows += 1;
result.id_sum += row.get::<i64>(0)?;
}
Ok(result)
}
async fn check_index(&self, case: QueryCase) -> Result<()> {
let mut rows = self
.conn
.query(&format!("EXPLAIN QUERY PLAN {}", case.sql()), ())
.await?;
let mut indexed = false;
let mut details = Vec::new();
while let Some(row) = rows.next().await? {
let detail = row.get::<String>(3)?;
indexed |= detail == "QUERY INDEX METHOD fts";
details.push(detail);
}
ensure!(indexed, "FTS index not used for {case:?}: {details:?}");
Ok(())
}
}
impl QueryCase {
pub fn sql(self) -> &'static str {
match self {
Self::Rare => "SELECT id FROM docs WHERE fts_match(title, body, 'rare')",
Self::Common => "SELECT id FROM docs WHERE fts_match(title, body, 'common')",
Self::And => "SELECT id FROM docs WHERE fts_match(title, body, 'alpha AND beta')",
Self::Or => "SELECT id FROM docs WHERE fts_match(title, body, 'alpha OR beta')",
Self::Phrase => "SELECT id FROM docs WHERE fts_match(title, body, '\"common rare\"')",
Self::Ranked => {
"SELECT id, fts_score(title, body, 'alpha OR beta') AS score FROM docs WHERE fts_match(title, body, 'alpha OR beta') ORDER BY score DESC LIMIT 10"
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn index_size_includes_segments_on_both_sides_of_document_flush() -> Result<()> {
for (documents, segments) in [(1000, 1), (1001, 2)] {
let fixture = FtsFixture::create(documents).await?;
let stats = fixture.index_stats(None)?;
assert_eq!(stats.segments, segments);
assert_eq!(stats.page_size, 4096);
assert!(stats.largest_segment_bytes > 0);
if segments == 1 {
assert_eq!(stats.segment_bytes, stats.largest_segment_bytes);
} else {
assert!(stats.segment_bytes > stats.largest_segment_bytes);
}
let session = fixture
.session(QueryCase::Common, QueryState::First)
.await?;
assert_eq!(session.query(QueryCase::Common).await?.rows, documents);
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn mvcc_transactions_overlap_repeat_and_finish_before_cleanup() -> Result<()> {
let mut observer = RecordingObserver::default();
let config = FtsConfig {
query: QueryCase::And,
state: QueryState::Warm,
documents: 103,
corpus: CorpusConfig {
extra_tokens: 1024,
cache_pages: Some(200),
min_index_bytes: 200 * 4096 + 1,
},
mode: JournalMode::Mvcc,
connections: 2,
execution: Execution::Transactions {
per_connection: 3,
queries_per_transaction: 2,
},
};
let workload = FtsWorkload::prepare(config, &mut observer).await?;
let mut mode = workload.sessions[0]
.conn
.query("PRAGMA journal_mode", ())
.await?;
assert_eq!(mode.next().await?.unwrap().get::<String>(0)?, "mvcc");
drop(mode);
let result = workload.run(&mut observer).await?;
assert_eq!(result.queries, 12);
assert_eq!(result.transactions, 6);
assert_eq!(result.max_active_transactions, 2);
assert_eq!(result.rows, 216);
assert_eq!(result.id_sum, 11_016);
assert_eq!(observer.batches, [(4, 2), (8, 4), (12, 6)]);
for session in &workload.sessions {
assert!(session.conn.is_autocommit()?);
let mut cache = session.conn.query("PRAGMA cache_size", ()).await?;
assert_eq!(cache.next().await?.unwrap().get::<i64>(0)?, 200);
}
workload.finish(&mut observer);
assert_eq!(
observer.phases,
[
FtsPhase::Setup,
FtsPhase::Open,
FtsPhase::Warmup,
FtsPhase::Run,
FtsPhase::Cleanup,
FtsPhase::Done
]
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn failed_query_workers_finish_before_transactions_are_rolled_back() -> Result<()> {
let config = FtsConfig {
query: QueryCase::Common,
state: QueryState::First,
documents: 5,
corpus: CorpusConfig::default(),
mode: JournalMode::Mvcc,
connections: 2,
execution: Execution::Transactions {
per_connection: 1,
queries_per_transaction: 1,
},
};
let workload = FtsWorkload::prepare(config, &mut ()).await?;
workload.sessions[0]
.conn
.execute("DROP TABLE docs", ())
.await?;
let mut observer = RecordingObserver::default();
assert!(workload.run(&mut observer).await.is_err());
assert!(observer.batches.is_empty());
for session in &workload.sessions {
assert!(session.conn.is_autocommit()?);
session.begin("BEGIN CONCURRENT").await?;
session.commit().await?;
}
workload.finish(&mut observer);
assert_eq!(
observer.phases,
[FtsPhase::Run, FtsPhase::Cleanup, FtsPhase::Done]
);
Ok(())
}
#[tokio::test]
async fn query_cases_return_expected_rows_after_reopening_and_warming() -> Result<()> {
let fixture = FtsFixture::create(103).await?;
for state in [QueryState::First, QueryState::Warm] {
for (case, count, sum) in [
(QueryCase::Rare, 2, 100),
(QueryCase::Common, 103, 5253),
(QueryCase::And, 18, 918),
(QueryCase::Or, 69, 3519),
(QueryCase::Phrase, 1, 0),
] {
let session = fixture.session(case, state).await?;
for _ in 0..2 {
assert_eq!(
session.query(case).await?,
QueryResult {
rows: count,
id_sum: sum
}
);
}
}
let session = fixture.session(QueryCase::Ranked, state).await?;
let mut rows = session.conn.query(QueryCase::Ranked.sql(), ()).await?;
let mut previous = f64::INFINITY;
let mut ids = Vec::new();
while let Some(row) = rows.next().await? {
let id = row.get::<i64>(0)?;
let score = row.get::<f64>(1)?;
assert!((0..103).contains(&id));
assert_eq!(id % 6, 0);
assert!(!ids.contains(&id));
assert!(score > 0.0 && score <= previous);
previous = score;
ids.push(id);
}
assert_eq!(ids.len(), 10);
}
Ok(())
}
#[tokio::test]
async fn ranked_limit_handles_fewer_than_ten_matches() -> Result<()> {
let fixture = FtsFixture::create(5).await?;
let session = fixture
.session(QueryCase::Ranked, QueryState::First)
.await?;
assert_eq!(
session.query(QueryCase::Ranked).await?,
QueryResult { rows: 4, id_sum: 9 }
);
Ok(())
}
#[derive(Default)]
struct RecordingObserver {
phases: Vec<FtsPhase>,
batches: Vec<(usize, usize)>,
}
impl FtsObserver for RecordingObserver {
fn on_phase(&mut self, phase: FtsPhase) {
self.phases.push(phase);
}
fn after_batch(&mut self, progress: &RunResult) {
assert_eq!(self.phases.last(), Some(&FtsPhase::Run));
self.batches.push((progress.queries, progress.transactions));
}
}
}

View File

@@ -0,0 +1,229 @@
use anyhow::Result;
use clap::Parser;
use memory_benchmark::fts::{
CorpusConfig, Execution, FtsConfig, FtsObserver, FtsPhase, IndexStats, QueryCase, QueryState,
RunResult, run_fts,
};
use memory_benchmark::workload::JournalMode;
use serde::Serialize;
use std::path::PathBuf;
use std::time::Instant;
#[cfg(not(clippy))]
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;
#[derive(Parser)]
#[command(about = "Profile FTS query allocations, excluding corpus setup and warm-up")]
struct Args {
#[arg(long, default_value = "common")]
query: QueryCase,
#[arg(long, default_value = "warm")]
state: QueryState,
#[arg(long, default_value = "10000")]
documents: usize,
#[arg(long, default_value = "0")]
extra_tokens: usize,
#[arg(long)]
cache_pages: Option<usize>,
#[arg(long, default_value = "0")]
min_index_bytes: usize,
#[arg(long, conflicts_with = "transactions_per_connection")]
queries: Option<usize>,
#[arg(long, default_value = "wal")]
mode: JournalMode,
#[arg(long, default_value = "1")]
connections: usize,
#[arg(long)]
transactions_per_connection: Option<usize>,
#[arg(long, requires = "transactions_per_connection")]
queries_per_transaction: Option<usize>,
#[arg(long, default_value = "dhat-heap.json")]
dhat_file: PathBuf,
}
#[derive(Serialize)]
struct QueryHeap {
completed_queries: usize,
completed_transactions: usize,
live_query_bytes: usize,
}
#[derive(Serialize)]
struct PhaseEvent {
event: &'static str,
phase: FtsPhase,
elapsed_ms: u128,
}
struct DhatObserver {
#[cfg(not(clippy))]
path: PathBuf,
#[cfg(not(clippy))]
profiler: Option<dhat::Profiler>,
stats: Option<dhat::HeapStats>,
query_heap: Vec<QueryHeap>,
phases: Vec<PhaseEvent>,
start: Instant,
rss_before: Option<usize>,
rss_after: Option<usize>,
index: Option<IndexStats>,
}
#[derive(Serialize)]
struct Report {
corpus: CorpusConfig,
index: IndexStats,
query: QueryCase,
state: QueryState,
mode: JournalMode,
connections: usize,
transactions: usize,
queries_per_transaction: Option<usize>,
max_active_transactions: usize,
documents: usize,
queries: usize,
rows_per_query: usize,
total_allocated_bytes: u64,
total_allocations: u64,
allocated_bytes_per_query: f64,
allocations_per_query: f64,
peak_live_query_bytes: usize,
retained_query_bytes: usize,
rss_before_query_bytes: Option<usize>,
rss_after_profiler_bytes: Option<usize>,
query_heap: Vec<QueryHeap>,
phases: Vec<PhaseEvent>,
dhat_file: PathBuf,
}
fn main() -> Result<()> {
let args = Args::parse();
let execution = match args.transactions_per_connection {
Some(per_connection) => Execution::Transactions {
per_connection,
queries_per_transaction: args.queries_per_transaction.unwrap_or(1),
},
None => Execution::Queries(args.queries.unwrap_or(match args.state {
QueryState::First => 1,
QueryState::Warm => 100,
})),
};
let config = FtsConfig {
query: args.query,
state: args.state,
documents: args.documents,
corpus: CorpusConfig {
extra_tokens: args.extra_tokens,
cache_pages: args.cache_pages,
min_index_bytes: args.min_index_bytes,
},
mode: args.mode,
connections: args.connections,
execution,
};
config.validate()?;
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(args.connections)
.enable_all()
.build()?;
let mut observer = DhatObserver {
#[cfg(not(clippy))]
path: args.dhat_file.clone(),
#[cfg(not(clippy))]
profiler: None,
stats: None,
query_heap: Vec::with_capacity(execution.batches()),
phases: Vec::with_capacity(6),
start: Instant::now(),
rss_before: None,
rss_after: None,
index: None,
};
let result = rt.block_on(run_fts(config, &mut observer))?;
let stats = observer
.stats
.expect("run phase must finish before reporting");
let report = Report {
corpus: config.corpus,
index: observer.index.expect("index measured during setup"),
query: args.query,
state: args.state,
mode: args.mode,
connections: args.connections,
transactions: result.transactions,
queries_per_transaction: match execution {
Execution::Queries(_) => None,
Execution::Transactions {
queries_per_transaction,
..
} => Some(queries_per_transaction),
},
max_active_transactions: result.max_active_transactions,
documents: args.documents,
queries: result.queries,
rows_per_query: result.rows / result.queries,
total_allocated_bytes: stats.total_bytes,
total_allocations: stats.total_blocks,
allocated_bytes_per_query: stats.total_bytes as f64 / result.queries as f64,
allocations_per_query: stats.total_blocks as f64 / result.queries as f64,
peak_live_query_bytes: stats.max_bytes,
retained_query_bytes: stats.curr_bytes,
rss_before_query_bytes: observer.rss_before,
rss_after_profiler_bytes: observer.rss_after,
query_heap: observer.query_heap,
phases: observer.phases,
dhat_file: args.dhat_file,
};
println!("{}", serde_json::to_string_pretty(&report)?);
Ok(())
}
impl FtsObserver for DhatObserver {
fn on_index(&mut self, stats: &IndexStats) {
eprintln!("{}", serde_json::json!({"event": "index", "index": stats}));
self.index = Some(stats.clone());
}
fn on_phase(&mut self, phase: FtsPhase) {
if phase == FtsPhase::Cleanup {
self.stats = Some(dhat::HeapStats::get());
#[cfg(not(clippy))]
drop(
self.profiler
.take()
.expect("run phase must start profiling"),
);
self.rss_after = rss();
}
let event = PhaseEvent {
event: "phase",
phase,
elapsed_ms: self.start.elapsed().as_millis(),
};
eprintln!(
"{}",
serde_json::to_string(&event).expect("phase event must serialize")
);
self.phases.push(event);
if phase == FtsPhase::Run {
self.rss_before = rss();
#[cfg(not(clippy))]
{
self.profiler = Some(dhat::Profiler::builder().file_name(&self.path).build());
}
}
}
fn after_batch(&mut self, progress: &RunResult) {
self.query_heap.push(QueryHeap {
completed_queries: progress.queries,
completed_transactions: progress.transactions,
live_query_bytes: dhat::HeapStats::get().curr_bytes,
});
}
}
fn rss() -> Option<usize> {
memory_stats::memory_stats().map(|stats| stats.physical_mem)
}

View File

@@ -1,3 +1,5 @@
#[cfg(feature = "fts")]
pub mod fts;
pub mod measure;
pub mod profile;
pub mod workload;

View File

@@ -11,7 +11,8 @@ use super::profile::{
update_churn::UpdateChurn,
};
#[derive(Debug, Clone, Copy, ValueEnum)]
#[derive(Debug, Clone, Copy, ValueEnum, serde::Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum JournalMode {
Wal,
Mvcc,

View File

@@ -0,0 +1,208 @@
#![cfg(feature = "fts")]
use serde_json::Value;
use std::process::Command;
#[test]
fn cli_profiles_only_queries_and_reports_each_completed_query() {
let directory = tempfile::tempdir().unwrap();
for (state, queries) in [("first", 1), ("warm", 3)] {
let path = directory.path().join(format!("{state}.json"));
let output = Command::new(env!("CARGO_BIN_EXE_fts-memory"))
.args([
"--query",
"common",
"--state",
state,
"--documents",
"103",
"--queries",
&queries.to_string(),
"--dhat-file",
])
.arg(&path)
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: Value = serde_json::from_slice(&output.stdout).unwrap();
assert_phase_events(&report, &output.stderr);
assert_eq!(report["queries"], queries);
assert_eq!(report["rows_per_query"], 103);
let index = &report["index"];
assert_eq!(index["segments"], 1);
assert_eq!(index["segment_bytes"], index["largest_segment_bytes"]);
assert!(index["segment_bytes"].as_u64().unwrap() > 0);
assert_eq!(index["page_size"], 4096);
let total = report["total_allocated_bytes"].as_u64().unwrap();
let peak = report["peak_live_query_bytes"].as_u64().unwrap();
let retained = report["retained_query_bytes"].as_u64().unwrap();
assert!(total >= peak && peak >= retained && peak > 0);
assert_eq!(
report["allocated_bytes_per_query"].as_f64().unwrap(),
total as f64 / queries as f64
);
let samples = report["query_heap"].as_array().unwrap();
assert_eq!(samples.len(), queries as usize);
for (i, sample) in samples.iter().enumerate() {
assert_eq!(sample["completed_queries"], i + 1);
}
assert_eq!(samples.last().unwrap()["live_query_bytes"], retained);
let profile: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
let frames = profile["ftbl"].as_array().unwrap();
assert!(
frames
.iter()
.any(|frame| frame.as_str().unwrap().contains("QuerySession::query"))
);
assert!(
!frames
.iter()
.any(|frame| frame.as_str().unwrap().contains("FtsFixture::"))
);
assert!(
!frames
.iter()
.any(|frame| frame.as_str().unwrap().contains("FtsWorkload::prepare"))
);
}
}
#[test]
fn cli_measures_begin_and_commit_across_overlapping_mvcc_transactions() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("transactions.json");
let output = Command::new(env!("CARGO_BIN_EXE_fts-memory"))
.args([
"--mode",
"mvcc",
"--connections",
"2",
"--transactions-per-connection",
"3",
"--queries-per-transaction",
"2",
"--query",
"and",
"--documents",
"103",
"--dhat-file",
])
.arg(&path)
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: Value = serde_json::from_slice(&output.stdout).unwrap();
assert_phase_events(&report, &output.stderr);
assert_eq!(report["mode"], "mvcc");
assert_eq!(report["queries"], 12);
assert_eq!(report["transactions"], 6);
assert_eq!(report["rows_per_query"], 18);
assert_eq!(report["max_active_transactions"], 2);
let samples = report["query_heap"].as_array().unwrap();
assert_eq!(samples.len(), 3);
for (i, sample) in samples.iter().enumerate() {
assert_eq!(sample["completed_queries"], (i + 1) * 4);
assert_eq!(sample["completed_transactions"], (i + 1) * 2);
}
let profile: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
let frames = profile["ftbl"].as_array().unwrap();
for function in [
"QuerySession::begin",
"QuerySession::query",
"QuerySession::commit",
] {
assert!(
frames
.iter()
.any(|frame| frame.as_str().unwrap().contains(function)),
"missing measured {function}"
);
}
assert!(!frames.iter().any(|frame| {
let frame = frame.as_str().unwrap();
frame.contains("FtsFixture::")
|| frame.contains("FtsWorkload::prepare")
|| frame.contains("FtsWorkload::finish")
}));
}
#[test]
fn undersized_index_is_rejected_before_profiling() {
let directory = tempfile::tempdir().unwrap();
let profile = directory.path().join("heap.json");
let output = Command::new(env!("CARGO_BIN_EXE_fts-memory"))
.args([
"--documents",
"5",
"--min-index-bytes",
"268435456",
"--dhat-file",
])
.arg(&profile)
.output()
.unwrap();
assert!(!output.status.success());
assert!(output.stdout.is_empty());
assert!(!profile.exists());
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("below requested minimum"), "{stderr}");
assert!(!stderr.contains("\"phase\":\"run\""));
}
#[test]
fn cli_rejects_empty_workloads_and_repeated_first_queries() {
for args in [
vec!["--cache-pages", "199"],
vec!["--queries", "0"],
vec!["--documents", "0"],
vec!["--state", "first", "--queries", "2"],
vec!["--connections", "0"],
vec!["--transactions-per-connection", "0"],
vec![
"--transactions-per-connection",
"2",
"--queries-per-transaction",
"0",
],
vec!["--queries-per-transaction", "2"],
vec!["--queries", "2", "--transactions-per-connection", "2"],
] {
let output = Command::new(env!("CARGO_BIN_EXE_fts-memory"))
.args(args)
.output()
.unwrap();
assert!(!output.status.success());
assert!(output.stdout.is_empty());
}
}
fn assert_phase_events(report: &Value, stderr: &[u8]) {
let events: Vec<Value> = String::from_utf8_lossy(stderr)
.lines()
.filter_map(|line| serde_json::from_str::<Value>(line).ok())
.filter(|event| event["event"] == "phase")
.collect();
assert_eq!(events, *report["phases"].as_array().unwrap());
let phases: Vec<&str> = events
.iter()
.map(|event| event["phase"].as_str().unwrap())
.collect();
assert_eq!(
phases,
["setup", "open", "warmup", "run", "cleanup", "done"]
);
assert!(
events
.windows(2)
.all(|pair| pair[0]["elapsed_ms"].as_u64().unwrap()
<= pair[1]["elapsed_ms"].as_u64().unwrap())
);
}