Skip to content

fix: deflake //rs/tests/query_stats:query_stats_above_threshold_local - #11771

Merged
basvandijk merged 2 commits into
masterfrom
ai/deflake-query_stats_above_threshold_local-2026-10-06
Oct 7, 2026
Merged

basvandijk merged 2 commits into
masterfrom
ai/deflake-query_stats_above_threshold_local-2026-10-06

Conversation

@basvandijk

@basvandijk basvandijk commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Raise the application subnet's unit_delay in the query_stats system tests from 200ms to 2s, so that a node whose clock runs ahead of its peers still gets its blocks, and with them its query stats, finalized.

Root cause

//rs/tests/query_stats:query_stats_above_threshold_local was the 2nd most flaky test last week (4 of 74 runs). Every flaky run failed its first attempt at aggregation.rs:112 with:

assertion `left == right` failed
  left: Nat(0)
 right: 4

The chain of events:

  1. The node clocks are skewed. The VMs of _local system tests set their clocks once at boot from QEMU's emulated RTC, which only has whole-second resolution (rtc_cmos 00:03: setting system clock to <second>). chrony is only configured with internet NTS servers and pools, which the sandbox can't reach: in all 40 node boots of the 8 attempts analysed below it logs nothing beyond its start-up lines. So the clocks are never corrected and can stay up to ~2s apart for the whole test.
  2. Peers defer the proposals of a node that is ahead. A block proposal is stamped with its proposer's clock (block_maker.rs). Peers don't validate a proposal whose timestamp is ahead of their own clock: ValidationContextNotReached, a silent transient error (validator.rs). So a rank-0 proposal from a node that is ~1s ahead only becomes valid at its peers ~1s later.
  3. The rank-1 fallback wins. With the test's 200ms unit_delay, the rank-1 block maker proposes after 200ms. The other 3 nodes notarize its block after 400ms (notary.rs), and 3 shares are enough for n=4. The leading node's proposals are therefore never notarized, and it never gets a block finalized.
  4. One reporting node short. A node's query stats only travel in its own block proposals (payload_builder.rs). Aggregating an epoch needs records from n - f = 3 nodes (state_machine.rs), and query_stats_above_threshold queries exactly 3 of the 4 nodes (node 0 never). So when the leading node is one of those 3, no epoch is ever aggregated and canister_status reports 0 query calls.

Evidence

  • No aggregation in the failures. The 4 failing attempts have 0 QueryStats aggregation summary replica log lines. The 4 passing retries have 4 each, logged 1-8s after the last round of queries. The failing attempts streamed logs for another ~45s after that round.

  • Only the clocks differ. Nothing else in the logs differs: no node lagged (all app nodes were in lockstep, well inside the expected epoch at each round), and every queried node, including the leading one, handed its first stats to its payload builder after round 2. So waiting longer, which is what fix: deflake //rs/tests/query_stats:query_stats_basic #9199 did for the same symptom, doesn't help.

  • A queried node leads in every failure. The node-side timestamps of the same Delivering finalized DKG summary at height N events give these leads over the closest other app node:

    attempt leading node lead
    2026-10-01 14:31 (failed) sspm4 (queried) 0.99s
    2026-10-05 13:13 (failed) qzbh4 (queried) 0.78s
    2026-10-06 08:22 (failed) u6tvo (queried) 0.94s
    2026-10-06 09:10 (failed) 5i56c (queried) 0.90s
    the 4 passing retries - ≤ 0.16s

    A node that lags is harmless, e.g. 4jy4s at -0.97s in a passing retry. I also checked the 18 successful runs since 2026-10-05 09:00. In 17 of them no node led its closest peer by more than 0.18s. The exception had a queried node leading by 0.85s: it was an unusually slow run whose leading node got a block in late, and it aggregated 40s after the last round instead of 1-8s.

  • Only this variant flakes. query_stats_basic_local didn't flake: it queries all 4 nodes and so tolerates one node never getting a block in.

  • Deterministic reproduction. See Verification below.

Fix

With unit_delay = 2s:

  • The rank-1 block maker only proposes after 2s, and only if it hasn't validated a rank-0 proposal by then.
  • Peers don't validate a rank-1 proposal before 2s, nor notarize it before 2.2s.
  • The skew is bounded to < 2s by two whole-second truncations: QEMU's RTC and the guest's hctosys. The largest lead seen was 0.99s.
  • So the leading node's rank-0 proposal becomes valid at its peers before a rank-1 block could collect the 3 notarization shares it needs, and the rank-0 block gets notarized instead.

