Skip to content

bench: deterministic rng and hashers; pin and shard the CodSpeed CI - #950

Merged
jlucaso1 merged 5 commits into
mainfrom
perf/bench-determinism
Jul 2, 2026
Merged

jlucaso1 merged 5 commits into
mainfrom
perf/bench-determinism

Conversation

@jlucaso1

@jlucaso1 jlucaso1 commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator

Applies the CodSpeed variance-reduction guidance (regression-causes / reducing-variance / sharded-benchmarks docs) to the bench suite and its CI, after the buffa-merge investigation showed 4 of the 6 reported regressions were measurement artifacts rather than code changes.

Bench code

Deterministic RNG in libsignal_benchmark. All 27 setup sites used rand::make_rng (entropy-seeded), so every run generated different key material. Signature verification is vartime over scalar bits, so the same benchmark legitimately executed a different instruction count on every run. bench_rng() now derives a distinct StdRng stream per call site from a fixed base seed (distinct streams so no two parties ever share keys; deterministic because divan's setup order is fixed).

Measured (callgrind, same binary, two consecutive runs of bench_group_decrypt_message):

run1 vs run2 delta
before (entropy) ~5,960 Ir
after (seeded) ~160 Ir

The residual is divan's wall-time calibration, which the CodSpeed instrumented runner does not execute.

Fixed-seed hashers for bench MemStores. The in-memory stores in send_receive_benchmark and libsignal_benchmark used HashMap with the default RandomState, whose per-process seed shuffles bucket layout, probe sequences, and therefore cache behavior between runs. They now use BuildHasherDefault<DefaultHasher> (SipHash with fixed keys, std-only). Trait-mandated signatures (fetch_prekeys) keep the std type.

send_receive_benchmark already had a deterministic BenchRng; this brings the rest of the suite to the same standard.

CI (codspeed.yml)

  • runs-on pinned to ubuntu-24.04: image drift (glibc, system libs) reads as toolchain-shaped regressions. The Rust toolchain and cargo-codspeed were already pinned.
  • glibc malloc adaptive thresholds frozen (MALLOC_ARENA_MAX/MMAP_THRESHOLD_/TRIM_THRESHOLD_/TOP_PAD_): mmap-vs-brk and trim decisions depend on allocation history and surface as spurious deltas under both instruments.
  • Unit benches sharded into two package-level jobs in the same workflow with the same OIDC auth (core = wacore+noise, proto-signal = binary+libsignal+appstate), roughly halving the serial bench wall time (the single job was taking 30-60 min); CodSpeed merges shards into a single run per the sharded-benchmarks contract.
  • paths-ignore for docs-only changes.

Not done (documented for later)

  • One-binary-per-benchmark (the docs' strongest layout-isolation lever) is impractical at 188 benchmarks; the artifact class it prevents (code-layout shifts on ns-scale benches, e.g. bench_unpad_message_ref swinging -10% on a protobuf-only change) is now understood and cheap to triage instead.
  • The library's internal random_pad_len (1..=16 pad) still adds a few bytes of legitimate per-run variance to send-path benches; benchable-seams for it were not worth the intrusion.

Bench code (codspeed.io/docs -> reducing-variance / regression-causes):
- libsignal_benchmark seeded every run from entropy (27 make_rng sites), so
  vartime signature paths measured different instruction counts per run;
  bench_rng() derives per-call-site StdRng streams from a fixed base seed.
  Run-to-run callgrind variance on bench_group_decrypt_message drops from
  ~6,000 to ~160 Ir (the residual is divan's timer calibration, absent
  under the instrumented runner).
- Bench MemStores hashed with the default RandomState, whose per-process
  seed shuffles bucket layout (and cache behavior) between runs; a fixed
  DefaultHasher keeps the layout stable. Trait-mandated signatures keep
  the std type.

CI (codspeed.yml):
- runs-on pinned to ubuntu-24.04 (image drift shows up as toolchain-shaped
  regressions).
- glibc malloc adaptive thresholds frozen via MALLOC_* env: mmap/trim/arena
  decisions vary with allocation history under both instruments.
- Unit benches split into two package shards in the same workflow (same
  OIDC auth), roughly halving the serial bench wall time; CodSpeed merges
  shards into one run.
- Docs-only changes no longer trigger the workflow.
@coderabbitai

coderabbitai Bot commented Jul 2, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@jlucaso1, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 34 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 6a27cd50-feb0-4188-97d1-c818cdcb1948

📥 Commits

Reviewing files that changed from the base of the PR and between 4acef4b and 22a8bd5.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • .github/workflows/codspeed.yml
  • Cargo.toml
  • wacore/libsignal/benches/libsignal_benchmark.rs
📝 Walkthrough

Walkthrough

Look, benchmarks that aren't reproducible aren't real benchmarks. This PR makes CodSpeed skip doc-only changes, freezes glibc malloc thresholds, and shards the benchmarks job into core and proto-signal matrix runs on ubuntu-24.04. Both benchmark suites now use DetHashMap instead of HashMap and a seeded bench_rng() instead of process-random RNG, so results are actually comparable run to run.

Changes

Deterministic Benchmarks and Sharded CodSpeed Workflow

Layer / File(s) Summary
CodSpeed workflow: path filters, determinism env, sharded matrix
.github/workflows/codspeed.yml
Adds paths-ignore filters, freezes MALLOC_* env vars, shards the benchmarks job into core/proto-signal matrix entries with per-shard cache prefixes and cargo codspeed commands, and moves integration-benchmarks to ubuntu-24.04.
send_receive_benchmark.rs: deterministic hash maps
wacore/benches/send_receive_benchmark.rs
Adds DetState/DetHashMap aliases and switches identity, pre-key, signed pre-key, session, and sender key stores plus User::new initialization to use them.
libsignal_benchmark.rs: deterministic RNG and store setup
wacore/libsignal/benches/libsignal_benchmark.rs
Adds bench_rng() seeded via an atomic counter and DetHashMap aliases, applies them to all in-memory Signal stores.
libsignal_benchmark.rs: bench_rng() applied across benchmarks
wacore/libsignal/benches/libsignal_benchmark.rs
Replaces rand::make_rng::<StdRng>() with bench_rng() across DM, group, signature, out-of-order, promote-matching-session, and backlog benchmark/setup functions.

Estimated code review effort: 2 (Simple) | ~15 minutes

Possibly related PRs

  • oxidezap/whatsapp-rust#828: Migrated these same benchmark suites to the CodSpeed/divan harness that this PR now makes deterministic.
  • oxidezap/whatsapp-rust#858: Touched the same libsignal_benchmark.rs setups/paths that this PR converts to deterministic RNG and hash maps.

Suggested labels: performance

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly captures the two main changes: deterministic benchmarks and CodSpeed CI pinning/sharding.
Description check ✅ Passed The description matches the PR changes and explains both the benchmark determinism work and the CodSpeed CI updates.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/bench-determinism

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Jul 2, 2026

Copy link
Copy Markdown

Greptile Summary

This PR reduces CodSpeed benchmark measurement noise through two complementary mechanisms: replacing entropy-seeded RNG calls with a deterministic counter-based bench_rng(), and switching all benchmark in-memory stores from HashMap<K, V, RandomState> to HashMap<K, V, BuildHasherDefault<DefaultHasher>> so bucket layout is fixed across runs. The CI workflow is hardened with a pinned ubuntu-24.04 runner, frozen glibc malloc thresholds, and a two-shard matrix that halves serial bench wall time while letting CodSpeed merge shard results into one run.

  • Both previously flagged issues are resolved: registration_id now draws from the same deterministic rng (no stray rand::random::<u32>() call), and fail-fast: false is set so a failing shard does not cancel its sibling before it can upload data to CodSpeed.
  • cargo-codspeed is bumped from 4.7.0 to 5.0.1 with matching Cargo.lock updates, and paths-ignore skips doc-only changes to avoid unnecessary bench runs.

Confidence Score: 5/5

Safe to merge — changes are confined to benchmark code and CI configuration with no impact on production paths.

Both previously flagged issues (stray rand::random entropy source for registration_id, and missing fail-fast: false on the matrix) are addressed in this diff. The bench_rng() counter design is sound: the static AtomicU32 starts at 0 each process invocation, divan executes the same iteration sequence under CodSpeed's deterministic runner, so two consecutive CodSpeed runs see an identical seed sequence. DetHashMap correctly substitutes BuildHasherDefault for RandomState across all five stores in both benchmark files.

No files require special attention.

Important Files Changed

Filename Overview
wacore/libsignal/benches/libsignal_benchmark.rs All 27 rand::make_rng / rand::random call sites replaced with deterministic bench_rng(); DetHashMap applied to all five in-memory stores; registration_id now drawn from the same seeded rng.
.github/workflows/codspeed.yml Runner pinned to ubuntu-24.04, MALLOC thresholds frozen, benchmarks split into two shards with fail-fast: false, cargo-codspeed bumped to 5.0.1, paths-ignore added for docs.
wacore/benches/send_receive_benchmark.rs All five MemStore structs switched from HashMap (RandomState) to DetHashMap (BuildHasherDefault); RNG was already deterministic in this file.
Cargo.toml codspeed-divan-compat version bumped from 4.7.0 to 5.0.1 to match the new cargo-codspeed CLI.
Cargo.lock Lock file updated for codspeed* 5.0.1, colored 3.1.1 (drops lazy_static), and removal of windows-sys 0.59.0; all checksums updated.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[CodSpeed trigger] --> B{paths-ignore check}
    B -- docs only --> Z[Skip workflow]
    B -- code changed --> C[Matrix 2 shards]
    C --> D[core shard]
    C --> E[proto-signal shard]
    D --> F[build simulation + memory]
    E --> G[build simulation + memory]
    F --> H[codspeed run]
    G --> I[codspeed run]
    H --> J[CodSpeed merges shards]
    I --> J
    style J fill:#4caf50,color:#fff
    style Z fill:#9e9e9e,color:#fff
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
flowchart TD
    A[CodSpeed trigger] --> B{paths-ignore check}
    B -- docs only --> Z[Skip workflow]
    B -- code changed --> C[Matrix 2 shards]
    C --> D[core shard]
    C --> E[proto-signal shard]
    D --> F[build simulation + memory]
    E --> G[build simulation + memory]
    F --> H[codspeed run]
    G --> I[codspeed run]
    H --> J[CodSpeed merges shards]
    I --> J
    style J fill:#4caf50,color:#fff
    style Z fill:#9e9e9e,color:#fff
Loading

Reviews (2): Last reviewed commit: "bench: random comes from RngExt in rand ..." | Re-trigger Greptile

Comment thread wacore/libsignal/benches/libsignal_benchmark.rs Outdated
Comment thread .github/workflows/codspeed.yml

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4acef4bfe2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread wacore/libsignal/benches/libsignal_benchmark.rs
Comment thread wacore/libsignal/benches/libsignal_benchmark.rs Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.github/workflows/codspeed.yml:
- Around line 69-81: The CodSpeed workflow currently interpolates
matrix.shard.packages directly inside the shell command, which triggers
template-injection risk; update the Build the benchmark targets step and the
CodSpeedHQ/action@v4 run input to read the package list from an environment
variable instead of embedding the expression in the run string. Use the existing
workflow job context to pass matrix.shard.packages into env, then reference that
env variable in both cargo codspeed build and cargo codspeed run so the shell
never sees the raw template expansion.

In `@wacore/libsignal/benches/libsignal_benchmark.rs`:
- Around line 259-264: `User::new` still has a nondeterministic entropy source
because `registration_id` is generated with `rand::random::<u32>()` instead of
the local `bench_rng()`. Update the `registration_id` assignment in `User::new`
to draw from the same benchmark RNG used for `identity_key_pair`, so all
benchmark user state is fully deterministic and consistent.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: ebdaf031-d81e-417a-9631-cfb65357376a

📥 Commits

Reviewing files that changed from the base of the PR and between 0ce4907 and 4acef4b.

📒 Files selected for processing (3)
  • .github/workflows/codspeed.yml
  • wacore/benches/send_receive_benchmark.rs
  • wacore/libsignal/benches/libsignal_benchmark.rs

Comment thread .github/workflows/codspeed.yml
Comment thread wacore/libsignal/benches/libsignal_benchmark.rs Outdated
@github-actions

github-actions Bot commented Jul 2, 2026

Copy link
Copy Markdown

📦 Binary size report

Metric main PR Δ
bin size (stripped) 10.62 MiB 10.62 MiB 0
bin .text 8.65 MiB 8.65 MiB 0
bin allocated (text+data+bss) 10.62 MiB 10.62 MiB 0
llvm-lines wacore 498,015 498,015 0
llvm-lines wacore copies 17,045 17,045 0
llvm-lines whatsapp-rust lib 714,243 714,243 0
llvm-lines whatsapp-rust lib copies 23,185 23,185 0
deps crates (Cargo.lock) 467 466 -1 (-0.21%) 🔽
.text per crate
Crate main PR Δ
.text whatsapp_rust 1.54 MiB 1.54 MiB 0
.text wacore 532.83 KiB 532.83 KiB 0
.text wacore_binary 157.58 KiB 157.58 KiB 0
.text wacore_libsignal 176.46 KiB 176.46 KiB 0
.text wacore_appstate 156.10 KiB 156.10 KiB 0
.text wacore_noise 26.05 KiB 26.05 KiB 0
.text waproto 1.59 MiB 1.59 MiB 0
.text whatsapp_rust_sqlite_storage 479.73 KiB 479.73 KiB 0
.text whatsapp_rust_tokio_transport 43.46 KiB 43.46 KiB 0
.text whatsapp_rust_ureq_http_client 9.05 KiB 9.05 KiB 0
.text std 1007.48 KiB 1007.48 KiB 0
.text other deps 2.94 MiB 2.94 MiB 0

Baseline: 0ce4907b2 (latest main run) · Head: 4ab3309fb · Graphs

@codspeed-hq

codspeed-hq Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will improve performance by 27.59%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

#### 🎉 Hooray! `codspeed-rust` just leveled up to 5.0.1!

A heads-up, this is a breaking change and it might affect your current performance baseline a bit. But here's the exciting part - it's packed with new, cool features and promises improved result stability 🥳!
Curious about what's new? Visit our releases page to delve into all the awesome details about this new version.

⚡ 2 improved benchmarks
✅ 186 untouched benchmarks

Performance Changes

Mode Benchmark BASE HEAD Efficiency
Simulation bench_unpad_message_ref 215.3 ns 165.3 ns +30.25%
Simulation send_and_receive[1] 1,169.1 µs 935.4 µs +24.98%

Tip

Curious why this is faster? Comment @codspeedbot explain why this is faster on this PR, or directly use the CodSpeed MCP with your agent.


Comparing perf/bench-determinism (22a8bd5) with main (0ce4907)

Open in CodSpeed

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 3 files

Confidence score: 4/5

  • In wacore/libsignal/benches/libsignal_benchmark.rs, User::new still uses rand::random::<u32>() for registration_id, so benchmark inputs can vary run-to-run and make performance regressions harder to trust or compare; derive registration_id from the seeded bench rng before merging.
  • In .github/workflows/codspeed.yml, relying on default matrix fail-fast: true can cancel sibling shards after one failure, which hides full benchmark signal and slows diagnosis; set strategy.fail-fast: false so both shard results are always reported.

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread wacore/libsignal/benches/libsignal_benchmark.rs
Comment thread .github/workflows/codspeed.yml
jlucaso1 added 2 commits July 2, 2026 19:19
AtomicU64 is a disallowed type in this repo (no native 64-bit atomics on
Xtensa/ESP32); a u32 counter is plenty for call-site streams. Pin
cargo-codspeed and codspeed-divan-compat to the latest release (5.0.1)
instead of 4.7.0, keeping CLI and harness crates on the same major.
registration_id still drew from the ambient rng and is varint-encoded into
prekey bundles, shifting payload sizes between runs. fail-fast: false keeps
one shard's failure from cancelling the other's upload (CodSpeed merges
shards into one run); the shard package list moves through an env var per
actions hardening guidance.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 4 files (changes from recent commits).

Auto-approved: Benchmark-only changes: deterministic RNG/hashers for reproducibility, CI config (pinned runner, malloc settings, sharding), and minor dev-dependency bumps.

Re-trigger cubic

@jlucaso1
jlucaso1 merged commit d772267 into main Jul 2, 2026
17 checks passed
@jlucaso1
jlucaso1 deleted the perf/bench-determinism branch July 2, 2026 22:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant