Skip to content

Latest commit

 

History

History
103 lines (53 loc) · 24.3 KB

testing.md

File metadata and controls

103 lines (53 loc) · 24.3 KB
purpose Implementation notes for testing (node-it ports, load tests, node-tests debugging)

Testing: node-it and node-tests

node-it: published ports

Docker.startNodeInternal publishes only the container ports a suite actually reaches from the host, one explicit PortBinding.randomPort each, never publishAllPorts.

Publishing everything the image EXPOSEs was a real CI failure, not just waste: publishAllPorts binds each of the image's ports on both 0.0.0.0 and ::, taking host ports out of ip_local_port_range, and dockerd shares that range with every outbound connection the test JVM makes. Under CI's parallelism container starts began failing with driver failed programming external connectivity ... failed to listen on TCP socket: address already in use, which aborts the whole suite because startNodeInternal has no retry.

Which ports a node needs is derived from its own resolved config: the REST port always, waves.grpc.port iff waves.extensions contains GRPCServerExtension, waves.blockchain-updates.grpc-port iff it contains BlockchainUpdates. Read that list from actualConfig, never from the suite's own nodeConfig fragment, which does not see template.conf or suiteConfig. The gRPC extension is therefore off in template.conf (extensions = []) and switched on per suite by GrpcIntegrationSuiteWithThreeAddress's createDocker. That override belongs on GrpcIntegrationSuiteWithThreeAddress, not on a narrower trait: a suite that mixes in the former directly would otherwise get no gRPC port.

An exposed-but-unpublished port is a key in docker's port map with an empty binding list, not a missing entry, so externalPort's guard rejects emptiness as well as null; a null check alone lets it through to an IndexOutOfBoundsException: Index: 0 that says nothing about which port was missing.

Two ports do not follow from the config. The node-to-node port is always listening inside the container, but nodes peer over the container network (containerNetworkAddress, and declared-address is the container IP), so it only needs publishing for a suite that speaks the binary protocol from the test JVM itself: override protected def publishNetworkPort = true (a DockerBased hook, e.g. SimpleTransactionsSuite). The debugger port is published only under enableDebugger.

Consequences: NodeInfo.hostNetworkAddress must stay lazy, or constructing any node without a published network port dies; externalPort fails with the port number and the published set rather than an NPE; and a suite that starts using a new port has to say so, by enabling the extension that owns it (the nodeExtensions hook; append to super.nodeExtensions so traits combine) or by adding a hook. Override the DockerBased hooks, not createDocker, or a trait's options are silently lost. Bindings use an empty host ip so they stay dual-stack, since suites connect to localhost, which resolves to ::1 first on some hosts.

Load tests

The @LoadTest-annotated suites (sbt "print node-it/Test/loadTestNames" for the current list) run on a runner of their own (the Run load tests entry of the node-it matrix in check-pr.yaml), through node-it/loadTests and pinned to -Dwaves.it.max-parallel-suites=1; the other entries run node-it/integrationTests, the complement, in shards (below). Do not fold the load suites into an integration entry. Each matrix entry sets its check name explicitly through name, so the required-check names stay stable however the entries are ordered or added.

node-it: a cancelled job must reach sbt

On a cancel (from the UI, cancel-in-progress, or timeout-minutes) the runner sends SIGINT, then SIGTERM, to the step's own process only. With a plain sbt ... line that process is the step's bash, which does not pass the signal on to its foreground child: the step was marked cancelled while sbt and its forked suites kept running through the if: always() steps, until "Cleaning up orphan processes" at the end of the job killed them. The node-it step therefore execs sbt (the sbt launcher script execs java in turn), and cancelable := true makes sbt cancel the running testOnly on SIGINT; the forked suites' shutdown hook (Docker.close) removes their containers. Reproducing this locally needs care: a non-interactive bash starts & jobs with SIGINT ignored and the JVM keeps that, so sbt ... & followed by kill -INT shows nothing; reset SIGINT to the default before exec-ing sbt.

node-it: integration tests are sharded across four runners

-Dwaves.it.shard=i/n (1-based) makes integrationTests run only the untagged suites whose CRC32(fully qualified name) % n == i - 1; without it, all of them. One runner took about 46 min of suite time at 5 parallel suites; two shards take about 26 and 20 (replayed from per-suite test.log durations), plus about 2.5 min each to compile and build the image. The split is by a hash, not by position in a sorted list, because Grpc/Http twin suites sort next to each other and alternating by position put 28 min on one shard and 19 on the other. A hash needs no committed timings file, but nothing balances it either: when one shard drifts well past the others, re-measure and either add a shard or pick suites by recorded duration. Moving from 3 to 4 shards (replayed from the per-suite durations in the TEST-*.xml reports of a green run, 142 untagged suites) cut the slowest shard's suite time from 42 to 35 min; the hash leaves it uneven, with 24, 24, 35 and 30 min. A malformed or out-of-range spec fails the task before anything starts, and an empty shard fails like an empty selection. The shards are entries of the same node-it matrix as the load tests (fail-fast: false, so one failing entry does not cancel the others and lose their results), named Run integration tests (i/n); the shard spec appears in both name and sbt of each entry. Changing the number of shards renames the required checks, so branch protection has to be updated with it.

These suites measure whether a node keeps up with thousands of transactions, so anything else on the same machine turns them into a measurement of the runner. Sharing a 4 vCPU runner with other node-it suites made WideStateGenerationSuite fail consistently: broadcasts slowed to seconds each, and the miner's UTX pool sat near empty while its peers held thousands, so the "UTX is empty" wait never converged.

