Skip to content

perf(binary-index): time dictionary lookups only when their debug log is on - #2101

Merged
aaj3f merged 2 commits into
mainfrom
perf/dict-lookup-timing
Oct 14, 2026
Merged

aaj3f merged 2 commits into
mainfrom
perf/dict-lookup-timing

Conversation

@aaj3f

@aaj3f aaj3f commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

DictTreeReader::reverse_lookup read the clock ten times on every call: five Instant::now()/elapsed() pairs, one per phase. load_leaf, which it calls, read it once or twice more. The only reader of those timings is a pair of debug logs, "slow reverse lookup" and "slow leaf load", that fire past 250 ms. Every term encoded or decoded through the dictionary takes this path, so on a lookup that hits a cached leaf, the clock reads were more than half of the instructions it ran.

The reader now takes these timings through a small DebugClock, which reads the time only when tracing::enabled!(Level::DEBUG) holds for the module, with one read per phase. So with debug logging off, a lookup doesn't read the clock at all, and with it on, the same logs fire with the same fields and thresholds, from half as many clock reads. reverse_lookup_many uses the same clock.

Numbers

Instructions retired (proc_pid_rusage), dev-fast builds of main at c5874d586 and of this branch, runs interleaved. The medians below are recomputed from the raw output. All of these are from macOS (arm64), since proc_pid_rusage only exists there, so there's no Linux run of the tables below.

Per reverse_lookup, 500,000 lookups in a fixed random order over an in-memory dictionary of 200,000 keys (11 reps × 2 runs):

