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! 🙂

Ume: Property Testing and Performance Fuzzing

As we know, the bugs that hurt are usually in the ones we didn’t think about, the ones that are hidden on the edge of a range, in nested JSON files, in regular expressions that take four seconds to execute a single match… Those…

Ume helps you search for those inputs. You describe how to build a receiver and the set of arguments for a method and what should hold about the result. Then, Ume:

  • Generates thousands of cases and checks your properties on each one.
  • Measures every execution (time, method calls, allocations, coverage, bytecodes, GCs).
  • Guides the search with those metric measurements, and it keeps mutating the inputs that made the code work hardest.
  • Segments what it found: errors, property failures, and metric outliers.
  • Turns the findings into ordinary Pharo unit tests.

The same engine covers classic property-based testing and performance fuzzing. This guide walks through both with small examples.


Installing

Metacello new
baseline: 'Ume';
repository: 'github://FedeLoch/Ume:main';
onConflictUseIncoming;
load.

Writing a Property

Let’s start by checking that factorial behaves as its definition says. Three ingredients are needed:

"1. How to build the receiver generator"
receiver := UmeGenerator oneOf: (10 to: 100).
"2. What must hold. The block receives the receiver, the arguments and the result"
property := [ :n :args :result | n * (n - 1) factorial = result ].
"3. A schema ties them to the method under test"
schema := UmeSchema new
receiverConstraint: receiver;
property: property;
method: Integer >> #factorial.

Then let a runner execute it:

runner := UmeRunner test: schema times: 1000.
runner collectAllCases. "keep every case, not only the remarkable ones"
result := runner run.

A method with arguments gets one constraint per argument:

schema := UmeSchema new
receiverConstraint: UmeGenerator oneOf: (SmallInteger minVal to: SmallInteger maxVal));
argumentConstraints: {
UmeGenerator oneOf: (SmallInteger minVal to: SmallInteger maxVal)
};
property: [ :a :args :result | result = (a + args first) ];
method: SmallInteger >> #+.

When to stop

Stop after…Code
Some casesUmeRunner test: schema times: 1000
Some timeUmeRunner test: schema for: 2 minutes
N cases without new coverageUmeRunner test: schema withCoverageTolerance: 100
Your own conditionUmeRunner testWithLowCost: schema withCriteria: [ :iteration :elapsed :coverage | ... ]

A campaign can be resumed later from its result: result continueFor: 5 minutes or result continue: 1000.


Ume Result

run returns a UmeResult:

result tests. "the collected cases (UmeTest instances)"
result topCases. "the cases that set a new record during the search"
result totalCoverage. "coverage accumulated over the whole campaign"
result totalTime.

Every case knows its receiver, its arguments, and how the execution went:

test := result tests first.
test receiver.
test arguments.
test result isSuccess. "the property held"
test result isFail. "the property did not hold"
test result isError. "the method raised an error"
test time. "how long it took"

Where is the bug?

Ume groups the problems for you and points at suspicious code:

bugs := result localizeBugs.
bugs uniqueErrors. "one report per distinct error"
bugs uniqueFailures. "property violations"
bugs uniqueOutliers. "performance outliers (see section 6)"

Failure reports rank the executed methods with a spectrum-based fault-localisation score. A method that runs in most failing cases and few passing ones comes first:

bugs uniqueFailures first suspectedMethods.

Ume Generators

Generators are the objects that produce values. The most common ones:

GeneratorWhat it produces
UmeGenerator oneOf: (1 to: 100)a random element of a collection
UmeGenerator always: 42always the same value
UmeGenerator do: [ :props :feedback | ... ]whatever your block returns. It also receives the feedback of the previous case
UmeGenerator onceInstance: [ :instance :props | ... ] of: OrderedCollectiona fresh instance of a class, configured by your block
UmeGrammarGenerator new grammar: JSONGrammar newstrings derived from a grammar
UmeGrammarMCTSGenerator from: JSONGrammar newthe same, choosing productions with Monte Carlo Tree Search and learning from feedback
UmeCorpusGenerator newstarts from seeds and keeps mutating the most interesting inputs

Building a richer object, such as a collection filled with generated items:

itemGen := UmeGenerator oneOf: (1 to: 100).
collection := UmeGenerator
onceInstance: [ :instance :props |
(1 to: 50) atRandom timesRepeat: [
instance add: (props at: 'item') gen ].
instance
] of: OrderedCollection.
receiver := UmeObjectConstraint new
generator: collection;
props: { 'item' -> itemGen }.

Need real object graphs, with back-pointers and constraints between fields? That is what Mate does. Its grammars plug into Ume as generators and mutators (UmeOGGrammarDerivationMutator).


Performance: From bugs to slow inputs

Here is the part that makes Ume different from a classic property-based testing tool. A property that is always true still leaves something to search for: cost.

The runner can be guided by a measurement. After each case, Ume compares what it measured with the best values seen so far. When a case beats a record, it becomes a top case, and the generators are told to build on it. Over time, the search drifts toward the inputs that make the code work hardest.

runner := UmeRunner test: schema for: 10 minutes.
runner guidedByMethodsCalls.
result := runner run.
GuidanceLooks for inputs that maximise…
guidedByMethodsCallshow many times each method runs (the default)
guidedByExecutionTimewall-clock time
guidedByAllocatedMemoryallocated memory
guidedByBytecodesexecuted bytecodes
guidedByGCsgarbage collections
guidedByCoveragereached code
guidedByErrorsnew kinds of errors
guidedByScoreyour own score: block in the schema

Raw measurements are grouped into logarithmic buckets (ln of the value, rounded). A case taking 101 µs instead of 100 µs isn’t news. One taking 10× longer is. This keeps measurement noise from steering the search.

Guiding by method calls works much like PerfFuzz: every method is its own objective. An input that only makes one inner loop run much more often still counts as progress, even if total time hasn’t moved yet. That’s often the first step toward a pathological input.

A complete example: slow JSON documents

mutator := (UmeGrammarDerivationMutator from: JSONGrammar new) maxInputSize: 200.
json := UmeCorpusGenerator new
seeds: { '{"a":[1,2,{"b":null}]}' };
mutationsPerIteration: 3;
mutators: { mutator };
heuristic: UmePickBestElementDifferenceHeuristic new.
schema := UmeSchema new
receiverConstraint: (UmeObjectConstraint new generator: (UmeGenerator always: NeoJSONReader));
argumentConstraints: { UmeObjectConstraint new generator: json };
property: [ :reader :args :result | true ];
method: NeoJSONReader class >> #fromString:.
runner := UmeRunner test: NeoJSONReader class >> #fromString: from: schema for: 10 minutes.
runner guidedByMethodsCalls.
result := runner run.
result topCases last arguments first. "the most demanding document found"

The same recipe has been applied to RxMatcher (regular expressions), Microdown, DataFrame, SVG parsing and Roassal graph layouts.


Mutating structured inputs

UmeCorpusGenerator keeps a corpus of interesting inputs. At each step it picks one, applies a mutator a few times and tries the result. Inputs that set a record are added to the corpus. Ume ships three families of mutators, from fast and blind to slow and structure-aware:

LevelMutatorsGood at
CharactersUmeAddByteMutator, UmeDelByteMutator, UmeByteFlipMutatorfast, and also finds invalid inputs that crash parsers
Grammar literalsUmeGrammarLiteralsMutator from: aGrammarinserts tokens the grammar knows ({, :, *, `
Grammar derivationsUmeGrammarDerivationMutator from: aGrammarparses the input, picks a subtree and regenerates it, so the result stays valid

You don’t have to choose one. Give the generator several and let a scheduler learn which mutator pays off:

json := UmeCorpusGenerator new
seeds: someSeeds;
mutators: {
UmeGrammarLiteralsMutator from: JSONGrammar new.
UmeGrammarDerivationMutator from: JSONGrammar new.
UmeAddByteMutator new.
UmeByteFlipMutator new.
UmeDelByteMutator new
}; mutatorSelector: UmeMOPTMutatorSelector new.
SchedulerHow it chooses
UmeRandomMutatorSelectoruniformly at random
UmeWeightedMutatorSelectorrewards mutators that produced a record (the default)
UmeMOPTMutatorSelectorMOPT: a particle-swarm optimisation over the mutator probabilities, as in the MOPT fuzzer

How the next input is picked from the corpus is a heuristic too: UmeRandomSelectorHeuristic, UmeTournamentSelectorHeuristic, UmePickBestElementDifferenceHeuristic (the best case for some measured key).

The corpus can also be compacted to the smallest set of inputs that still holds every record: generator minimizeCorpus.


Explaining slow inputs

A slow input alone isn’t enough: you want to know why it’s slow. Ume compares each top case with the previous one and reports what grew:

outlier := result localizeBugs uniqueOutliers last.
outlier delta. "which measurements grew, and by how much"
outlier suspectedMethods. "methods this case executed that the previous record did not"

Charts help too (they use Roassal):

result plotByExecutionTime. "time per case"
result plotByImprovements. "when the records were broken"
result plotOutliers open. "box plots of the outliers for time, memory, score and coverage"

To analyse a campaign somewhere else:

result exportAsCSV: 'json-campaign.csv'. "one row per case: time, improvement, mutation metadata, inputs"
result writeToFile: 'json-campaign.ston'. "the whole result, serialised with STON"

Keeping what you found as tests

A fuzzing campaign is only worth something if what it finds stays found. Subclass UmeUnitTest, describe the search once, and Ume writes the test methods for you:

UmeUnitTest << #PlayerDamageTest
package: 'MyGame-Tests'.
PlayerDamageTest >> targetMethod [ ^ Player >> #damage ]
PlayerDamageTest >> receiverGenerator [
^ self
corpusGenFrom: (Player new name: 'fede'; characterClass: Rogue new; level: 1; missingExperienceForNextLevel: 0)
mpi: 3
mutators: { UmeOGGrammarDerivationMutator from: MatePlayerGrammarByLang new }
]
PlayerDamageTest >> argumentGenerators [ ^ #() ]
PlayerDamageTest >> assert: receiver arguments: arguments result: result [ ^ result >= 0 ]
PlayerDamageTest >> guidedBy [ self guidedByMethodsCalls ]
PlayerDamageTest >> generateTests [
<script: 'self new generateTests'>
super generateTests: 10 minutes
]

Click the script. After ten minutes, the class has new methods such as:

test_692162816 [
self doTest: {
'method' -> (Player >> #damage) selector.
'receiver' -> 'Player{#name:''odqi'',#characterClass:Rogue{},#level:1,#missingExperienceForNextLevel:542890132034813952}'.
'arguments' -> '[]'.
} asDictionary
]

Inputs are stored as STON, so the tests are plain Pharo methods: they run in the Test Runner and in CI and can be committed. generateRegressionTests: goes one step further: each test also stores the measurements of its case, so it fails if the input stops behaving as recorded.


Takeaway

  • Instrumentation has a cost. Measuring calls and coverage means installing metalinks on every method in scope. Start with testWithLowCost: (only the target method). Widen the scope (methodsToInstrument:, package coverage) when the search stops finding new records.
  • Prefer counting to timing. Time is noisy: the machine, the GC, and the JIT all leave their mark. Method calls, bytecodes and allocations are deterministic, so guide with them and use time to confirm the final candidates. When you do measure time, don’t run several campaigns in parallel on the same machine.
  • Bound your inputs. Mutators accept maxInputSize:. Without a bound, “slowest input” quickly becomes “longest input”, which isn’t interesting. Fix a size, then find the shape that is slowest at that size.
  • Invalid inputs are inputs too. Character mutators produce plenty of invalid JSON or regexes. That’s how you find crashes in parsers, but it also costs iterations. Grammar mutators keep inputs valid when validity is what you need.
  • Collect what you need. By default, the runner keeps only top cases and errors, which keeps long campaigns light. Call collectAllCases if you want every case (for example, to analyse the whole run or to see every property failure).

Thanks a lot for reading! 🙂

Mate in 10 Minutes: Fuzzing Object Graphs

Common fuzzers generate bytes, strings, or structured grammar-based inputs. Pharo programs, however, work with objects: a BlElement with children that point back to their parent, a Player whose level must stay between 0 and 99, a model where some fields may be nil and others never are.

Mate is a small language and toolkit for describing those object graphs. From one description you can:

  • Generate valid objects, as many as you want, for testing and fuzzing;
  • Guide generation with feedback, so it explores the shapes that matter;
  • Validate existing objects against the description;
  • Infer a description from real objects or from your test suite;
  • Visualize how generation explored the grammar.

This guide walks through each use with small examples.


Installing

Metacello new
baseline: 'Mate';
repository: 'github://FedeLoch/Mate:main';
onConflictUseIncoming;
load.

Your first object grammar

Suppose we have a small game model:

Object << #Player
slots: { #name . #characterClass . #level . #missingExperienceForNextLevel };
package: 'MyGame'.

characterClass holds a Warrior, a Rogue or a Mage.

A Mate grammar says which classes each field may hold and which values are acceptable:

Player -> {
name: ByteString,
characterClass: Warrior | Rogue | Mage,
level: { type: SmallInteger, between: 0 and: 99 },
missingExperienceForNextLevel: { type: SmallInteger, greaterThan: 0 }
}

Read it as: a Player has a name that is a string, a characterClass that is one of three classes, a level from 0 to 99, and a strictly positive amount of missing experience.

To use it, subclass MateOGGrammar and return the description from defineObjectGraph:

MateOGGrammar << #PlayerGrammar
package: 'MyGame'.
PlayerGrammar >> defineObjectGraph [
^ 'Player -> {
name: ByteString,
characterClass: Warrior | Rogue | Mage,
level: { type: SmallInteger, between: 0 and: 99 },
missingExperienceForNextLevel: { type: SmallInteger, greaterThan: 0 }
}'
]

You can also load a grammar from a file:

grammar := MateOGGrammar fromFile: 'player.mate'.

Generating objects

grammar := PlayerGrammar new.
player := grammar gen: Player.
player level. "=> always between 0 and 99"
player characterClass. "=> a Warrior, a Rogue or a Mage"

Need a hundred?

players := (1 to: 100) collect: [ :i | grammar gen: Player ].

Values built for finding bugs

Mate does not pick values uniformly. It favours the values that tend to break code:

TypeWhat you get
Integers0, ±1, powers of two, 32 and 64-bit limits, SmallInteger minVal / maxVal, the edges of your constraints, plus small and random values
Floats0.0, -0.0, ±1.0, tiny and huge values, NaN and ±infinity when the declared type is Float, and the edges of your constraints
Stringsempty, short, very long, punctuation, control bytes, and Unicode for WideString

Constraints are always respected: a level declared between: 0 and: 99 will be 0, 1, 98, 99 and everything in between, but never 100.

Reproducible runs

When a generated object crashes your code, you want to get it back. Give the grammar a seed:

grammar := PlayerGrammar new.
grammar seed: 1234.
players := (1 to: 100) collect: [ :i | grammar gen: Player ].

The same seed produces the same sequence of objects.


The language at a glance

Here is a grammar for a hypothetical shop model that uses most of the language:

"Comments go between double quotes"
Shop -> {
name: ByteString,
rating: { type: Float, between: 0.0 and: 5.0 },
stock: { type: SmallInteger, atLeast: 0 },
status: { oneOf: { #open . #closed . #moved } },
website: ByteString?,
logo: (PNGImage | JPEGImage)?,
products: { type: [ Product ], sizeBetween: 0 and: 20 },
owner: { refType: Person },
selfReferences: { products[ .shop ] }
}
You writeIt means
A | Bthe field holds an A or a B
T?the field may also be nil
between: a and: b, atLeast:, atMost:numeric bounds, inclusive
greaterThan:, lessThan:numeric bounds, exclusive
in: [ 200, 404, 500 ]the value is one of these literals
oneOf: { #open . #closed }the value is one of these literals (symbols, strings, numbers, booleans, nil or classes)
{ type: [ T ], sizeBetween: a and: b }an Array of T, with a size range (size: n for an exact size, 0 to 10 by default)
refType: Ta back-pointer, filled in by selfReferences instead of being generated
selfReferences: { products[ .shop ] }after building a Shop, set the shop field of each of its products to that shop
X classthe class object itself (a metaclass type)

Relationships between objects

Real object graphs are not trees. In Bloc, every child points back to its parent:

BlElement -> {
children: BlChildrenArray,
parent: { refType: BlElement },
visuals: BlCustomVisuals | BlDefaultVisuals,
constraints: BlLayoutCommonConstraints,
selfReferences: { children.array[ .parent ] }
}
BlChildrenArray -> {
array: { type: [ BlElement ], sizeBetween: 0 and: 10 }
}

children.array[ .parent ] reads: follow children, then array, and for each element set its parent to me. Every generated element tree is therefore consistent: child parent == element holds for every child.

Recursion

Grammars can be recursive (BlElement contains BlElements). Generation stops at a maximum depth (12 by default). At that depth, a field takes a simple value if its type allows one, and nil otherwise. You can tune this and how often nullable fields are nil:

grammar generator
maxDerivationHeight: 6;
nilProbability: 0.2.

Let’s stop for 5 seconds to drink a mate🧉… Let’s continue! 🙂

Guided fuzzing: Teaching the grammar what is interesting

Random generation finds shallow bugs. To go deeper, tell Mate which objects were interesting: they reached new code, were slow, or produced a bigger difference in the output. Mate keeps a reward for every choice it made while building that object (which union option, which value, which size) and favours the choices that paid off, while still exploring the rest. Under the hood, this is the UCT formula from Monte Carlo Tree Search.

grammar := PlayerGrammar new.
grammar seed: 42.
1 to: 1000 do: [ :i |
| player score |
player := grammar gen: Player.
score := self newCoverageReachedBy: player.
grammar backPropagate: score from: player ].

backPropagate:from: takes a generated object, works out its derivation, and rewards every choice in it. If you already have the derivation tree, use backpropagate:improvement: directly:

derivation := grammar gen: Player from: MateContext new.
player := derivation instance.
grammar backpropagate: derivation improvement: 42.

Mutating part of an object

Sometimes you want to keep an object and regenerate only one part of it. Take a node of the derivation tree, generate a variant, and swap it in. References such as parent are kept consistent:

derivation := grammar gen: BlElement from: MateContext new.
node := derivation edges at: 'children'.
variant := grammar genVariant: node.
grammar replace: node by: variant.

How much of the grammar did we explore?

grammar explorationPercentage. "=> fraction of the grammar visited so far"
grammar explorationPercentageFrom: Player. "=> the same, counting only what is reachable from Player"

Validating objects

The same grammar can check objects that come from anywhere: your application, a file, a test.

grammar := PlayerGrammar new.
grammar parse: (Player new
name: 'Fede';
level: 42;
characterClass: Rogue new;
missingExperienceForNextLevel: 1).
"=> a derivation tree: the object is valid"
grammar parse: (Player new
name: 'Fede';
level: 500;
characterClass: Rogue new;
missingExperienceForNextLevel: 1).
"=> Error: Value 500 of type SmallInteger violates MateConstraint( min: 0 max: 99)"

parse: checks field types (subclasses are accepted), array sizes, value constraints, and selfReferences. It never modifies the object, and it handles cyclic graphs.

This makes Mate useful as an oracle too: generate objects, run an operation on them, and check that the result still matches the grammar.


Inferring a grammar from real objects

Writing a grammar by hand is not always practical. Mate can infer one from objects you already have:

grammar := MateOGGrammar fromObjects: { player1 . player2 . player3 }.
grammar mateDefinition.
Player -> {
name: ByteString,
characterClass: Mage | Rogue | Warrior,
level: SmallInteger,
missingExperienceForNextLevel: SmallInteger
}

Mate merges what it sees across all instances: field types become unions, arrays get the element types and size ranges observed, booleans become Boolean, and fields that hold classes become oneOf choices.

You can also infer a grammar from the objects your test suite builds:

grammar := MateOGGrammar fromTest: PlayerTest.

Every test is set up and run, and the objects held in its instance variables, plus its return value, are fed to the inference. Failing tests are skipped.

Inferred grammars are a starting point: they know the types but not yet the constraints (ranges, relationships). Edit the output of mateDefinition, which can be parsed back with no changes, and turn it into your hand-written grammar.


Seeing what happened

Mate uses Roassal to draw two things.

A derivation tree: how one object was built, with every choice made.

(PlayerGrammar new gen: Player from: MateContext new) render.

The grammar as a heat map: which declarations and options were visited most during generation.

grammar := MateBlocGrammar new.
100 timesRepeat: [ grammar gen: BlElement ].
grammar render.

Cheat sheet

I want to…Code
generate one objectgrammar gen: Player
generate reproduciblygrammar seed: 42
get the derivation tree toogrammar gen: Player from: MateContext new
reward an interesting objectgrammar backPropagate: score from: player
regenerate part of an objectgrammar replace: node by: (grammar genVariant: node)
check an objectgrammar parse: anObject
infer a grammarMateOGGrammar fromObjects: objects or MateOGGrammar fromTest: aTestClass
print a grammargrammar mateDefinition
load a grammar from a fileMateOGGrammar fromFile: 'grammar.mate'
measure explorationgrammar explorationPercentageFrom: Player
visualizederivation render, grammar render
limit recursiongrammar generator maxDerivationHeight: 6

Thanks for reading!! 🙂

Learn more in the repository and the other pages of this wiki.

Shin: Shrinking inputs in Pharo

You found an input that breaks your program, for example, a 3 KB JSON document, or a 200-character regex, or an SVG path that makes the renderer hang. Before you can debug it, you want the smallest input that still shows the problem, right?

That is what Shin does. You give it an input and a way to recognize the problem, and it removes everything that doesn’t matter.

shrinker := ShinDDminPaperShrinker new.
shrinker oracle: (ShinBooleanInputOracle from: [ :string | string includes: $e ]).
shrinker shrink: 'asqjjkqsbdvieqvsbdoivbq'. "=> 'e'"

Shin is a Pharo library with self-contained implementations of the main input-reduction algorithms (delta debugging, HDD, Perses-like grammar reduction, Nautilus, Vulcan, ProbDD, CDD, WDD, SADD…), plus a small framework to benchmark them against each other.


Installation

Metacello new
baseline: 'Shin';
repository: 'github://FedeLoch/Shin:main';
onConflictUseIncoming;
load.

This also loads Gnocco (grammars and parsing), NeoJSON, and PBA. Benchmark plots use Roassal, which ships with Pharo.


Three concepts: Shrinker, Oracle, and Grammar

ConceptQuestion it answersExample
ShrinkerHow do I make the input smaller?ShinDDminPaperShrinker, ShinHDDShrinker, ShinVulcanShrinker
OracleDoes this smaller input still show the problem?“it raises ZeroDivide“, “it covers the same code”
GrammarWhat does a valid input look like? (optional)AritExpressionGrammar, SvgPathGrammar

The three are independent: any oracle works with any shrinker, and a grammar is only needed by the tree-based shrinkers. That’s what makes it easy to compare algorithms on exactly the same problem.

Every shrinker is used the same way:

shrinker := SomeShrinker new.
shrinker grammar: aGrammar. "only for grammar-based shrinkers"
shrinker oracle: anOracle.
smallest := shrinker shrink: input.

The result always still satisfies the oracle.


Shrinking strings and collections

Flat shrinkers see the input as a sequence (a String or any Collection) and remove elements. They know nothing about syntax.

shrinker := ShinDDminFuzzingBookShrinker new.
shrinker oracle: (ShinBooleanInputOracle from: [ :s |
(s includes: $e) and: [ s includes: $a ] ]).
shrinker shrink: 'kjdsfhkjqsdhfehdkjsqfhkjsa'. "=> 'ea'"

Each element is handled independently, so repeated elements are not a problem:

shrinker oracle: (ShinBooleanInputOracle from: [ :s | s includesSubstring: 'bug' ]).
shrinker shrink: 'zzbzzuzzgzzbugzz'. "=> 'bug'"

Collections other than strings keep their class:

shrinker oracle: (ShinBooleanInputOracle from: [ :array | array includes: 4 ]).
shrinker shrink: #(1 2 3 4 5 6 7 8). "=> #(4)"

Flat shrinkers available: ShinDDminPaperShrinker, ShinDDminFuzzingBookShrinker, ShinProbDDShrinker, ShinCDDShrinker, ShinWDDminShrinker, ShinWDDProbShrinker.

The catch: a flat shrinker happily produces inputs that are no longer syntactically valid. If your program rejects them early, the oracle says “no”, and the reduction stalls. For structured inputs, use a grammar.


Shrinking structured grammar-based inputs

Grammar-based shrinkers parse the input into a tree and reduce the tree. Every candidate they try is valid according to the grammar, so the oracle spends its time on meaningful inputs.

Using a bundled grammar

Shin ships an arithmetic-expression grammar. Let’s find the smallest expression that still divides by zero:

shrinker := ShinVulcanShrinker new.
shrinker grammar: AritExpressionGrammar new.
shrinker oracle: ShinDivideZeroOracle new.
shrinker shrink: '((8500/(208000*80))+(165468468)*(423-12)*(999/(12+88)))/(((145*4)-580)*3)+((456)*12)-(89/(45+(12*8)))+(77*14)'.

The benchmarks also use grammars for regexes (GncRegexGrammar), JSON (JSONGrammar), Markdown/Microdown (ExtendedMarkdownGrammar), SVG paths (SvgPathGrammar) and Roassal graph scripts (RoassalGraphGrammar).

Writing your own grammar

Grammars are Gnocco grammars: a subclass of GncGrammar with one slot per non-terminal (names start with nt) and a defineGrammar method. Here is a grammar for lists of numbers such as [12,7,345]:

GncGrammar << #NumberListGrammar
slots: { #ntStart. #ntItems. #ntNumber. #ntDigit };
package: 'MyProject'.
NumberListGrammar >> defineGrammar [
ntStart --> '[' , ']' | '[' , ntItems , ']'.
ntItems --> ntNumber | ntNumber , ',' , ntItems.
ntNumber --> ntDigit | ntDigit , ntNumber.
ntDigit --> ($0 - $9).
^ ntStart
]

--> defines the rules of a non-terminal, | separates alternatives, , concatenates, strings are literals, and ($0 - $9) is a character range.

Now shrink a list while keeping two equal numbers:

shrinker := ShinHDDShrinker new.
shrinker grammar: NumberListGrammar new.
shrinker oracle: (ShinBooleanInputOracle from: [ :s |
| numbers |
numbers := (s copyFrom: 2 to: s size - 1) substrings: ','.
numbers size ~= numbers asSet size ]).
shrinker shrink: '[12,7,345,8,7,90]'. "=> '[7,7]'"

Every intermediate candidate is a well-formed list, and so is the result.

Shin Grammar-based shrinkers

ShrinkerIdea
ShinHDDShrinker / ShinHDDPaperShrinkerHierarchical Delta Debugging: ddmin applied level by level on the tree.
ShinGRABRShrinkerReplaces subtrees by smaller subtrees (or alternatives) of the same symbol, Perses style.
ShinNautilusShrinkerReplaces subtrees with the smallest derivation of their symbol.
ShinVulcanShrinkerHDD followed by auxiliary reducers: identifier replacement, subtree replacement, and tree-based local exhaustive enumeration.
ShinSADDminShrinker, ShinSAProbDDShrinkerStructure-aware ddmin / ProbDD: elements weighted by their position and shape in the tree.
ShinSADDminHDDShrinker, ShinSAProbDDHDDShrinkerThe two above, applied level by level inside HDD.

Oracles: Deciding what “still fails” means

The oracle is where you encode what you are preserving. Shin evaluates the original input once to get a baseline, then asks the oracle, for every candidate, whether it still matches that baseline.

Ready-made oracles

OracleKeeps inputs that…
ShinBooleanInputOracle from: aBlockmake the block answer true. The everyday choice.
ShinDivideZeroOracleraise ZeroDivide when evaluated as Pharo code.
ShinExecutionTimeOracletake at least threshold × the original execution time (default 95%).
ShinMethodCallsOraclecall at least threshold × as many instrumented methods as the original (default 95%).
ShinCoverageOraclecover exactly the same code as the original.
ShinFeedbackTableOraclekeep a PBA profiling score at least threshold × the original.

Boolean oracles

ShinBooleanInputOracle from: [ :input | [ MyParser parse: input. false ]
on: MyParserError do: [ true ] ]

Catch the error you are looking for inside the block, as above. Grammar-based shrinkers treat any other exception as “the problem disappeared”, but flat shrinkers let it propagate, and the reduction stops.

Preserving code coverage

Useful to find a small input that still exercises the same code, for instance to turn a fuzzer finding into a readable test:

oracle := ShinCoverageOracle new
methodsToInstrument: RxMatcher package methods;
evalBlock: [ :regex | regex asRegex matches: regex minimalStringMatching ];
yourself.
shrinker := ShinDDminFuzzingBookShrinker new oracle: oracle; yourself.
shrinker shrink: 'b+bc||'.

The coverage oracle instruments the methods with metalinks once per reduction, and removes them when it finishes (even if it is interrupted).

Preserving a performance problem

oracle := ShinExecutionTimeOracle new
evalBlock: [ :input | MySlowParser parse: input ];
threshold: 0.9;
yourself.

Candidates are kept as long as they stay at least 90% as slow as the original.

Writing your own oracle

Subclass ShinInputOracle (or ShinThresholdOracle for numeric scores) and implement:

MethodResponsibility
evalInput: inputMeasure the input (a Boolean, a number, a set…). Used to build the baseline.
accepts: input from: baselineAnswer whether input still shows the problem compared to baseline.
valueBound: aBoundTurn a measure into a number, used for the “% problem preservation” statistic.
during: aBlock (optional)Do an expensive setup/teardown once around a whole reduction.
ShinInputOracle << #LongestLineOracle
package: 'MyProject'.
LongestLineOracle >> evalInput: input [
^ (input lines collect: #size) inject: 0 into: [ :a :b | a max: b ]
]
LongestLineOracle >> accepts: input from: baseline [
^ (self evalInput: input) = baseline
]
LongestLineOracle >> valueBound: aBound [
^ aBound
]

Thanks a lot for reading! 🙂

Source code, issues, and datasets: https://github.com/FedeLoch/Shin

Creating a Pharo application for MacOS

Packaging your code as an application is an important point. It is the last step that makes a difference between a bunch of packages and a complete application. 

Thanks to the beautiful work in the PharoApplicationGenerator package, developed by Pablo Tesone, it is now possible to quickly generate an application and an .dmg installer, specifying your Metacello baseline, so you can have an executable for your application.

Now you can use a one-line command to build an installer for your own Pharo macOS application.

If you just want the sample command, this is it:

wget -O- get.pharo.org/64/130+vm | bash; ./pharo Pharo.image metacello install github://hernanmd/the-note-taker/src BaselineOfTheNoteTaker --groups=Release; ./pharo Pharo.image eval "NTCommandLineHandler generateApplication"; chmod 755 build/build.sh; cd build; ./build.sh; open NoteTaker.app

Let’s dive into each step of this one-liner. We will create an installer for a sample application for the Note Taker project:

Downloading Pharo

wget -O- get.pharo.org/64/130+vm | bash

This part downloads Pharo 13.0 (64-bit) and its Virtual Machine (VM). The output is piped directly to bash for execution.

Installing the Project

./pharo Pharo.image metacello install github://hernanmd/the-note-taker/src BaselineOfTheNoteTaker --groups=Release

We’re using Metacello (Pharo’s package manager) to install “The Note Taker” project from its GitHub repository, specifically the Release group. The Release group should include a package that will be only loaded for the executable generation process and includes an NTCommandLineHandler class used to generate a build shell script.

Generating the Application

./pharo Pharo.image eval "NTCommandLineHandler generateApplication"

This step invokes a custom command line handler to generate the application. It’s worth noting that NTCommandLineHandler is a subclass of CommandLineHandler, and CommandLineHandler is already provided in vanilla Pharo images. You should implement a very simple generateApplication class method in your own “NTCommandLineHandler“. Check an example implementation for macOS in the project’s GitHub repository. (https://github.com/hernanmd/the-note-taker/blob/master/src/TheNoteTaker-Release/NTCommandLineHandler.class.st)

Here is the gist of the command line handler

NTCommandLineHandler class >> generateApplication 

  (self environment at: #AppGeneratorOSXGenerator) new
    properties: { 
    #AppName -> 'NoteTaker' .
    #InfoString -> 'A note taking application written in Pharo' .
    #BundleIdentifier -> 'org.pharo.notetaker' .
    #ShortVersion -> '1.0.0' .
    #DisplayName -> 'Note Taker' .
    #CommandLineHandler -> 'noteTaker' .
    #CompanyName -> 'INRIA' .
      #VMType -> 'Spur' } asDictionary;
    outputDirectory: FileLocator workingDirectory / 'build';
    generate.

NTCommandLineHandler >> activate

   AppGeneratorSupport errorHandler: AppGeneratorSDLMessageErrorHandler new.
   OSWindowDriver current startUp: true.

   OSPlatform current isMacOSX
    ifTrue: [ | main |
        main := CocoaMenu new.
        main    title: 'MainMenu'; "Only informative"
            addSubmenu: 'Application' with: [ :m |
                m
                    addItemWithTitle: 'Quit'
                    action: [ Smalltalk snapshot: false andQuit: true ]
                    shortcut: 'q';

                    addItemWithTitle: 'Restart'
                    action: [ NTSpApplication new start ]
                    shortcut: 's' ];
            addSubmenu: 'Help' with: [ :m |
                m
                    addItemWithTitle: 'Show Help'
                    action: [ self inform: 'Help' ]
                    shortcut: '' ].
        main setAsMainMenu.
        NTSpApplication new startFullScreen ]
    ifFalse: [ self inform: 'Not OSX' ].

Preparing the Build Script

chmod 755 build/build.sh

This command makes the build script executable.

Building the Application

cd build; ./build.sh

We change to the build directory and execute the build script. It’s important to note that the build.sh script requires the create-dmg package, which you can install via Homebrew (brew install create-dmg). This dependency is crucial for creating the macOS disk image (DMG) file.

Opening the Application

open NoteTaker.app

Finally, we will open the newly created NoteTaker application.

Conclusion

This command line showcases the power and flexibility of Pharo’s development ecosystem. It demonstrates how we can automate the entire process from downloading Pharo to building and launching a desktop application, all in one command. In future posts, we will explore how to expand this process for GNU/Linux and Windows systems.

Next Pharo Sprints @ Lille

For those interested, we are organizing monthly Pharo sprints in Lille, in the Inria Research Center every last friday of the month! Tell us if you would like to come!

What’s a Pharo Sprint?

Imagine coding in something fun. And having cookies. Pair-programming with a guy that does something completely different than you in your every-day job. And candies. Some coffee too.

Well, that’s the best I can describe a Pharo sprint :).

Organised usually internally in the Evref Inria team @ Lille, we talked about opening to anybody that would like to join! We can connect on discord and do some remote sessions.

The goal? Could be fixing bugs. Could be improving some part of Pharo. Could be just learn something new. You choose.

When?

These are the following Sprint dates:

  • 29/09
  • 27/10
  • 24/11
  • 22/12

If you want to come, find the address below, and please keep us updated on discord or mail so we can organise it better!

INRIA – Avenue Halley,
Parc Scientifique de la Haute Borne,
Bat.A, Park Plaza
France

G

Pharo @ ESUG’23

The yearly European Smalltalk User Group conference happened last week in Lyon, France.
Unofficial numbers tells it had more than 80 participants, and we had met with lots of people we hadn’t seen for years!
We are slowly recovering from COVID 🙂

Of course, you can find the full conference info and schedule in here: https://esug.github.io/2023-Conference/agenda/agenda.html.
However, the goal of this post is to be short and give some highlights on the Pharo activity @ESUG, to keep you updated and steer some discussions.

The Slides of all talks are already in the ESUG Archive, videos will be online soon. I’ll update this post when that happens!

Besides the typical news around Pharo, the announcement of Pharo11 release (from earlier this year), we have seen lot of work on tooling, AI, Databases, web frameworks, infrastructure, and people using Pharo to build different kind of (maybe even crazy in some cases) applications.

Infrastructure

Pharo 11 has improvements in the bytecode compiler, block closure optimizations, Ephemeron support.
Git integration has been stable and working during years, and we keep you updated with the latest libgit releases.

Packaging Pharo desktop applications is being improved a lot.
This even opens the door to build fancy desktop applications using the new versions of Bloc and Roassal!

Profiling and tooling

Pharo has seen in the last year lots improvements in the debugger infrastructure and the refactoring engine.
There is also interesting advances in program instrumentation, used for example to build memory consumption profilers.
There is also a fuzzing framework under development to perform automatic detection of bugs!

AI and BioInformatics

Pharo keeps moving in the AI front with performance improvements, library extensions and bindings to external libraries!
Lapack integration, better dataframes, fancy algorithms and numerical libraries.
All these power toolkits like Bio Smalltalk, which has lots of tools to do exploratory analysis on DNA and other biological analyses.
Imagine all these with the power of live debugging and interactive visualizations!

Databases

Besides the fancy and stable gemstone object databases that can iteract with Pharo, new things are appearing in this area.
Soil is a new object database written in Pharo, with fresh views on old concepts.
It’s even being used in production and apparently we can build sexy query systems on top!

Web Frameworks

The Pharo community keeps delivering high quality frameworks to help you build web applications.
Pharo JS has been updated for the latest Pharo and latest ECMA.
Also, the guys from Yesplan have integrated the Hotwire framework from Ruby-on-Rails into Seaside!

Applications in Pharo!

Of course, not only Pharo is changing, but it also allows people to do amazing applications with it.
We have seen amazing demos of custom desktop applications by the people from Thales, native UIs and command line tools by the people from SCHMIDT, super fun simulators using Cormas.
Also a big heads up for the amazing Glamourous toolkit built on top of Pharo that announced its v1.0 release during the conf!

Community and fun stuff

We had also slots to discuss about the Google Summer of Code results with Pharo, where students did an amazing job on the Pharo IDE, Roassal, the charting libraries, the virtual machine…
Also, we had some interesting and fun community input on the current IDE thanks to the YesPlan people that run a survey and presented the results.
Domenico (Lucrezio), the crazy DJ that makes live coding music, showed his work on synthetizing music from Pharo, now with integrated visualizations!
Finally, there was an announcement on a new MOOC on Advanced Object-Oriented Design.

Conclusion

Of course, there were also lots of nice projects presented in the show us your projects, in the technology awards, in the research workshop.
Put on top the coffee break discussions, the social events, and the nights out!

ESUG’23 was a success, and it was lots of fun.
Let’s hope ESUG’24 will be as fun as this one too!

See you around!
Guille

Writing benchmarks with SMark

Introduction

SMark is a benchmarking framework for Pharo written originally by Stefan Marr. It serves as an essential tool for Pharo developers, enabling them to benchmark their code, identify performance bottlenecks, and make informed decisions to enhance their software’s efficiency.

It is composed of four main components: A Suite (which represents the benchmarks), a Runner (responsible to execute benchmarks), a Reporter (which knows how and what data to report) and a Timer.

SMark behaves similar to the testing framework SUnit with setUp and tearDown methods. And the runner can do what it wants/needs to reach warmup. For instance, the SMarkCogRunner will make sure that all code is compiled before starting to measure. Both warmup and setup/teardown methods can be specified per-benchmark.

Installation

You can install SMark in Pharo evaluating the following expression:

Metacello new
    baseline: 'SMark';
    repository: 'github://guillep/SMark';
    load.

How to implement a benchmark

Create a subclass of SMarkSuite. Inheritance from SMarkSuite is not a requirement but a convenient way to use the multiple hooks which the Suite offers.

SMarkSuite subclass: #MyBenchmarkSuite
	instanceVariableNames: ''
	classVariableNames: ''
	package: 'MyProject'

Add a method named #bench<MyBenchmark>, like: #benchFactorial. This will be your real benchmark method. For example, a simple case repeating the benchmarking task would look like:

benchMyBenchmark

	self problemSize timesRepeat: [ … ]

and a benchmark which uses an index variable on each iteration, and the problem size:

benchMyBenchmark

	| i |
	i := self problemSize.
	[ i > 0 ] whileTrue: [
		" Some task using i "
		i := i - 1 ].

Hooks

There are multiple optional hooks to implement in your benchmark suite:

Define number of iterations in class side:

MyBenchmarkSuite class>>defaultNumberOfIterations
	^ 50

Define number of processes in class side:

MyBenchmarkSuite class>>defaultNumberOfProcesses
	^ 8

Define problem size in class side

MyBenchmarkSuite class>>defaultProblemSize
	^ 30

You can also override MyBenchmarkSuite>>setUp to set up the necessary environment for a benchmark and, if a specific benchmarks in your suite needs additional configuration, then create a method named MyBenchmarkSuite>>setUpBench<yourBenchmarkName> to set up the custom configuration (for example if you are benchmarking benchRegexDNA then you can create a setUpBenchRegexDNA if necessary).

Overriding MyBenchmarkSuite>>processResult:withTimer: will allow you to access the timer after a benchmark execution. And do not forget to override MyBenchmarkSuite>>tearDown to clean up the environment after a benchmark.

How to run benchmarks

To run a benchmark suite directly from Pharo, let’s say for example performing 100 Iterations:

MyBenchmarkSuite run: 100

However, that would only run the benchmark with the default settings in SMark. You can run more complex configurations of your suite using the Harness support, which is a conveninence executor around the runner strategies and the reporter, for example:

SMarkHarness run: { 
	'SMarkHarness'. 
	'SMarkLoops.benchIntLoop' . 
	1 . "The number of iterations"
	1 . "The number of processes"
	5   "The problem size"
	}.

Running built-in benchmarks

For instance to run the built-in benchmarks related to bioinformatics, often used to compare different programming languages, libraries, and algorithms for handling large-scale data processing tasks, these Harness can be evaluated:

SMarkHarness run: { 'SMarkHarness'. 'BenchmarkGameSuite.benchKNucleotide'. 20 . 1 . 2 }.
SMarkHarness run: { 'SMarkHarness'. 'BenchmarkGameSuite.benchFasta'. 25 . 1 . 10 }.
SMarkHarness run: { 'SMarkHarness'. 'BenchmarkGameSuite.benchRegexDNA'. 3 . 1 . 10 }.

The K-Nucleotide benchmark involves counting the occurrences of all k-length substrings (k-mers) in a given DNA sequence. The benchmark will be run 20 times, using 1 process

The FASTA benchmark is composed of 3 sub-benchmarks:

  • The first sub-benchmark writes DNA sequences to a special stream. The nucleotide sequences corresponds to a specific DNA repeated sequence called “ALU“. The benchmark also setup a problem size of 10 to instantiate a custom “repeat” stream, a stream for which its “end” is configured to a limit number and it automatically restarts its position when this end is reached as result of receiving #next. This stream is set to 20 repetitions as limit (2 * problemSize). Finally, the fasta is configured with a line length to write 60 nucleotide positions (columns) before a new line.
  • The second sub-benchmark is configured to 30 repetitions (3 * problemSize) as limit and performs additional calculations instead of just writing the sequence. It iterates another custom repeat stream (a random stream, which uses a naïve linear congruential generator to calculate a random number for each #next message it receives along with percentages – the cumulative probabilities to select each nucleotide) adding and storing the percentage of each ambiguity code (codes used in molecular biology to represent positions in a DNA or protein sequence where the exact nucleotide or amino acid is not known with certainty) in a sequence to provide information about the composition of the sequence in terms of ambiguous and non-ambiguous positions.
  • The third and last sub-benchmark is configured to 50 repetitions as limit but includes preconfigured frequencies instead of performing the ambiguity codes additions for each code.

Finally, the benchRegexDNA measures the performance of regular expression-based DNA sequence analysis on a given DNA sequence, including pattern matching and substitution operations for sequences with “degenerate” codes.

Running from command-line

To run the benchmark harness from CLI:

./pharo -headless Pharo.image --no-default-preferences eval "SMarkHarness run: { 'SMarkHarness'. 'BenchmarkGameSuite.benchFasta'. 1 . 1 . 25000000 }."

And the default output (the console) should look like:

Runner Configuration:
  iterations: 1
  processes: 1
  problem size: 25000000
Report for: BenchmarkGameSuite
Benchmark Fasta
Fasta total: iterations=1 runtime: 14508ms

Some benchmarks are already pre-configured with convenience accessors and default values for the benchmarks game, so it is easier to run them, however, by default, they will not use the SMark reporting support and thus runtime results are not written to the output. For example the FASTA benchmark which expects a 10 kb output file can be run as:

./pharo -headless Pharo.image --no-default-preferences eval "BGFasta fasta"

which output the FASTA format (truncated here):

'>ONE Homo sapiens alu
GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGA
TCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACT
AAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAG
GCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCG
CCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGT
... 

Parametrized benchmarks

If you have complex combinations of benchmarks, for example combining multiple data source with multiple readers and reading strategies, you can write your own benchmarkParameters method in your suite class, to access the built-in support for parametrized test matrix.

To see example code where this is used, check this implementation of JSON benchmarking using NeoJSON and SMark. You can evaluate the benchmark from Pharo with the following expression:

JSONSMarkSuite new benchReadJSON.

In this case, on a new execution, the benchmarks are executed by expanding the matrix of parameters. One important note is that results are collected after a warm up. This means that there will be some executions in what is called the “steady state”, a state where the JIT compiler already produced the code and represents a representative execution.

You can check a benchmark has started looking at the terminal, where output should be something reflecting your parameters:

Runner Configuration:
  iterations: 1
  processes: 1
  problem size: 1

Customize reporting

If you want to send the benchmark output to another destination instead of the console, you can subclass ReBenchReporter with your own reporter class:

ReBenchReporter subclass: #MyBenchmarkReporter
	instanceVariableNames: ''
	classVariableNames: ''
	package: 'MyProject'

and override the method #reportResult:for:of: where you have access to an output stream and an Array of results:

reportResult: aResultsArray for: aCriterion of: benchmark
	"Report duration"
	aResultsArray size < 2 ifTrue: [
		aResultsArray average printOn: stream.
		stream << 'ms'; << $, ].
	"Report iterations count"	
	aResultsArray size printOn: stream.
	stream << $,.
	"Report image name"
	Smalltalk image version printOn: stream.
	stream << $,.
	"Report VM name"
	Smalltalk vm interpreterClass substrings first printOn: stream.
	stream flush.

If this is your case, the harness also should be linked to your reporter:

ReBenchHarness subclass: #MyBenchmarkHarness
	instanceVariableNames: ''
	classVariableNames: ''
	package: 'MyProject'

and the defaultReporter method in class side should answer your reporter class. Also the method defaultOutputDestination should be overriden to configure the output:

defaultOutputDestination
	"Answer a <Stream> used to output receiver's contents"

	^ self defaultOutputFilename asFileReference writeStream

Conclusion

In conclusion, this articule has provided an overview of the SMark benchmark for Pharo. Continued exploration and utilization of SMark will lead to the creation of high-performance software in Pharo, ultimately benefiting the broader community. So, go forth, experiment, and strive for excellence in your Pharo projects with the insights gained from this tutorial.

Happy benchmarking!

Connecting the Dots: Class Names in Pharo Comments Revealed

In this article, I share the outcomes of our experiment aimed at identifying class names, that are references to classes that exist in Pharo environment, within comments in all Pharo classes and methods. The experiment was conducted on a Pharo 11 image, and the identification process relied on regular expressions to detect UpperCamelCases tokens. These tokens were expected to conform to Pharo’s naming conventions for class names. Once they were detected, the next step involved identifying the corresponding class definition for each one of them.

Analysis over class comments

I initiated the analysis on the comments within classes. The environment comprises a total of 9816 classes. Out of these, 8928 classes include comments that do not start with ‘Please comment me’, which is the beginning of default Pharo comments. This indicates that developers have modified 90 % of these comments to add their custom ones.

Using the following regular expression '\b[A-Z][a-zA-Z\d]+\b' asRegex in Pharo, I applied a search over all classes that have custom comments to detect all UpperCamelCase tokens like OrderedCollection. In total I found 3371 classes that have in their comments tokens matching this pattern, moreover, I found in total 7505 references to classes in comments, with duplicates removed in each comment. In other words, if same token is found multiple times in the same comment, it will be counted once to enhance the searching performance over classes in the system.

Having those results, I decided to choose 20 classes with the largest number of references in their comments, and I checked the recall and precision ratios. Below table summarizes 5 classes, to avoid overcrowding the blog post with all the 20 classes:

Class NameRecall ratioPrecision ratio
EncoderForSistaV110.72
IRBytecodeGenerator10.86
ClyNavigationEnvironment10.86
RSLocation10.25
SettingBrowser10.73
Class names in classes comments

On one hand, Recall ratio, also known as the true positive rate, measures the ability to accurately identify all true positive instances. It is high when the number of missing results (False Negatives) is high. On the other hand, Precision ratio focuses on the ability to make accurate positive predictions and avoid including irrelevant matches (false positives). It is high when the number of incorrect matches detected is high.

In the table provided above, the recall ratio for all classes is 1, indicating that the regular expression (regEx) successfully matched all instances of UpperCamelCases in the comments. The only potential scenario where results might be missed is if class names are misspelled or if they are mentioned without adhering to the specified naming convention. As for the precision ratio, results were not as good as the recall ratio because certain keywords, intended for other purposes, were incorrectly identified as classes, leading to more false positives in the classification. Some of them are used in comments to start a sentence (ex: Set the variable …) or a comment block (ex: “` Smalltalk “`).

Analysis over methods comments

Following the execution of the search algorithm within the environment 4,062 classes were found to contain 30,340 commented methods, with a total of 40,422 comments. Upon closer examination, it was determined that 7.5% of these commented methods belong to 368 classes and contain 3,270 references to existing classes in environment.

Having those results, I decided to choose 20 classes with the largest number of references in their methods comments, and I checked the recall and precision ratios. Below table summarizes 5 classes, to avoid overcrowding the blog post with all the 20 classes:

Class NameNumber of commented
methods with references
Recall ratioPrecision ratio
RSLineBuilder1210.94
RSNormalizer710.82
RSLabel910.86
Color2610.95
LargeInteger1711
Class names in methods comments
Boosting performance

Based on the previous research, I discovered that the accuracy of the results could be significantly improved by excluding certain tokens, such as Smalltalk, Set, True, False, Key, etc., which are known to produce false positive results. Additionally, enhancing the research algorithm by excluding code blocks from comments (i.e., everything between “` Smalltalk “` ), would not only optimize the search speed but also ensure that only the intended class names in comments are returned, leading to an overall improvement in precision ratio.

Our research has primarily concentrated on class names rather than method names. However, searching for method references in comments could prove to be more challenging due to two main reasons. Firstly, Pharo’s method naming convention follows camelCase, which increases the possibility of encountering false positive results when attempting to identify them within comments. This occurs because many tokens used in sentences to describe specific functionalities may coincide with method names, leading to potential confusion. Secondly, accurately linking tokens to their corresponding method definitions could also present difficulties, given that the same method might be defined in multiple classes. This situation adds complexity to the process of association and retrieval.

To address the problem, my initial idea involved utilizing AI to identify relevant tokens linked to classes and methods. I discussed this idea with AI experts, but they discouraged its usage for this particular project. They explained that a considerable amount of AI training data, tens of thousands of records, would be necessary to enable AI to accurately detect tokens in less than 10,000 methods and classes. Despite this challenge, the precision and recall ratios were already considered high, and implementing the previously suggested enhancements could further improve them.

Why we need this ?

Following this experiment, I believe that there are reasonable points of why we might need this:

  1. Enhancing Code Documentation: Programs are commented to help other developers understand the purpose and the usage of every code. When class names are clearly mentioned in comments, they provide additional context about the classes and their relationships, making it easier for developers to understand the codebase.
  2. Navigation: In Pharo, every class name that is enclosed between back-ticks like `OrderedCollection` within a comment, becomes clickable in view mode, thus helping the developer navigating to the class definition. However, during our search, we noticed that many classes are not marked in this manner. So why not benefiting from this search and enclosing every token we found in comments that has a valid link to an existing class ?
  3. Maintenance: Also during this search I found some tokens that conform to the naming convention of classes in Pharo, but actually the classes they refer to, do not exist anymore or are deprecated. I guess, this could be solved by enhancing the functionality of renaming a class in Pharo, to apply changes not only over references to these classes in source code, but also in comments, only for those enclosed between back-ticks. However, to be sure this could be done, a previous refactoring should be applied over comments to enclose class names correctly.

Takuzu, a new puzzle game using Bloc

Today I present to you Takuzu, a little puzzle game available for Pharo.

Takuzu is game I proposed to implement during my internship where I’m discovering Bloc, the low-level graphic framework for Pharo 11. The goal of this internship is to create little games with some basic UI using Bloc and after “finishing” the first MineSweeper project (you can find here: https://github.com/Enzo-Demeulenaere/MineSweeper), I started working on this new project.

The name Takuzu is the original Japanese name for this puzzle that is also commonly called ‘Binary Sudoku’ as you fill a grid with 0s and 1s following only 3 rules :
> You can’t have more than 2 cells of the same value aligned.
> There must be as many 0 as 1 on each row and column.
> Rows and columns must be all different one to another.

I first discovered this game around last year when searching for mobile puzzle games when I saw ‘0h h1’ on the Google Play Store (but you can also play it here: https://0hh1.com) and I immediately loved the logic behind it and wondered how could I implement it, what are the algorithms that seem simple but yet hide some complex thinking.

For the UI, I decided to entirely follow the look of 0hh1 with simple red and blue cells on a dark gray background, nothing too creative. Then I had to use Bloc to draw the UI while also using Toplo to have a menu with some widgets and this I what I’ve got so far:

You can discover this project by executing this snippet in Pharo 11:

Metacello new
baseline:'Takuzu';
repository: 'github://Enzo-Demeulenaere/Takuzu:main';
load: 'core'


and launch the application by executing : Takuzu openWithMenuBar

When in the main menu, you can try some pre-loaded levels from size 4×4 to 12×12 in the ‘Levels’ menu or choose the ‘Random’ menu to play with some randomly generated 4×4 and 6×6 levels (but the grids aren’t so good as my generation algorithm isn’t perfect at all)

You can also find all the informations about the project on its GitHub page: https://github.com/Enzo-Demeulenaere/Takuzu

Feel free to give me any feedback about this game and enjoy discovering Takuzu !

Enzo Demeulenaere