Sergey Kopanev: you sleep — agents ship

Go Back
NTK

The Math.max of Empty Arrays


The CLI output suddenly collapsed in production, completely breaking the neat column alignment. The culprit wasn’t a complex rendering bug. It was padEnd attempting to pad a string with -Infinity spaces, triggered by a trivial mistake in an “obviously correct” utility function.

The most insidious bugs rarely live in complex algorithms. They live in the trivial code that no one bothers to double-check.

The Iterator Trap

We had a basic utility to calculate the maximum width of a column to align the output. The logic was simple: iterate over the strings, find the longest one using Math.max(), and use that as the padding width.

The code worked perfectly in testing, but broke randomly in production.

The issue was an iterator that was consumed twice. We used a generator to yield the rows. The first pass consumed the generator to find the maximum width. The second pass attempted to iterate over the rows again to print them. But the generator was already exhausted.

Because the second pass saw an empty collection, Math.max() was called without arguments. In JavaScript, Math.max() with no arguments doesn’t return 0 or undefined. It returns -Infinity. The CLI obediently attempted to call padEnd(-Infinity), silently corrupting the output.

Strings That Evaluate to True

In another instance of trivial code failing, we added a flag --force-body=false to bypass ticket body generation. It didn’t work; the body was always generated.

The parsing library read --force-body=false not as a boolean false, but as the literal string "false". In JavaScript, the string "false" is truthy. The CLI evaluated if (options.forceBody) and happily executed the branch it was explicitly told to skip.

Trivial code isn’t immune to bugs. It’s often the most vulnerable, because it’s the code we look at with the least suspicion.


Next in the NTK series: how perfectly logical bug fixes can fail completely if they target the wrong runtime in Fixing Bugs That Don’t Exist.