That last shape looks like a propagation bug and is not one: TransactionSynchronizer feeds network transactions through .whileBusyBuffer(OverflowStrategy.DropNew(maxQueueSize)). A node whose validation pipeline falls behind silently drops incoming transactions, logs nothing, and has no way to re-request them; the sender only re-offers on its own rebroadcast cycle. A CPU-starved miner therefore starves itself of work while its peers hold the pool. Expect this (miner UTX near zero, peers' pools stuck or growing) whenever a node-it suite is resource-starved rather than functionally broken.

Both halves are selected by loadTestNames (project/IntegrationTestsPlugin.scala), which partitions definedTests by isAnnotationPresent through the test classloader: tagging a suite @LoadTest moves it in both directions at once, and there is no tag string in the workflow. The annotation is @Target(ElementType.TYPE) on purpose; discovery is class-level, so a method-level tag would be excluded from the integration job and never selected by the load job, i.e. silently stop running.

Selecting by name rather than by ScalaTest -n/-l tag arguments is deliberate. A renamed or mistyped tag in -n selects nothing, and sbt reports No tests were executed and exits 0: green CI running no load tests. The same drift on -l silently puts the load suites back in the main job. Deriving both halves from one LoadTestTag constant makes a rename a ClassNotFoundException and an empty selection a sys.error. (-n is also bypassed for a suite named on testOnly: ScalaTest rebuilds the filter around Suite.SELECTED_TAG for an explicitly specified suite, so testOnly X -- -n Some.Tag runs X in full.)

loadTests and integrationTests both go through testOnly, both refuse to run an empty selection, and loadTests additionally refuses to start when SCALATEST_EXCLUDE_TAGS would filter out the very tag it selects on.

node-it: is the runner saturated?

Every node-it CI job samples the runner into the uploaded logs while sbt runs: cpu.log (the first line of /proc/pressure/cpu, plus the 1-minute load average, every 5s) and vmstat.log (vmstat -t 5), both in target/out/jvm/u/node-it/logs/<run-id>/. Read them against a timeline of the suites, built from the first and last timestamps of each suite's test.log. Do not use the JUnit XML timestamp/time, which leave out container startup and are misleading. Rough reading: CPU pressure some avg10 well under 20% with vmstat id above 0 means there is room for more parallel suites; a sustained avg10 above about 40%, or a run queue (r) above the vCPU count, means the runner is saturated, which leads to the starvation described under Load tests. Also check wa and free: every node container gets -Xmx2g, so memory can run out before CPU does.

node-it: wait for the transaction, not for the next block

Most node-it suites are slow because of how they wait, not because of how much they check. Before the merge, IssueReissueBurnAssetSuite and its gRPC twin each spent about 4.4 of their 7.5 minutes in height >= N waits (about 105 per suite). Three helpers hide such a wait: waitForHeightAriseAndTxPresent, nodes.waitForHeightArise() after a broadcast, and, less obviously, every SyncGrpcApi broadcast with waitForTx = true, which goes through waitForTxAndHeightArise. The REST waitForTx = true waits only for the transaction. With micro-block-interval = 1s a transaction lands in the liquid block within about a second, and both REST and gRPC serve liquid state (balances, asset info, state changes, transactions by address), so on a single node a plain transaction wait is enough. Keep a block wait only where the API reads solid state (/assets/{id}/distribution), where the test is about heights (rollback, activation, depth), or where another node has to have the block. The default 1s poll in waitForTransaction adds up too: across ~165 waits, polling every 200ms took the merged suite from 4:00 to 3:15. The liquid block is not final, though: the miner can orphan its own newest microblock ("Key block forged on a stale parent" in docs/notes/mining.md), taking its transactions out of the state for about 200ms. Both a broadcast validated against such a transaction and a read of its results fail in that window (CI hit each within two runs), so wait until the next key block is on top of the transaction and it is still at the same height; settled in IssueReissueBurnAssetSuite does that, at the cost of up to one block interval per wait.

node-it: blocks come about every two seconds

template.conf pre-activates FairPoS (feature 8) and BlockV5 (VRF) at height 0, so PoSSelector uses FairPoSCalculator.fromSettings(min-block-time, delay-delta), whose delay is min-block-time + 70s * ln(1 + 5e17 * -ln(hit) / (baseTarget * balance)). min-block-time is a hard floor between blocks; it is 2s rather than mainnet's 15s so height waits stay cheap. The log term is what makes a small stake slow, and it is set by the genesis: with initial-base-target = 50000, node01 mining alone (1e13 wavelets) drew 22s and then 61s delays on CI, and UpdateAssetInfoTransactionGrpcSuite, GrpcReflectionApiSuite and MinerStateTestSuite timed out. At 1000000 a lone 1e13 miner takes about 4s per block (12s at p95) and BiggestMiner (6e15) a flat 2s. FairPoS moves the base target 1% per block only while the 3-block mean delay (whole seconds) is outside [average-block-delay / 2, average-block-delay * 3 / 2]; average-block-delay = 4s makes that 2s to 6s, which covers both, so the base target stays put and later blocks are no slower than early ones (with 10s it fell 1% per block below 5s, and waits grew through a suite). Under Nxt the same base target puts every miner at 1s, so a suite that delays FairPoS (FairPoSTestSuite, until height 10) gets tied blocks from different miners until it activates. TxInBlockchainAwaitTime used to be 8 * average-block-delay and is now a fixed 80s. The test JVM can reach the node 20 blocks later on a loaded runner (SetAssetScriptTxFeatureSuite), so a feature activation height that a test expects not to have been reached yet needs that much margin.

A suite that forges blocks itself (PoSSuite, BlockChallengeSuite, DuplicateFeatureVotesRollbackSuite) must mirror PoSSelector: take the calculator from the node's functionality settings (FairPoSCalculator.V1 only before VRF activates), the target delay from average-block-delay, and the great-grandparent timestamp from the chain, since the base target is validated against all three. All nodes of a suite must agree on the FairPoS activation height, or one rejects the others' blocks on delay.

node-it: a lone miner catches up in a burst

A miner whose last block is older than its next slot forges back-to-back, one block per append, until the block timestamps catch up with the clock ("No pacing between key blocks" in mining.md): up to about 1 minute / min-block-time = 30 blocks in node-it, instantly. It happens after nodes.rollback (the target block is minutes old) and after a slow start (the genesis is now + 12s when the suite builds its config, and container startup can eat more than that). A test that waits for height N and then reads tip-relative data (rewardStatus() with no height, balance rather than balanceAtHeight, "the block at N + 1") can find the chain far past N. Read at the height you mean, and anchor heights to the event (the height waitForTransaction reports), not to a constant. RewardsTestSuite (rewardAt(h)) failed on CI this way.

The same change (scheduleMining after the commit, see mining.md) moved one height check: MinerImpl.scheduleMining lets a light node mine only once supportsLightNodeBlockFields() holds at the current height, which it used to evaluate before the new block was visible, i.e. one block late. A light node now competes for the block right after the fields become supported (LightNodeMiningSuite: activation 2 + absence interval 2, so it may mine block 5, not only from block 6).

node-it: a window of N blocks lasts seconds, not minutes

Every height a suite fixes in its config (a feature activation, the sponsorship switch at FeeSponsorship activation + feature-check-blocks-period, a generation period) now arrives about two seconds per block after genesis, and faster at first: the genesis is dated before the containers start, so the miner forges back to back (about 1s apart on CI, timestamps 7s behind the clock) until the chain catches up. A suite whose test starts at height 3 to 5 is at 8 by its third transaction. CustomFeeTransactionSuite expected its "unsponsored" transfer below a switch at height 8 and sometimes got it sponsored; OneNodeFinalizationTestSuite's single voting transfer missed its three-block period and finality waited 100 blocks for depth. UpdateAssetInfoTransactionSuite expected a second update to be rejected within min-asset-info-update-interval = 2 of the first, with a block wait and an invoke in between, and got it accepted; the interval is now 10 and the check comes right after the update (the boundary itself is covered by AssetTransactionsDiffTest). Size such a window in tens of blocks, assert that the transaction landed inside it (so a miss names the cause), and never let the outcome depend on reaching it before a fixed height.

The test JVM itself is not fast either: the first transaction it signs locally comes 4 to 7s after the previous request on CI (OneNodeFinalizationTestSuite, MassTransferSmartContractSuite, IssueReissueBurnAssetSuite); server-side signing (signCommitToGenerationRequest, createKeyPairServerSide) does not pay it. Put no locally signed transaction inside a window of a few blocks.

Read a transaction back by id, at its height: waitForSettledTransaction waits until a key block covers it at the same height (the miner can orphan its own newest microblock, see above), then blockAt(height), blockById and blockSeq(height, height) all hold it; lastBlock() and utx() hold it only for a moment and .head of either picks whatever is there. Check /blocks/last with checkLastBlockMatchesExplicit, and a pending view only while the transaction is still pending (AmountAsStringSuite.checkPending). Likewise, a batch of transactions spreads over however many blocks its broadcasts take: MicroblocksSponsoredFeeTestSuite read three blocks, the last of them still liquid, while its 50 transfers took four. Settle every transaction and read up to the block after the last one.

node-it: micro-block-interval does not hold the miner back

A test that needs several transactions in the UTX pool before the miner packs any of them cannot get that from a long micro-block-interval. After every key block the microblock sequence restarts with lastMicroBlock = 0 (Miner.startMicroBlockMining), so the first microblock is packed and appended at once, and key blocks come about every two seconds (above); with an empty pool the miner also re-packs every interval / 2. Nothing pauses mining at runtime either: quorum gates only key blocks, and a restart drops the UTX pool. The UTX pool validates each transaction against the chain, not against other pending transactions, so order the broadcasts so that losing the race is harmless. AcceptFailedScriptActivationSuite sent a priority-fee setAssetScript(false) before its invokes; when a key block let it be mined in between, the remaining invokes were rejected (Transaction is not allowed by token-script) instead of being saved as failed. Broadcasting the invokes first and the script change last means a lost race only lets some invokes succeed.

node-tests: finding why a block was rejected

Tests log at OFF by default (node/tests/src/test/resources/logback-test.xml), so an append rejected inside the appender surfaces only as Can't apply block ..., see logs from Domain.appendBlock. Re-run with sbt --server -Dlogback.test.level=TRACE --batch "node-tests/testOnly ..." and grep for the real reason. node-tests run in a forked JVM, so build.sbt forwards the property into its Test / javaOptions; through the thin client (sbt -D..., sbt --client) it never reaches the build.

node-it: the test JVM counts toward the miner quorum

MinerImpl checks waves.miner.quorum against allChannels.size, which includes any connection the test JVM opens over the binary protocol (sendByNetwork), not only peer nodes. A suite that idles its miners with a quorum of exactly nodes.size (each node has nodes.size - 1 peers) gets the quorum reached the moment it connects, and the miner's 5s retry can forge a block that races whatever the suite injects. BlockChallengeSuite lost its injected block to that race on a loaded runner. Use an unreachable quorum instead; BlockChallenger does not check the quorum, so challenge blocks are still forged. Also, do not bound the chain height in an assertion about something else (OneNodeFinalizationTestSuite checked finality by requiring height <= N): the test JVM can stall for 10s under CPU pressure, so wait for the condition itself.

node-it: a slow handshake used to isolate a freshly started node

Until a handshake is accepted a node has no peers (HandshakeHandler puts the channel into peerConnectionsMap only then), and outbound handshakes used to time out after 1s in that state instead of handshake-timeout. A peer that answered later than that on a loaded runner hit HandshakeTimeoutExpired, which suspends its whole host for suspension-residence-time, so a node with two or three peers could suspend all of them and sit isolated. The short timeout bought nothing: while peerConnectionsMap is empty, scheduleConnectTask keeps trying a new candidate every 0.5 to 1.5s anyway, and a pending handshake only occupies one of max-outbound-connections slots. The inbound side always used handshake-timeout.

node-tests: suite resources close when the instance's run completes, not in afterAll

ParallelTestExecution (through OneInstancePerTest) runs every test in a fresh suite instance made by newInstance, which runs the constructor again, and passes runTestInNewInstance = true to it; BeforeAndAfterAll skips both beforeAll and afterAll on such an instance. WithState used to open its RocksDB in the constructor and close it in afterAll, so every test of a ParallelTestExecution suite leaked one rocks-temp-* directory and an open DB (about 1G per node-tests run, enough to fill a tmpfs /tmp and fail unrelated suites with No space left on device). Resources a suite trait owns therefore go through ClosesAfterRun and OnFirstUse (node-testkit): opened on first use, closed when that instance's own run completes or throws, after afterAll. TempRDB is the temp-directory RocksDB that also deletes its directory when the open fails, and TestHelpers.closeAll runs every close step even when an earlier one throws. SharedDomain refuses OneInstancePerTest outright: a per-test instance never runs beforeAll, so each test would silently get an empty domain of its own. TempDbCleanupSpec runs probe suites from code and checks that nothing is left behind.

node-tests: TestScheduler does not keep FIFO order

Monix TestScheduler runs tasks due at the same instant in random order, so two tasks queued back to back on it may run in either order, and a test that relies on that order passes or fails from run to run. The real appender (singleThread("appender")) is FIFO. To pin an ordering on the appender, either let one side finish in its own tick() before queuing the other, or use a real Scheduler.singleThread held behind a latch (see LastMicroBlockSuite, "key block builds on a microblock appended on the appender ahead of the key block attempt"). A Task-based appender call such as MicroblockAppender(...) also takes more than one scheduler hop, so even on a FIFO scheduler its work can land behind a task queued after it; queue a plain runnable when the position matters.

node-tests: TestTime and the genesis timestamp come from different clocks

TestTime() starts at the wall clock, but Domain's genesis (and every TxHelpers transaction) takes its timestamp from TxHelpers.timestamp, a JVM-wide counter that starts at JVM start and moves one millisecond per transaction. In a long forked run it lags the wall clock by minutes, so time.setTimeIfGreater(d.nextBlockTime(...)) leaves the clock far ahead of the chain, forgeBlock dates the key block now - 1 minute, and the next attempt computes a zero offset and forges at once, inside the same scheduler tick. A test that passes alone then fails in testFull or CI (seen in LastMicroBlockSuite: a block3 appeared mid-scenario). Anchor the clock to the chain first, time.setTime(d.lastBlock.header.timestamp), as LastMicroBlockSuite.withThisNodeMiner does. Separately, UtxPoolImpl in Domain uses SystemTime, not the suite's TestTime.

Logs caught with CatchLogs.withLogsOf(cls) come from a JVM-wide logger, so they include other suites running in parallel; filter by thread (a TestScheduler runs its tasks on the test thread).

node-it: finalization suites and generation periods

template.conf sets generation-period-length = 3, so a period lasts about 6s. A CommitToGeneration transaction names the next period and is rejected once the chain enters it ("Expected the next period start height 7, got 4"), so read the next period right after a boundary (nextGenerationPeriodWithMargin), never late in the current one. That moves the committed period, so express every expected height relative to period1.start, not to the initial finalized height or a fixed number. The generators of a period vote from its first block, and the votes carried by a microblock at height h finalize h - 1: one transfer mined at period1.start finalizes period1.start - 1 and nothing more until the next microblock, so period1.start - 1 is the target a single transfer is guaranteed to reach. The test-side FinalityStatus reader rebuilds a period from start and end; only the zero period (starting at activation) includes both ends, every later one ends at start + length - 1 (GenerationPeriod.end), and FinalityStatusSpec pins the round trip.