Hunting bugs in Pharo with PerfUMate

A few weeks ago, I presented Ume, Mate, and Shin. So, what if we combine them and look for potential bugs in Pharo?

This idea led to PerfUMate.

PerfUMate

Each tool does one thing well:

  • Ume is the fuzzer engine. It keeps mutating inputs and keeps the ones that look promising:
    • Coverage
    • Execution time
    • Method calls
  • Mate generates object instances built from a grammar.
  • Shin shrinks the potential bugs found until only the part that matters is left.

Wiring the three together in PerfUMate hides all of that behind some simpler abstractions.

So, given a few object inputs, the code to run, and what you’re looking for:

report := PerfUMate new
examples: { order1. order2. order3 };
benchmark: [ :order | Checkout new process: order ];
lookFor: #slowInputs;
budget: 5 minutes;
run.
report open.
The pipeline

PerfUMate goes through five steps.

1. Infer what an input looks like (Mate). Mate infers a grammar from your examples: which classes appear, what goes in each instance variable, how big the collections get, which ranges the numbers live in.

2. Measure what “normal” is. It runs your examples and a few freshly generated inputs, and keeps the median time. That’s the yardstick: when looking for slow inputs, “slow” means five times slower than this median.

3. Fuzzing (Ume). Ume starts from your examples and keeps mutating them. There are six mutators. Which mutator to use next isn’t random: MOpt scheduler learns which
mutators pay off for this code and picks them more often. And each run is scored by what you asked for: execution time (or method calls) for #slowInputs; new coverage and new errors for #errors.

The inputs with the best scores go back into the pool to be mutated again.

4. Check. Every candidate is run again on its own. A slow input is re-timed several times and has to stay above the limit; an error has to happen again, with the
same error class at the same place. Two inputs that fail the same way are one finding, not two.

5. Shrink (Shin). Each confirmed finding is minimized while it keeps failing the same way: Shin’s delta debugging over every collection and every string, numbers pushed towards 0, 1, or -1. If the original input respected the grammar, the small one does too, so you don’t end up with a “bug” that only exists in an impossible object. And if a shrunk slow input stops being slow when measured again, you get the original instead.

The report provides the minimized found inputs, a few charts of the search, and Unit tests you can paste into your project so the bug never comes back.

Pharo Hunting

The idea for PerfUMate came from hunting bugs ( performance bottlenecks, unexpected behavior, or crashes ). In the article, we perform a first hunt, exploring the compiler, Pharo collections, STON, Zinc, and the JIT. The result? 31 potential bugs.

Where do we start?

Before anything, we have to answer one question per library: what should always be true/expected? A fuzzer is great at finding inputs, but it only knows something is wrong if you tell it what “right” means.

Let’s start with a little example on NeoJSON:

PerfUMate new
examples: #( '{"a":[1,2.5e10,-3,{"b":null,"c":true}]}' '[]' '"\u0000\t"' );
benchmark: [ :json | MyHuntCampaigns checkNeoJSON: json ];
lookFor: #errors;
budget: 5 minutes;
instrument: { 'Neo-JSON-Core' }
MyHuntCampaigns class >> checkNeoJSON: aString [
| value |
value := [ NeoJSONReader fromString: aString ]
on: NeoJSONParseError do: [ :error | ^ self ].
(NeoJSONReader fromString: (NeoJSONWriter toString: value)) = value
ifFalse: [
PerfUMateBrokenInvariant signal: 'inconsistent parsing'
]
]
  • examples: are where the search starts. Mate learns from them what a “normal” input looks like.
  • benchmark: runs one input and checks the property.
  • lookFor: #errors tells Ume what’s interesting: new coverage and new errors. For performance bugs, it would be #slowInputs.
  • instrument: is the Pharo package or methods that Ume will instrument to gather feedback.

In PerfUMate terms, the benchmark is a block that does those runs and
signals PerfUMateBrokenInvariant when the answers differ.

So, let’s hunt!

CampaignsInput typeBenchmark
NeoJSON, NeoCSV, STON, Fueltextwhat you write, you read back equal
Compiler, number parsing, regex, Microdowntextanything goes in, nothing but a syntax error comes out
Zinc: URLs, MIME types, encoderstext, bytesparse, print, parse again: same thing
Fuel, STONobject graphsa graph comes back with the same meaning, and its Sets still find their elements
Copyingobject graphsdeepCopy and veryDeepCopy keep the meaning
Equalityobject graphs= is symmetric, and equal objects have equal hashes
Printingobject graphseverything prints, and its storeString compiles back to an equal object

