Skip to content

Latest commit

 

History

History
269 lines (201 loc) · 11.9 KB

testing.md

File metadata and controls

269 lines (201 loc) · 11.9 KB

Testing

This page is for people who change ycpp and need to know their change is right. It explains each layer of tests, what it checks, how to run it, and how to add to it.

ycpp has one promise that matters more than any other: it behaves like Yjs. Same document, same bytes, same events. A unit test written by hand can only check what its author thought Yjs does. So most of the weight is on tests where real Yjs gives the answer.

The test layers, their inputs and their oracles

Running the tests

meson setup builddir
ninja -C builddir
meson test -C builddir                 # every C++ suite
meson test -C builddir text            # one suite, by name
meson test -C builddir --print-errorlogs

Each tests/test_<name>.cpp is one executable and one meson test named <name> (tests/meson.build). A suite that needs a type is only built when that type is compiled in. For example -Dtext=disabled drops text, update, differential and the suites that need text too; that build still runs the core suites (encoding, doc, monkey, sync, ...).

The Python tests need the extension built (-Dpython=enabled) and installed, or on PYTHONPATH:

python -m pytest python/tests -q
python -m pytest python/tests/pycrdt_suite -q   # on its own, see below

Unit tests

The unit tests use doctest. There is roughly one test file per header: test_encoding.cpp for encoding.hpp, test_text.cpp for text.hpp, and so on. They are plain TEST_CASEs with CHECKs.

Fixture paths come from the TEST_FIXTURE_DIR macro, which tests/meson.build sets to tests/fixtures.

Write a unit test when the right answer is obvious without Yjs: a var-uint of 300 is AC 02, a truncated update is refused, a moved Doc keeps working. When the right answer is "whatever Yjs does", write a differential fixture instead.

Differential tests

A differential test runs real Yjs once, records what it did and what came out, and commits that recording. The C++ test then replays the same input into ycpp and compares the output with Yjs's.

Record in Yjs, commit the fixture, replay in ycpp, compare bytes

The pipeline

  1. A generator script in tests/differential/gen_<topic>.mjs runs in Node with Yjs. The Yjs version is pinned in tests/differential/package.json (13.6.33), and each fixture records it.
  2. The script creates documents with fixed client ids, makes them edit and sync, and captures every update as hex. It also captures Yjs's results: the final state bytes, the state vector, the JSON, and for text the string, the length and the delta after every step.
  3. It writes tests/fixtures/<topic>.json (or a directory, for updates/ and v2/). The fixture is committed. CI never runs Node for these tests.
  4. The C++ test (tests/test_differential.cpp, test_text.cpp, test_update_v2.cpp, ...) parses the fixture with ycpp's own parse_json. It builds a Doc with the same client id and applies the updates in the recorded order.
  5. It compares. The main check is encode_state_as_update() against Yjs's bytes, byte for byte.