Rounds without a leading node don't get slower: a rank-0 block only waits for initial_notary_delay, which stays at 200ms. A larger unit_delay only costs time in rounds whose rank-0 block maker stalls. In runs with a leading node, that node's rounds now wait until its proposal becomes valid, i.e. about its lead. In the reproduction below that meant ~65s instead of ~40s per 120 blocks, well within the timeouts. Production application subnets use a unit_delay of 1s.

The clock skew itself is a property of the Local backend's VMs, and could be fixed separately, e.g. by not seeding the guest clocks from the RTC or by giving chrony a reachable time source. This is now done by #11778. We still need the larger unit_delay of this PR since the first time sync happens ~30s after chronyd starts before which the query_stats_above_threshold test could have already ran its queries.

Verification

Deterministic reproduction

I used a throwaway change that is not part of this PR. It made unit_delay configurable, and before installing the canister it stepped one app node's clock 1s ahead of the other three. The step used sudo date -u -s over SSH, setting all 4 nodes concurrently right after a second boundary. The leads below were measured afterwards from the DKG-summary timestamps, as above.

unit_delay node stepped ahead its lead over the closest peer result
200ms (master) node 1 (queried) 0.98s ❌ left: Nat(0), right: 4, no aggregation at all, like on CI
2s (this PR) node 1 (queried) 1.03s ✅ aggregated 2.2s after the last round, with records from all 3 queried nodes (aggregatable_records: 3)
200ms (master) node 0 (never queried) 0.96s ✅ control: aggregated 2.3s after the last round, aggregatable_records: 3, so stepping a clock is harmless in itself

An earlier attempt set the clocks one after the other and ran two tests at once. That reached leads of only 0.33s and 0.78s, and both runs passed, the 0.78s one without the leading node's first record (aggregatable_records: 2). Running two tests at once on one machine slows the rounds down. That raises the rank-1 notary delay (it grows with the finality gap), which occasionally lets the leading node win. It is the same effect as the slow passing CI run above.

Normal runs

I ran bazel test --test_output=errors --runs_per_test=3 --jobs=3 //rs/tests/query_stats:query_stats_above_threshold_local on this PR twice. 5 of the 6 runs passed.

The sixth failed in round 1 with Nodes returned different values in round robin query call, before unit_delay comes into play. A node didn't have the canister's data yet 5s after the update call. That is the race #6479 addressed by raising the sleep after the update from 2s to 5s, so it is unrelated to this change. It showed up here because 3 runs on one machine overload it: that run's setup took 85s instead of the usual 35-50s. CI doesn't show it either. The other three _local query_stats tests, which share the same setup and round 1, had 0 non-successes in 140 runs each since 2026-07-27. All 4 recent flakes of this test were Nat(0).


This PR was created following the steps in .claude/skills/fix-flaky-tests/SKILL.md.

🤖 Generated with Claude Code

Raise the application subnet's unit_delay of the query_stats tests from
200ms to 2s. The VMs of local system-tests set their clocks from QEMU's
whole-second RTC at boot and never sync them, so one node can run up to
~2s ahead of the others. Its peers then defer its block proposals until
their clocks reach the proposal's timestamp, and with a 200ms unit_delay
the rank-1 fallback block gets notarized first. Such a node never gets a
block finalized, so its query stats never reach the state. In
query_stats_above_threshold only 3 of the 4 nodes are queried, so if that
node is one of them, no epoch is ever aggregated and the test reads
num_calls_total 0 instead of 4.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@basvandijk basvandijk added the CI_ALL_BAZEL_TARGETS Runs all bazel targets label Oct 6, 2026
@github-actions github-actions Bot added the fix label Oct 6, 2026
@basvandijk
basvandijk requested a balanced review from Copilot October 6, 2026 18:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟢 Approval recommended

The focused configuration change matches the diagnosed consensus timing issue and is supported by deterministic verification.

Review effort: Balanced
Findings: None

What changed in this PR

Raises the Query Stats test subnet delay to prevent clock-skewed nodes from losing block proposals and dropping query statistics.