What did we find?

Here are some of the 31 potential bugs:

Microdown

Ume found a 244-character Markdown document that broke Microdown. Shin shrank it:

Microdown parse: '|'.
"SubscriptOutOfBounds: 1 in an OrderedCollection()"

A line with just a pipe opens a table, and closing a table starts with rows first. No rows, no first. Its sibling came from a 372-character document:

Microdown parse: (String cr join: #( '- i' '- e' )).
"PrimitiveFailed: primitive #basicNew: in ByteString class failed"
Regex
'::' asRegex. "SubscriptOutOfBounds: an empty :selector: predicate"
'a{x}' asRegex. "MessageNotUnderstood: receiver of #- is nil, the bound is not a number"
'[[:]]' asRegex. "MessageNotUnderstood: receiver of #asInteger is nil, reads past the end"
Zinc
ZnMimeType fromString: 'text'.
"PrimitiveFailed: primitive #basicNew: in ByteString class failed"
ZnBase64Encoder new decode: '=='. "PrimitiveFailed"
NeoJSON
NeoJSONReader fromString: '1e-2'. "(1/100), a Fraction"
NeoJSONReader fromString: '1.0e-2'. "0.01"
NeoJSONWriter toString: Float nan. "'Float nan'"
STON
STON fromString: (STON toString: (Bag with: 1 -> 2)).
"MessageNotUnderstood: Association >> #adaptToNumber:andSend:"
STON fromString: '1/0'. "ZeroDivide"
STON fromString: 'Time[12]'. "MessageNotUnderstood: SmallInteger >> #readStream"
STON fromString: '[[1],@21]'. "KeyNotFound: key 21"
Fuel
| copy |
copy := FLMaterializer materializeFromByteArray:
(FLSerializer serializeToByteArray: (Set with: (Set withAll: #(1 2 3)))).
copy includes: copy anyOne. "false"
deepCopy
| set copy |
set := IdentitySet with: 'k' copy.
copy := set deepCopy.
copy includes: copy anyOne. "false"
Equality
#[97] = 'a'. "true"
'a' = #[97]. "false"
(1 to: 3) = #(1 2 3). "true"
(1 to: 3) hash = #(1 2 3) hash. "false"
(Set withAll: #(1 2)) = (IdentitySet withAll: #(1 2)). "true, with different hashes"
storeString
(#+ -> 4) storeString. "'(#+->4)': #+-> is read as one symbol"
(1 @ -0.0) storeString. "'((1@-0.0))': read as the binary selector #@-"

The 31 findings

#WhereWhatKind
1KernelLargeNegativeInteger>>asFloat rounds the wrong waywrong
2Compilermalformed radix literals (16rs)crash
3Compiler<primitive: :=crash
4Regex'::' asRegexcrash
5Regex'a{x}' asRegexcrash
6Regex'[[:]]' asRegexcrash
7ZincContent-Type without a slash, also from ZnRequest readFrom:crash
8ZincBase64 with more padding than datacrash
9ZincUTF-16: byte order mark honoured anywherewrong
10ZincUTF-16: lead surrogate swallows the next characterwrong
11ZincUTF-16: lone trail surrogates acceptedwrong
12NeoJSON1e-2 read as a Fractionwrong
13NeoJSONinfinity and NaN written as Smalltalk codewrong
14STONout-of-range referencecrash
15STONzero denominatorcrash
16STONTime[12] and friendscrash
17STON16 characters make the reader loop foreverhang
18STONa Bag holding an Association can’t be read backcrash
19Microdowna line that is just ``
20Microdownlist item indented by four spacescrash
21Fuela Set holding a collection loses itwrong
22CollectionsdeepCopy of IdentitySet and IdentityDictionarywrong
23CollectionsInterval = Array, different hasheswrong
24CollectionsSet = IdentitySet, different hasheswrong
25CollectionsByteArray = String, but not the other waywrong
26CollectionsNaN key breaks Dictionary printingcrash
27KernelstoreString of 1 @ -0.0wrong
28KernelstoreString of #+ -> 4wrong
29KernelstoreString of symbols like #¥wrong
30VMJIT comparison of large integers with floatswrong
31VM0 bitShift: 64wrong

What now?

Every bug has a draft issue with the cause and the exact campaign that found it. The complete report was sent to the community to consider whether they deserve treatment or not.

For now, that’s episode 1. If you know a corner of Pharo that deserves a hunt, let me know; maybe we can find something there!.

Thanks for reading! 🙂