1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
// SPDX-FileCopyrightText: 2026 Blackcat InformaticsĀ® Inc. <paudley@blackcatinformatics.ca>
// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0
//! Counts of the work the index does, for tests that assert a bound on the
//! work instead of timing it.
//!
//! A place that does a unit of work calls [`add`] with the kind and the amount.
//! Outside `cfg(test)` the call compiles to nothing. In a test, [`measure`]
//! runs a closure against fresh tallies and panics the moment any tally passes
//! its ceiling, so an implementation that does too much work fails at once
//! instead of running to the end. The tallies belong to the calling thread, so
//! only work done on that thread is counted.
/// One kind of work that is counted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Work {
/// An attribute summarised by the fact extractor.
Attributes,
/// A line and column converted to a byte offset.
Positions,
/// A character walked converting a column to a byte offset.
ColumnSteps,
/// An iteration of the glob segment matcher.
PatternSteps,
/// A wildcard pattern tried against a path by the exclude list.
ExcludeTests,
/// A path segment appended or visited while resolving a path.
SegmentReads,
/// A lookup of a name in the settled tables.
Lookups,
/// A name or binding read through a glob scope view.
ViewReads,
/// A unit of work charged to the export walk.
WalkSteps,
/// A glob read looked at by the search for the modules that hold an item
/// apart from a reading module.
SupplySteps,
/// A reading again of what the globs of a module bring in under one name,
/// in one name space, for one class of its importers, while the glob
/// tables settle.
Recomputations,
/// A glob read of a module looked at by such a reading again.
RecomputedReads,
/// A glob read of a module looked at while the drops that the settled
/// tables show are recorded.
DropReads,
/// A list of the items that a view holds under a name, copied for a glob
/// read that reads the view.
ListCopies,
/// A glob read of a module looked at by a lookup of what the globs of the
/// module bring in under a name.
LookupReads,
/// A route to an item made and offered to the bindings that a lookup of
/// what the globs of a module bring in returns: one for each glob read
/// and item under a name that a view holds a companion under, and one
/// for each item, its routes combined first, under any other.
LookupRoutes,
/// A view that holds a name, looked at to find the glob reads of a module
/// whose view holds the name.
HolderScans,
/// A step of a glob read whose module has views, none of which can
/// access what the glob brings in: a name of the view it reads probed or
/// looked at when the read is made, a name passed on to the module then,
/// a waiting name of the module looked up, and the read looked at when
/// its view grows.
CovertChecks,
/// An arrival found to change nothing, tested without a copy.
Deltas,
/// A new inaccessible item that requires rereading the name before
/// exposing its ambiguity beside the visible routes.
Exposures,
/// The record of the names under which a view dropped what its class
/// cannot access, or a view its module reads through a glob whose level
/// the class cannot access, looked at when an item it can access first
/// arrives under a name.
HiddenChecks,
/// A lookup of whether the globs of a module bring in anything under a
/// name.
AnyLookups,
/// A view that holds a name, looked at by a lookup of what the globs of
/// a module bring in under it to find the glob reads whose view holds
/// the name.
LookupScans,
/// A lookup step charged to a work budget: a glob read a lookup looks at
/// or a view it looks at to find them, charged to the work of the load at
/// a checkpoint or counted on the meter of a query.
LookupCharges,
/// An incoming candidate checked for an already represented route.
CandidateSteps,
/// A queue entry, subscription or undecided-import graph step.
SettleSteps,
/// Resident/source cells read by constructive glob-table validation.
ProofReads,
/// Cells copied or materialized in constructive validation scratch.
ProofCopies,
/// Ranked-validation bookkeeping, comparisons and transfer operations.
ProofSteps,
/// A token read by the lexing of a file for reachability.
ReachTokens,
/// A step of placing the units of a file and the paths of its text in
/// them: a unit opened or closed, or a path given to its unit.
ReachUnits,
/// A path run resolved for reachability: one asked for the first time in
/// its module.
ReachPaths,
/// A step of the reachability walk: a node or an edge handled, or an
/// entry of the tables built for the walk.
ReachSteps,
/// A token or context edge inspected for format-capture provenance.
ReachFormatTokens,
/// A source, decoded literal or attribute byte admitted or inspected for captures.
ReachFormatBytes,
}
/// The number of kinds of [`Work`].
#[cfg(test)]
const KINDS: usize = 35;
/// Every kind of [`Work`], in tally order.
#[cfg(test)]
const ALL: [Work; KINDS] = [
Work::Attributes,
Work::Positions,
Work::ColumnSteps,
Work::PatternSteps,
Work::ExcludeTests,
Work::SegmentReads,
Work::Lookups,
Work::ViewReads,
Work::WalkSteps,
Work::SupplySteps,
Work::Recomputations,
Work::RecomputedReads,
Work::DropReads,
Work::ListCopies,
Work::LookupReads,
Work::LookupRoutes,
Work::HolderScans,
Work::CovertChecks,
Work::Deltas,
Work::Exposures,
Work::HiddenChecks,
Work::AnyLookups,
Work::LookupScans,
Work::LookupCharges,
Work::CandidateSteps,
Work::SettleSteps,
Work::ProofReads,
Work::ProofCopies,
Work::ProofSteps,
Work::ReachTokens,
Work::ReachUnits,
Work::ReachPaths,
Work::ReachSteps,
Work::ReachFormatTokens,
Work::ReachFormatBytes,
];
/// What one [`measure`] counted, per kind of [`Work`].
#[cfg(test)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Tally([usize; KINDS]);
#[cfg(test)]
impl Default for Tally {
fn default() -> Self {
Self([0; KINDS])
}
}
#[cfg(test)]
impl Tally {
/// The count of one kind of work.
pub(crate) const fn get(&self, work: Work) -> usize {
self.0[work as usize]
}
}
#[cfg(test)]
mod counting {
use std::cell::Cell;
use super::{KINDS, Tally, Work};
thread_local! {
/// The counts of this thread since the last reset.
static TALLY: Cell<Tally> = const { Cell::new(Tally([0; KINDS])) };
/// The count a kind may not pass while a measure runs: the one kind
/// it limits, or every kind when that is `None`.
static CEILING: Cell<Option<(Option<Work>, usize)>> = const { Cell::new(None) };
}
/// Count `amount` units of `work`, and panic if that passes the ceiling.
pub(crate) fn add(work: Work, amount: usize) {
let mut tally = TALLY.get();
let slot = &mut tally.0[work as usize];
*slot = slot.saturating_add(amount);
let count = *slot;
TALLY.set(tally);
if let Some((limited, ceiling)) = CEILING.get()
&& limited.is_none_or(|kind| kind == work)
{
assert!(
count <= ceiling,
"{work:?} work passed the ceiling of {ceiling}: {count}"
);
}
}
/// Clears the ceiling when a measure ends, even by a panic.
struct Armed;
impl Drop for Armed {
fn drop(&mut self) {
CEILING.set(None);
}
}
/// Run `run` against fresh tallies and return its result with what it
/// counted. Panics the moment any kind of work passes `ceiling`.
pub(crate) fn measure<T>(ceiling: usize, run: impl FnOnce() -> T) -> (T, Tally) {
measured(None, ceiling, run)
}
/// Like [`measure`], but only `limited` is held to `ceiling`; the other
/// kinds are counted without a limit.
pub(crate) fn measure_kind<T>(
limited: Work,
ceiling: usize,
run: impl FnOnce() -> T,
) -> (T, Tally) {
measured(Some(limited), ceiling, run)
}
fn measured<T>(limited: Option<Work>, ceiling: usize, run: impl FnOnce() -> T) -> (T, Tally) {
TALLY.set(Tally::default());
CEILING.set(Some((limited, ceiling)));
let _armed = Armed;
let result = run();
(result, TALLY.get())
}
}
#[cfg(test)]
pub(crate) use counting::{add, measure, measure_kind};
/// Count work: nothing outside tests.
#[cfg(not(test))]
#[inline]
pub(crate) fn add(_work: Work, _amount: usize) {}
#[cfg(test)]
mod tests {
use super::{ALL, Work, add, measure, measure_kind};
#[test]
fn a_counter_increments_by_what_is_added() {
let ((), tally) = measure(100, || {
add(Work::Lookups, 1);
add(Work::Lookups, 4);
add(Work::WalkSteps, 7);
});
assert_eq!(tally.get(Work::Lookups), 5);
assert_eq!(tally.get(Work::WalkSteps), 7);
assert_eq!(tally.get(Work::Attributes), 0);
}
#[test]
fn every_kind_has_its_own_counter() {
let ((), tally) = measure(100, || {
for (index, work) in ALL.into_iter().enumerate() {
add(work, index + 1);
}
});
for (index, work) in ALL.into_iter().enumerate() {
assert_eq!(tally.get(work), index + 1, "{work:?}");
}
}
#[test]
fn the_table_holds_every_kind_once_at_the_place_of_its_counter() {
// A kind left out of the table, or listed twice or out of order,
// would share or lose a counter: each kind's place in the table is
// the place of its counter.
for (index, work) in ALL.into_iter().enumerate() {
assert_eq!(work as usize, index, "{work:?}");
}
}
#[test]
fn the_result_of_the_closure_is_returned() {
let (value, tally) = measure(10, || 42);
assert_eq!(value, 42);
assert_eq!(tally, super::Tally::default());
}
#[test]
#[should_panic(expected = "PatternSteps work passed the ceiling of 3: 4")]
fn passing_the_ceiling_panics_at_once() {
measure(3, || {
for _ in 0..4 {
add(Work::PatternSteps, 1);
}
});
}
#[test]
#[should_panic(expected = "ColumnSteps work passed the ceiling of 3: 4")]
fn the_panic_comes_before_the_work_that_follows_it() {
measure(3, || {
add(Work::ColumnSteps, 4);
unreachable!("the ceiling should have stopped the closure");
});
}
#[test]
fn reaching_the_ceiling_is_allowed() {
let ((), tally) = measure(3, || add(Work::Positions, 3));
assert_eq!(tally.get(Work::Positions), 3);
}
#[test]
#[should_panic(expected = "Attributes work passed the ceiling of 2: 3")]
fn a_limited_kind_panics_at_its_ceiling() {
measure_kind(Work::Attributes, 2, || add(Work::Attributes, 3));
}
#[test]
fn a_limited_measure_counts_the_other_kinds_without_a_ceiling() {
let ((), tally) = measure_kind(Work::Attributes, 2, || {
add(Work::Attributes, 2);
add(Work::Lookups, 500);
});
assert_eq!(tally.get(Work::Lookups), 500);
}
#[test]
fn the_tallies_are_reset_between_measures() {
let ((), first) = measure(10, || add(Work::ViewReads, 5));
let ((), second) = measure(10, || add(Work::ViewReads, 2));
assert_eq!(first.get(Work::ViewReads), 5);
assert_eq!(second.get(Work::ViewReads), 2);
}
#[test]
fn a_measure_that_panicked_leaves_neither_counts_nor_ceiling_behind() {
let caught = std::panic::catch_unwind(|| measure(1, || add(Work::Lookups, 2)));
assert!(caught.is_err());
let ((), tally) = measure(10, || {});
assert_eq!(tally.get(Work::Lookups), 0);
// With no measure running there is no ceiling.
add(Work::Lookups, 1000);
}
}