Changes:

  • Increases unit_delay from 200ms to 2s.
  • Documents the local system-test clock-skew constraint.
File Description
rs/​tests/​query_stats/​lib/​src/​lib.rs Adjusts the shared Query Stats application subnet configuration.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@basvandijk
basvandijk marked this pull request as ready for review October 6, 2026 22:26
@basvandijk
basvandijk requested a review from a team as a code owner October 6, 2026 22:26
@basvandijk
basvandijk added this pull request to the merge queue Oct 7, 2026
Merged via the queue into master with commit a2d823d Oct 7, 2026
43 checks passed
@basvandijk
basvandijk deleted the ai/deflake-query_stats_above_threshold_local-2026-10-06 branch October 7, 2026 14:51
AleDema pushed a commit to AleDema/ic that referenced this pull request Oct 11, 2026
The local system-test backend now runs an NTS time server for each test
group, so the VMs of `_local` system tests synchronize their clocks to
the host, as Farm VMs do with the public time servers.

# Why

The VMs seed their clocks from QEMU's emulated RTC, which only has
whole-second resolution, and their chrony can't reach any time server
from the backend's network namespace. So nodes stay up to ~2s apart for
the whole test. A node whose clock runs ahead has its block proposals
deferred by its peers, which made `query_stats_above_threshold_local`
flake (dfinity#11771).

A plain NTP server is not enough. IC-OS's `chrony.conf` pairs 14 NTS
servers with two plain pools. Under chrony's default `authselectmode
mix`, the NTS sources then get the `require` option, so chrony only
adjusts the clock while an NTS source is selectable. Names that never
resolve count too. dfinity#11265 tried a plain server and reverted it for this
reason ("Can't synchronise: no required source in selectable sources").

# How

- `create_group` starts ntpd-rs, bound to the group's gateway address.
It answers NTS key exchanges (tcp/4460) and NTP (udp/123) and serves the
host's clock as stratum 1 (`local-stratum = 1`). It has no sources of
its own, so it never adjusts the host clock.
- It presents a certificate for `time.cloudflare.com`, the first NTS
server in `chrony.conf`. The certificate is issued from the dev root CA,
which dev GuestOS and HostOS images trust and which the backend already
uses for the IC gateway's certificate.
- The group's dnsmasq resolves `time.cloudflare.com` to the gateway (and
answers its A query with an empty NOERROR).
- `delete_group` stops the server and logs its log, which names every VM
that completed a key exchange. That is the only record for VMs whose
journals are not streamed, such as API boundary nodes and nested HostOS.
- ntpd-rs comes from its 1.9.0 release `.deb` (amd64, so the target is
x86_64-only), extracted like the OVMF firmware.

# Limitations

- **First sync takes ~30s after chronyd starts.** chronyd's first DNS
lookup happens before GuestOS networking is up, and chrony only retries
28s later. Offsets under 1s are then slewed, which takes up to 12s more.
A test whose setup is fast can therefore start before the clocks are in
sync. This is why we still need dfinity#11771:
`query_stats_above_threshold_local` can run its first queries before its
nodes are in sync, so it keeps the larger `unit_delay` that tolerates
the skew.
- **Production images aren't covered.** Production IC-OS images don't
trust the dev CA, so nodes booted from them stay unsynchronized as
before. That includes the mainnet versions some upgrade and
compatibility tests start from. SetupOS doesn't trust the dev CA either,
but its NTP check is already skipped in test images.

# Verification

- chronyd 4.8 (the GuestOS version) with IC-OS's unmodified
`chrony.conf` against this ntpd-rs configuration, in a private network
namespace: the source was NTS-authenticated and selected 8s after start.
- `//rs/tests/query_stats:query_stats_above_threshold_local`, run twice:
all 5 nodes logged `Selected source <gateway> (time.cloudflare.com)`. At
the end of the test, chrony reported a ~2µs offset on every node.
- `//rs/tests/nested:registration_local`: the system node, the API
boundary node and the nested HostOS completed NTS key exchanges. SetupOS
failed the TLS handshake, as expected.

# Side finding

The same `authselectmode mix` rule applies in production: the "INSECURE
POOL (FALLBACK)" in `chrony.conf` never acts as a fallback, because
chrony won't adjust the clock from the pools while no NTS source is
selectable.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
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.

3 participants