Qué hace
- Escritor de 4 KiB, una syscall por flush
- Enteros sin buffer temporal, coma flotante mediante Grisu2
- Argumentos con sugerencias ortográficas, variables de entorno y subcomandos
- Color de 24 bits con degradación a 256, 16 y ninguno
- Barra de progreso con un modo texto fuera de un terminal
- Editor de línea sin asignaciones, con modo contraseña
Medido
- 100,000 escrituras en <code>/dev/null</code>: 25 llamadas a <code>write</code> (el camino anterior hacía flush en cada escritura)
- Formateo de enteros: 5.4x más rápido que <code>snprintf</code> (objetivo 5x)
- Actualización de la barra de progreso: 28.1 ns por llamada
Límites conocidos
- Sin autocompletado y sin búsqueda inversa en el historial
What this module did with what already existed, and why
There was a terminal.hpp with color, terminal width, a progress bar and an argument parser called CArgs. It worked. The spec, however, opens with two numbers it did not meet, and the reason is concrete:
"A CLI that allocates a string per log line and issues a write syscall per update will dominate the runtime of the tool it is embedded in."
Before touching a line, I measured what was there. Writing "what is here makes one syscall per write" without counting the syscalls is opinion.
| what | how it was | the spec target |
|---|---|---|
| terminal writes | **1 fwrite + 1 fflush per call** | one syscall per flush |
| 1,000 small writes | 1,000 flushes (see the caveat below) | 1 |
| formatting an integer | std::to_string / snprintf | 5× faster than snprintf |
| reading an argument | Get( "output" ), lookup by name | no result map |
| color | 16 fixed colors, no detection | 24 bits with downgrade |
The syscalls, counted
strace is not installed in this WSL, and the spec asks for the number, not an impression. I wrote the instrument: tools/count_write.c, an LD_PRELOAD that intercepts write, fwrite and fflush.
Method note. The first attempt counted only
writeand gave zero. That was not a defect of the module: glibc'sstdiocallswritethrough an internal alias thatLD_PRELOADdoes not reach. The old path goes throughfwrite/fflush, which are our calls, and the counter catches those. The new path calls::writedirectly. Counting only one of the layers would have given a nice and false number.
Measured, with output to /dev/null:
| 1,000 one-byte writes | trace |
|---|---|
old path (Cli::Write) | fwrite=1000, **fflush=1000** |
new path (CWriter) | **write=1**, 1,000 bytes |
| new path, 100,000 writes | **write=25**, 100,000 bytes |
Twenty-five is 100,000 ÷ 4096 rounded up: one syscall per full buffer, plus one for the final flush. It is literally "one per flush".
What is measured and what is inferred. For the new path the number is a direct measurement: these are our calls to
::write, and the counter sees each one. For the old path what is measured is the 1,000 calls tofflush. That each one produces a syscall is an inference, because glibc'sstdiodoes not let us count them from here. The inference is solid (flushing a stream has to reach the system), but it is not the same as having the number, and that is stated.
---
The design, piece by piece
The writer
CWriter has its own 4 KiB and three modes: full, per line, none. The destructor flushes: a buffer that dies with bytes inside loses them, and the lost line is almost always the one that says what went wrong.
The formatter uses no temporary buffer. It counts the digits first (clz plus the approximation (bits * 1233) >> 12) and writes directly into the destination, back to front. The previous version wrote into a local buffer and copied: 3.7×. This one gives 5.4×.
Two traps in this number. The first:
CountDigits( 0 )returned zero digits, and the wide sweep did not catch it because it went from −100000 in steps of 7, and never lands on zero. A sweep that skips the failing value is not a sweep. It now steps one by one near zero. The second: the benchmark usedi * 7919, which goes pastINT_MAXand is undefined behavior. GCC generated an infinite loop (-Waggressive-loop-optimizations) and the test hung for fifteen minutes. The correct form is(i % 1000) * 7919.
The parser
"Registration writes directly into caller-owned variables. No result map, no lookup by string after parsing."
CArgParser writes into the caller's variables and does not allocate memory while parsing. The old CArgs stays where it is. It returns through Get( "output" ), which is exactly the result map the spec rejects, and there is no way to make it allocation-free without changing its shape.
It brings did-you-mean by Levenshtein distance (cutoff at 3) and the environment variable fallback, with the command line always winning, because whoever wrote the line wanted that.
Wrapped help text left a trailing space that went past the requested width. The separator is now written only when the next word fits.
Color and style
SColor is 4 bytes. SStyle is 10, and the spec asks for 8, but its arithmetic does not add up: 4 + 4 + 2 is ten, and alignment takes it to twelve. It would fit in eight by squeezing bits, at the price of shifts in every place that reads a color, to save four bytes in a structure that lives on the stack. It stays at ten, and the number is written in the code, instead of the spec being cited as if it were met.
CStyleState::Apply writes only what changed. Applying the same style twice returns zero bytes, and that is what turns a thousand-row table in the same color into a single sequence.
The downgrade is 24 bits → 256 → 16 → none, and the sixteen are the baseline: a terminal without them gets no color at all. A terminal that says "I know 24 bits but not 16" does not exist.
Width
Bytes, characters and columns are three different things. An ideogram has three bytes, one character and two columns. A combining accent has two bytes, one character and no column. Only the third measure aligns a table.
Measured: 300 bytes of ASCII in 226 ns (shortcut for pure ASCII), 300 bytes of ideograms in 1,355 ns.
BytesForColumns never cuts a character in half, and takes the combining accent along with the letter it belongs to.
The screen and restoration on signal
EmergencyRestore can be called from inside a signal handler: it writes bytes to a descriptor and nothing more, without printf, without allocation, without a lock. The registration is a volatile std::sig_atomic_t[3].
SIGSEGV and SIGABRT are on the list because a program that crashes with the terminal in raw mode leaves the console unusable, and whoever is in front of it has less chance of understanding what happened.
Progress
Rate limiting, redrawing only what changed, and degradation outside a terminal (to do: 50/100 (50%), one line per period, instead of escape sequences into a pipe).
The rate limit test measured the wrong path: outside a terminal nothing is drawn, so it counted zero frames and passed. And the comment said it forced drawing, without forcing anything. Now there is
SProgressStyle::bForceDraw, and the test measures what it says it measures.uPlainSeconds = 0meant "never". It now means "on every update".
Measured: a million Update calls with a rate limit of one frame cost 28.1 ns per call, or 28.13 ms in a 100 ms budget.
The line editor
CLineBuffer applies keys to a buffer and reads from nowhere. CLineEditor adds raw mode and drawing. Without this split, the key bindings could only be tested by hand, in a terminal, with a person pressing the keys.
Nothing allocates memory: a line editor runs inside a password prompt or an interpreter already short on memory, the worst place to find out that an allocation failed. In password mode the buffer is wiped byte by byte, not just marked as empty.
---
The C layer
"Full surface. CLI tools written in C or Rust are a realistic consumer."
ethereal/c/cli/console.h: opaque handles and about ninety functions. Passing NULL to any of them never brings anything down.
Two things the crossing forced us to fix, found by reading the headers on both sides before compiling anything:
The stream numbers. The C++ side knows two (eOut = 0, eErr = 1) and the C header numbered three, with ETL_STREAM_IN = 0. A number that does not exist would fall into the default branch, and the default branch would write to the wrong place, silently. Now there are two, with static_assert tying the two sides together.
**ETLC_ArgParser_AddFlag takes an unsigned char *, not an int *.** The C++ side writes a bool, which takes one byte. With the address of an int, it would write one byte and leave the other three with whatever garbage was there, and an if( iFlag ) would be true for a flag that never appeared.
The defect only MSVC sees
console_cli stopped linking on Windows with LNK2019 on Cli::Reserved::SaveTerminalMode, with the definition right next to it and Linux linking cleanly.
- declaration, in
input.cpp:const void * pMode→ mangles asPEBX - definition, in
screen.cpp:const void * const pMode→ mangles as **QEBX**
In standard C++ the top-level const of a parameter is not part of the function type: both declare the same function, and GCC mangles both the same way. **MSVC mangles the const anyway**, and makes them two different functions. Now the declaration is identical to the definition, character for character.
It is a class of defect that is invisible on Linux, and the reliable check is the link on Windows itself, which covers all translation units at once.
---
What was measured, and on which machines
| configuration | result |
|---|---|
| Linux Release | console.cli 187, console.cabi 106 × C11 and C17 |
| Linux Debug | green |
| Linux ASan + UBSan | zero errors. 184 + 106 (three timing gates are left out on purpose) |
| Windows x64 Release | ctest 58/58 |
| Windows x64 Debug | ctest 58/58 |
The spec targets, measured in this test environment:
| target | spec | measured |
|---|---|---|
| write syscalls | one per flush | 1 per 4 KiB + 1 final ✓ |
| integer formatting | 5× faster than snprintf | 5.4× ✓ |
Parse without allocations | zero | zero ✓ |
SColor | 4 bytes | 4 ✓ |
SStyle | 8 bytes | 10 ✗ (the spec's arithmetic does not add up, see above) |
| key sequences | table, not a chain of comparisons | 22 of 22 ✓ |
---
How this was verified
Passing proves nothing. Each crossing of the C layer got a defect planted on purpose, with the requirement that the test break:
| planted defect | the test |
|---|---|
| unknown stream goes to output instead of error | broke |
| the did-you-mean does not cross | broke |
bForceDraw ignored | broke |
| the count writes to a local instead of the caller's destination | broke |
| the buffer mode is ignored | broke |
| columns treated as bytes | broke |
| the style always writes, without a delta | broke |
| the option value does not reach the caller's destination | broke |
Eight planted, eight killed.
And one of the test cases was weak. "Three ideograms, three columns requested" answers three bytes, and a naive implementation that returned uColumns would give the same three. In that case, what catches the defect is the returned width, and only that. The case is now "one a plus one ideogram, requesting two columns": the correct answer is one byte and the naive one would give two, and two would cut the ideogram in half.
Two intermittent tests, hidden behind a green ctest
The full ctest, with 62 tests competing for the processor, brought down two timing gates that passed on their own.
**event.signal: emitting to a hundred measured 220.3 ns against a target of 200. Investigated: with five repetitions the test failed on its own, once in every five, with no load at all. With fifteen, the spread drops to 2.5 % (183.9 to 188.6 ns) and the spike disappears. But 200 ns with a 7 % margin cannot be met on a busy machine, and that is not a defect of the code. The floor says whether the test environment is reliable**: if the same path done by hand already goes past 175 ns, the machine is busy and the absolute number does not measure what it says it measures. In that case the test reports and does not fail. The gate against the floor always applies.
**console.cli**: the "five times faster than snprintf". It was a ratio gate, which should be immune to load, but the two sides were measured one after the other: the nine repetitions of A before the nine of B. A load in the middle hits only one of the sides and ruins the ratio without either number looking odd. MeasureMinPair alternates (A, B, A, B), and both minimums come from the same window. The ratio stabilized at 5.4× (it was 5.1 to 6.0).
After both fixes: **three full ctest passes, 62/62 in all of them**.
---
The audit against spec 08
This README had no pending items section. The audit made one, and found five pieces the spec names in the public surface that did not exist. One went into this batch. The other four are described below with the cost of each.
| what the spec asks for | was it there? |
|---|---|
OnResize(): terminal size change | did not exist → delivered |
AddSubcommand: subcommands in the parser | did not exist → delivered |
SetCompletionCallback + ICompletionSink | does not exist |
| Ctrl-R, reverse history search | does not exist |
| floating-point formatting (Ryu/Grisu) | did not exist → delivered |
---
Resizing, and why it does not turn on by itself
Without this, a table or a progress bar drawn with the width from when the program started keeps that width forever, and whoever drags the corner of the window sees a broken drawing until the end.
The hard part is not storing the listeners. It is that both systems report the change through paths that cannot be read from inside a library without getting in the way of whoever uses it.
On POSIX, a signal handler can only do one thing
SIGWINCH arrives at any moment, and what a handler can do inside it is in the standard: write to a volatile sig_atomic_t flag, and nothing more. Calling the listeners from there would be running the integrator's code inside a signal handler. That is undefined behavior, and the typical symptom is a hang inside the memory allocator.
And installing the handler is an effect global to the process. A library that does it behind your back tramples whoever already had their own, and that is why it has to be requested, with EnableResizeWatch. The previous handler is saved, chained while this one is on, and restored when it is turned off. A library that swallows another one's SIGWINCH breaks the integrator's program.
And sigaction takes SA_RESTART. Without it, a read blocked on input returns with EINTR when the window changes size, and code that does not handle EINTR sees the read fail for a reason it does not understand.
On Windows, the event comes through the queue the keys come from
It arrives as WINDOW_BUFFER_SIZE_EVENT in ReadConsoleInput, the same queue every key comes from. A thread of this library reading that queue **would steal the keys from the integrator's CLineEditor**, and the symptom would be an editor that loses characters now and then.
So, on Windows, the change is detected by asking for the size.
So the caller is the one who notifies, and that is the contract
PollResize runs on the caller's thread, at the moment it chooses: between two frames of a bar, at the top of an event loop. It is the same design as the event bus's Drain, and for the same reason: the library does not decide which thread the integrator's code runs on.
On POSIX the signal flag is only a hint: it says it is worth asking, not that something changed. Asking for the size is an ioctl, and without the flag a loop at a thousand rounds per second would make a thousand ioctl calls per second for nothing. But what decides is the size compared to the previous one, because a SIGWINCH can arrive without the size having actually changed.
And it is not a CSignal, which is a declared divergence
The spec writes it as SSignal<uint16_t, uint16_t>& OnResize(). Returning an Events::CSignal would force this module to include the Event module's header, and section 2 of the conventions forbids that explicitly:
"A module never includes another module's headers directly to get functionality."
The same spec 08 says, three lines above the public surface, that this module "depends on: nothing at link time". The two sentences cannot both hold, and the one that wins is the conventions, which the spec itself says to read first. In its place is the form this module already uses everywhere: a function pointer with the caller's context, with inline capacity for four and no memory allocation.
And the change cannot be tested without an injection point
There is no way to resize a terminal from inside a test, and a case that only runs when someone drags a window never runs. SimulateResize changes the remembered size, and does not call the listeners. The next PollResize sees the difference and walks the same path as a real change. A shortcut that called the listeners directly would test only the shortcut.
There are 25 checks, and three of them enforce things that would be lost through carelessness:
- turning on monitoring does not notify (otherwise everyone would redraw once with nothing having changed).
- the same context+function pair does not get in twice (otherwise the bar would redraw twice).
- what reaches the listeners is the real size, not the simulated one.
---
What is still missing from spec 08
- ~~**
AddSubcommand.~~ Delivered in this batch, ~~and it still has to cross into the C layer~~, also delivered**: see its own section further below, with the declared divergence in form, the defect the test caught, and the three decisions the crossing forced. - Autocompletion. The spec's
SetCompletionCallbackandICompletionSink. The editor has history, password mode with byte-by-byte wiping and the Emacs bindings. It does not have autocompletion. - Ctrl-R, reverse history search. The spec puts it in the required minimum, next to Ctrl-A, Ctrl-E, Ctrl-K, Ctrl-U and Ctrl-W, which exist.
- ~~Floating-point formatting.~~ Delivered in this batch: see its own section further below, with the three measured properties and the defect no other check caught.
- The escape sequence corpus from xterm, Windows Terminal, iTerm2 and Konsole that the spec asks for as an acceptance criterion. The decoder is a table-driven state machine, as the spec requires, and has test cases. The real corpus is not there.
- And resizing was not compiled on Linux. That is precisely the side where it installs a signal handler, the more delicate path of the two. This is on record.
---
Floating point, and the defect no other check caught
The spec is explicit in both sentences: *"No printf, no iostreams, no std::format at runtime", and "Float formatting uses a Ryu or Grisu-style shortest representation, not snprintf"*.
There was nothing. There were FormatUInt and FormatInt, with the two-digit table and measured at 5.4× snprintf. For floating point, neither the fast path nor the slow one: anyone who wanted to print a double had to format it outside the module.
The problem, in one sentence
A double is a binary number. **0.1 does not exist inside it**: what exists is 0.1000000000000000055511151231257827021181583404541015625.
Printing seventeen digits guarantees that reading it back returns the same number, and shows that. The shortest representation is something else: the text with the fewest digits that, read back, gives exactly the same double. For that number it is "0.1". That is not rounding. It is choosing, among all the texts that map back to this same double, the shortest one.
The algorithm is Grisu2, with eighty-seven table entries
Ryu never fails to find the shortest, and brings six hundred entries. Grisu2 fails in a small fraction (measured, not estimated) and brings eighty-seven. The spec accepts both by name.
---
Three properties, and only the first is guaranteed by the algorithm
| property | result |
|---|---|
exact round trip: the text, read back, gives the same double | 200,000 random values, zero failures |
| shortest: there is no shorter text that also maps back to the same value | fails in 0.07% (the earlier 0.17% came from the test's yardstick, which counted the trailing zeros of an integer) |
| closest: at the same length, these are the digits everyone prints | fails in 0.05% |
The values are drawn by their bits, not as a double between zero and one. Drawing the mantissa and the exponent separately would concentrate the sample in one range, and the hard cases are exactly at the extremes.
And the third property is where the defect was
The first version gave the digits of the closest in only 68% of cases. Measured: 31.9% came out with other digits, all valid, all with the right length, and all mapping back to the same number. They just were not the ones every other language prints:
0.1+0.2 → 0.30000000000000007 (ours, before)
0.1+0.2 → 0.30000000000000004 (what everyone prints)The cause: the closeness criterion of the final adjustment compares the remainder with the distance to the number, and that distance has to be scaled by the same power of ten that scaled the remainder. For long outputs (fifteen to seventeen digits) that power goes past 10⁹ and the product overflows 64 bits. The classic implementation handles this by zeroing the factor, which scales nothing: it turns off the criterion, the condition becomes false, and the adjustment never runs.
Saturating is the right answer: when the product goes past 64 bits, it is larger than any possible remainder, which is exactly what the maximum value represents in the comparisons that follow.
31.9% → 0.05%.
And no other check caught this
The texts round-tripped exactly. They had the right length. They passed everything one normally asks of a formatter. What separated them from the correct output was only that they were different digits, and seeing that required comparing with the oracle digit by digit, discounting leading and trailing zeros on both sides.
snprintf is the test's oracle, not the module's
The spec forbids it in the module. In the test it is the only way to know whether the text represents the same double: write with %.*e and read back with strtod. A test that compared our text with another text of ours would be confirming itself.
Three decisions on record
- **Negative zero comes out as
-0.** It is a distinct value (typically from a subtraction that gave exactly zero from below), and erasing it would hide where the number came from. - The exponent is not padded with zeros:
1e-4, not1e-04. The library's%epads to two digits by convention, and this module exists precisely so as not to be%e. The declared goal is the shortest text. *(My first test expectation asked for1e-04: it was asking for the library's convention instead of the module's rule.)* - **
FormatFixedis not the shortest representation and does not try to be.** It is what you want in a column of numbers, where what matters is alignment. It rounds half to even, which is the processor's rule, so that there are not two different roundings in the same program.
The worst case measured 24 bytes against the 32 the header promises, and the test enforces this on the six hardest values there are.
---
Subcommands, and the case that decides the design
The parser had everything else: flags, negatable flags, counts, values, positionals, environment fallback, did-you-mean and aligned help. Not subcommands.
The case that decides everything is the repeated option
prog --verbose copy --verbose a.txt b.txtThe first --verbose belongs to the parent and the second to the child, and they may mean different things. A parser that read both into the same place would make it impossible for a subcommand to have an option with the name of one of the parent's, which is half the reason subcommands exist.
Hence the rule: with subcommands declared, the first argument that is not an option stops being a positional. It is the subcommand name, and everything after it belongs to the child.
**And -- still wins.** After it there is no subcommand at all: prog -- copy x puts copy and x raw into Rest, because that is what whoever wrote the line asked for.
And it is not AddSubcommand, which is this module's second declared divergence
The spec writes CArgParser& AddSubcommand( SStringView sName, SStringView sHelp ). Returning a reference implies that the parent creates the child's parser, and this module does not allocate memory. Its whole surface is like that: the caller provides the declaration array, the line buffer, the history.
So the caller provides the child's parser, like everything else. The form changes. What the spec asks for (a command with subcommands, each with its own options and its own help) stays the same.
SArgSlot aParentSlots[ 8 ], aCopySlots[ 8 ];
CArgParser Parent, CopyCmd;
Parent.Init( aParentSlots, 8u, "prog" );
CopyCmd.Init( aCopySlots, 8u, "copy" );
const SSubcommand aSubs[] = { { "copy", "copies files", &CopyCmd } };
Parent.SetSubcommands( aSubs, 1u );Two new states, and why they are not one
- **
eUnknownSubcommand** is distinct fromeUnknownOptionbecause it has its own suggestion, from the subcommand names. Sending whoever typedcpoyto look among the options would be sending them to the wrong list. - **
eMissingSubcommand**: a program that only makes sense with a subcommand (likegit) should refuse instead of doing something by default. The state says what happened. Anyone who wants a default handles the state and chooses, instead of guessing fromSelectedSubcommand()being null.
And declaring a subcommand without a parser gives eBadDefinition, which is the state that blames the program, not the command line. The two cases are mistakes made by different people.
The help now lists them
Without this, the user sees the list of options, calls the program with no arguments and gets a "missing subcommand" without knowing which ones exist. It is the case where the help has to be most useful, and it was where it said nothing.
The defect the test caught
Parse did not clear the selected subcommand. A parser reused for a second command line kept saying that the first line's subcommand had been invoked. Worse: eMissingSubcommand never fired, because the field never went back to null after the first run.
It is the same thing already done with Rest and with each declaration's bSeen: Parse starts from scratch, and does not continue where the previous one stopped. Three checks failed at once, and all three were the same missing line.
21 checks, and the last one enforces what cannot change: with no subcommands declared, the first non-option is still a positional. A parser that changed behavior because of code nobody used would break every program that already exists.
---
The crossing into the C layer, and what it forced us to decide
The spec wants the complete C layer. Subcommands and negatable flags only existed in C++, and crossing them forced three decisions that are not mechanical.
1. The declaration array changes owner, and it has to
In C++, SetSubcommands takes an array of SSubcommand that the caller keeps. There that is correct: this module's whole surface is like that, and the caller provides the declaration array, the line buffer, the history.
Here it cannot be that way. A caller going through the C layer has no way to keep an array of a C++ structure without coming to know its size, and that is exactly what a C ABI exists not to require.
So the array lives on this side, inside the parent parser, and grows with each ETLC_ArgParser_AddSubcommand. It is this module's third declared divergence in form, and for the same reason as the other two: the contract holds, the path changes.
2. And an array that grows moves
push_back can reallocate. The C++ side kept the old pointer, and not calling SetSubcommands again would leave the parent reading freed memory on the next parse.
What makes this dangerous is that it only breaks from the subcommand that makes the array grow. A program with two or three subcommands would never show a sign. The fourth would open the hole. It is the kind of defect that passes three tests and fails the fourth, months later, on someone else's machine.
The test enforces this head-on: it declares eight subcommands on a parser created with room for four, and then invokes all of them, one by one. The first covers the registration made before all the moves. The last ones cover positions that never existed in the old block.
3. There is no going back from CArgParser * to a handle by conversion
SelectedParser() returns a CArgParser *. What has to come out of the C layer is an ETLC_ArgParser, which is an SParserC *. Converting one into the other by relying on Parser being the first member would be betting on the structure's layout, which no rule guarantees.
The code keeps two parallel arrays (the declarations and the handles) and looks up the index. It is a linear search over a list of subcommands, which can be counted on the fingers of one hand.
And the parent does not become the child's owner
Each handle created with ETLC_ArgParser_Create is destroyed by whoever created it. Declaring one of them as a subcommand transfers nothing. This means the child has to outlive the parent, and that is written in the header in capital letters, because it is the trap that remains.
The one-step cycle (a parser declared as a subcommand of itself) is rejected by an if. Longer cycles are not detected without walking the graph. This one is detected by a comparison, and it is the one written by mistake.
---
What a C caller was missing to be able to decide
ETLC_ArgParser_Parse returned a number, and the C layer did not say which number was which. There was ETLC_ArgParser_ErrorName, and nothing more.
A name is for printing, not for deciding. Comparing the returned string to find out whether the subcommand was missing is tying the program to a text that exists to be read by people, and that changes the day someone improves the sentence. Without the codes, an ETL_PARSE_MISSING_SUBCOMMAND, which the C++ enumeration has had since this batch, does not even exist on the other side.
The twelve ETL_PARSE_* went in, and with them **twelve static_assert that tie them to the C++ enumeration. The enumeration already stated in writing that values are added at the end, and never in the middle, because they cross the C layer. This is what verifies** that sentence instead of trusting it. If any value falls out of alignment, the build breaks there, and not in a caller's switch.
The four ETL_VALUE_* got the same treatment, for the same reason. They already existed and had never been verified.
The C side test went from 165 to 204 checks.
---
The intermittent test that escaped three times
On three different occasions the full ctest failed one test and passed on the following runs. In all three, it was not possible to capture the name: the search pattern only caught the line The following tests FAILED:, and the name comes on the next line, written (Failed), in lowercase.
A report of "something failed and then passed", repeated three times, is not a report. It is noise. So the whole ctest ran eight times, alternating Debug and Release, with the output saved to a file and the name captured separately.
**It failed once in eight, and it is console.cli.**
And "one in eight" is an estimate drawn from a single failure, which is worth not forgetting. Counting everything that has run since then (eight alternating runs, ten verification runs and fourteen with --output-on-failure), there are thirty-two full runs and one failure. The real rate is closer to one in thirty than to one in eight, and that is why counting green runs was never going to be enough.
Where: established. Why: two measurements, and the second contradicted the first
On its own console.cli never fails: not in twenty consecutive runs, not with eight compression benchmarks consuming the machine next to it, not in **sixty repetitions inside ctest with the whole test suite looping next to it. What remains is the shape** of the load, not the amount.
The first measurement, and why it was badly done
The suspect was the file's only absolute gate: a million calls to CProgress::Update must fit in 1% of a ten-second operation, that is, a hundred milliseconds. The gate received the guard this project had already decided on for event.signal (the floor says whether the test environment is reliable), the measurement was taken with ctest running alongside, gave 30.3 to 35.3 ms, and it was written here that the gate had three times the margin and that it was not the culprit.
That conclusion was wrong, and the defect was in the measurement. The load placed alongside was too light. Repeated with the whole test suite running in a loop (eight processes competing for eight threads without pause), the same measurement gives this:
| idle machine | light load (the 1st measurement) | whole test suite in a loop | |
|---|---|---|---|
cost of a million Update calls | 28.8 ms | 30.3 to 35.3 ms | 35.9 to 71.0 ms |
| budget | 100 ms | 100 ms | 100 ms |
Seventy-one out of a hundred. The gate did not have three times the margin. It had a little more than one.
And the floor guard did not protect it, which is also measured
In the run that gave 71.0 ns per call, the floor read 1.25 ns. That is, the machine looked idle to the instrument that was supposed to say it was not. The guard would not have fired.
The reason is simple and should have been seen earlier: the floor is a loop of integer additions, and the progress path formats, compares and writes. The two do not suffer the same contention, and so one does not represent the other. In a sample of ten, the guard fired once (floor of 5.98 ns), and it was not in the 71 ns run.
The real cause: it was the only measurement in the file taken just once
Every measurement in this file goes through MeasureMin or MeasureMinPair (minimum of several repetitions), for a reason written there: a window hit by a spike gives a number that is the cost of nothing.
This one was measured in a single window. And it was, of the file's three, the only one tied to an absolute gate, that is, the only one where a spike translates directly into a number that fails.
It now takes five repetitions, each one complete (new CProgress, new Start, because the rate limit is state), keeping the minimum. Measured under the same load as the right-hand column:
| before | after | |
|---|---|---|
cost of a million Update calls, worst of ten | 71.0 ms | 46.5 ms |
| best of ten | 35.9 ms | 29.8 ms |
| width of the spread | 35 ms | 17 ms |
And there was a second gate with the defect this file already condemned in writing
MeasureMinPair exists because the "five times faster than snprintf" gate passed on its own and broke in the full ctest. The note is written at the top of the file.
And the text width gate (ASCII against ideograms) was still measuring one side and then the other, which is exactly what the note forbids. It went unnoticed because it passed: the typical ratio is 5.6 and the gate asks for 2.
It is now alternated. Under the whole test suite in a loop, the ratio stays between 4.19 and 5.35. It moves even when alternated, and still has twice the margin the gate requires.
What is on record, including what remains unproven
- The floor guard stays, for the case where the machine is so busy that not even the minimum is saved. But what does the work now is the minimum, and that is written in the code.
- The floor is still printed on every run, because its absence from the report is what left the first question unanswered.
- None of this proves that this was the check that broke. The failure was not reproduced: once in thirty-two full runs, and none of the remaining thirty-one repeated it. What is proven is that the gate reached 71% of the budget and now reaches 46%, and that the guard that was supposed to protect it did not.
- And ten clean runs would prove nothing at a rate like this. That is why the margin was measured, instead of counting green runs.
Recording both measurements is deliberate. The first was reasonable and was wrong. Erasing it would lead the next person to repeat the conclusion instead of repeating the experiment with real load.
The ratio gates still do not need the floor guard.
snprintfagainst ours measures between 10.5× and 13.5× with the test suite alongside, against a target of 5×: both sides come from the same window, alternated, and a load in the middle hits both. That is why it was converted from absolute to ratio in the previous batch, and that is why the text width one is now alternated.
---
And then a case appeared that was testing the wrong defense
Running the test suite in Debug with --parallel 8, something that was hardly ever done, made a check fail that had nothing to do with the previous ones:
ten calls with the same value draw no frame
What it did, and what it measured
P.Start( 1000, S ); // width 10, a thousand frames per second, forced drawing
P.Redraw( W ); // draws ZERO
uBefore = P.FrameCount();
for( int i = 0; i < 10; ++i )
P.Update( W, 500 ); // ...and 500 is not what is drawn**The first of those Update calls really does change the bar. From zero to half, on a ten-cell bar, is five different cells. What kept it from going out was not the repeated value defense, but the rate limit**: at a thousand frames per second one goes through per millisecond, and with an idle machine the ten calls all fit inside the same millisecond.
Why this matters more than the failure
The failure itself is trivial: with the machine under contention, a millisecond passes in the middle, the frame goes out, and the check says the repeated value defense does not work.
What matters is that this defense had never been exercised. In no run, on no machine. The case had been passing, green, for who knows how long, measuring another defense that already has its own case a few lines above.
A test that passes through the wrong defense does not test that defense. It is a green line taking the place of a check that does not exist.
The fix
The test draws the 500 first:
P.Update( W, 500 );
P.Redraw( W ); // now what is drawn IS 500
uBefore = P.FrameCount();From then on the repeated value really is repeated, and what is counted is what the sentence says, regardless of how much time passes between calls.
And the progress gate got the same remedy as the previous section
The missing MeasureMin. It was the only measurement in this file taken in a single window, and the only one tied to an absolute gate. It now takes the minimum of five repetitions, each one complete (new CProgress, new Start), because the rate limit is state and reusing it would measure an already warmed-up bar.