Skip to content

feat(system-tests): serve NTS time to local-backend VMs - #11778

Merged
basvandijk merged 2 commits into
masterfrom
bas/local-backend-nts-time-server
Oct 7, 2026
Merged

basvandijk merged 2 commits into
masterfrom
bas/local-backend-nts-time-server

Conversation

@basvandijk

@basvandijk basvandijk commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator

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 (#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. #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 fix: deflake //rs/tests/query_stats:query_stats_above_threshold_local #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

The VMs of `_local` system tests seed their clocks from QEMU's whole-second
RTC 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. That skew is
what made `query_stats_above_threshold_local` flake (#11771).

The local backend now runs an ntpd-rs time server on each group's gateway and
points the nodes at it. A plain NTP server would be ignored: IC-OS's
chrony.conf pairs NTS servers with plain pools, and under chrony's default
`authselectmode mix` it only adjusts the clock while an NTS source is
selectable (#11265 tried a plain server and reverted it). So the server
answers NTS key exchanges as `time.cloudflare.com`, the first NTS server in
chrony.conf, with a certificate from the dev root CA that dev GuestOS and
HostOS images trust, and the group's dnsmasq resolves that name to the
gateway.

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 7, 2026
@basvandijk
basvandijk requested a balanced review from Copilot October 7, 2026 12:50
@github-actions github-actions Bot added the feat label Oct 7, 2026

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

🟡 Changes recommended

The amd64-only daemon target incorrectly declares compatibility with all Linux architectures.

Review effort: Balanced
Findings: 1 High severity

Open (1)
What changed in this PR

Adds an NTS server to local system-test groups so IC-OS VMs can synchronize clocks.

Changes:

  • Packages and exposes ntpd-rs to local tests.
  • Configures NTS certificates, DNS, startup, and teardown.
  • Reuses the development CA for trusted certificates.
File Description
MODULE.bazel Downloads ntpd-rs.
BUILD.bazel Extracts the NTP daemon.
rs/​tests/​system_tests.bzl Adds the daemon runtime dependency.
rs/​tests/​driver/​src/​driver/​local_backend.rs Runs and manages the NTS server.
rs/​tests/​driver/​src/​driver/​ic_gateway_vm.rs Exposes development CA material internally.

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

Comment thread BUILD.bazel Resolved
The `.deb` it is extracted from is amd64, so on a Linux arm64 host the
target would produce a binary that can't run.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

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

🔵 Needs a closer look

The network, DNS, TLS, and clock synchronization behavior warrants final human review despite no confirmed defects.

Review effort: Balanced
Findings: None

Resolved since last review (1)

@basvandijk
basvandijk marked this pull request as ready for review October 7, 2026 12:58
@basvandijk
basvandijk requested a review from a team as a code owner October 7, 2026 12:58
@github-actions github-actions Bot added the @infra label Oct 7, 2026
@basvandijk
basvandijk added this pull request to the merge queue Oct 7, 2026
Merged via the queue into master with commit 371b4bf Oct 7, 2026
46 checks passed
@basvandijk
basvandijk deleted the bas/local-backend-nts-time-server branch October 7, 2026 14:39
AleDema pushed a commit to AleDema/ic that referenced this pull request Oct 11, 2026
…dfinity#11771)

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](https://github.com/dfinity/ic/blob/1806391241/rs/tests/query_stats/lib/src/aggregation.rs#L112)
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](https://github.com/dfinity/ic/blob/1806391241/rs/consensus/src/consensus/block_maker.rs#L264-L267)).
Peers don't validate a proposal whose timestamp is ahead of their own
clock: `ValidationContextNotReached`, a silent transient error
([validator.rs](https://github.com/dfinity/ic/blob/1806391241/rs/consensus/src/consensus/validator.rs#L1356-L1367)).
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](https://github.com/dfinity/ic/blob/1806391241/rs/consensus/src/consensus/notary.rs#L336-L341)),
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](https://github.com/dfinity/ic/blob/1806391241/rs/query_stats/src/payload_builder.rs#L241-L249)).
Aggregating an epoch needs records from n - f = 3 nodes
([state_machine.rs](https://github.com/dfinity/ic/blob/1806391241/rs/query_stats/src/state_machine.rs#L307-L311)),
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 dfinity#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
dfinity#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 dfinity#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](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
AleDema pushed a commit to AleDema/ic that referenced this pull request Oct 11, 2026
…es_test_local (dfinity#11795)

## Problem

`//rs/tests/consensus/subnet_recovery:sr_nns_failover_nodes_test_local`
flaked twice in the week up to 2026-10-08 (2 of 78 runs, both on
master). Both times it failed the same way in the `ProposeCUP` step: all
three of `ic-admin`'s connection attempts to the parent NNS node's
`:8080` timed out (`Failed to connect to [...]:8080: Elapsed(())`, then
`None of the provided NNS urls are reachable`). In the passing retries
the step took 2-4 s.

## Root cause

The Local backend creates each group's bridge with `ip link add name
{bridge} type bridge`, without specifying a MAC address. It creates each
VM's TAP with `ip tuntap add`, which gives the TAP a random MAC. A Linux
bridge whose MAC was not set explicitly takes the lowest MAC among its
ports, and recomputes it whenever a port is added or removed
(`br_stp_recalculate_bridge_id`). The bridge's MAC is the MAC of the
gateway `<prefix>1`, through which GuestOS reaches the driver's
addresses.

Right before `ProposeCUP`, the test starts the `httpbin` universal VM
that serves the registry tarball. Its TAP is the 10th on the bridge, so
in about 1 of 10 runs it has the lowest MAC and the gateway's MAC
changes under the running guests:
- Their neighbour-cache entries for the gateway keep the old MAC, which
still belongs to another TAP.
- So the bridge passes their frames up as `PACKET_OTHERHOST`, and IPv6
input drops them. The one exception is the guest behind the TAP that
owns the old MAC, whose frames still match.
- A guest only recovers once its own entry for the gateway expires and
is re-resolved. The entry stays REACHABLE for a random 15-45 s, then
goes STALE. The next packets go through 5 s of DELAY and 3 unicast
probes before a multicast solicitation finds the new MAC. The host's
neighbour solicitations come from the bridge's link-local address, so
they don't refresh the entry for `<prefix>1`.
- New connections therefore get through again about 23-53 s after the
flip. Long-lived TCP streams resume only at their next retransmission,
after about 53 s or about 107 s.

`ic-admin` gives up 40 s after its first connection attempt. So the test
fails when the parent NNS node is cut off and its random reachable time
is long.

Both failed attempts show this fingerprint. The driver streams the
journald of the restored IC's 5 nodes. In each failure, within about 0.3
s of the httpbin TAP being attached, 4 of those 5 streams stopped. Five
of these eight streams resumed together, 52.6-52.9 s after the attach.
The other three were still silent when the test ended, including the
second failure's parent NNS node. Meanwhile the serial consoles, the
driver and VM-to-VM traffic carried on. The backlog that the first
failure's parent NNS node delivered once its stream resumed shows its
replica finalizing blocks throughout the gap. The passing retries show
no stall.

The MAC flip is as old as the Local backend; what changed is how long
the outage lasts.
- We have logs for 162 passing attempts of this test and its `_head_nns`
variant from before dfinity#11768. In 21 of them (13%), `ProposeCUP` took 11-40
s instead of 2-4 s.
- These durations mostly match `ic-admin` connecting on a later try: it
tries at 0, 15 and 30 s, for up to 10 s each. Seven attempts got through
only on the third and last try, and two of those (39 s and 40 s) only
seconds before it would have given up.
- In those 21 attempts, the parent NNS node's last traffic with the
driver before the flip was the `DownloadParentNNSStore` rsync. It had
ended 15-37 s earlier, so the parent's gateway entry had less REACHABLE
time left when the MAC changed.

dfinity#11768 dropped the name of the restored IC, so the driver now streams
its nodes' journald. That stream keeps the parent's gateway entry fresh
until the very moment of the flip. Of the 40 attempts that ran with this
change, 4 show the fingerprint of a MAC flip. In 3 of those the parent
NNS node was cut off, and 2 of the 3 failed. dfinity#11778, merged 8 minutes
before dfinity#11768, also added guest traffic to `<prefix>1` by serving NTS
there, and CI can't tell the two changes apart.

## Fix

Give the bridge a fixed, deterministic MAC at creation (`ip link add
name {bridge} address {mac} type bridge`). This sets `addr_assign_type`
to `NET_ADDR_SET`, after which the kernel never recomputes the MAC.

The MAC is `6a:ff:` followed by the first 4 bytes of the digest that
also names the bridge. It can't equal a VM's MAC. VM MACs have a
`NodeType` index as their second byte, both in the backend (`vm_mac`:
`6a:01:…`) and in IC-OS (`calculate_deterministic_mac`: `6a:<index>:…`
or `7a:<index>:…`), and 0xff is not a `NodeType` index.

This also covers VM restarts and reboots: `start_vm` deletes and
recreates the VM's TAP, so a restart could move the gateway MAC too.

## Verification

- **Kernel source and namespace reproductions.** I checked the kernel
source (v6.8 and master) and reproduced the bug in unprivileged network
namespaces on the devenv's kernel 6.8.
- The largest reproduction used a bridge set up like `create_group`,
with 9 veth "guests" streaming TCP to an off-link address on `lo`.
- In 4 of 4 runs, attaching a TAP with the lowest MAC cut 8 of the 9
guests off from the host, for about 53 s or about 107 s. VM-to-VM
traffic was unaffected.
- With a fixed bridge MAC, the MAC never changed and no guest lost
connectivity.
- **A/B runs of the real test on the devenv.** These used throwaway
instrumentation, not part of this PR. It gives the httpbin TAP a MAC
lower than any random TAP MAC (`02:00:00:00:00:01`) and logs the
bridge's MAC around every TAP attach.
- **Without the fix**, attaching httpbin's TAP moved the bridge MAC in 2
of 2 runs (e.g. `0e:3d:07:9f:24:f2` → `02:00:00:00:00:01`). In both runs
the journald streams of 4 of the 5 streamed VMs stopped for 53-55 s. The
one survivor was each time the VM whose TAP held the old bridge MAC.
- In the first run, the parent NNS node was among the stalled VMs, and
`ProposeCUP` took 32 s because 2 of `ic-admin`'s 3 tries failed.
- In the second run, the parent NNS node was the survivor, and
`ProposeCUP` took 3.6 s.
- **With the fix**, the bridge kept its `6a:ff:…` MAC through every TAP
attach, including httpbin's `02:00:00:00:00:01`, in 2 of 2 runs. No
journald stream stalled (largest gap 5.5 s), and `ProposeCUP` took 3.6 s
and 2.1 s.
- The runs were sequential. On the 64-core devenv, 3 concurrent runs of
this test (27 VMs with 6 vCPUs each) slowed the VMs so much that the NNS
canister installation timed out (300 s) in setup.
- **This PR as is.** `bazel test --runs_per_test=3 --local_test_jobs=1
//rs/tests/consensus/subnet_recovery:sr_nns_failover_nodes_test_local`
passed 3 of 3, with `ProposeCUP` taking 2.1-4.8 s.
- `//rs/tests/driver:unit_tests` and `//rs/tests/idx:test_e2e_scenarios`
pass, and `ci/scripts/rust-lint.sh` is clean.

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

🤖 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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants