Repository navigation
perf(binary-index): time dictionary lookups only when their debug log is on - #2101
Conversation
… 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.
bplatz
left a comment
There was a problem hiding this comment.
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.
| /// 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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, | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
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 |
Summary
DictTreeReader::reverse_lookupread the clock ten times on every call: fiveInstant::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 whentracing::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_manyuses the same clock.Numbers
Instructions retired (
proc_pid_rusage),dev-fastbuilds ofmainatc5874d586and of this branch, runs interleaved. The medians below are recomputed from the raw output. All of these are from macOS (arm64), sinceproc_pid_rusageonly 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):mainPer query, a person graph split across three named graphs of one ledger and read
FROMall three (20 iterations, 2 runs; the rows marked † include SPARQL JSON formatting):mainCOUNT(DISTINCT ?s)overex:nameCOUNT(*)over every tripleCOUNT(*)GROUP BY ?pDISTINCT ?foverex:friendCOUNT(?f)GROUP BY ?sORDER BY DESC(?n) LIMIT 10†STRSTARTS,>) †OPTIONAL†COUNT(DISTINCT ?s)drops from 69.9M to 53.4M.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. OneInstant::now()pluselapsed(), 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_counterclock 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 (tscreads 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_setandload_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.sort,groupby,join,optional,aggregate,group_aggregateandrunner: 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.rspin when the clock reads the time: with no subscriber, or with the reader at INFO,DebugClocknever starts andlap()is zero, and with the reader at DEBUG it starts andlap()covers a 5 ms sleep. Each installs its subscriber as the thread's default (tracing::subscriber::with_default) and callstracing::callsite::rebuild_interest_cache(), so a callsite interest cached by another test can't decide the result. They fail against each of astart()that never reads, alap()that always returns zero, astart()that always reads, and astart()gated on ERROR rather than DEBUG.tracing-subscriber, already a workspace dependency, is now a dev-dependency offluree-db-binary-index.Gates at
973af22da:cargo fmt --check;fluree-db-binary-indexandfluree-db-querywith default features and with--all-features;fluree-db-binary-indexalone);fluree-db-binary-indexandfluree-db-querylibrary tests (2,080 passed).Gates at
f0f5f2715, which adds the tests:cargo fmt --check;fluree-db-binary-indexwith default features and with--all-features;fluree-db-binary-index;fluree-db-binary-indexlibrary tests: 415 passed, 1 ignored with default features, and 418 passed, 1 ignored with--all-features.