tracing main this branch ratio
no subscriber 3,885 1,833 0.472
INFO subscriber (a server's default) 3,884 1,833 0.472
DEBUG subscriber 3,883 3,322 0.855

Per query, a person graph split across three named graphs of one ledger and read FROM all three (20 iterations, 2 runs; the rows marked † include SPARQL JSON formatting):

query main this branch ratio
COUNT(DISTINCT ?s) over ex:name 70.0M 53.5M 0.765
COUNT(*) over every triple 461.3M 342.9M 0.743
COUNT(*) GROUP BY ?p 470.9M 352.8M 0.749
DISTINCT ?f over ex:friend 422.5M 307.3M 0.727
COUNT(?f) GROUP BY ?s 226.5M 176.9M 0.781
ORDER BY DESC(?n) LIMIT 10 † 76.5M 60.0M 0.784
every triple, projected † 1,217.7M 1,098.0M 0.902
two filters (STRSTARTS, >) † 453.7M 422.8M 0.932
OPTIONAL † 505.4M 469.4M 0.929
two-pattern join † 1,100.5M 1,026.2M 0.933
  • The same queries over the union default graph show the same ratios: COUNT(DISTINCT ?s) drops from 69.9M to 53.4M.
  • Single-graph queries that don't go through the dictionary per row are unchanged (0.998–1.003).
  • Allocation counts are identical.

On Linux, Instant::now() goes through the vDSO and its cost depends on the clock source, so I measured the cost of a clock read directly, since that's what the ratios above lean on. One Instant::now() plus elapsed(), best of 15 runs of 5M pairs, takes about 35 ns on macOS (arm64) and about 35 ns on arm64 Linux (Ubuntu 22.04 in Docker on the same machine, arch_sys_counter clock source), so a Linux/macOS ratio of about 1.0 over three interleaved runs of each. Both read the same hardware counter from userspace, so on arm64 I'd expect the gain above to carry over. I didn't measure x86 Linux; there it depends on the clock source (tsc reads in userspace through the vDSO, while some VM clock sources fall back to a syscall), so the per-query gain on an x86 server could be smaller or larger than the tables show.

What else the sweep looked at

These clock reads sit in per-load, per-fetch, per-batch or per-operator code rather than per row or per lookup, so I left them as they are:

  • dict/reader.rs, remote leaf fetch timing: one read per CAS fetch, and the network dominates.
  • read/binary_index_store.rs, load_from_root_bytes, build_dictionary_set and load_per_graph_arenas: once per index load.
  • read/batched_lookup.rs, batched_lookup_predicate_refs: once per batched class lookup.
  • dict/pack_reader.rs: tests only.
  • The query operators' timings in sort, groupby, join, optional, aggregate, group_aggregate and runner: once per batch or per operator.

Nothing else in fluree-db-binary-index, fluree-db-core's range reads, novelty, or the result formatters reads the clock per row.

Compatibility

No persisted format changes. The debug logs keep their messages, fields and thresholds.

Tests and gates

The existing dictionary reader tests cover the lookups themselves. Two unit tests in dict/reader.rs pin when the clock reads the time: with no subscriber, or with the reader at INFO, DebugClock never starts and lap() is zero, and with the reader at DEBUG it starts and lap() covers a 5 ms sleep. Each installs its subscriber as the thread's default (tracing::subscriber::with_default) and calls tracing::callsite::rebuild_interest_cache(), so a callsite interest cached by another test can't decide the result. They fail against each of a start() that never reads, a lap() that always returns zero, a start() that always reads, and a start() gated on ERROR rather than DEBUG. tracing-subscriber, already a workspace dependency, is now a dev-dependency of fluree-db-binary-index.

Gates at 973af22da:

  • cargo fmt --check;
  • clippy on fluree-db-binary-index and fluree-db-query with default features and with --all-features;
  • wasm32 clippy (the engine crates, and fluree-db-binary-index alone);
  • fluree-db-binary-index and fluree-db-query library tests (2,080 passed).

Gates at f0f5f2715, which adds the tests:

  • cargo fmt --check;
  • clippy on fluree-db-binary-index with default features and with --all-features;
  • wasm32 clippy on the engine crates, which lints fluree-db-binary-index;
  • fluree-db-binary-index library tests: 415 passed, 1 ignored with default features, and 418 passed, 1 ignored with --all-features.

… is on

`DictTreeReader::reverse_lookup` read the clock ten times per call (five
start/elapsed pairs), and `load_leaf` once or twice more, only to decide
whether to emit the "slow reverse lookup" / "slow leaf load" debug logs.
A clock read costs a few hundred instructions, a large share of a lookup
that hits a cached leaf, and every term decode or encode goes through it.

The reader now takes those timings through a clock that reads the time
only when `tracing` has debug enabled for this module, with one read per
phase. The logs, their fields and their thresholds are unchanged. The
batched `reverse_lookup_many` uses the same clock.
@aaj3f aaj3f added area:query Query execution, planning, fast paths, overlay, result formatting performance Performance improvement (release notes: Performance) labels Oct 12, 2026
@aaj3f
aaj3f requested a review from bplatz October 12, 2026 16:42

@bplatz bplatz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving, with two small suggestions inline.

What I checked: all seven slow-lookup debug logs in this file use the module's default target, which is the one enabled! tests, so turning on debug for this module brings back the same logs. The server's OTEL layer allowlists crates at DEBUG and doesn't include fluree_db_binary_index, so turning on OTEL export doesn't bring the clock reads back.

Comment on lines +24 to +27
/// A clock for the slow-lookup debug logs below, read only when this module
/// logs at debug level. A clock read costs a few hundred instructions, a large
/// share of a lookup that hits a cached leaf, and nothing else reads these
/// timings.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The "few hundred instructions" figure here, and the numbers in the description, are from macOS: proc_pid_rusage only exists there. On Linux, Instant::now() goes through the vDSO and is usually much cheaper, though that depends on the clock source. So the per-query ratios likely overstate the gain on production servers. Could you say in the description that the numbers are from macOS? A Linux comparison on one query would also do, if you want the numbers in the release notes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call, and you're right that the description read as if those numbers held everywhere. They're all from macOS (arm64), and I've said so in the description now. I did want to know how far off they'd be on Linux, though, so I timed one Instant::now() + elapsed() pair (best of 15 runs of 5M) on macOS and in an arm64 Ubuntu container on the same machine: about 35 ns on both, arch_sys_counter clock source on the Linux side. I was a bit surprised, but I think it makes sense, as on arm64 both end up reading the same hardware counter from userspace, so I'd expect the gain to carry over there. I didn't measure x86 Linux, where it depends on the clock source (tsc stays in userspace, while some VM clock sources fall back to a syscall), and the description says that rather than guessing a direction. The comment at reader.rs:24 no longer gives the "few hundred instructions" figure as if it were platform-independent; it now says the cost depends on the platform and clock source and gives the ~35 ns arm64 number. Both are in f0f5f2715.

Comment on lines +30 to +48
impl DebugClock {
fn start() -> Self {
Self(tracing::enabled!(tracing::Level::DEBUG).then(Instant::now))
}

/// Time since the start or the previous lap, and restart the lap; zero
/// when not timing.
fn lap(&mut self) -> std::time::Duration {
match &mut self.0 {
Some(started) => {
let now = Instant::now();
let lap = now.duration_since(*started);
*started = now;
lap
}
None => std::time::Duration::ZERO,
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing tests this. If a later edit breaks start() or lap(), the slow-lookup logs stop firing and no test fails. A small unit test would pin it: with no subscriber, lap() returns zero, and under a subscriber with this module at DEBUG, it returns the elapsed time. One gotcha: tracing caches each callsite's interest, which has bitten tests here before (the routing-stamp flake), so the test may need tracing::callsite::rebuild_interest_cache() after installing its subscriber.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, this was worth pinning. f0f5f2715 adds two unit tests next to DebugClock: with no subscriber, or with a subscriber that has the reader at INFO, the clock never starts and lap() is zero; with the reader at DEBUG it starts and lap() covers a 5 ms sleep. The INFO case is there so the test checks the module's level and not just whether any subscriber is installed. Each test installs its subscriber with tracing::subscriber::with_default and then calls tracing::callsite::rebuild_interest_cache(), so a cached interest from another test (the routing-stamp flake you mentioned) can't decide the result, and nothing global is set. I checked they aren't vacuous: they fail against a start() that never reads, a lap() that always returns zero, a start() that always reads, and a start() gated on ERROR instead of DEBUG. The lib suite also passed five times in a row with the default parallel test threads. It does add tracing-subscriber as a dev-dependency of fluree-db-binary-index (it's already a workspace dependency), which I think is fine for a test-only use, but happy to swap it for a tiny hand-rolled subscriber if you'd rather keep the crate's dev-deps lean.

`DebugClock` reads the time only when this module logs at debug level, and
nothing failed if a later edit broke that: the slow-lookup logs would just
stop firing. Two unit tests now pin both sides. With no subscriber, or with
the reader at INFO, the clock never starts and `lap()` is zero; with the
reader at DEBUG, it starts and `lap()` covers a 5ms sleep. Each test installs
its subscriber as the thread's default and rebuilds callsite interest, so a
cached interest from another test can't decide the outcome.

The clock's comment no longer gives the macOS instruction count as if it
held everywhere. It gives the measured cost of a read and its `elapsed()`,
about 35 ns on arm64 under both macOS and Linux, and says it varies with the
platform and clock source.
@aaj3f

aaj3f commented Oct 14, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the careful pass, and especially for checking the debug targets and the OTEL allowlist, which I hadn't thought to double-check. Both inline notes are folded into f0f5f2715: tests for DebugClock and a platform-honest comment and description. The Linux check turned out a bit differently than expected: on arm64 a clock read costs about the same on Linux as on macOS (~35 ns per now() + elapsed() pair), so the macOS ratios should hold there. I haven't measured x86, and the description says so.

@aaj3f
aaj3f merged commit f3c3b00 into main Oct 14, 2026
19 checks passed
@aaj3f
aaj3f deleted the perf/dict-lookup-timing branch October 14, 2026 13:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:query Query execution, planning, fast paths, overlay, result formatting performance Performance improvement (release notes: Performance)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants