Skip to content

ci, tests: optimize integration test suite and CI sharding - #9774

Open
daywalker90 wants to merge 39 commits into
ElementsProject:masterfrom
daywalker90:t3/optimize-ci-integration-tests
Open

daywalker90 wants to merge 39 commits into
ElementsProject:masterfrom
daywalker90:t3/optimize-ci-integration-tests

Conversation

@daywalker90

@daywalker90 daywalker90 commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Speeds up Core Lightning's CI integration test pipeline while keeping 100% test coverage and staying within GitHub's 20-runner hosted concurrency limit:

Metric Before After Delta
CI wall-clock time 95.0m 42.0m −53.0m (−55.8%)
Total runner-minutes (53 CI jobs) 1,071m (17.85h) 768.5m (12.81h) −302.5m (−28.2%)
Slowest Valgrind shard ~75m 34.5m −54%

(Measured on full all-green CI runs on this branch.)


What Changed

1. C daemon / plugin fixes & memleak speedup

  • common/memleak.c: Precompute a common_mask over pointer-table entries to reject non-pointer words early during leak scans.
  • openingd / dualopend: Handle dev-memleak while waiting on master replies so teardown leak checks don't stall.
  • connectd: Free unconnected struct subd on peer disconnect (latent leak exposed under faster teardown).
  • plugins/bcli.c: Allocate getutxout script hex on tmpctx instead of attaching an unreferenced copy to response (memleak exposed under ASan).
  • channeld: Exempt WIRE_ANNOUNCEMENT_SIGNATURES from the stfu_wait_single_msg check (matching commit e11c2f6c04 for !stfu_wait_single_msg) and preserve stfu_wait_single_msg so belated announcement_signatures arriving right after STFU quiescence don't disconnect the channel.
  • plugins/rest-plugin: Skip the certificate-generation retry sleep when custom --clnrest-certs are already present.

2. Test harness (pyln-testing) & dev timeout options

  • lightningd / bookkeeper: Add --dev-* timeout/interval knobs (--dev-no-version-checks, --dev-no-plugin-checksum, HTLC/gossip/plugin/bookkeeper tolerance options) and sync dev-bkpr-currencyrate-tolerance into listconfigs.json / schema.json.
  • pyln-testing:
    • Cache loaded JSON schemas across tests/nodes and cache --version output.
    • Run killall memleak checks and node stops in parallel.
    • Shorten initial poll intervals in wait_for / wait_for_logs.
    • Speed up BitcoinRpcProxy and fix a cheroot ready race during fast teardown.
    • Make db_provider session-scoped with per-test cleanup, and make PostgresDb lazy and thread-safe.
    • Under Valgrind: add --vgdb=no, skip Rust LSPS plugins (*cln-lsps-client*, *cln-lsps-service*, matching the other Rust plugins), extend the existing SLOW_MACHINE single-node valgrind_plugins cap from get_nodes() to get_node() as well, and avoid O(N^2) RPC polling in join_nodes().

3. Individual integration test speedups & race fixes

  • Replace blind time.sleep(...) waits with wait_for / sync_blockheight / shorter dev timers across test_coinmoves.py, test_splicing.py, test_currencyrate.py, test_runes.py, test_clnrest.py, test_pay.py, test_invoices.py, test_plugin.py, test_connection.py, test_gossip.py, and test_closing.py.
  • Batch channel creation and reuse networks where safe in test_xpay.py, test_renepay.py, and test_cln_lsps.py.
  • Fix timing races exposed under faster/more-parallel execution and Valgrind (test_splicing_disconnect.py, test_askrene.py, test_gossip.py, test_currencyrate.py, test_xpay.py, test_closing.py).

4. CI workflow & duration-balanced sharding

  • tests/conftest.py + tests/test_durations*.json: Add --balanced-group=G/N LPT (Longest Processing Time) sharding, cap ASan quarantine size (quarantine_size_mb), group memory-heavy tests (xdist_group("heavy")), and gate new xdist test starts when available RAM drops below PYTEST_MIN_AVAIL_MB.
    • New/unlisted tests fall back to the median recorded duration, so adding tests never requires updating the JSON files.
  • .github/scripts/setup.sh: Add TEST_ONLY=1 mode so jobs unpacking prebuilt binaries skip build/lint toolchains while keeping all runtime and test dependencies; remove the unused microsoft-prod apt repo (transient 403s) and enable Acquire::Retries=3.
  • .github/workflows/ci.yaml:
    • Switch first-integration (6), integration-valgrind (16), and integration-sanitizers (6) to --balanced-group.
    • Shard full-integration postgres (3) and liquid (3), and min-btc-support (2).
    • Start integration-valgrind and min-btc-support immediately after compile instead of waiting on first-integration.
    • Drop redundant git submodule sync && git submodule update --init --recursive from the 6 pytest-only jobs (which unpack prebuilt binaries and never compile C submodules), eliminating ~200 simultaneous GitHub clones per run that triggered transient 403 rate limits.

Changelog-None

@daywalker90
daywalker90 force-pushed the t3/optimize-ci-integration-tests branch 6 times, most recently from 91c6bd2 to 42162cf Compare November 27, 2026 21:51
@daywalker90 daywalker90 changed the title Optimize CI integration tests ci, tests: optimize integration test suite and CI sharding Nov 27, 2026
During dev-memleak teardown, scan_for_pointers() tests every pointer-sized
word in every tal allocation against memtable via memleak_ptr(). Previously
each word ran siphash24() and probed the htable even for NULLs, small
integers, and ASCII data, taking ~1.5s per node on debug builds.

Use htable's existing common_mask/common_bits invariant to reject
non-matching words before hashing, and replace siphash24 with a fast
invertible pointer mix for this local-only dev table. Identical leak
detection, ~20x faster dev-memleak.
The autouse jsonschemas fixture was function-scoped, reloading and
compiling all 164 doc/schemas/*.json validators on every test (~150ms
each). Similarly, checkPluginJSON() reloaded all 39 notification and
hook schemas for every node in teardown (~30ms per node).

Make jsonschemas session-scoped and lru_cache _extra_validator() and
_plugin_schemas(). No test mutates the loaded schema dicts, and the
exact same request, response, hook, and notification validations run.
openingd and dualopend can block in wire_sync_read(REQ_FD) while a
plugin hook (such as openchannel/openchannel2) delays master's reply.
If lightningd sends WIRE_OPENINGD_DEV_MEMLEAK (or
WIRE_DUALOPEND_DEV_MEMLEAK) during that window—for example when
NodeFactory.killall() runs dev-memleak concurrently across nodes before
disconnecting peers—the daemon failed with STATUS_FAIL_MASTER_IO
(Error parsing 6105: 1791).

Loop on dev-memleak messages at those wire_sync_read(REQ_FD) call sites,
matching the existing pattern in dualopend.c.
NodeFactory.killall() previously checked dev_memleak and stopped each
node sequentially, multiplying teardown latency by the number of nodes
(especially noticeable on 5-14 node tests and under Valgrind). Run
dev_memleak across all nodes in parallel via self.executor, then stop
all nodes in parallel, preserving deterministic error reporting.

Also cache lightningd --version per executable path in LightningD instead
of spawning a subprocess for every node created.
Cheroot's Server defaults expiration_interval to 0.5s, causing each
BitcoinRpcProxy.stop() to block for up to 500ms. BitcoinD.stop() also
stopped all proxies sequentially before stopping bitcoind, adding ~0.5s
per node to every test teardown (~2.5s on a 6-node test).

Additionally, BitcoinRpcProxy.start() probed TCP connect to check
readiness, which succeeds as soon as cheroot's prepare() calls listen(),
before prepare() finishes starting worker threads and sets
server.ready = True. Fast start=False tests could then enter teardown
and call server.stop() while server.ready was still False, causing
cheroot's stop() to return as a no-op before prepare() set ready = True
and entered serve() forever, deadlocking proxy_thread.join().

Lower expiration_interval to 0.05s, wait for self.server.ready in
start(), bound/retry proxy_thread.join() in stop(), and stop all proxies
concurrently with bitcoind shutdown.
…_for_logs

wait_for() previously started at 0.25s and backed off up to 5s, while
TailableProc.wait_for_logs() polled at a fixed 0.25s and wait_for_route()
polled at 1s. Across thousands of sync_blockheight, node startup, and
log waits, this added substantial idle sleep latency.

Start wait_for() at 0.05s (capped at 1s, or 2s on SLOW_MACHINE), start
wait_for_logs() at 0.02s backing off to 0.25s, and implement
wait_for_route() using wait_for().
…ves.py

check_coin_moves() iterated over enumerate(expected_moves) (so
isinstance(m, list) was always False) and compared expected_count
against all accounts' moves rather than account_id's moves, triggering
an unconditional 5-second sleep on nearly every call. Count per-account
moves properly and poll with wait_for(..., timeout=10) only when lagging.

In test_coinmoves.py, wait for 'onchaind complete, forgetting peer'
before checking final moves instead of sleeping 5 seconds six times.
…cing tests

Ten time.sleep(5) calls in test_splicing.py and test_splicing_disconnect.py
waited to check either that no unilateral close tx was recorded in
channeltxs (only written during chaintopology block processing) or that
channel_funding_inflights cleared.

Replace them with sync_blockheight(bitcoind, [l1, l2]) and wait_for(),
saving ~50s across splicing tests while making the checks deterministic.
- Add --dev-bkpr-currencyrate-tolerance (defaulting to 60s) in bookkeeper
  so test_bkpr_currencyrate_warns_for_old_events can test stale-event
  warning without two 61s sleeps (~116s saved), and wait for the Unix
  second to advance past inv2 before paying inv3 so inv2's 1s cached
  rate does not cover inv3.
- In test_bkpr_currencyrate_persisted, l1.restart() already clears
  cln-currencyrate's cache, so sleep(1) suffices for a new timestamp
  instead of sleep(61) (~60s saved, matching test_bkpr_currencyrate_ranges).
- In test_bkpr_listaccountevents_realtime, wait_for() the datastore entry
  instead of a blind sleep(10) (~9.5s saved).
- In test_currencyrate_rounding, test all three sources on one node
  instead of starting three nodes sequentially, and lower fake_rateserver
  slow_delay from 1s to 0.2s.
- In test_createrune, use rate=30 (2s) and rate=15 (4s) instead of
  rate=3 (20s) and rate=1 (60s), and use a 3s (8s under Valgrind)
  expiry for rune3 instead of 15s, exercising the exact same
  rate_limit_check and last_time_check paths (~108s saved).
- In test_createrune_per_restriction, check all five 2s per-unit runes
  across a single 2.2s sleep instead of five sequential 3s sleeps, and
  verify per=1min stays rate-limited after 2.2s instead of sleeping 61s
  (~75s saved).
…t_behaviors

test_lsps2_mock_transport_behaviors was parametrized across 8 transport
configs, starting a fresh bitcoind and two lightningd nodes for each case
only to call lsps2-mock-configure and lsps0.list_protocols. Run all 8
cases sequentially on a single node pair (lsps2-mock-configure replaces
the config), cutting ~7 node-pair startups/teardowns with identical
coverage.
cln-grpc only writes certificates to the default lightning network
directory, never to a custom --clnrest-certs path. Waiting 5 seconds
(10 x 500ms) before generating certificates in a custom directory
stalled startup unnecessarily. Also poll every 100ms instead of 500ms
when waiting on the default directory so cln-grpc certs are picked up
promptly.
In notifications_received_via_websocket(), sio.connect() already
completes the Socket.IO namespace handshake before returning, so remove
the 2s pre-RPC sleep and replace the 2s post-RPC sleep with wait_for()
on the expected notification key. Also drop the two 2s sleeps in
test_websocket_upgrade_header() where sio.connect() already failed.
- Replace time.sleep(5) with wait_for() on listforwards() in
  test_forward_local_failed_stats and wait_for_logs() on
  dev_ignore_htlcs in test_htlcs_cltv_only_difference.
- Use timeout=2 instead of 10 for the intentional timeout check in
  test_fetchinvoice.
- Use shorter recurrence/expiry/enforcedelay windows (scaling up on
  VALGRIND or SLOW_MACHINE) in test_fetchinvoice_recurrence,
  test_recurrence_expired_offer, test_recurring_currency_invoice_refresh,
  and test_setchannel_enforcement_delay, while still checking 1minutes
  recurrence parsing and next_period calculation.
Add an open_channels() helper that funds all channels in one sendmany
transaction and confirms/announces them in a single block batch, and
replace sequential join_nodes() loops in test_xpay_limited_max_accepted_htlcs,
test_xpay_unknown_next_peer_excludes_node, setup_failing_hub,
test_xpay_maxparts, and test_xpay_maxparts_unannounced_retry (waiting
for l2 to sync l1's public channels via gossip before creating the
unannounced invoice so listincoming includes the routehint). Also use
retry_for=2 instead of 10 for the intentional timeout check in
test_xpay_blockheight_mismatch.
Scale invoice expiry durations down on fast machines (keeping larger
margins under VALGRIND or SLOW_MACHINE) in test_invoice_expiry and
test_expiry_startup_crash, and verify the invoice status is expired
after restart in test_expiry_startup_crash.
Use shorter autoclean-cycle intervals on non-Valgrind runs in
test_autoclean and test_autoclean_batch, poll more frequently in
test_autoclean, and sleep 4s instead of 20s (with an explicit getinfo
liveness check) in test_autoclean_timer_crash.
Instead of spawning 7 separate 14-node networks serially in the heavy
xdist group (98 nodes and 84 sequential join_nodes calls), build one
batched 14-node network and iterate through all 7 (receive_maxparts,
amount_sat) cases using dynamic setconfig, askrene_age, and 2-hop
channel rebalancing between cases. Cast get_option('receive_maxparts')
to int so dynamic setconfig updates work cleanly.
Add --developer options --dev-htlc-offer-timeout-secs (default 30),
--dev-plugin-startup-timeout-secs (default 120), and
--dev-stable-connection-secs (default 60) so integration tests can
exercise these timers without long wall-clock sleeps, leaving production
defaults unchanged.
- Use --dev-htlc-offer-timeout-secs in test_htlc_failed_noclose instead
  of sleeping 35 seconds.
- Synchronize mock_donothing with a threading.Event in
  test_fundee_node_unconfirmed instead of sleeping 10 seconds.
…ifferent_fees

Use node_factory.get_nodes() instead of starting peers sequentially,
and pass allow_bad_gossip=True on peers since l1 closes all four
announced channels before peers finish receiving each other's
channel_announcements.
Use the existing start_channels() helper in test_mpp, test_errors, and
test_limits instead of pairs of sequential join_nodes() calls, and
deduplicate nodes in start_channels().
Wait only until the clock passes after_12 + 1 instead of sleeping 10
seconds unconditionally between creating the two channels.
… by default

Every lightningd startup was spawning all subdaemons with --version and
allocating/reading/CRC32C-hashing ~1 GB of debug plugin binaries, nearly
doubling startup time (~276ms -> ~145ms locally, and much more under
ASan/UBSan). Enable both dev flags unconditionally in LightningNode,
while clearing dev-no-version-checks in test_version_reexec (just as
test_restart_on_update already clears dev-no-plugin-checksum) so both
code paths remain covered.
- Open PostgresDb's psycopg2 connection lazily on first Python query/exec
  instead of eagerly per node (most nodes never query Postgres from Python).
- Fix the missing f-string in PostgresDb.stop(), close the client
  connection, and delegate database removal to PostgresDbProvider.drop_db().
- Guard CREATE/DROP DATABASE with a lock so parallel NodeFactory.get_nodes()
  calls are thread-safe, poll readiness every 50ms instead of 500ms, disable
  unnecessary durability settings for ephemeral test clusters, and add
  ScopedDbProvider for per-test database cleanup.
Reuse one PostgreSQL cluster per pytest worker session instead of running
initdb and starting/stopping a new postgres instance for every single test.
NodeFactory wraps the session provider in ScopedDbProvider so every
database created during a test (including bookkeeper accounts DBs) is
dropped during fixture teardown once all nodes have stopped.
Both disconnect_peer() and destroy_peer_conn() removed unconnected
(subd->conn == NULL) entries from peer->subds via tal_arr_remove()
without calling tal_free(peer->subds[i]), unlike free_all_subds(). That
left the struct subd orphaned under struct peer, triggering a connectd
MEMLEAK if dev-memleak ran before peer was freed (e.g. in
test_restorefrompeer).
json_add_string() copies its string argument into the json_stream buffer,
so allocating tal_hex() on response leaves an unreferenced char[] child
attached to struct json_stream that dev_memleak reports as a leak.
Both cln-currencyrate and tests/plugins/currencyUSDAUD5000.py register
the currencyconvert RPC method at manifest time. Match test_offer,
test_fetchinvoice, and test_recurring_currency_invoice_refresh by
passing disable-plugin=cln-currencyrate in
test_fetchinvoice_invoice_expiry and test_xpay_currency_offer to avoid
a startup duplicate-method race.
Full-suite ASan memory profiling across all 1,328 tests showed that
every unmarked test above ~4.1 GB private USS (or >=3.0 GB with
quarantine_size_mb=16) was either a >=7-node test added after
1a1dc8d or test_commando_stress (5 nodes, 6.0 GB USS).

Under ASan/UBSan (--dist loadgroup -n 4), ungrouped 10-13 node tests
overlapped across workers (test_xpay_maxhops_bolt11 [13],
test_xpay_failing_node_tolerance [10], test_xpay_failing_node_nonfinal
[10], and test_xpay_maxparts_no_mpp_bolt11 [4] = 37 concurrent
lightningd instances, ~15.6 GB on a 16 GB runner), causing OOM.

Mark those 11 tests with @pytest.mark.xdist_group("heavy") so they
serialize on one worker in the ASan job without affecting other jobs.
ASan's default quarantine_size_mb=256 retains up to 256 MB of freed
heap per daemon/plugin process. Profiling the top 25 heaviest tests
under ASan showed that setting ASAN_OPTIONS=quarantine_size_mb=32 cuts
peak private physical RAM (USS) by ~25-45% (e.g.
test_xpay_maxparts 10.0->7.6 GB, test_reservations_leak_under_load
6.9->4.4 GB) while keeping all ASan checks enabled, matching/exceeding
Valgrind's 20 MB freelist-vol default, and with no slowdown.

Also add an opt-in deadlock-free low-memory admission gate in
tests/conftest.py (PYTEST_MIN_AVAIL_MB=4096 in the ASan CI job): when
MemAvailable is healthy, workers run at full -n $(nproc) parallelism
with negligible overhead; if MemAvailable dips below the threshold
(e.g. from a future ungrouped heavy test), newly starting workers wait
for active workers to free memory rather than OOMing the 16 GB runner.
…e join_nodes

- Add *cln-lsps-client* and *cln-lsps-service* to Valgrind's
  --trace-children-skip pattern, matching every other Rust plugin
  (cln-grpc, clnrest, wss-proxy, cln-bip353, cln-currencyrate).
- Pass --vgdb=no to Valgrind to avoid per-process gdbserver FIFO/shm
  setup across thousands of subdaemon and plugin spawns without
  changing Memcheck error detection.
- Extend NodeFactory's SLOW_MACHINE one-node-per-batch valgrind_plugins
  cap to cover individual get_node() and multi-call get_nodes() tests
  (tracing plugins on at least one node per test, rather than every
  node created via individual get_node() calls).
- Avoid O(N^2) getinfo()/listnodes(id) RPC polling at the end of
  NodeFactory.join_nodes().
Pass --dev-plugin-startup-timeout-secs (10s, or 30s under Valgrind) in
test_plugin_slowinit, test_plugin_command, test_failing_plugins, and
test_plugin_startdir_lol, and --dev-stable-connection-secs (25s under
Valgrind, 10s on SLOW_MACHINE, 5s otherwise) in
test_last_stable_connection.
…leak_under_load

300 concurrent HTLCs across 6 Valgrind nodes on a 4-vCPU runner can
briefly exceed connectd's 5s wake-delay threshold; allow the
'connectd: wake delay for' log under VALGRIND.
…ttle

Pass --dev-gossip-cpu-budget=500000 under VALGRIND so Valgrind's ~20x
CPU overhead does not blow the 1500usec dev CPU budget and stall out4
past connectd's ping timeout, while keeping the 1000-byte/s traffic
throttle active.
In test_splice_upgrade_with_pending_splice, connect and wait for
WIRE_CHANNEL_REESTABLISH on both l1 and l2 before calling
bitcoind.generate_block(6), matching test_splice_reconnect_after_lock_no_channel_ready.

Under Valgrind, l1's reconnect could take longer than block generation,
causing l2 to process all 6 blocks while channeld was detached and never
send WIRE_SPLICE_LOCKED after reconnecting.
Random sharding (--test-group-random-seed=42) created wide shard
variance across Valgrind and first-integration shards.

Add a zero-dependency --balanced-group=G/N option in tests/conftest.py
that partitions collected tests via deterministic Longest Processing
Time first (LPT) greedy bin-packing over tests/test_durations.json (and
tests/test_durations_valgrind.json when VALGRIND=1, since CPU-heavy
tests scale much more steeply than sleep-heavy tests under Valgrind):
- Skip-aware weighting prevents skipped slow_test / v2-only items from
  skewing active shard runtime.
- Preserves original collection order within each shard so heavy
  multi-node tests do not all launch simultaneously at t=0.
- New tests not yet in the durations JSON fall back to a default weight
  and deterministically land in exactly one shard.
…n jobs

- Add TEST_ONLY=1 mode to .github/scripts/setup.sh so test-only jobs
  unpacking prebuilt artifacts skip heavy build/lint toolchains while
  keeping all runtime libraries and test tools; remove the unused
  microsoft-prod apt repo (which transiently 403s) and enable apt
  retries.
- Skip redundant 'git submodule sync && git submodule update' in the
  6 pytest-only jobs (40 runners total) that never run make or touch
  external/ C submodules, eliminating ~200 simultaneous GitHub clones
  that can trigger GitHub 403 rate limiting.
- Switch first-integration (6), integration-valgrind (16), and
  integration-sanitizers (6) to --balanced-group=G/N.
- Shard full-integration postgres (3) and liquid (3) plus
  min-btc-support (2).
- Start integration-valgrind and min-btc-support directly after compile
  and enable PYTEST_MIN_AVAIL_MB=4096 as a low-RAM safety net on
  Valgrind runners.
Commit e11c2f6 exempted WIRE_ANNOUNCEMENT_SIGNATURES when in STFU mode with !stfu_wait_single_msg, but missed the stfu_wait_single_msg check immediately below it.

Because announcement_signatures is sent asynchronously via connectd (e.g. right after a prior splice reaches 6 confirmations), it can arrive right after STFU quiescence completes while stfu_wait_single_msg is true, causing channeld to warn and disconnect (seen in test_splice_funding_tx_index_increments under Valgrind).

Exempt WIRE_ANNOUNCEMENT_SIGNATURES from the stfu_wait_single_msg check and preserve stfu_wait_single_msg so the following STFU protocol message is still accepted.
@daywalker90
daywalker90 force-pushed the t3/optimize-ci-integration-tests branch from afb4a8d to 17c4d09 Compare November 27, 2026 23:41
@daywalker90
daywalker90 marked this pull request as ready for review November 27, 2026 23:41

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant