Developing and testing Sonde
This guide is for people changing the library: fixing bugs, adding tools or features. It covers setting up a build, running and writing tests, the quality checks every change must pass, and two worked examples. Read architecture.md first for how the code fits together.
- Set up
- Code style and git hooks
- Build
- Run the demos
- Tests
- Writing tests
- Coverage
- Static analysis with clang-tidy
- Sanitizers
- Fuzzing
- The chaos test
- Documentation comments
- Worked example: adding a tool
- Worked example: fixing a bug
- Debugging tips
- Before you ask for review
Set up
The quickest way is mise-en-place. The repository’s mise.toml pins CMake, Ninja, Python and the exact clang-format version the code is formatted with:
mise install # the pinned tools, into mise's own directory
mise run setup # configure build/ (Debug, Ninja) and install the git hooks
mise tasks # build, test, format, lint, check, fuzz, chaos, package-test, docker-test
mise doesn’t install Qt or LLVM. Get those as described below.
Without mise, you need:
| Tool | Version | Used for |
|---|---|---|
| Qt | 6.8 or newer, with Core, Network, Gui, Widgets, Quick, Qml and Test | building and testing |
| CMake | 3.24 or newer | the build |
| Ninja | any recent version | recommended generator (make also works) |
| A C++17 compiler | Clang, GCC or MSVC | the build. Coverage needs Clang. |
| Python 3 | 3.8 or newer | the end-to-end, package and Docker tests, and tools/check.py (using Sonde doesn’t need it) |
| clang-tidy and run-clang-tidy | from LLVM | the clang-tidy target |
| Doxygen | 1.9.5 or newer | the docs target |
| clang-format | exactly the version in mise.toml (23.1.5) |
formatting; other versions format some code differently |
| git | GoogleTest is fetched with git if it is not installed |
On macOS with Homebrew:
brew install qt cmake ninja llvm doxygen
Homebrew’s llvm provides clang-tidy. You don’t have to change your
compiler: the build still uses Apple’s clang, and the tooling finds
/opt/homebrew/opt/llvm/bin/clang-tidy by itself.
If your Qt is somewhere CMake doesn’t look (for example from the Qt online installer), tell CMake where it is:
cmake -S . -B build -G Ninja -DCMAKE_PREFIX_PATH=$HOME/Qt/6.8.3/macos
GoogleTest does not need to be installed. If CMake can’t find an installed copy, it downloads v1.17.0 during configuration, so the first configure needs network access.
Code style and git hooks
The code follows the Qt project’s style: .clang-format
holds the settings of Qt’s own _clang-format (4-space indents, 100
columns, the brace and line-break rules Qt’s sources use). Don’t format by
hand:
mise run format # or: python3 tools/check.py format
The git hooks in .githooks/ check every commit and push.
mise run setup installs them, or run python3 tools/check.py hooks, which
sets git config core.hooksPath .githooks.
| Hook | Checks | Typical time |
|---|---|---|
| pre-commit | The staged C++ files are formatted (their staged content); a file that isn’t is formatted and staged again, unless it also has unstaged changes, which stops the commit. Staged Python files compile. If Markdown is staged, the documentation links resolve. If code or build files are staged: build, unit tests and smoke test. | about 20 s; a few seconds for documentation-only commits |
| pre-push | Every C++ file is formatted, then build, unit tests, smoke test, clang-tidy, Doxygen and the link check. | about 1 minute |
Both hooks run tools/check.py, which also runs the
checks by hand: mise run test, mise run lint, mise run format-check,
mise run check (everything the pre-push hook runs).
Things to know:
- The build and the tests run on your working tree, including changes you haven’t staged; the hook says so when there are any. The format check looks at exactly what you’re committing.
- The build directory is
build, orSONDE_BUILD_DIR. If it doesn’t exist, it is configured as a Debug build with Ninja. - Inside a mise environment the hooks use mise’s Python and the pinned
clang-format. Outside one, they use
clang-formatfrom your PATH (or Homebrew’s LLVM) and warn if its version isn’t the pinned one. - Skip the hooks once with
git commit --no-verifyorgit push --no-verify, for example for a work-in-progress commit on a branch. Run the checks before you ask for review anyway. - Doxygen 1.18 on macOS sometimes crashes with no output. The Doxygen step retries up to twice when that happens, and says so. A failure that prints a warning fails at once.
- Long single-statement
ifs need braces. clang-tidy allows leaving them out only for one-line bodies, as Qt’s coding style does. When clang-format wraps a statement onto two lines, add braces. - Put
NOLINTcomments on their own line, as// NOLINTNEXTLINE(check): reasonabove the statement. clang-format can move a trailing// NOLINT(...)onto a continuation line, where it no longer suppresses anything.
The slower checks are not in the hooks, so run them yourself when they
apply: coverage, the sanitizers, the fuzzers
(mise run fuzz) and the Docker test (mise run docker-test).
Continuous integration
.github/workflows/ci.yml runs on every push to any branch and every pull request. It catches what the hooks can’t: other platforms, other Qt versions, and pushes or pull requests made without the hooks.
| Job | Runs | Where |
|---|---|---|
| test | tools/check.py test, then the smoke test again with SONDE_THREADED=1 |
Linux with Qt 6.8 and GCC, macOS with Qt 6.12 and Apple Clang, Windows with Qt 6.8 and MSVC |
| lint | format check, link check, clang-tidy and Doxygen, with the versions the hooks use (clang-format 23.1.5, LLVM 23, Doxygen 1.18) | Linux with Qt 6.12 and Clang 23 |
| chaos | the chaos test, 3 fixed and 3 random seeds in both threading modes, in its container (below) | Linux |
| docker | tests/docker_test.py: Debian’s packaged Qt 6.8, and the container workflows |
Linux |
- More workflows: chaos.yml
runs longer chaos tests under AddressSanitizer every night;
tsan.yml runs the unit tests and the
smoke test under ThreadSanitizer every week, against a Qt built with it
(below); and
docs.yml publishes the documentation
website, https://asgeir.github.io/sonde/, when a release is published: the
README, the guides, the walkthroughs and the changelog (laid out for Jekyll
by
tools/site.py), and the API reference underapi/. The design documents stay on GitHub. A push that changes the docs builds the site without publishing it, as a check. Both can also be run by hand from the Actions tab. - Missing tools fail in CI. Locally,
check.py lintskips clang-tidy or Doxygen when CMake didn’t find them, and the Docker test skips without Docker. CI setsSONDE_REQUIRE_TOOLS=1, which turns those skips into failures, so a broken install can’t pass as green. - Why a job failed is on the run’s summary page:
check.pyalso prints a failing step’s output as an error annotation there. The full logs need a GitHub sign-in. - A test that fails now and then is a bug, not noise. When unit tests
fail,
check.pyshows each failed test’s own output, then runs the failed ones again on their own. The step fails either way. If they pass the second time, it says so: look for a timing assumption, in the test or in the code. So far each has been one:- a fixed wait (
QTest::qWait(50)) for something that takes longer on a busy machine. Wait for the condition withwaitUntil()instead, or better, make the code under test not need the wait; - a port or file that a test running at the same time also uses. ctest
runs each test and its
SONDE_THREADEDcopy in parallel; - a callback that runs on another thread, or later, than the test assumed.
- a fixed wait (
- The smoke test has a time limit of 5 minutes, after which it is ended with everything it started. In CI its output goes to the log as it runs.
- Not in CI: coverage, UndefinedBehaviorSanitizer and AddressSanitizer on the unit tests (the chaos test runs under both nightly), and the fuzzers. Run them yourself when they apply, as below.
- Changing a tool version: update
mise.tomland theenvblock at the top ofci.ymltogether.
Design: 0024.
Build
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug
cmake --build build
This builds the libraries, sonde-bridge, both demos and both test programs.
Build options (pass as -D<option>=ON|OFF):
| Option | Default | Effect |
|---|---|---|
SONDE_BUILD_GUI |
ON | Build Sonde::Gui |
SONDE_BUILD_WIDGETS |
ON | Build Sonde::Widgets if Qt Widgets is found |
SONDE_BUILD_QUICK |
ON | Build Sonde::Quick if Qt Quick is found |
SONDE_BUILD_BRIDGE |
ON | Build sonde-bridge |
SONDE_BUILD_EXAMPLES |
ON when top-level | Build the demos |
SONDE_BUILD_TESTS |
ON when top-level | Build the unit tests |
SONDE_STRICT_WARNINGS |
ON when top-level | Build Sonde’s own targets with a strict warning set, as errors (see Warnings) |
SONDE_INSTALL_SHELL_FILES |
ON | Install the man pages and the bash and zsh completions (written at build time; never on Windows or when cross-compiling) |
SONDE_COVERAGE |
OFF | Instrument for coverage and add the coverage target (Clang only) |
BUILD_SHARED_LIBS |
OFF | Build shared instead of static libraries |
Use a separate build directory for each configuration, for example build
for everyday work and build-cov for coverage. All build*/ directories are
ignored by git.
Warnings
Sonde builds with a strict set of warnings, as errors, set in
cmake/SondeWarnings.cmake: -Wall -Wextra
-Wpedantic, -Wshadow, -Woverloaded-virtual, -Wold-style-cast,
-Wconversion -Wsign-conversion and more, for GCC and Clang. The reason:
an application that adds Sonde with FetchContent compiles Sonde’s sources
with its own flags, and many applications turn warnings into errors. A
warning Sonde lets through can break someone else’s build.
- It applies to every target in this repository (libraries, bridge, examples, tests), but not to googletest.
- It is off when Sonde is a subproject (
SONDE_STRICT_WARNINGSdefaults toPROJECT_IS_TOP_LEVEL), so a new warning in a newer compiler can’t break a consumer’s build. - To build once without
-Werror, for example while trying something out:cmake --build build --compile-no-warning-as-error. - Fix warnings rather than silencing them. When Qt’s API differs between
versions (
QMetaEnumtakesquint64since Qt 6.9 andintbefore), convert to the type the version expects, asmetaEnumValue()does.
Run the demos
build/examples/widgets/sonde-widgets-demo # HTTP on 8765, local socket "sonde-widgets-demo"
build/examples/quick/sonde-quick-demo # HTTP on 8766, local socket "sonde-quick-demo"
SONDE_HTTP=8799 build/examples/acme-orders/acme-orders # the walkthrough's app (has a deliberate bug)
To run without opening a window (on a server, or so it doesn’t get in your way):
QT_QPA_PLATFORM=offscreen build/examples/widgets/sonde-widgets-demo
Then connect a client as described in using.md. The demos are the quickest way to try a change by hand.
Tests
There are two kinds:
| Kind | Where | What it covers | How to run |
|---|---|---|---|
| Unit tests (GoogleTest) | tests/core/, tests/gui/ |
Everything in the libraries, in-process, including the real transports | ctest --test-dir build |
| The same unit tests in WorkerThread mode | the same programs, as tests named *.worker |
Everything again, with the transports on a worker thread (SONDE_THREADED=1) |
ctest --test-dir build (runs both) |
| End-to-end smoke test (Python) | tests/smoke_test.py, with its parts in tests/smoke/ (the transports; the sonde command on a project) |
The demo application, sonde-bridge and the sonde command (build/sonde) as separate processes |
python3 tests/smoke_test.py build |
| Package test (Python) | tests/package_test.py |
Installing Sonde, moving the install, and building and running an application against it with find_package |
python3 tests/package_test.py build |
| Chaos test (only in its container) | tests/chaos/ |
Random changes to an application while random tool calls, cancellations and disconnections hit it (below) | python3 tests/chaos/run.py |
| Docker test (Python) | tests/docker_test.py |
Building against Qt 6.8 in Debian, and the container workflows in containers.md | python3 tests/docker_test.py |
The Python tests share tests/mcptest.py: check() and the summary, MCP clients
over HTTP and over a command’s stdio, and a line reader with a timeout. They use only
the standard library.
The unit tests are built into three programs:
sonde_core_teststestsSonde::Coreand uses only QtCore, QtNetwork and QtTest (no GUI). Its files:test_types.cpp(value types),test_server.cpp(dispatch, registries, environment variables),test_toolcall.cpp(asynchronous calls),test_http.cpp,test_local.cpp(transports),test_events.cpp,test_objecttree.cppandtest_introspection.cpp.sonde_gui_teststestsGui,WidgetsandQuickwith real windows on Qt’soffscreenplatform. Its files includetest_windows.cpp,test_input.cpp,test_widgets.cpp,test_quick.cpp, andtest_catalogue.cpp, which keeps the tool list within its size budget and checks that the tool tables inREADME.mdandusing.mdname every tool and no other.sonde_cli_tests(tests/cli/test_cli.cpp) tests the parts of thesondecommand that start no processes, fromtools/cli/.
Running tests
ctest --test-dir build # everything (add -j8 to run in parallel)
ctest --test-dir build -R 'HttpTest\.' # tests whose name matches a regex
ctest --test-dir build --output-on-failure # show the output of failing tests
ctest runs each test case as its own process. To run a test program directly, which is faster when you are iterating and easier to debug:
QT_QPA_PLATFORM=offscreen build/tests/sonde_core_tests --gtest_filter='ToolCallTest.*'
build/tests/sonde_core_tests --gtest_list_tests
The GUI test program sets QT_QPA_PLATFORM=offscreen itself if it isn’t set.
To watch the GUI tests on your screen, set QT_QPA_PLATFORM=cocoa (macOS),
xcb or wayland (Linux), or windows.
Writing tests
The helpers
tests/support/testsupport.h has everything needed to talk to a server from
a test, without starting another process:
| Helper | Use |
|---|---|
waitUntil(predicate, timeoutMs) |
Run the event loop until the predicate is true. Use it instead of sleep. |
spin(ms) |
Run the event loop for a fixed time. Only use it when you need nothing to happen, e.g. to check that no notification arrives. |
uniqueName(prefix) |
A local socket name no other test uses. |
LocalClient |
An MCP client over the local socket: initialize(), request(), callTool(), callToolText(), notify(), sendRaw(), notifications(), waitForNotification(). |
HttpClient |
An MCP client over HTTP: initialize(), request(), post(). |
http(), rawHttp() |
Send one HTTP request, or exact raw bytes (for malformed requests and pipelining). |
SseStream |
Open GET /mcp and collect the server-sent events. |
resultText(result) |
The text blocks of a tool result, joined. |
tests/support/testobject.h defines TestObject, a QObject with
properties of many types, an enum, a flags type, slots and invokable methods,
for introspection and conversion tests.
tests/gui/guifixture.h defines GuiTest: a fixture with a server that has
all tools and integrations installed, a widget form (edit, button,
check, slider, list, hiddenLabel, and a Ctrl+K shortcut) and a QML
window (box, input). It provides call(), text() and fails()
shortcuts for calling tools.
An example
#include <sonde/server.h>
#include "testsupport.h"
#include <gtest/gtest.h>
using namespace Sonde;
using namespace SondeTest;
TEST(MyFeature, EchoToolReturnsItsArgument)
{
Server server;
const QString name = uniqueName(QStringLiteral("myfeature"));
ASSERT_TRUE(server.listenLocal(name));
ToolDefinition def;
def.name = QStringLiteral("echo");
server.addTool(def, [](const QJsonObject &args) {
return ToolResult::text(args.value(QStringLiteral("text")).toString());
});
LocalClient client(name);
client.initialize();
EXPECT_EQ(client.callToolText(QStringLiteral("echo"), {{QStringLiteral("text"), QStringLiteral("hi")}}),
QStringLiteral("hi"));
}
Add a new test file to the sonde_add_test(...) list in
tests/CMakeLists.txt.
Tips and traps
- Everything is asynchronous. Sockets, queued log events and timers only
move forward when the event loop runs. If a check fails because “nothing
happened”, wrap the condition in
waitUntil. - Never use fixed sleeps to wait for something. They make tests slow and
flaky.
waitUntilreturns as soon as the condition is true. - Use
uniqueName()for local sockets. ctest runs tests in parallel, and two tests using the same name will interfere. - Some state is process-wide: the GUI integration registry, the object
tree providers, and the Qt message handler. Only one
LogEventSourcecan be active at a time, and eachGuiTestserver creates one, so don’t create anotherLogEventSourceinside aGuiTest. Providers you register in a test stay registered for the rest of that test program, so register them under a test-specific key and reset them at the end, asObjectTreeTest.ProvidersAddAndReplacedoes. - Test the error paths too. Most branches in this code are error handling, and the coverage target expects them to be exercised: wrong argument types, unknown objects, closed windows, malformed HTTP.
- Bug fix? Write the failing test first. It proves the bug, and proves the fix.
- QtTest is available (
QSignalSpy,QTest::qWaitForWindowExposed,QTest::qWaitFor, …), but GoogleTest is the test framework: useTEST,TEST_FandEXPECT_*. - moc and
Q_PROPERTY(... MEMBER ...)with aQFlagstype generate code that doesn’t compile. UseREAD/WRITEfunctions for flags properties.
Coverage
cmake -S . -B build-cov -G Ninja -DCMAKE_BUILD_TYPE=Debug -DSONDE_COVERAGE=ON -DSONDE_BUILD_EXAMPLES=OFF
cmake --build build-cov
cmake --build build-cov --target coverage
The coverage target runs all unit tests, then prints a per-file table for
the library sources (not tests, examples or the bridge). It also writes an HTML
report that shows each line’s hit count: open
build-cov/coverage/html/index.html.
The project’s bar is at least 80% line coverage of the libraries. It is currently about 97%. A change should not lower coverage noticeably: new code comes with tests for its success and error paths. The remaining gaps are mostly paths behind long timers (the 15-second SSE ping, 30-minute session expiry) and defensive branches that cannot be reached from outside.
Coverage needs Clang. The coverage target uses llvm-cov and
llvm-profdata (from Xcode on macOS, or from your LLVM installation).
Static analysis with clang-tidy
cmake --build build --target clang-tidy
This runs clang-tidy over every .cpp file under src, tools, examples
and tests, using the configuration in .clang-tidy. That
configuration enables the bugprone, cert, clang-analyzer, concurrency,
cppcoreguidelines, misc, modernize, performance, portability and
readability check groups, and any finding fails the target. The file
lists the checks that are switched off, with the reason for each. Most clash
with ordinary Qt code (parent-owned new, QStringLiteral, implicit
QPointer to bool).
Two limits keep functions readable:
- Cognitive complexity of at most 25 (
readability-function-cognitive-complexity). - At most 120 lines per function (
readability-function-size).
Nested lambdas count towards the function that contains them. So a tool
is written as named functions (a handler, plus an install...() that registers
it), not as one long installer full of lambdas. See src/core/introspectiontools.cpp
for the pattern.
When clang-tidy reports something:
- Fix the code. This is almost always the right answer.
- If the finding is wrong for this one line, suppress it on that line with
the reason:
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access): QKeySequence has no at(); i < count()A
NOLINTwithout a reason will not pass review. - Only change
.clang-tidyif a check is wrong for the whole project, and explain why in the comment at the top of that file.
Be careful with -fix. clang-tidy can rewrite code automatically
(run-clang-tidy -fix), but review every change it makes before committing.
In this project an automatic cppcoreguidelines-prefer-member-initializer fix
once changed LogEventSource so that a second, inactive instance believed it
was active. Its destructor would then have removed the first instance’s
message handler. Commit or stash your work before running -fix, so you can
diff the result.
Sanitizers
The compiler’s sanitizers find undefined behaviour and memory errors that tests alone can miss. Run the whole suite under each before a release, and after any change to parsing, number conversion, or object lifetimes:
# Undefined behaviour: overflow, out-of-range conversions, bad casts, ...
cmake -S . -B build-ubsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DSONDE_BUILD_EXAMPLES=OFF \
-DCMAKE_CXX_FLAGS="-fsanitize=undefined,float-cast-overflow -fno-sanitize-recover=all" \
-DCMAKE_EXE_LINKER_FLAGS="-fsanitize=undefined"
cmake --build build-ubsan && ctest --test-dir build-ubsan
# Memory errors: use after free, use after scope, buffer overflows
cmake -S . -B build-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DSONDE_BUILD_EXAMPLES=OFF \
-DCMAKE_CXX_FLAGS="-fsanitize=address -fno-omit-frame-pointer" \
-DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address"
cmake --build build-asan && ASAN_OPTIONS=detect_leaks=0 ctest --test-dir build-asan
# Data races: ThreadSanitizer (works with a normal, uninstrumented Qt; see below)
cmake -S . -B build-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DSONDE_BUILD_EXAMPLES=OFF \
-DCMAKE_CXX_FLAGS="-fsanitize=thread" -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=thread"
cmake --build build-tsan && QT_QPA_PLATFORM=offscreen ctest --test-dir build-tsan
ThreadSanitizer usually needs every library built with it, because it can’t
see the locking inside uninstrumented code, Qt’s event queue included. Sonde
gets around that: whatever it hands from one thread to another goes through
HomeLink, which takes a mutex TSan can see on both sides. So TSan runs
against a normal Qt. Hand-overs of your own (a QMetaObject::invokeMethod
carrying data from another thread) should go through HomeLink too, or TSan
will report them.
Any report is a bug, in test code as much as in the library. Undefined
behaviour often “works” on one machine: an out-of-range double to
quint64 cast happens to saturate on Apple silicon, for example. That is why a
passing test is not proof that none is there.
ThreadSanitizer, weekly
Against a normal Qt, TSan only sees the hand-overs that go through
HomeLink. The TSan workflow runs every
Sunday, and by hand from the Actions tab, against Qt 6.8’s qtbase and
qtdeclarative built with ThreadSanitizer too, so it sees Qt’s own locking and
event queue as well (design 0032):
- The image,
ghcr.io/asgeir/sonde-tsan-qt:6.8.5, comes from tests/tsan/Dockerfile. Building it takes hours, so tsan-image.yml does it only by hand and when the Dockerfile changes on master. Run by hand from a branch, it publishes6.8.5-<branch>, which the TSan workflow can be pointed at, so a change to the image is tried before it replaces the one in use. - The run builds
build-tsan/with-fsanitize=thread, then runs the unit tests (each in both threading modes) and the smoke test, also withSONDE_THREADED=1. Every process, the applications the smoke test starts included, writes its reports tobuild-tsan-out/tsan.<pid>. Any report fails the run; each is an error annotation on the summary page, naming its first frame in Sonde, and the files are in the run’stsan-reportsartifact. - Locally, with Docker:
python3 tests/tsan/run.py. On a Linux host, firstsudo sysctl vm.mmap_rnd_bits=28: TSan can’t start with more address randomisation, and Docker stops it working around that itself. - Slower tests. Under TSan the tests run several times slower, so the run
raises the per-test limit (
-DSONDE_TEST_TIMEOUT, 60 s by default) and the smoke test’s (SONDE_SMOKE_TIMEOUT, 300 s). A test that fails only under TSan’s slowness still has a timing assumption to fix. - Suppressions, in tests/tsan/tsan.supp,
are only for races in Qt itself that Sonde reaches by using Qt as
documented: three so far, in Qt Network, Qt Widgets and Qt Core. Each
names the Qt function the race is in, never a library, and says what the
race is. Qt is instrumented, so “it’s inside Qt” is not enough: check that
Qt’s code is on both sides and that Sonde used Qt as documented. A false
positive is avoided rather than suppressed where Qt allows it (the image
turns off PCRE2’s JIT with
QT_ENABLE_REGEXP_JIT=0).
Fuzzing
A fuzzer calls the code with millions of generated inputs. It keeps the inputs that reach new code, mutates them, and stops when one makes the program crash or trips a sanitizer. It finds the inputs nobody thinks of writing a test for. Sonde uses libFuzzer for the code that reads what clients send:
| Target | What it feeds | What it checks |
|---|---|---|
fuzz_http_parser |
Raw bytes to Http::parseRequest (as a stream of pipelined requests), decodeChunked and bearerTokenMatches |
No crash or UB. Nothing is consumed unless a request completes, every complete request consumes input, bodies stay within the limit, and errors are 4xx |
fuzz_jsonrpc |
Lines of JSON to ServerPrivate::handleMessage, with the introspection tools, an event source and an echo tool installed |
No crash or UB. Every request gets at most one reply, and every request other than tools/call is answered before handleMessage returns |
fuzz_json_variant |
JSON to ObjectTree::jsonToVariant for 20 property types, then back with variantToJson; the same text as an object spec to ObjectTree::find |
No crash or UB |
Apple’s clang doesn’t include libFuzzer, so the fuzzers are built and run in a Debian container. You need Docker:
python3 tests/fuzz/run.py # all targets, 60 s each
python3 tests/fuzz/run.py --seconds 600 fuzz_jsonrpc
The script builds the sonde-fuzz image from
tests/fuzz/Dockerfile, then runs each target
with AddressSanitizer and UndefinedBehaviorSanitizer. The inputs a run finds
interesting are kept in build-fuzz/corpus/<target>/ and reused next time,
so later runs start where earlier ones stopped. The hand-written starting
inputs (“seeds”) are in tests/fuzz/corpus/<target>/ and are always included.
When a target crashes, the script prints the report and the input is saved in
build-fuzz/crashes/. To reproduce it:
docker run --rm -v "$PWD/build-fuzz:/out" sonde-fuzz build/tests/fuzz/fuzz_jsonrpc /out/crashes/<file>
Then fix it like any other bug:
- Write a unit test that fails with the crashing input (shortened by hand to what matters).
- Fix the bug.
- Copy the crashing input into
tests/fuzz/corpus/<target>/with a name that says what it was, so every later run tries it first.
On Linux with clang you can also build the fuzzers directly:
CC=clang CXX=clang++ cmake -S . -B build-fuzz-native -DSONDE_BUILD_FUZZERS=ON.
The option compiles the whole library with -fsanitize=fuzzer-no-link,address,undefined,
so use a separate build directory.
Adding a target: add fuzz_<name>.cpp to tests/fuzz/, with an
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
function. Add sonde_add_fuzzer(fuzz_<name>) to
tests/fuzz/CMakeLists.txt, put a few
seeds in tests/fuzz/corpus/fuzz_<name>/, and add the name to TARGETS in
run.py. Check invariants with std::abort(), not assert, so they also
work in a release build. Keep per-input work small: a slow target explores
less. Shared state such as a QCoreApplication goes in a static fixture,
created once.
Run the fuzzers for a few minutes after any change to httpparser.cpp,
JSON-RPC dispatch, argument validation, or the JSON conversion code.
The chaos test
The chaos test (design 0029) changes a running application at random (widgets, Qt Quick items, windows, models, short stalls of the main thread) while clients call tools with arguments drawn from their schemas, cancel calls and disconnect. After every step it checks that each request got exactly one well-formed answer, and that a tool’s failure is a tool error, not a protocol error. At the end it checks that the main thread answers and nothing is left behind.
It runs only in a disposable container, never on your machine: nobody has
read what a given seed will do. The program is built only with
SONDE_BUILD_CHAOS, which a normal build leaves off, and refuses to start
without its image’s marker.
python3 tests/chaos/run.py # 3 fixed + 3 random seeds, both modes, 300 steps
python3 tests/chaos/run.py --variant address 42 # one seed, with AddressSanitizer and UBSan
python3 tests/chaos/run.py --steps 1000 --random 10
mise run chaos
run.py builds the image (sonde-chaos-none, -address or -thread) and
runs the seeds in one new container, with --rm, no network, no
capabilities, no new privileges, a read-only root filesystem, and limits on
memory, CPUs and processes. Only build-chaos-out/ is mounted.
- Each run reports what it did (calls, tool errors, cancellations, disconnections, changes to the application), so a run that passed because nothing happened shows.
- A failure prints the seed and the last 200 operations, as JSON lines,
also in
build-chaos-out/. Rerun it withpython3 tests/chaos/run.py --modes 1 <seed>(the mode it failed in). The timing isn’t reproducible, so a seed may not fail every time; the operation log is what turns the bug into an ordinary test, which is where a chaos failure should end up. - CI runs it on every push (the
chaosjob), and nightly with AddressSanitizer (the Chaos workflow, which can also be run by hand with another variant). - ThreadSanitizer is by hand only for the chaos test (the
weekly TSan run covers the designed tests).
Debian’s Qt isn’t built with it, so it
reports races inside Qt’s own threads;
tests/chaos/tsan.suppsilences the ones seen so far, narrowly. Treat a report whose frames are all Qt’s as noise, and one with Sonde frames on top as real.
Documentation comments
cmake --build build --target docs
This runs Doxygen with the Doxyfile configuration and writes
HTML to build/docs/html/index.html. Each published release also puts
them on the website, under api/, with the release’s version (docs.yml). Every class, function, member variable
and enum value must have a doc comment, including private and internal ones.
Any undocumented entity, or a malformed comment, fails the target. Test case
bodies (TEST, TEST_F) are exempt; fixtures and helpers in test files are not.
The style used throughout:
/// @brief One sentence saying what it does.
///
/// Optional details: when to use it, what to watch out for.
/// @param name Only when the meaning isn't obvious from the name.
/// @return Only when it isn't obvious.
QString describe(const QObject *object);
int count = 0; ///< Short description, for members.
Each source file starts with a /// @file block saying what the file is for.
The guides in notes/ are not processed by Doxygen, because it cannot
resolve their GitHub-style section links. The reference’s front page is
notes/api-reference.md, which avoids Markdown links
for that reason.
Known problem: Doxygen 1.18.0 occasionally crashes with “Bus error” (exit status 138) on this project, about one run in six. This is a Doxygen bug, not a documentation problem. Run the target again. Real documentation problems are reported as
warning:orerror:lines that name a file.
Guides like this one live in notes/. If your change affects behaviour a guide
describes, update the guide in the same change.
Worked example: adding a tool
Suppose we want a clipboard_text tool that returns the clipboard’s text.
It needs QtGui, so it belongs in src/gui/ (see
architecture.md, “Where to put new code”).
1. Write the tool. Add it to installWindowTools() in
src/gui/windowtools.cpp, following the other tools there:
// --- clipboard_text -------------------------------------------------------
{
ToolDefinition def;
def.name = QStringLiteral("clipboard_text");
def.title = QStringLiteral("Clipboard text");
def.description = QStringLiteral("The text currently on the clipboard (empty if it holds no text).");
def.annotations = QJsonObject{{QStringLiteral("readOnlyHint"), true}};
server.addTool(def, [](const QJsonObject &) {
return ToolResult::text(QGuiApplication::clipboard()->text());
});
}
Write the description for the AI that will read it. Say what comes back and what happens in the edge cases.
2. Test it. In tests/gui/test_windows.cpp:
TEST_F(GuiTest, ClipboardText)
{
QGuiApplication::clipboard()->setText(QStringLiteral("copied"));
EXPECT_EQ(text(QStringLiteral("clipboard_text")), QStringLiteral("copied"));
}
3. Document it. Add the tool to the table in using.md and in the repository README.
4. Check everything with the list in Before you ask for review.
Worked example: fixing a bug
Suppose input_keys with "é" types É. This really happened. The process:
- Reproduce it in a test. In
tests/gui/test_input.cpp, theKeyPressAndShortcutstest presseséand expects the line edit to containé. Run it and see it fail:cmake --build build && build/tests/sonde_gui_tests --gtest_filter='GuiTest.KeyPressAndShortcuts' - Find the cause.
textForKey()insrc/gui/inputtools.cpplower-cased ASCII letters only. Qt key codes for letters are always upper case, so the non-ASCII branch returnedÉ. - Fix it with the smallest change that makes the test pass. Here, apply the Shift rule to non-ASCII characters too.
- Run the whole suite, clang-tidy and docs, not just the one test.
Debugging tips
- Call tools by hand with
build/sonde <tool> '<json>'(see using.md). - See the protocol traffic. Use the curl commands in
using.md, or the MCP Inspector.
For the local socket, pipe JSON lines through the bridge:
printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"me","version":"1"}}}' \ '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \ | build/tools/bridge/sonde-bridge sonde-widgets-demoThe bridge waits for the answers before it exits.
- Sonde’s own warnings start with
Sonde:and go throughqWarning(), so they also show up inevent_read. - Debug one test in a debugger:
lldb -- build/tests/sonde_core_tests --gtest_filter='HttpTest.ChunkedBodies'(
gdb --args ...on Linux.) - A GUI test only fails on the offscreen platform? Run it with your real platform (see Running tests) to see what happens on screen.
- Widget or item not found? Call
object_treewithvisibleOnly: false. Hidden objects are left out by default.
Before you ask for review
Run all of these and make sure they pass:
mise run check # formatting, build, tests, smoke test, clang-tidy, Doxygen, links
mise run docker-test # Qt 6.8 build + container workflows (needs Docker)
cmake --build build-cov --target coverage # coverage still at or above the bar
mise run check is what the pre-push hook runs. Without mise, run
python3 tools/check.py pre-push. The individual commands are
cmake --build build, ctest --test-dir build, python3 tests/smoke_test.py build,
cmake --build build --target clang-tidy, cmake --build build --target docs
and python3 tests/check_links.py.
If you touched parsing, number conversion or object lifetimes, also run the sanitizers. If you touched the HTTP parser, dispatch or JSON conversion, run the fuzzers for a few minutes too.
Then check your change against reviewing.md. The reviewer will.
Making a release
Releases are made from master, once its CI is green:
- Run the sanitizers (UBSan and ASan) over the whole suite.
- Review the examples. The README’s “See it in action” list should
name the three to five examples that best show what Sonde can do. When
an example has been added or has grown, ask whether it belongs there,
and what it would replace. Check that every folder in
examples/has a README, and a row in examples/README.md. - Make the release commit, “Release X.Y.Z”, with:
- the version in the top-level
CMakeLists.txt; - the changelog’s “Unreleased” heading changed to “X.Y.Z (date)”;
- the versions in the README’s and using.md’s
find_package(Sonde X.Y ...)andGIT_TAG vX.Y.Zlines.
- the version in the top-level
- Tag it
vX.Y.Z, annotated “Sonde X.Y.Z”, and pushmasterand the tag together. - Publish the GitHub release once CI is green, titled “Sonde X.Y.Z”.
Use the changelog section as the notes, with its links made absolute to
the tag (
https://github.com/asgeir/sonde/blob/vX.Y.Z/...). Publishing puts the documentation of that version on the website.