Most generators write the fixture of the same name: gen_text.mjs writes text.json, gen_sessions.mjs writes sessions.json. Three exceptions:

  • gen_updates.mjs writes fixtures/updates/*.bin and a manifest.json: one update per content kind, GC and Skip structs.
  • gen_v2.mjs writes fixtures/v2/manifest.json: v1 and v2 bytes of the same documents.
  • gen_pending_corpus.mjs writes fuzzer seeds into tests/fuzz_corpus/.

Why only the recorded order must match byte for byte

The session tests also replay each session in a shuffled order. A shuffled replay must reach the same document: same state vector, same JSON. It does not have to produce Yjs's exact bytes.

That is because Yjs itself does not. When a type is deleted, Yjs turns its children into GC structs if it sees the deletion after them. If the deletion arrived first, the children arrive already deleted and stay as ContentDeleted. So the bytes depend on delivery order, in Yjs too. In the recorded order, ycpp sees exactly what Yjs saw, so it must write exactly what Yjs wrote (check_converged, tests/test_differential.cpp:166).

Hard seeds stay in the suite

Wider concurrency finds rarer bugs. sessions_5peer.json and text_sessions_5peer.json hold five-peer seeds that once diverged. They are regenerated with an explicit seed list, written in the test's comment, for example:

node tests/differential/gen_sessions.mjs --only 81,210,227,244,311 --peers 5 --ops 400
  --out tests/fixtures/sessions_5peer.json

Adding a fixture

  1. Install the generator dependencies once:

    cd tests/differential && npm install
    
  2. Write tests/differential/gen_<topic>.mjs. Copy the closest existing generator. Set doc.clientID explicitly on every document; a random id makes the bytes unreproducible. Record inputs (updates as hex, operations) and Yjs's outputs.

  3. Run it: node tests/differential/gen_<topic>.mjs. Commit the fixture next to the script.

  4. Replay it in a C++ test. Read the file from TEST_FIXTURE_DIR, parse it with parse_json, apply, compare. tests/test_text.cpp and tests/test_differential.cpp show the helpers.

  5. A new test file goes in the test_sources map in tests/meson.build, inside the feature condition it needs.

When Yjs is upgraded, bump package.json, rerun every generator, and read the fixture diffs. A changed fixture means Yjs changed its output, and ycpp must follow.

The monkey test

tests/test_monkey.cpp is adversarial use of the public API. Each case states what a reasonable user expects, then checks it. Examples from the file:

  • an observer that disconnects itself, or applies another update, inside its own callback;
  • an empty key, a 1 MB key, a key with a NUL byte, an invalid UTF-8 key;
  • an Any nested exactly at the depth cap, and one level past it;
  • NaN, infinities, -0, int64 extremes;
  • an update truncated at every byte offset, or with every byte flipped in turn;
  • the same update applied 1000 times; 200 clients delivered in reverse; 1000 documents in a ring.

Where the right answer is genuinely unclear, the test only asks that nothing crashes and the document stays usable.

The fuzzer

tests/fuzz_apply_update.cpp is a libFuzzer target. It hands random bytes to every reader of untrusted input, and checks invariants on whatever is accepted:

Reader Invariant
Doc::apply_update applying twice changes nothing; the state round-trips through its own encoding
Doc::apply_update_v2 the state round-trips through v2
relative positions decode, encode, decode gives the same position; JSON too
snapshots decode, encode, decode gives an equal snapshot; create_doc_from_snapshot survives
sync messages the document stays usable; a reply is accepted by a fresh peer
awareness applying twice invents nothing; expiry and rewriting survive

After a successful apply, it also edits the text at clamped positions, to prove that a hostile document leaves the text core usable. A broken invariant calls __builtin_trap(), which libFuzzer reports as a crash. It is built with AddressSanitizer, so a bad memory access is a crash too.

It needs clang:

CXX=clang++ meson setup builddir-fuzz -Dfuzz=true
ninja -C builddir-fuzz
builddir-fuzz/fuzz_apply_update tests/fuzz_corpus -max_total_time=300

The fuzzer is not a meson test and no CI job runs it. Run it by hand after a change to any decoder.

The corpus lives in tests/fuzz_corpus/. Some seeds come from gen_pending_corpus.mjs; the rest are inputs libFuzzer found interesting. A crash that was found and fixed goes into tests/fuzz_crashers/ and gets a regular unit test that replays it (clock-space-abort.bin, replayed in tests/test_update.cpp:749).

Python tests

The Python binding has its own suites in python/tests/. They test the binding, but they also reach the C++ core through it, from a different angle.

API tests

python/tests/test_*.py are ordinary pytest tests of the Python API. test_fuzz_regressions.py pins cases the state machine below once shrunk: each one regressed once and is asserted directly now, with the bytes Yjs produces.

The vendored pycrdt suite

python/tests/pycrdt_suite/ is pycrdt 0.14.13's own test suite, unchanged. Its conftest.py sets sys.modules["pycrdt"] = ycpp, so the tests import ycpp while thinking it is pycrdt. This checks that ycpp is a drop-in replacement.

Because of that alias, it must run in its own pytest process. pyproject.toml excludes it from the normal run (norecursedirs). The only skipped tests reach Rust internals (PyO3 borrows, private fields); each one is listed with its reason in python/tests/pycrdt_suite/SKIPPED.md.

Random sessions against pycrdt

python/tests/test_random_vs_pycrdt.py builds seeded random operation lists and runs each one through both pycrdt and ycpp, with the same client ids. After every sync the contents must agree. For value types, both libraries write the same bytes, so the update bytes must match too. It is skipped when pycrdt is not installed.

The state machine against a Yjs oracle

python/tests/fuzzing/ is a Hypothesis state machine (test_machine.py). It drives three ycpp peers with random rules: map, array and text edits, formatting, transactions and observers that write back. After every rule it checks invariants: each peer is self-consistent, maps agree with pycrdt, arrays and text agree with Yjs.

The answer for text comes from real Yjs. yjs_oracle.py keeps one Node process alive (node/oracle.mjs) and talks to it in JSON lines. The oracle performs the same operations as each ycpp peer, with the same client id. Replaying ycpp's updates would not be enough: a split inside a surrogate pair only happens when the operation runs locally. Maps are checked against pycrdt instead. Text is not, because Yrs counts text positions in UTF-8 bytes and disagrees with Yjs on non-ASCII text.

Known divergences are counted in KNOWN_DIFFERENCES instead of failing, so the machine still guards everything else (python/tests/fuzzing/session.py:20).

Profiles:

  • default (ci): 100 examples for the property tests; the state machine runs 60 examples of 12 steps.
  • HYPOTHESIS_PROFILE=night: 1000 examples, and the state machine runs 300 examples of 40 steps.
  • YCpp_FUZZ_EXAMPLES=<n> overrides the state machine's example count.

The oracle needs node and the Yjs install under tests/differential/node_modules. Without them, the state machine tests skip.

CI

Three workflows in .github/workflows/:

ci.yml, on every push to main and every pull request:

Job What it proves
GCC 14 release build with -Dwerror=true, full suite, plus the utf8_check self-check
Map only -Dtext=disabled -Darray=disabled still builds and passes
Clang 18, libc++, -Werror the second compiler and standard library (what PRISM's browser build uses)
Clang 18, ASan + UBSan the full suite under sanitizers
arm-none-eabi size scripts/size_check.sh: the code size on a microcontroller

simd.yml, when the UTF-8 code, benchmarks or build files change:

  • builds with -Dsimd=none, sse4.2 and avx2, and runs utf8_check and the full suite on each. utf8_check compares the vector kernels with a plain copy of the WHATWG decoder.
  • builds the Python extension with SSE4.2 (as the wheels are), then runs the C++ suite, the Python suite and the vendored pycrdt suite.

wheels.yml, when Python, source or build files change: builds wheels with cibuildwheel for Linux (x86-64, aarch64), macOS (x86-64, arm64) and Windows, and runs pytest python/tests on each.

What CI does not run:

  • the generator scripts: fixtures are committed and only change when someone reruns them;
  • the fuzzer, nor a replay of its corpus;
  • the Yjs-oracle state machine: no job installs tests/differential/node_modules, so it skips.

Run those by hand when a change touches what they cover.