diff --git a/.github/actions/install-foundry/action.yml b/.github/actions/install-foundry/action.yml new file mode 100644 index 00000000..738b1e80 --- /dev/null +++ b/.github/actions/install-foundry/action.yml @@ -0,0 +1,19 @@ +name: Install foundry +description: The foundry release named in services/network-smoke/toolchain/foundry-version, checked against its SHA-256, with FOUNDRY_BIN_DIR set for later steps. +runs: + using: composite + steps: + - name: Install foundry + shell: bash + env: + # foundry_v_linux_amd64.tar.gz; change with toolchain/foundry-version. + FOUNDRY_SHA256: 6c66ffcc55fa4249197721baa3098bc208014ea1d8aa04b2ed50ac6bccffb226 + run: | + version=$(cat services/network-smoke/toolchain/foundry-version) + dir="$RUNNER_TEMP/foundry" + mkdir -p "$dir" + curl -fsSL --retry 3 -o "$dir/foundry.tar.gz" \ + "https://github.com/foundry-rs/foundry/releases/download/v${version}/foundry_v${version}_linux_amd64.tar.gz" + echo "$FOUNDRY_SHA256 $dir/foundry.tar.gz" | sha256sum -c - + tar -xzf "$dir/foundry.tar.gz" -C "$dir" + echo "FOUNDRY_BIN_DIR=$dir" >> "$GITHUB_ENV" diff --git a/.github/workflows/network-smoke.yml b/.github/workflows/network-smoke.yml index e4f220a0..847d34b1 100644 --- a/.github/workflows/network-smoke.yml +++ b/.github/workflows/network-smoke.yml @@ -56,6 +56,7 @@ jobs: - '.nvmrc' - '.github/workflows/network-smoke.yml' - '.github/actions/setup-yarn/**' + - '.github/actions/install-foundry/**' - '.github/scripts/check-job-results.sh' smoke: @@ -68,19 +69,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - name: Install foundry - env: - # foundry_v_linux_amd64.tar.gz; change with toolchain/foundry-version. - FOUNDRY_SHA256: 6c66ffcc55fa4249197721baa3098bc208014ea1d8aa04b2ed50ac6bccffb226 - run: | - version=$(cat services/network-smoke/toolchain/foundry-version) - dir="$RUNNER_TEMP/foundry" - mkdir -p "$dir" - curl -fsSL --retry 3 -o "$dir/foundry.tar.gz" \ - "https://github.com/foundry-rs/foundry/releases/download/v${version}/foundry_v${version}_linux_amd64.tar.gz" - echo "$FOUNDRY_SHA256 $dir/foundry.tar.gz" | sha256sum -c - - tar -xzf "$dir/foundry.tar.gz" -C "$dir" - echo "FOUNDRY_BIN_DIR=$dir" >> "$GITHUB_ENV" + - uses: ./.github/actions/install-foundry - uses: ./.github/actions/setup-yarn - name: Build the services, the harness and the runner run: >- @@ -114,10 +103,91 @@ jobs: # Both output directories start with a dot. include-hidden-files: true + smoke-scripted: + name: Explorer pipeline against a scripted pruning node + needs: changes + if: needs.changes.outputs.run == 'true' + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # No foundry and no Aztec toolchain: the scripted mode starts neither. + - uses: ./.github/actions/setup-yarn + - name: Build the services, the harness and the runner + run: >- + yarn workspaces foreach --all --topological-dev + --include '@chicmoz-pkg/*' --include '@chicmoz/test-harness' + --include '@chicmoz/aztec-listener' --include '@chicmoz/explorer-api' + --include '@chicmoz/network-smoke' + run build + - name: Pull the stack images + run: docker compose -f packages/test-harness/compose/compose.yaml --profile infra pull --quiet + - name: Run the scripted smoke + run: yarn smoke:scripted + - name: Keep the run logs + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: network-smoke-scripted + path: | + .network-smoke/*/logs/ + .network-smoke/*/marks.txt + .harness/ + retention-days: 7 + if-no-files-found: ignore + # Both output directories start with a dot. + include-hidden-files: true + + smoke-prune: + name: Explorer pipeline through forced epoch prunes on an Aztec local network + needs: changes + if: needs.changes.outputs.run == 'true' + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: ./.github/actions/install-foundry + - uses: ./.github/actions/setup-yarn + - name: Build the services, the harness and the runner + run: >- + yarn workspaces foreach --all --topological-dev + --include '@chicmoz-pkg/*' --include '@chicmoz/test-harness' + --include '@chicmoz/aztec-listener' --include '@chicmoz/ethereum-listener' + --include '@chicmoz/explorer-api' --include '@chicmoz/websocket-event-publisher' + --include '@chicmoz/network-smoke' + run build + # npm's content cache only; `npm ci` re-checks each tarball against the lock's integrity. + - name: Cache the Aztec toolchain downloads + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~/.npm/_cacache + key: network-smoke-npm-${{ hashFiles('services/network-smoke/toolchain/package-lock.json') }} + - name: Pull the stack images + run: docker compose -f packages/test-harness/compose/compose.yaml --profile infra pull --quiet + - name: Run the prune smoke + run: yarn smoke:prune + - name: Keep the run logs + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: network-smoke-prune + path: | + .network-smoke/*/logs/ + .network-smoke/*/marks.txt + .harness/ + retention-days: 7 + if-no-files-found: ignore + # Both output directories start with a dot. + include-hidden-files: true + status: name: network-smoke-status if: always() - needs: [changes, smoke] + needs: [changes, smoke, smoke-scripted, smoke-prune] runs-on: ubuntu-latest timeout-minutes: 5 steps: @@ -130,4 +200,6 @@ jobs: changes|${{ needs.changes.result }}|success smoke filter|${{ needs.changes.outputs.run }}|bool smoke|${{ needs.smoke.result }}|${{ needs.changes.outputs.run == 'true' && 'success' || 'skipped' }} + smoke-scripted|${{ needs.smoke-scripted.result }}|${{ needs.changes.outputs.run == 'true' && 'success' || 'skipped' }} + smoke-prune|${{ needs.smoke-prune.result }}|${{ needs.changes.outputs.run == 'true' && 'success' || 'skipped' }} run: bash .github/scripts/check-job-results.sh diff --git a/package.json b/package.json index f0e88e31..0207dfa4 100644 --- a/package.json +++ b/package.json @@ -33,6 +33,8 @@ "test:integration": "yarn workspace @chicmoz/test-harness test:integration && yarn workspace @chicmoz/explorer-api test:integration && yarn workspace @chicmoz/aztec-listener test:integration", "harness": "yarn workspace @chicmoz/test-harness harness", "smoke": "yarn workspace @chicmoz/network-smoke smoke", + "smoke:scripted": "yarn workspace @chicmoz/network-smoke smoke:scripted", + "smoke:prune": "yarn workspace @chicmoz/network-smoke smoke:prune", "g:lint": "cd $INIT_CWD && eslint --fix", "postinstall": "husky install", "prepare": "husky install" diff --git a/services/network-smoke/README.md b/services/network-smoke/README.md index cb70eb3d..62acf899 100644 --- a/services/network-smoke/README.md +++ b/services/network-smoke/README.md @@ -7,24 +7,26 @@ End-to-end smoke run of the explorer backend against a real Aztec 6.0.0 local ne ```sh yarn build # the four services, the harness and this package yarn smoke # one run: set up, assert, tear down; exit code is the verdict +yarn smoke:scripted # one run against a scripted node that prunes (see below) +yarn smoke:prune # one run in which the local network prunes (see below) yarn workspace @chicmoz/network-smoke down # clean up a run whose runner was killed (SIGKILL) yarn harness ls | down # compose projects, as for integration tests ``` Needs Linux (`/proc`), Docker with the compose plugin, Node 24 with npm, and foundry at the version in `toolchain/foundry-version` (`anvil` and `forge` on `PATH`, or in `FOUNDRY_BIN_DIR`). The first run installs the Aztec toolchain from `toolchain/package-lock.json` with `npm ci --ignore-scripts` (about 1.2 GB) and reuses it while the lock is unchanged. Later runs take about a minute. -| Variable | Default | Meaning | -| ----------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------ | -| `NETWORK_SMOKE_DIR` | `/.network-smoke` | run directories | -| `NETWORK_SMOKE_TOOLCHAIN_DIR` | `$XDG_CACHE_HOME/chicmoz-network-smoke` (`~/.cache/...`) | one installed toolchain per lock hash; delete old `aztec-*` dirs at will | -| `NETWORK_SMOKE_PORTS` | random free ports below the kernel's ephemeral range | `anvil,aztec,aztecAdmin,aztecP2p,explorerApi,ws,wsHealth`; `wsHealth = ws + 1` | -| `FOUNDRY_BIN_DIR` | `PATH` | directory holding `anvil` and `forge` | +| Variable | Default | Meaning | +| ----------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------ | +| `NETWORK_SMOKE_DIR` | `/.network-smoke` | run directories | +| `NETWORK_SMOKE_TOOLCHAIN_DIR` | `$XDG_CACHE_HOME/chicmoz-network-smoke` (`~/.cache/...`) | one installed toolchain per lock hash; delete old `aztec-*` dirs at will | +| `NETWORK_SMOKE_PORTS` | free ports below the ephemeral range, unlisted in the host registry | `anvil,aztec,aztecAdmin,aztecP2p,explorerApi,ws,wsHealth`; `wsHealth = ws + 1` | +| `FOUNDRY_BIN_DIR` | `PATH` | directory holding `anvil` and `forge` | -Each run gets an id (`ns` + 10 hex) used as its Kafka namespace, its own compose project and databases, and its own process groups, so parallel runs on one host do not collide. Teardown stops only the run's own groups and project, on success, failure, Ctrl-C or SIGTERM. +Each run gets an id (`ns` + 10 hex) used as its Kafka namespace, its own compose project and databases, and its own process groups, so parallel runs on one host do not collide. Its ports are claimed in the host's port registry, `~/.agents/ports.md`, which other tools on the host read and write under the same lock (`src/port-registry.ts`); the claim lasts while the runner lives. Teardown stops only the run's own groups and project and releases its ports, on success, failure, Ctrl-C or SIGTERM. A group that survives SIGKILL keeps the ports claimed and fails the run, as does a release that fails. A run binds every port it claims, `NETWORK_SMOKE_PORTS` too, so it never claims one that a survivor still holds. A known limit: a SIGKILL of the runner ends its claims with its PID while its children run on, so another run can claim a port that a child has not bound yet; closing that gap would take the children's process groups in the registry. ## In CI -`.github/workflows/network-smoke.yml` runs it on pull requests that change what it builds or starts, nightly, and on demand, and reports `network-smoke-status`. It is not a required check. On failure, CI keeps whatever run logs, marks and harness logs exist, for 7 days. +`.github/workflows/network-smoke.yml` runs it, the scripted mode and the prune mode, as three jobs, on pull requests that change what they build or start, nightly, and on demand, and reports all three in `network-smoke-status`. It is not a required check. On failure, CI keeps whatever run logs, marks and harness logs exist, for 7 days. ## What it checks @@ -35,6 +37,65 @@ Each run gets an id (`ns` + 10 hex) used as its Kafka namespace, its own compose 5. `/l2/tips` is not degraded, and its proposed tip has reached that block. 6. No consumer logs three or more handler failures on one topic. One or two can be at-least-once delivery recovering, and the run prints them. +## Scripted mode + +`yarn smoke:scripted` replaces anvil and the Aztec node with a scripted JSON-RPC node (`src/scripted-node.ts`) and starts only `aztec-listener` and `explorer-api`, with the same harness, isolation and teardown. It installs no toolchain and needs no foundry. Before any service starts, it creates the block topic with 3 partitions, so blocks published without a key can reach the API out of order. + +The node serves the SDK's `AztecNodeApiSchema` through the SDK's own server and answers any method it does not implement with "Method not found". Its chain (`src/scripted-chain.ts`) grows blocks 1–10, proves and finalizes 1–6, then prunes 7–10 and grows 7′–12′ on 6. The block that deploys a contract dies at 8; its tx is mined again in 7′. The test (`src/prune.scripted.ts`) steps the node through each state on its control port (the `aztecAdmin` port: `GET /script`, `POST /script/step`), waits up to 30 s for the API to serve what it expects, then until the API's consumers have committed every record the broker held at that point, and checks through REST only what it reads after that: + +1. Heights 1–12 serve the final chain, and nothing exists at 13. +2. `/l2/reorgs` lists one reorg: height 7, 4 blocks, rooted at the dead 7. +3. The moved tx is not dropped, its effect is on 7′, and the contract instance is on 7′. +4. Each dead block is served by its hash, as orphaned. +5. `scripts/compare-chain.ts` finds no mismatch before the prune. After it, `sample` and `window` each read the heights they should (the API's top 40; the node's finalized to proposed tip) and name the first divergence within them, without printing either URL. + +That prune's replacing block is there at once. Then the script prunes the other way: 7′–12′ become proven and finalized, 13′–16′ grow with a tx at 14′, and the node serves the shorter chain, tip 12′, before it proposes 13″ with that tx and grows 13″–16″. The test holds the shorter chain for at least 7 s and until a pass of the listener has handled it, 15 s at most. Holding a longer chain, the SDK's block stream walks back from its own tip, reading heights the node lacks, then rereads the tips in the same pass, so a walk after a tip read that follows a walk is the next pass's, and the first has ended. Tip reads alone show neither, since an election probes nodes it may not follow. The quiet window opens when the node answers the listener's first read of the shorter tip, so what the pass over the old chain sent is stamped before it, and closes when the node moves on. The checks: + +1. While the node serves the shorter chain, a pass of the listener handles it; no block or tips record is stamped in the window, counted by record timestamp once the API has settled, so a record that lands late still counts; and the API keeps serving 13′–16′ and its reorgs from the window's start to just before the node moves on. +2. Heights 13–16 serve 13″–16″, and nothing exists at 17. +3. `/l2/reorgs` lists two reorgs: the first prune's, and height 13, 4 blocks, rooted at the dead 13′. +4. The moved tx is not dropped, and its effect is on 13″. +5. Each dead block is served by its hash, as orphaned. + +Then the script prunes twice more, each time with the replacing block there at once, and the test kills a service while it handles the prune, then starts it again (`src/crash-stops.ts`). It stops the service with a row lock, held from a Postgres session of its own on a row the service writes at that point. Before it kills the service's process group with SIGKILL through the runner (`src/service-control.ts`, on the port scripted mode leaves to anvil), it proves from `pg_stat_activity` and `pg_blocking_pids`, read from a second session, that the service's write is held up by the lock: waiting on it, or queued behind a session that is. The run names each service's Postgres sessions after the service (`PGAPPNAME`, which `pg` sends as `application_name`), and the stop finds the service's writes by that name. It also reads, through SQL and the broker, the state that stop implies (below), and kills only when it is the expected one. It then ends every session the service opened, whatever it is doing, checks that none is left, releases the lock, and starts the service again with the command and environment the run first used. A session never sees its client go, and a statement it had sent, waiting on the lock or not yet, would run once the lock is released, and an autocommit one would commit. So once the kill is sent, if it fails, or ending those sessions fails or leaves one, the scenario fails with the lock still held for the rest of the suite, rather than let that write land in what later scenarios read. A crash scenario after it fails at once, and the run's teardown removes the database. A service that does not reach its stop within 15 s, or reaches it in another state, fails the scenario's first check, and nothing is killed. So does a stop proven after those 15 s: the deadline is checked again just before the kill, since a hook that timed out runs on and its kill would land in a later scenario. The stop's broker reads give up after 10 s, as its SQL statements and connections do. Each restart takes about 30 s: the killed member's Kafka session has to end before the service's consumers join. + +1. **The listener, between sending a batch and storing it** (17″–18″, replaced by 17‴ on 16″). The lock is on the listener store's hash row at height 17. The stop depends on the listener's block stream handler sending a batch's blocks before it stores them, on the SDK's store writing each block's hash before the tip, and on the prune leaving the hash rows above its target as they are. At the kill, the topic holds one more record, and the store is still on 16″, with 17″ at 17. Once restarted, the listener finds the node in sync and sends 17‴ again, under the same key. The checks: those two copies; heights 1–19 serve the node's chain, 17‴–19‴ on top, and nothing exists at 20; `/l2/reorgs` lists three reorgs: the earlier prunes', and height 17, 2 blocks, rooted at the dead 17″; the moved tx is not dropped, and its effect is on 17‴; the contract instance stays on 7′; each dead block is served by its hash, as orphaned. A restart that finds only nodes behind the sent batch is a known limit of the listener, and is not played. +2. **The API, between a block's commit and its offset's** (20‴–21‴, replaced by 20⁗ on 19‴). Once the API's consumers have committed every record, the lock is on the API's rollup-version observation rows, which its block handler upserts after each block it applies. Its catch-up, chain-info, staking-asset and node-info handlers upsert them too, each while its group holds a record it has not committed, and a group handles one record at a time. So the stop counts as reached only when the lock holds up more of the API's upserts than those four groups, counted by id, hold uncommitted records. Each group is judged by its committed offsets, which outlive a member that expired while its handler waited. At the kill, the topic holds one more record, 20⁗ is canonical in the API's database and 20‴–21‴ are not, and the block group's committed offset is still that record's, with no other API group on that partition. The lock stays through the restart, and the check reads the block group's committed offset twice. The first read comes once the restarted API's block handler is held up at the same upsert again, and the offset must still be the record's, which shows the record was consumed again. The second comes after the lock goes, and the offset must be past the record. An early commit before the restart fails the first read. The replayed batch is that record alone, so the replay brings back no dead block and writes no second reorg record; the REST checks are the first crash's, for heights 1–22 and four reorgs, the fourth at height 20. Where the API bumps its chain revision (the key of its cached chain reads) between the commit and that upsert, the kill comes after the bump: a crash between the two is not played, and the API bumps the revision again at start-up. + +A listener without the block stream's store misses the first stop, and one that never sends a prune's replacing block misses the second; either way the scenario fails. + +Before each prune the test waits until the API holds the blocks it removes, with the moved tx's effect (and in the first, its contract) on its dead block, so neither can pass as a first insert. The reorgs it expects are the script's, one per prune played so far, never a list read from the API, which would take in a record the API added between two scenarios. After the last prune, the broker must hold every block record in one of the topic's 3 partitions: steps 2 s apart reach the API in order from any partition, so only the broker shows whether the records share one. Their order within it is not read. + +`logs/scripted-node.log` has each state change and every block lookup with the state it was answered in. + +## Prune mode + +`yarn smoke:prune` starts the same services, toolchain and isolation as `yarn smoke`, with the block topic on 3 partitions, but runs the local network through `toolchain/local-network.mjs`: `createLocalNetwork` with the epoch auto-settle off, which the stock CLI cannot turn off. There the proven and finalized tips move only on `aztecDebug_prove`. Node runs a copy of the launcher from the run directory, whose `node_modules` links to the installed toolchain's. + +`src/force-prune.ts` has the node prune: it proves every checkpoint, builds the doomed blocks, then warps L1 past their epoch's proof window with `RollupCheatCodes.advanceToEpoch`, and the node's archiver removes them. The test (`src/epoch-prune.prune.ts`) plays two scenarios on one network, reading every depth and hash from the run, since tx packing changes them: + +1. **Replaced at once.** The doomed blocks hold two account deployments, which the node mines again at once in a replacing block. Through REST: the canonical chain is the node's, starting from the node's genesis (not the SDK's constant), with nothing above its tip; one reorg, rooted at the first removed height, counting the removed blocks; each tx not dropped, its effect and its account contract on the node's new block; each dead block served by its hash, as orphaned. +2. **A shorter chain.** The doomed blocks are empty, so the node sits on the shorter chain. For 15 s the websocket publisher relays no block and no tips from the listener, and the API keeps the dead blocks canonical, while the listener keeps reading the node: no gap between its tip reads may exceed 4 polls plus the node's hold on a read of the block one past its tip. The run sets that hold (`RPC_UNSEEN_BLOCK_BY_NUMBER_WAIT_MS`) to 6 s, twice the block duration, as the node defaults to, so a walk back over the shorter chain waits as it would in production. Then one tx makes the node build at the first pruned height, and the API applies the prune: the node's chain above the target, one reorg rooted at the first dead block, the dead blocks orphaned. + +The listener reads the node through `src/rpc-tap.ts`, a pass-through proxy on the run's `aztecAdmin` port that records each of its reads of the proposed tip in `logs/rpc-tap.jsonl`. From those reads each scenario prints which state of its prune the listener read first: `listener order: shorter-chain-first` (the tip at the prune target, before the replacement) or `listener order: replacement-first`, by the earliest answer that shows either, whichever request went out first. The node builds the replacement 0.15–0.35 s after the prune, so either can happen; the checks hold for both. + +Each scenario starts once the API agrees with the node up to the proven base, so it judges its own prune. The deployments publish their account instances, which an account deployment skips by default, after one deployment publishes the account class: without that the explorer stores no contract to check. + +## compare-chain + +`scripts/compare-chain.ts` checks, read-only, that an explorer API's canonical chain is a node's. Node 24 runs it directly: + +```sh +COMPARE_NODE_URL= COMPARE_API_URL= node scripts/compare-chain.ts sample | window | reorgs | watch +``` + +- `sample`: the API's top 40 heights against the node's hashes. It reads the node's tips before and after, and marks the sample `blind` if they moved. +- `window`: every height from the node's finalized tip to its proposed tip, one API call every 2 s. +- `reorgs`: each `/l2/reorgs` record whose dead root block is still on the node's chain. +- `watch`: `sample` every minute, `reorgs` every 10 minutes and `window` every hour, until stopped. A failed check is reported and skips only itself. It reports a witnessed prune at a height where the API and the node agree on a hash other than the one they last agreed on there; only samples that are not blind count. + +Each check prints one JSON line, with the first mismatch and the count; a one-shot check exits 1 on a mismatch and 2 when a call fails. `COMPARE_API_URL` is a base URL without a query. Each request to either side gives up after `COMPARE_TIMEOUT_MS` (15 s by default), and a node read gets one attempt. The URLs can hold an API key, so they are never printed: a failed node call prints only its operation and its HTTP status or timeout (the SDK's message names the host and can quote the server's error body), a failed API call its path and status, and every line is printed with both URLs redacted. A server can echo a key inside a valid answer, such as a hex key as a block hash, so each path segment, query value and fragment of 8 characters or more is redacted on its own too, raw or decoded, in any case. + ## Reading a failure - Marks with elapsed seconds go to stdout and to `/marks.txt`. The last mark shows the stage that failed. @@ -47,8 +108,13 @@ Each run gets an id (`ns` + 10 hex) used as its Kafka namespace, its own compose - **The local network is not a live network.** - The automine sequencer builds one block per checkpoint, only when transactions arrive, and warps L1 time to each slot. - The proven tip moves by a storage write, so no `L2ProofVerified` event is emitted and nothing proof-related is checked. - - There are no multi-block checkpoints and no reorgs. -- **Interfaces.** anvil binds `127.0.0.1`. The node's RPC and admin ports, explorer-api and the websocket publisher have no host option and listen on all interfaces. The admin API keeps authentication on with a random key hash generated per run, and the network holds only the public test accounts. Run it on a host whose network you trust. + - There are no multi-block checkpoints. The only reorgs are the epoch prunes `yarn smoke:prune` forces, by warping L1 time, not by an L1 reorg. +- **Interfaces.** anvil and the prune mode's launcher bind `127.0.0.1`; the launcher serves no admin API. The stock node's RPC and admin ports, explorer-api and the websocket publisher have no host option and listen on all interfaces. The admin API keeps authentication on with a random key hash generated per run, and the network holds only the public test accounts. Run it on a host whose network you trust. - **Kills and supply chain.** - - A SIGKILL of the runner leaves its processes and project for `down `. A kill during the harness's `up()` leaves a labelled project for `yarn harness down`. A kill during the first toolchain install can leave `npm ci` running and an `aztec-*.tmp-` directory in the toolchain dir. + - A SIGKILL of the runner leaves its processes, its project and, during the first toolchain install, its `aztec-*.tmp-` staging directory in the toolchain dir, for `down `. `down` looks in the toolchain dir of its own environment, so it needs the run's `NETWORK_SMOKE_TOOLCHAIN_DIR`, and fails on a toolchain dir it cannot read. A kill during the harness's `up()` leaves a labelled project for `yarn harness down`. + - Known limits: the `npm ci` such a kill orphans is not stopped; it exits on its own, and can write into the staging directory again if it outlives `down`. A kill before `up()` starts the first container can leave the project's network or volumes, which `yarn harness ls` and `yarn harness down` do not see, since they go by containers. - `yarn npm audit` does not cover the toolchain's npm tree. +- **Known limits of the checks.** + - The broker reads that settle the API and count the quiet window's records run on KafkaJS's request timeout and retries, not on the settle's 30 s. A broker that stalls still fails the run, but on Vitest's hook timeout, whose message names no partition or group. + - The API crash's replay check samples the block group's committed offset, and does not trace when a commit is issued. A commit that lands between the sample at the record and the unlock passes for the replay's. + - `listener order` is informational. The tap reads each reply whole on the event loop that relays the tip reads, so a slow reply can delay a pass and the state it sees first. A tip read without a hash, between the prune target and the old tip, counts as the replacement, though the old chain held that height too. Either can change the printed order, never a check: the checks hold for both orders. diff --git a/services/network-smoke/package.json b/services/network-smoke/package.json index b8c801ac..cc0e195b 100644 --- a/services/network-smoke/package.json +++ b/services/network-smoke/package.json @@ -13,15 +13,24 @@ "test": "vitest run --dir src", "test-once": "vitest run --dir src", "smoke": "node build/cli.js run", + "smoke:scripted": "node build/cli.js run scripted", + "smoke:prune": "node build/cli.js run prune", "down": "node build/cli.js down" }, "dependencies": { "@aztec-foundation/l1-artifacts": "6.0.0", "@aztec-labs/accounts": "6.0.0", "@aztec-labs/aztec.js": "6.0.0", + "@aztec-labs/ethereum": "6.0.0", + "@aztec-labs/foundation": "6.0.0", + "@aztec-labs/stdlib": "6.0.0", "@aztec-labs/wallets": "6.0.0", + "@chicmoz-pkg/message-registry": "workspace:^", "@chicmoz-pkg/types": "workspace:^", "@chicmoz/test-harness": "workspace:^", + "bson": "6.2.0", + "kafkajs": "2.2.4", + "pg": "8.11.3", "viem": "2.20.0", "vite": "8.3.8", "vitest": "5.1.0", @@ -30,6 +39,7 @@ }, "devDependencies": { "@types/node": "24.19.2", + "@types/pg": "8.11.8", "@types/ws": "8.5.12", "@typescript-eslint/eslint-plugin": "6.11.0", "@typescript-eslint/parser": "6.11.0", diff --git a/services/network-smoke/scripts/compare-chain.ts b/services/network-smoke/scripts/compare-chain.ts new file mode 100644 index 00000000..847932b5 --- /dev/null +++ b/services/network-smoke/scripts/compare-chain.ts @@ -0,0 +1,410 @@ +/** + * Read-only check that the explorer API's canonical chain is the node's. + * + * COMPARE_NODE_URL=… COMPARE_API_URL=… node scripts/compare-chain.ts + * + * - `sample`: the API's top 40 heights, in 20-block calls, against the + * node's hashes there. The node's tips are read before and after; the + * sample is `blind` if they moved. + * - `window`: every height from the node's finalized tip to its proposed + * tip, one API call every 2 s. + * - `reorgs`: each `/l2/reorgs` record whose dead root the node still has. + * - `watch`: `sample` every 60 s, `reorgs` every 10 min and `window` every + * hour, until stopped. A height where the API and the node agree on a + * hash other than the one they last agreed on, both in samples that are + * not blind, is reported as a witnessed prune. + * + * Each check prints one JSON line; a one-shot check exits 1 when it finds a + * mismatch. COMPARE_API_URL is a base URL without a query; each request to + * either side gives up after COMPARE_TIMEOUT_MS (15 s). The URLs can hold + * credentials: they are read from the environment and never printed. A + * failed node call prints only its operation and its HTTP status or timeout, + * and every line is printed with the URLs' parts redacted. + */ +import { BlockNumber } from "@aztec-labs/aztec.js/fields"; +import { createAztecNodeClient } from "@aztec-labs/aztec.js/node"; +import { jsonStringify } from "@aztec-labs/foundation/json-rpc"; +import { setLogLevel } from "@aztec-labs/foundation/log"; +import { + chicmozL2BlockLightSchema, + chicmozReorgSchema, +} from "@chicmoz-pkg/types"; +import { z } from "zod"; + +const SAMPLE_HEIGHTS = 40; +// The API's widest range (DB_MAX_BLOCKS); `to` is exclusive. +const API_PAGE = 20; +// The node's widest getBlocks (MAX_RPC_BLOCKS_LEN). +const NODE_PAGE = 50; +const WINDOW_GAP_MS = 2_000; +const MINUTE = 60_000; + +const env = z + .object({ + COMPARE_NODE_URL: z.string().url(), + COMPARE_API_URL: z.string().url(), + COMPARE_TIMEOUT_MS: z.coerce.number().int().positive().default(15_000), + }) + .safeParse(process.env); +if (!env.success) { + process.stderr.write( + "compare-chain: set COMPARE_NODE_URL (an Aztec node's JSON-RPC) and COMPARE_API_URL (the explorer API's base URL); COMPARE_TIMEOUT_MS, if set, is a positive integer\n", + ); + process.exit(2); +} +const { + COMPARE_NODE_URL: nodeUrl, + COMPARE_API_URL: apiUrl, + COMPARE_TIMEOUT_MS: timeoutMs, +} = env.data; + +const decoded = (part: string) => { + try { + return decodeURIComponent(part); + } catch { + return part; + } +}; + +// Below this, a path segment, query value or fragment is redacted only as part +// of its URL, so a segment like `v1` does not blank every line. +const MIN_PART = 8; + +// A server can echo any one part of a URL alone, even inside a valid answer +// (a hex key as a block hash), so each part is redacted on its own, raw and +// decoded, besides the whole URL; the host and the hostname too, since an +// error can name either. +const partsOf = (u: string) => { + const url = new URL(u); + const { href, host, hostname, pathname, search, hash, username, password } = + url; + const pieces = [ + ...pathname.split("/"), + ...search + .slice(1) + .split("&") + .map((p) => p.slice(p.indexOf("=") + 1)), + ...url.searchParams.values(), + hash, + hash.slice(1), + ] + .flatMap((p) => [p, decoded(p)]) + .filter((p) => p.length >= MIN_PART); + return [ + u, + href, + host, + hostname, + pathname.length > 1 ? pathname : "", + search, + username, + decoded(username), + password, + decoded(password), + ...pieces, + ]; +}; +const secrets = [ + ...new Set( + [nodeUrl, apiUrl] + .flatMap(partsOf) + // As it reads inside a printed JSON string. + .flatMap((s) => [s, JSON.stringify(s).slice(1, -1)]) + .filter((s) => s.length > 0), + ), +].sort((a, b) => b.length - a.length); +// Blind to case: hashes are printed in lowercase. +const secretPattern = new RegExp( + secrets.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), + "gi", +); +const redact = (text: string) => text.replace(secretPattern, ""); + +const print = (line: Record) => + process.stdout.write( + `${redact(JSON.stringify({ at: new Date().toISOString(), ...line }))}\n`, + ); + +const timedOut = (e: unknown) => (e as Error).name === "TimeoutError"; + +/** + * The SDK client's transport, with a deadline its own fetch has no way to + * set, and one attempt per read: a check reports a failed read, and `watch` + * reads again on its next round. Its errors are fixed text. + */ +const nodeFetch = async ( + host: string, + body: unknown, + extraHeaders: Record = {}, +) => { + let res: Response; + try { + res = await fetch(host, { + method: "POST", + body: jsonStringify(body), + headers: { "content-type": "application/json", ...extraHeaders }, + signal: AbortSignal.timeout(timeoutMs), + }); + } catch (e) { + throw new Error(timedOut(e) ? "timed out" : "request failed"); + } + if (!res.ok) { + throw new Error(`HTTP ${res.status}`); + } + try { + return { response: (await res.json()) as unknown, headers: res.headers }; + } catch (e) { + throw new Error(timedOut(e) ? "timed out" : "not JSON"); + } +}; + +// The SDK's client logs a failed request with the node's full URL. +setLogLevel("silent"); +const node = createAztecNodeClient(nodeUrl, { fetch: nodeFetch }); + +const NODE_FAILURE = /^(HTTP \d{3}|timed out)$/; + +/** + * A node error can carry the server's own message, which can echo a key; + * only the operation and a status or a timeout leave. + */ +const nodeCall = async (operation: string, call: () => Promise) => { + try { + return await call(); + } catch (e) { + const detail = NODE_FAILURE.exec((e as Error).message)?.[1]; + throw new Error(`node ${operation} failed${detail ? `: ${detail}` : ""}`); + } +}; + +const api = async (path: string): Promise => { + let res: Response; + try { + res = await fetch(`${apiUrl.replace(/\/+$/, "")}${path}`, { + signal: AbortSignal.timeout(timeoutMs), + }); + } catch (e) { + // fetch's message can quote the URL. + throw new Error( + `API ${path}: ${timedOut(e) ? "timed out" : "request failed"}`, + ); + } + if (!res.ok) { + throw new Error(`API ${path}: HTTP ${res.status}`); + } + try { + return (await res.json()) as unknown; + } catch (e) { + throw new Error(`API ${path}: ${timedOut(e) ? "timed out" : "not JSON"}`); + } +}; + +/** A parse error can quote what the API sent, which can echo a key. */ +const apiParsed = async ( + path: string, + schema: z.ZodType, +): Promise => { + const body = await api(path); + try { + return schema.parse(body); + } catch { + throw new Error(`API ${path}: invalid response`); + } +}; + +type Tips = Awaited>; + +const chainTips = () => nodeCall("getChainTips", () => node.getChainTips()); + +const tipsView = (t: Tips) => ({ + proposed: Number(t.proposed.number), + checkpointed: Number(t.checkpointed.block.number), + proven: Number(t.proven.block.number), + finalized: Number(t.finalized.block.number), + hashes: [ + t.proposed.hash, + t.checkpointed.block.hash, + t.proven.block.hash, + t.finalized.block.hash, + ], +}); + +/** Canonical hashes per height in [from, to], as the API serves them; a height may list two. */ +const apiHashes = async (from: number, to: number, gapMs = 0) => { + const hashes = new Map(); + for (let start = from; start <= to; start += API_PAGE) { + if (start > from && gapMs > 0) { + await new Promise((r) => setTimeout(r, gapMs)); + } + const end = Math.min(start + API_PAGE, to + 1); + const blocks = await apiParsed( + `/l2/blocks?from=${start}&to=${end}`, + z.array(chicmozL2BlockLightSchema), + ); + for (const b of blocks) { + const height = Number(b.height); + hashes.set(height, [...(hashes.get(height) ?? []), b.hash.toLowerCase()]); + } + } + return hashes; +}; + +const nodeHashes = async (from: number, to: number) => { + const hashes = new Map(); + for (let start = from; start <= to; start += NODE_PAGE) { + const blocks = await nodeCall("getBlocks", () => + node.getBlocks(BlockNumber(start), Math.min(NODE_PAGE, to - start + 1)), + ); + for (const b of blocks) { + hashes.set(Number(b.number), b.hash.toString().toLowerCase()); + } + } + return hashes; +}; + +type Mismatch = { height: number; api: string[]; node: string | null }; + +const compare = async (from: number, to: number, gapMs = 0) => { + const before = tipsView(await chainTips()); + const fromApi = await apiHashes(from, to, gapMs); + const fromNode = await nodeHashes(from, to); + const after = tipsView(await chainTips()); + const mismatches: Mismatch[] = []; + for (let height = from; height <= to; height++) { + const a = fromApi.get(height) ?? []; + const n = fromNode.get(height) ?? null; + const agree = a.length === 0 ? n === null : a.length === 1 && a[0] === n; + if (!agree) { + mismatches.push({ height, api: a, node: n }); + } + } + return { + from, + to, + tips: after, + blind: JSON.stringify(before) !== JSON.stringify(after), + mismatches, + fromApi, + fromNode, + }; +}; + +const report = ( + check: string, + { from, to, tips, blind, mismatches }: Awaited>, +) => { + print({ + check, + from, + to, + tips: { ...tips, hashes: undefined }, + blind, + firstMismatch: mismatches[0] ?? null, + mismatches: mismatches.length, + }); + return mismatches.length === 0; +}; + +const latestApiHeight = () => apiParsed("/l2/latest-height", z.number().int()); + +const sample = async () => { + const top = await latestApiHeight(); + return compare(Math.max(1, top - SAMPLE_HEIGHTS + 1), top); +}; + +const windowCheck = async () => { + const tips = tipsView(await chainTips()); + return compare(Math.max(1, tips.finalized), tips.proposed, WINDOW_GAP_MS); +}; + +const reorgs = async () => { + const records = await apiParsed("/l2/reorgs", z.array(chicmozReorgSchema)); + const stillOnChain: { height: number; hash: string }[] = []; + for (const r of records) { + const height = Number(r.height); + const hash = r.orphanedBlockHash.toLowerCase(); + if ((await nodeHashes(height, height)).get(height) === hash) { + stillOnChain.push({ height, hash }); + } + } + print({ check: "reorgs", records: records.length, stillOnChain }); + return stillOnChain.length === 0; +}; + +const watch = async () => { + let stopped = false; + for (const signal of ["SIGINT", "SIGTERM"] as const) { + process.once(signal, () => (stopped = true)); + } + // A failed check is reported and skips only itself. + const attempt = async (check: string, work: () => Promise) => { + try { + await work(); + } catch (e) { + print({ check, error: (e as Error).message }); + } + }; + // Per height, the hash the API and the node last agreed on. + const agreed = new Map(); + let lastReorgs = 0; + let lastWindow = 0; + while (!stopped) { + const started = Date.now(); + await attempt("sample", async () => { + const s = await sample(); + report("sample", s); + if (s.blind) { + return; + } + for (let height = s.from; height <= s.to; height++) { + const onApi = s.fromApi.get(height) ?? []; + const onNode = s.fromNode.get(height); + if (onNode === undefined || onApi.length !== 1 || onApi[0] !== onNode) { + continue; + } + const before = agreed.get(height); + if (before !== undefined && before !== onNode) { + print({ check: "prune-witnessed", height, before, after: onNode }); + } + agreed.set(height, onNode); + } + }); + if (started - lastReorgs >= 10 * MINUTE) { + lastReorgs = started; + await attempt("reorgs", reorgs); + } + if (started - lastWindow >= 60 * MINUTE) { + lastWindow = started; + await attempt("window", async () => + report("window", await windowCheck()), + ); + } + while (!stopped && Date.now() - started < MINUTE) { + await new Promise((r) => setTimeout(r, 500)); + } + } +}; + +const checks: Record Promise> = { + sample: async () => report("sample", await sample()), + window: async () => report("window", await windowCheck()), + reorgs, + watch: async () => { + await watch(); + return true; + }, +}; + +const check = checks[process.argv[2] ?? ""]; +if (!check) { + process.stderr.write( + "usage: compare-chain.ts sample | window | reorgs | watch\n", + ); + process.exit(2); +} +try { + process.exitCode = (await check()) ? 0 : 1; +} catch (e) { + print({ check: process.argv[2], error: (e as Error).message }); + process.exitCode = 2; +} diff --git a/services/network-smoke/src/broker.test.ts b/services/network-smoke/src/broker.test.ts new file mode 100644 index 00000000..049defdf --- /dev/null +++ b/services/network-smoke/src/broker.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from "vitest"; +import { bounded, lateGroups } from "./broker.js"; + +describe("a broker read", () => { + it("gives up once its time runs out", async () => { + await expect( + bounded("a read", () => new Promise(() => undefined), 20), + ).rejects.toThrow("a read: no answer from the broker within 0.02 s"); + }); +}); + +describe("judging consumer groups", () => { + it("counts a group with a record it has not committed, whatever its state, and no group without one", () => { + expect( + lateGroups([ + // Its member expired while its handler held offset 5. + { + groupId: "expired-holding", + state: "Empty", + partitions: [{ committed: 5, low: 0, end: 6 }], + }, + { + groupId: "expired-idle", + state: "Empty", + partitions: [{ committed: 6, low: 0, end: 6 }], + }, + { + groupId: "rejoining-idle", + state: "PreparingRebalance", + partitions: [{ committed: 6, low: 0, end: 6 }], + }, + { + groupId: "stable-holding", + state: "Stable", + partitions: [{ committed: -1, low: 2, end: 3 }], + }, + { groupId: "unknown", state: "Empty", partitions: [] }, + { groupId: "absent", state: "Dead", partitions: [] }, + { groupId: "stable-idle", state: "Stable", partitions: [] }, + ]), + ).toEqual(["expired-holding", "stable-holding", "unknown"]); + }); +}); diff --git a/services/network-smoke/src/broker.ts b/services/network-smoke/src/broker.ts new file mode 100644 index 00000000..33f442fd --- /dev/null +++ b/services/network-smoke/src/broker.ts @@ -0,0 +1,352 @@ +import { randomUUID } from "node:crypto"; +import { setTimeout as sleep } from "node:timers/promises"; +import { AssignerProtocol, Kafka, logLevel } from "kafkajs"; +import { z } from "zod"; + +export const brokerAccessSchema = z.object({ + brokers: z.string(), + username: z.string(), + password: z.string(), + /** The block topic, under the run's namespace. */ + blockTopic: z.string(), + /** The listener's tips topic, under the run's namespace. */ + tipsTopic: z.string(), + /** Every consumer group of the explorer API starts with it. */ + apiGroupPrefix: z.string(), +}); + +export type BrokerAccess = z.infer; + +/** A partition a group is assigned, and its end offset when it was read. */ +type Mark = { + group: string; + topic: string; + partition: number; + low: number; + end: number; +}; + +/** A consumer group, and each partition of the topics it has committed on or is assigned: the offset it committed there (-1 for none), and the partition's low and end offsets. */ +export type GroupOffsets = { + groupId: string; + state: string; + partitions: { committed: number; low: number; end: number }[]; +}; + +/** + * The groups that have not committed a record published before the read, + * which their handler may still hold. Committed offsets outlive a group's + * members, so a group whose member expired is judged as any other. One with + * no partition to judge counts, unless it is stable or does not exist. + */ +export const lateGroups = (groups: GroupOffsets[]) => + groups + .filter(({ state, partitions }) => + partitions.length === 0 + ? state !== "Stable" && state !== "Dead" + : partitions.some( + ({ committed, low, end }) => + (committed < 0 ? low : committed) < end, + ), + ) + .map((g) => g.groupId); + +// The admin reads a crash stop makes give up after this, as the harness's +// SQL does: KafkaJS retries a request for far longer on its own. +const READ_TIMEOUT_MS = 10_000; + +/** `read`'s answer, or a throw naming `what` once `ms` pass without one. */ +export const bounded = async ( + what: string, + read: () => Promise, + ms = READ_TIMEOUT_MS, +): Promise => { + let timer: NodeJS.Timeout | undefined; + try { + return await Promise.race([ + read(), + new Promise((_, reject) => { + timer = setTimeout( + () => + reject( + new Error( + `${what}: no answer from the broker within ${ms / 1000} s`, + ), + ), + ms, + ); + }), + ]); + } finally { + clearTimeout(timer); + } +}; + +/** Offsets and consumer groups on the run's broker, read through the admin API, and a partition's records (`recordsOf`), read by a consumer of a group of its own. */ +export const brokerReads = ({ + brokers, + username, + password, + apiGroupPrefix, +}: BrokerAccess) => { + const kafka = new Kafka({ + clientId: "network-smoke", + brokers: brokers.split(","), + sasl: { mechanism: "plain", username, password }, + logLevel: logLevel.NOTHING, + }); + const admin = kafka.admin(); + let connected: Promise | undefined; + const ready = () => (connected ??= admin.connect()); + + const ends = async (topic: string) => + (await admin.fetchTopicOffsets(topic)).map((p) => ({ + partition: p.partition, + low: Number(p.low), + high: Number(p.high), + })); + + /** The end offset, now, of each partition the API's groups are assigned; `unsettled` names groups without a stable assignment. */ + const apiMarks = async () => { + await ready(); + const ids = (await admin.listGroups()).groups + .map((g) => g.groupId) + .filter((id) => id.startsWith(apiGroupPrefix)); + const unsettled = + ids.length === 0 ? [`no group starts with ${apiGroupPrefix}`] : []; + const marks: Mark[] = []; + const { groups } = await admin.describeGroups(ids); + for (const group of groups) { + if (group.state !== "Stable" || group.members.length === 0) { + unsettled.push(`${group.groupId} (${group.state})`); + continue; + } + const topics = new Set( + group.members.flatMap((m) => + Object.keys( + AssignerProtocol.MemberAssignment.decode(m.memberAssignment) + ?.assignment ?? {}, + ), + ), + ); + for (const topic of topics) { + for (const { partition, low, high } of await ends(topic)) { + marks.push({ + group: group.groupId, + topic, + partition, + low, + end: high, + }); + } + } + } + return { marks, unsettled }; + }; + + /** The marks a group has not committed through, with the offset it has. */ + const behind = async (marks: Mark[]) => { + const late: (Mark & { committed: number })[] = []; + const pairs = new Set(marks.map((m) => `${m.group}\n${m.topic}`)); + for (const pair of pairs) { + const [groupId, topic] = pair.split("\n"); + const [committed] = await admin.fetchOffsets({ + groupId, + topics: [topic], + }); + for (const m of marks.filter( + (m) => m.group === groupId && m.topic === topic, + )) { + const offset = Number( + committed?.partitions.find((p) => p.partition === m.partition) + ?.offset ?? -1, + ); + const at = offset < 0 ? m.low : offset; + if (at < m.end) { + late.push({ ...m, committed: at }); + } + } + } + return late; + }; + + return { + /** Each partition of `topic`'s end offset: the offset its next record gets (`bounded`). */ + endOffsets: (topic: string) => + bounded(`the end offsets of ${topic}`, async () => { + await ready(); + return new Map((await ends(topic)).map((p) => [p.partition, p.high])); + }), + /** + * The offsets the API's groups have committed on `topic`, per group and + * partition: the next record each would consume (`bounded`). Committed + * offsets outlive the group's members, so this reads a crashed + * consumer's too. + */ + apiCommitted: (topic: string) => + bounded(`the API's offsets on ${topic}`, async () => { + await ready(); + const ids = (await admin.listGroups()).groups + .map((g) => g.groupId) + .filter((id) => id.startsWith(apiGroupPrefix)); + const committed = new Map>(); + for (const groupId of ids) { + const [offsets] = await admin.fetchOffsets({ + groupId, + topics: [topic], + }); + const held = (offsets?.partitions ?? []) + .map((p) => [p.partition, Number(p.offset)] as const) + .filter(([, offset]) => offset >= 0); + if (held.length > 0) { + committed.set(groupId, new Map(held)); + } + } + return committed; + }), + /** The late ones (`lateGroups`) of `groupIds`, whatever their state (`bounded`). */ + groupsBehind: (groupIds: string[]) => + bounded("the groups behind", async () => { + await ready(); + const { groups } = await admin.describeGroups(groupIds); + const judged: GroupOffsets[] = []; + for (const { groupId, state, members } of groups) { + // Without a topic list: every topic the group has committed on. + const committed = await admin.fetchOffsets({ groupId }); + const topics = new Set([ + ...committed.map((t) => t.topic), + ...members.flatMap((m) => + Object.keys( + AssignerProtocol.MemberAssignment.decode(m.memberAssignment) + ?.assignment ?? {}, + ), + ), + ]); + const partitions: GroupOffsets["partitions"] = []; + for (const topic of topics) { + const own = committed.find((t) => t.topic === topic)?.partitions; + for (const { partition, low, high } of await ends(topic)) { + partitions.push({ + committed: Number( + own?.find((p) => p.partition === partition)?.offset ?? -1, + ), + low, + end: high, + }); + } + } + judged.push({ groupId, state, partitions }); + } + return lateGroups(judged); + }), + /** + * The records of one partition of `topic` from offset `from` up to `to`, + * read by a consumer of a group of its own; throws if they are not all + * there within `timeoutMs`. + */ + recordsOf: async ( + topic: string, + partition: number, + { from, to }: { from: number; to: number }, + timeoutMs = 30_000, + ) => { + const consumer = kafka.consumer({ + groupId: `network-smoke-reader-${randomUUID()}`, + }); + const found = new Map(); + let all: () => void = () => undefined; + const complete = new Promise((resolve) => (all = resolve)); + try { + await consumer.connect(); + await consumer.subscribe({ topic, fromBeginning: true }); + await consumer.run({ + eachMessage: ({ partition: p, message }) => { + const offset = Number(message.offset); + if (p === partition && offset >= from && offset < to) { + found.set(offset, { + key: message.key ?? undefined, + value: message.value ?? undefined, + }); + if (found.size === to - from) { + all(); + } + } + return Promise.resolve(); + }, + }); + if (to > from) { + const timedOut = sleep(timeoutMs).then(() => "timed out" as const); + if ((await Promise.race([complete, timedOut])) === "timed out") { + throw new Error( + `${topic} partition ${partition}: ${found.size} of the ${to - from} records from offset ${from} in ${timeoutMs / 1000} s`, + ); + } + } + } finally { + await consumer.disconnect(); + } + return [...found.entries()] + .sort(([a], [b]) => a - b) + .map(([offset, record]) => ({ offset, ...record })); + }, + /** How many records each partition of `topic` holds. */ + recordsPerPartition: async (topic: string) => { + await ready(); + return (await ends(topic)).map(({ partition, low, high }) => ({ + partition, + records: high - low, + })); + }, + /** + * How many records of `topic` carry a timestamp in [from, to), by the + * clock of the host whose producers stamped them. A record counts once it + * has landed, whenever that is. + */ + publishedBetween: async (topic: string, from: number, to: number) => { + await ready(); + // Per partition, the first offset stamped at or after `at`. + const before = async (at: number) => + (await admin.fetchTopicOffsetsByTimestamp(topic, at)).reduce( + (sum, { offset }) => sum + Number(offset), + 0, + ); + return (await before(to)) - (await before(from)); + }, + /** + * Takes the end offsets of the API's assigned partitions once, then waits + * until its groups have committed through them; throws with what is + * still behind after `timeoutMs`. Records published after the call + * (tips, node liveness) do not hold it up. + */ + apiConsumedThrough: async (timeoutMs: number) => { + const deadline = Date.now() + timeoutMs; + let taken = await apiMarks(); + while (taken.unsettled.length > 0 && Date.now() < deadline) { + await sleep(500); + taken = await apiMarks(); + } + if (taken.unsettled.length > 0) { + throw new Error( + `the API's consumer groups have no stable assignment: ${taken.unsettled.join(", ")}`, + ); + } + let late = await behind(taken.marks); + while (late.length > 0 && Date.now() < deadline) { + await sleep(500); + late = await behind(taken.marks); + } + if (late.length > 0) { + throw new Error( + `the API did not commit through these offsets within ${timeoutMs / 1000} s: ${JSON.stringify(late)}`, + ); + } + }, + close: async () => { + if (connected) { + await admin.disconnect(); + } + }, + }; +}; + +export type BrokerReads = ReturnType; diff --git a/services/network-smoke/src/cli.ts b/services/network-smoke/src/cli.ts index 78a1597b..91df6610 100644 --- a/services/network-smoke/src/cli.ts +++ b/services/network-smoke/src/cli.ts @@ -1,11 +1,13 @@ -import { existsSync, readFileSync } from "node:fs"; +import { existsSync, readFileSync, rmSync } from "node:fs"; import { platform } from "node:os"; import { join } from "node:path"; import { downProject } from "@chicmoz/test-harness"; import { readConfig } from "./config.js"; +import { releasePorts } from "./port-registry.js"; import { ownerAlive, readPgids, stopGroup } from "./processes.js"; import { RUN_ID_PATTERN, type RunRecord, run } from "./run.js"; import { removeTmpDir, tmpDirs } from "./tmp.js"; +import { stagingDirs } from "./toolchain.js"; const HARNESS_RUN_ID = /^ih[0-9a-f]{10}$/; @@ -29,6 +31,8 @@ const down = async (runId: string) => { ); } const stuck: number[] = []; + let released = false; + let stagingError: Error | undefined; try { for (const pgid of readPgids(runDir).reverse()) { if (!(await stopGroup(pgid, runId))) { @@ -60,25 +64,81 @@ const down = async (runId: string) => { for (const dir of Object.values(tmpDirs(runId, runDir))) { removeTmpDir(dir); } + // A failure here fails `down`, but only once the ports are released. + try { + for (const dir of stagingDirs(readConfig().toolchainDir, runId)) { + rmSync(dir, { recursive: true, force: true }); + process.stdout.write( + `removed the toolchain staging directory ${dir}\n`, + ); + } + } catch (e) { + stagingError = e as Error; + } + // Only once every group stopped: a survivor may still bind a port. + released = stuck.length === 0 && (await releasePorts(runId)); + } + if (stagingError) { + throw new Error( + `run ${runId} is not down: its toolchain staging directories were not removed: ${stagingError.message}`, + ); } if (stuck.length > 0) { - throw new Error(`run ${runId} is not down: process groups survived`); + throw new Error( + `run ${runId} is not down: process groups survived, so its port claims stay listed (their runner is gone, so other tools may reap them)`, + ); + } + if (!released) { + throw new Error( + `run ${runId} is not down: its port claims could not be released`, + ); } process.stdout.write(`run ${runId} is down\n`); }; -const [command, arg] = process.argv.slice(2); +const portOf = (value: string) => { + const port = Number(value); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error(`"${value}" is not a port`); + } + return port; +}; + +const [command, ...args] = process.argv.slice(2); const main = async () => { - if (command === "run") { - process.exitCode = await run(); + if (command === "run" && args.length === 0) { + process.exitCode = await run("network"); return; } - if (command === "down" && arg) { - await down(arg); + if ( + command === "run" && + args.length === 1 && + (args[0] === "scripted" || args[0] === "prune") + ) { + process.exitCode = await run(args[0]); + return; + } + if (command === "down" && args.length === 1) { + await down(args[0]); + return; + } + // A child of `run scripted`; it serves until the run stops its group. + if (command === "scripted-node" && args.length === 2) { + // Imported here, so `run` and `down` never load the SDK. + const { startScriptedNode } = await import("./scripted-node.js"); + const node = await startScriptedNode({ + rpcPort: portOf(args[0]), + controlPort: portOf(args[1]), + }); + process.stdout.write( + `scripted node: rpc ${node.rpcUrl}, control ${node.controlUrl}\n`, + ); return; } - throw new Error("usage: cli.js run | cli.js down "); + throw new Error( + "usage: cli.js run [scripted | prune] | cli.js down | cli.js scripted-node ", + ); }; main().catch((e: Error) => { diff --git a/services/network-smoke/src/compare-chain.test.ts b/services/network-smoke/src/compare-chain.test.ts new file mode 100644 index 00000000..5902cfbe --- /dev/null +++ b/services/network-smoke/src/compare-chain.test.ts @@ -0,0 +1,231 @@ +import { execFile } from "node:child_process"; +import { type IncomingMessage, type Server, createServer } from "node:http"; +import { type AddressInfo } from "node:net"; +import { fileURLToPath } from "node:url"; +import { loadFixture } from "@chicmoz/test-harness"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { startScriptedNode } from "./scripted-node.js"; + +const SCRIPT = fileURLToPath( + new URL("../scripts/compare-chain.ts", import.meta.url), +); + +const KEYS = ["usr-5c1e", "pwd-5c1e", "pth-5c1e", "qry-5c1e"]; +const [USER, PASSWORD, PATH, QUERY] = KEYS; + +const run = ( + check: "sample" | "window" | "reorgs", + nodeUrl: string, + apiUrl: string, + env: Record = {}, +) => + new Promise<{ code: number; output: string }>((resolve) => + execFile( + process.execPath, + [SCRIPT, check], + { + env: { + ...process.env, + COMPARE_NODE_URL: nodeUrl, + COMPARE_API_URL: apiUrl, + ...env, + }, + timeout: 30_000, + }, + (error, stdout, stderr) => + resolve({ + code: typeof error?.code === "number" ? error.code : 0, + output: stdout + stderr, + }), + ), + ); + +const listen = async (server: Server) => { + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return (server.address() as AddressInfo).port; +}; + +// Each path segment and query value of a request, bare, as a server echoing +// the key it rejects would quote it, not the path or query as sent. +const quotedOf = (req: IncomingMessage) => { + const url = new URL(req.url ?? "/", "http://echo"); + return [ + ...url.pathname.split("/").filter(Boolean), + ...url.searchParams.values(), + ].join(" "); +}; + +const echo500 = () => + createServer((req, res) => { + res.writeHead(500, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + jsonrpc: "2.0", + id: null, + error: { code: -32000, message: `rejected ${quotedOf(req)}` }, + }), + ); + }); + +// A 200 whose reorg record holds the quote as its height, which fails the +// schema. Zod 4 leaves the input out of its error, so this guards a parser +// that names the value it refused. +const echo200 = () => + createServer((req, res) => { + res.writeHead(200, { "content-type": "application/json" }); + res.end( + JSON.stringify([ + { + orphanedBlockHash: "0x01", + height: quotedOf(req), + timestamp: 0, + nbrOfOrphanedBlocks: 1, + }, + ]), + ); + }); + +describe("compare-chain against a failing or echoing node or API", () => { + let server: Server; + let echoPort: number; + let closedPort: number; + + beforeAll(async () => { + const probe = createServer(); + closedPort = await listen(probe); + await new Promise((resolve) => probe.close(resolve)); + server = echo500(); + echoPort = await listen(server); + }); + + afterAll(() => { + server?.closeAllConnections(); + server?.close(); + }); + + it("prints a fixed diagnostic, without a credential or the host", async () => { + const urls = (port: number, userinfo: string) => ({ + node: `http://${userinfo}127.0.0.1:${port}/${PATH}?key=${QUERY}`, + api: `http://${userinfo}127.0.0.1:${port}/${PATH}`, + }); + // fetch refuses a URL with userinfo before it connects, so only the + // closed port gets one and the echoing server sees the path and query. + const setups = [ + { port: closedPort, ...urls(closedPort, `${USER}:${PASSWORD}@`) }, + { port: echoPort, ...urls(echoPort, "") }, + ]; + for (const { port, node, api } of setups) { + for (const [check, failed] of [ + ["window", "node getChainTips failed"], + ["sample", "API /l2/latest-height"], + ] as const) { + const { code, output } = await run(check, node, api); + const at = `${check} against port ${port}`; + expect.soft(code, `${at}: exit code`).toBe(2); + expect.soft(output, `${at}: diagnostic`).toContain(failed); + for (const fragment of [...KEYS, "127.0.0.1", `:${port}`]) { + expect.soft(output, `${at}: output`).not.toContain(fragment); + } + } + } + expect( + (await run("window", setups[1].node, setups[1].api)).output, + "the status, from the SDK's message", + ).toContain("node getChainTips failed: HTTP 500"); + }, 60_000); + + it("prints fixed text for a 200 it cannot parse, without the value it echoed", async () => { + const ok = echo200(); + const port = await listen(ok); + const node = `http://127.0.0.1:${port}/${PATH}?key=${QUERY}`; + const api = `http://127.0.0.1:${port}/${PATH}`; + try { + for (const [check, failed] of [ + ["reorgs", "API /l2/reorgs: invalid response"], + ["sample", "API /l2/latest-height: invalid response"], + ["window", "node getChainTips failed"], + ] as const) { + const { code, output } = await run(check, node, api); + expect.soft(code, `${check}: exit code`).toBe(2); + expect.soft(output, `${check}: diagnostic`).toContain(failed); + for (const fragment of [PATH, QUERY, "127.0.0.1", `:${port}`]) { + expect.soft(output, `${check}: output`).not.toContain(fragment); + } + } + } finally { + ok.closeAllConnections(); + ok.close(); + } + }, 60_000); + + it("redacts a key that the API echoes inside a valid answer", async () => { + // Hex, so it passes as a block hash; in capitals, as hashes print in + // lowercase. + const key = "5C1EA7E5".repeat(4); + const block = loadFixture("local-network", "api-body", "block-by-height") + .data.body as Record; + const echoing = createServer((req, res) => { + const url = new URL(req.url ?? "/", "http://api"); + const [quoted, ...route] = url.pathname.split("/").filter(Boolean); + const from = Number(url.searchParams.get("from")); + const to = Number(url.searchParams.get("to")); + res.writeHead(200, { "content-type": "application/json" }); + res.end( + JSON.stringify( + route.join("/") === "l2/latest-height" + ? 3 + : Array.from({ length: to - from }, (_, i) => ({ + ...block, + height: String(from + i), + hash: `0x${quoted}`, + })), + ), + ); + }); + const port = await listen(echoing); + const node = await startScriptedNode({ + rpcPort: 0, + controlPort: 0, + log: () => undefined, + }); + try { + const { code, output } = await run( + "sample", + node.rpcUrl, + `http://127.0.0.1:${port}/${key}`, + ); + expect.soft(code, "exit code").toBe(1); + expect.soft(output, "the mismatch").toContain('"firstMismatch":{'); + expect(output.toLowerCase()).not.toContain(key.toLowerCase()); + } finally { + await node.close(); + echoing.closeAllConnections(); + echoing.close(); + } + }, 60_000); + + it("gives up on a node or an API that never answers", async () => { + const silent = createServer(() => { + // Never answers. + }); + const port = await listen(silent); + const url = `http://127.0.0.1:${port}`; + try { + for (const [check, failed] of [ + ["window", "node getChainTips failed: timed out"], + ["sample", "API /l2/latest-height: timed out"], + ] as const) { + const started = Date.now(); + const { code, output } = await run(check, url, url, { + COMPARE_TIMEOUT_MS: "500", + }); + expect.soft(code, `${check}: exit code`).toBe(2); + expect.soft(output, `${check}: diagnostic`).toContain(failed); + expect.soft(Date.now() - started, `${check}: ms`).toBeLessThan(20_000); + } + } finally { + silent.closeAllConnections(); + silent.close(); + } + }, 60_000); +}); diff --git a/services/network-smoke/src/compare-ranges.test.ts b/services/network-smoke/src/compare-ranges.test.ts new file mode 100644 index 00000000..983fecf5 --- /dev/null +++ b/services/network-smoke/src/compare-ranges.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vitest"; +import { checkRanges, firstMismatch } from "./compare-ranges.js"; + +/** Hashes at heights 1 to `to`, with another block at `diverged`. */ +const chain = (to: number, diverged?: number) => + new Map( + Array.from({ length: to }, (_, i) => [ + i + 1, + i + 1 === diverged ? "0xdead" : `0x${i + 1}`, + ]), + ); + +describe("compare-chain's first mismatch, by check", () => { + it("finds a head the API lags behind only in the range that reaches it", () => { + // The API stalled at 10; the node is at 11, finalized at 6. + const ranges = checkRanges({ + apiLatest: 10, + nodeFinalized: 6, + nodeProposed: 11, + }); + expect(ranges).toEqual({ + sample: { from: 1, to: 10 }, + window: { from: 6, to: 11 }, + }); + expect(firstMismatch(ranges.sample, chain(10), chain(11))).toBeUndefined(); + expect(firstMismatch(ranges.window, chain(10), chain(11))).toBe(11); + }); + + it("finds a block the API kept, inside both ranges, at its height", () => { + const ranges = checkRanges({ + apiLatest: 12, + nodeFinalized: 6, + nodeProposed: 12, + }); + expect(firstMismatch(ranges.sample, chain(12, 7), chain(12))).toBe(7); + expect(firstMismatch(ranges.window, chain(12, 7), chain(12))).toBe(7); + }); +}); diff --git a/services/network-smoke/src/compare-ranges.ts b/services/network-smoke/src/compare-ranges.ts new file mode 100644 index 00000000..75115e87 --- /dev/null +++ b/services/network-smoke/src/compare-ranges.ts @@ -0,0 +1,35 @@ +/** Heights `from` through `to`. */ +export type HeightRange = { from: number; to: number }; + +/** + * The heights each one-shot check of `scripts/compare-chain.ts` compares: + * `sample` the API's top 40, `window` the node's finalized tip to its + * proposed tip. The script imports nothing from this package, so this + * restates it; a scenario checks it against the range each check prints. + */ +export const checkRanges = ({ + apiLatest, + nodeFinalized, + nodeProposed, +}: { + apiLatest: number; + nodeFinalized: number; + nodeProposed: number; +}) => ({ + sample: { from: Math.max(1, apiLatest - 39), to: apiLatest }, + window: { from: Math.max(1, nodeFinalized), to: nodeProposed }, +}); + +/** The lowest height in `range` where the API's canonical hash is not the node's, a missing one included. */ +export const firstMismatch = ( + { from, to }: HeightRange, + api: Map, + node: Map, +) => { + for (let height = from; height <= to; height++) { + if (api.get(height) !== node.get(height)) { + return height; + } + } + return undefined; +}; diff --git a/services/network-smoke/src/crash-stops.test.ts b/services/network-smoke/src/crash-stops.test.ts new file mode 100644 index 00000000..a841e5c4 --- /dev/null +++ b/services/network-smoke/src/crash-stops.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, it } from "vitest"; +import { apiStateAtStop, killService, stopHold } from "./crash-stops.js"; + +describe("killing a stopped service", () => { + const stopped = ({ + kill = () => Promise.resolve(), + endSessions = () => Promise.resolve([]), + }: { + kill?: () => Promise; + endSessions?: () => Promise; + }) => { + const calls: string[] = []; + const hold = stopHold({ + waiters: () => Promise.resolve([]), + endSessions: (name) => { + calls.push(`end the sessions of ${name}`); + return endSessions(); + }, + release: () => { + calls.push("release the lock"); + return Promise.resolve(); + }, + }); + const services = { + kill: (name: string) => { + calls.push(`kill ${name}`); + return kill(); + }, + }; + return { hold, services, calls }; + }; + + it("kills nothing past the stop's deadline, and otherwise ends the service's sessions after the kill", async () => { + const { hold, services, calls } = stopped({}); + expect( + await killService(hold, services, "explorer-api", Date.now() - 1), + ).toMatch(/past its 15 s deadline, so explorer-api was not killed$/); + expect(calls, "past the deadline").toEqual([]); + expect( + await killService(hold, services, "explorer-api", Date.now() + 60_000), + ).toBeUndefined(); + await hold.release(); + expect(calls, "before it").toEqual([ + "kill explorer-api", + "end the sessions of explorer-api", + "release the lock", + ]); + }); + + const failures: [string, Parameters[0]][] = [ + [ + "a failed kill", + { kill: () => Promise.reject(new Error("kill explorer-api: 409")) }, + ], + [ + "a failed cleanup", + { endSessions: () => Promise.reject(new Error("Connection terminated")) }, + ], + [ + "a cleanup that leaves a session", + { endSessions: () => Promise.resolve([1700]) }, + ], + ]; + + it.each(failures)("keeps the lock held after %s", async (_, failing) => { + const { hold, services, calls } = stopped(failing); + await expect( + killService(hold, services, "explorer-api", Date.now() + 60_000), + ).rejects.toThrow("the lock stays held"); + await hold.release(); + expect(calls).not.toContain("release the lock"); + expect(hold.kept()).toBeDefined(); + }); +}); + +describe("the API's state at its stop", () => { + const atStop = { + canonical: { replacing: true, dead: [false, false] }, + sent: [{ partition: 1, from: 32, to: 33 }], + committed: { blockHandler: [32] }, + }; + + it("is the kill's only while the block group itself, and no other, is before the record", () => { + expect(apiStateAtStop(atStop, 2), "the block group before it").toBe(true); + expect( + apiStateAtStop({ ...atStop, committed: { renamedHandler: [32] } }, 2), + "another group in its place", + ).toBe(false); + expect( + apiStateAtStop( + { ...atStop, committed: { blockHandler: [32], otherHandler: [32] } }, + 2, + ), + "a second group on the partition", + ).toBe(false); + expect( + apiStateAtStop({ ...atStop, committed: { blockHandler: [33] } }, 2), + "the block group past it", + ).toBe(false); + }); +}); diff --git a/services/network-smoke/src/crash-stops.ts b/services/network-smoke/src/crash-stops.ts new file mode 100644 index 00000000..afb80132 --- /dev/null +++ b/services/network-smoke/src/crash-stops.ts @@ -0,0 +1,630 @@ +import { setTimeout as sleep } from "node:timers/promises"; +import { isDeepStrictEqual } from "node:util"; +import { L2Block } from "@aztec-labs/stdlib/block"; +import { BSON } from "bson"; +import { z } from "zod"; +import { type BrokerReads } from "./broker.js"; +import { + type PgAccess, + type RowLock, + type Waiter, + lockRows, + queryRows, +} from "./row-lock.js"; +import { type BlockId } from "./script-control.js"; +import { type serviceControl } from "./service-control.js"; + +type Services = ReturnType; + +// A service that reaches its stop does so within a few of the listener's 1 s +// polls; a service that never does fails its scenario after this. +const STOP_WAIT_MS = 15_000; +// A restarted service's consumers join their groups only once the killed +// member's 30 s session has run out, and the listener polls only after that. +const RECOVERY_WAIT_MS = 120_000; + +// The services the scenarios kill, by the names the runner and their +// Postgres sessions go by. +const LISTENER = "aztec-listener"; +const API = "explorer-api"; + +// What the listener's store and the API's post-commit step send for the row +// each scenario locks; Drizzle writes them as upserts. +const LISTENER_WRITE = /^insert into "l2_block_stream_hash"/i; +const API_WRITE = /^insert into "l2_rollup_version_observation"/i; + +// The API's handlers, besides the block handler, whose records reach that +// upsert (`observeRollupVersion`): catch-up blocks, after their commit; chain +// info and staking-asset info, through `storeChainInfo`; node info with a +// rollup version, through `storeL2RpcNode`. +const OTHER_API_WRITERS = [ + "catchupHandler", + "chainInfoHandler", + "stakingAssetInfoHandler", + "l2RpcNodeInfoHandler", +]; + +/** The waiting write a stop caught, as `pg_stat_activity` showed it. */ +export type CaughtWrite = { + application: string; + database: string; + statement: string; +}; + +/** Offsets `[from, to)` of one partition. */ +export type OffsetRange = { partition: number; from: number; to: number }; + +/** The partitions whose end offset moved between two reads, with the offsets they moved over. */ +const grown = (before: Map, after: Map) => + [...after.entries()] + .filter(([partition, end]) => end !== before.get(partition)) + .map( + ([partition, to]): OffsetRange => ({ + partition, + from: before.get(partition) ?? 0, + to, + }), + ); + +/** `read`'s first defined value, or undefined once `timeoutMs` passed without one. */ +const poll = async ( + read: () => Promise, + timeoutMs: number, + intervalMs = 100, +) => { + const deadline = Date.now() + timeoutMs; + for (;;) { + const value = await read(); + if (value !== undefined || Date.now() >= deadline) { + return value; + } + await sleep(intervalMs); + } +}; + +const until = async ( + read: () => Promise, + timeoutMs: number, + what: string, +) => { + const value = await poll(read, timeoutMs, 250); + if (value === undefined) { + throw new Error(`no ${what} within ${timeoutMs / 1000} s`); + } + return value; +}; + +/** + * `lock` as a crash stop holds it. `kill` kills the stopped service, then + * ends every Postgres session it opened, by the name the run gives them: a + * session never sees its client go, so a statement it had sent, waiting on + * the lock or not yet, would run once the lock goes, and an autocommit one + * would commit. Once the kill is sent, a failure or a session left makes + * `kill` throw and `release` keep the lock held for the rest of the suite, + * rather than let such a write land in what later scenarios read; `kept` + * says why. + */ +export const stopHold = (lock: RowLock) => { + let kept: string | undefined; + const keep = (why: string) => { + kept = why; + return new Error(`${why}; the lock stays held`); + }; + const orKeep = async (what: string, run: () => Promise) => { + try { + return await run(); + } catch (e) { + throw keep(`${what} failed: ${(e as Error).message}`); + } + }; + return { + waiters: lock.waiters, + kill: async (name: string, kill: () => Promise) => { + await orKeep(`killing ${name}`, kill); + const left = await orKeep(`ending the sessions of ${name}`, () => + lock.endSessions(name), + ); + if (left.length > 0) { + throw keep( + `sessions of ${name} outlived their termination: ${left.join(", ")}`, + ); + } + }, + release: async () => { + if (kept === undefined) { + await lock.release(); + } + }, + kept: () => kept, + }; +}; + +type StopHold = ReturnType; + +/** The sessions of service `name` whose `write` waits on `lock`. */ +const writesWaiting = async ( + lock: Pick, + name: string, + write: RegExp, +) => + (await lock.waiters()).filter( + (w) => + w.application === name && + w.waitEventType === "Lock" && + write.test(w.query), + ); + +const caughtWrite = ({ + application, + database, + query, +}: Waiter): CaughtWrite => ({ + application, + database, + statement: query.split("(")[0].trim(), +}); + +const missedStop = async ( + lock: Pick, + writer: string, + withinMs: number, + more = {}, +) => + `the lock held up no write of the ${writer} within ${withinMs / 1000} s (${JSON.stringify({ waiting: await lock.waiters(), ...more })})`; + +/** + * Kills service `name` and ends its sessions (`stopHold`). Past the stop's + * `deadline` it kills nothing and resolves with why: a hook that timed out + * runs on, and its kill would land in a later scenario. + */ +export const killService = async ( + lock: Pick, + services: Pick, + name: string, + deadline: number, +): Promise => { + const late = Date.now() - deadline; + if (late > 0) { + return `the stop was proven ${late} ms past its ${STOP_WAIT_MS / 1000} s deadline, so ${name} was not killed`; + } + await lock.kill(name, () => services.kill(name)); + return undefined; +}; + +// The message bus's envelope: BSON of `{ data: }`. +const blockRecordSchema = z.object({ + data: z.object({ + blockNumber: z.number(), + block: z.string(), + ordered: z.object({ proposedTip: z.number() }).optional(), + }), +}); + +const blockRecord = async ( + { offset, key, value }: { offset: number; key?: Buffer; value?: Buffer }, + sentBeforeKill: boolean, +) => { + const document: unknown = BSON.deserialize(value ?? Buffer.alloc(0)); + const event = blockRecordSchema.parse(document).data; + const block = L2Block.fromBuffer(Buffer.from(event.block, "hex")); + return { + offset, + key: key?.toString(), + height: event.blockNumber, + proposedTip: event.ordered?.proposedTip, + hash: (await block.hash()).toString().toLowerCase(), + sentBeforeKill, + }; +}; + +export type ListenerStop = { + /** Why nothing was crashed; absent once the listener was. */ + missed?: string; + waiting?: CaughtWrite; + /** What the batch had put on the topic, and what the listener's store held, at the stop; the kill needs both as expected. */ + atKill?: { + sent: OffsetRange[]; + store: { proposed: number | null; hash: string | null }; + }; + /** The block records sent from the prune on, read once the restarted listener stored the batch. */ + records?: Awaited>[]; + /** From the restart to the restarted listener's store holding the batch. */ + recoveryMs?: number; +}; + +/** + * Kills the listener between sending a batch and storing it. `arm` locks the + * listener store's hash row at the first dead height, which the prune leaves + * as it is and the replacing batch's store writes first; only that store + * writes the row. `fire`, once the node has pruned, waits for that write to + * wait on the lock, kills the listener, so the write's transaction never + * commits, and starts it again. + */ +export const listenerStop = ({ + pg, + database, + broker, + blockTopic, + services, +}: { + pg: PgAccess; + database: string; + broker: BrokerReads; + blockTopic: string; + services: Services; +}) => { + const result: ListenerStop = {}; + let armed: + | { lock: StopHold; before: Map; first: BlockId } + | undefined; + const store = async (height: number) => { + const [row] = await queryRows<{ + proposed: number | null; + hash: string | null; + }>( + pg, + database, + `SELECT (SELECT block_number FROM l2_block_stream_tip WHERE tag = 'proposed') AS proposed, + (SELECT block_hash FROM l2_block_stream_hash WHERE block_number = $1) AS hash`, + [height], + ); + return { proposed: row.proposed, hash: row.hash?.toLowerCase() ?? null }; + }; + return { + result, + /** Before the prune, once the store holds `dead`. */ + arm: async (dead: BlockId[]) => { + const [first] = dead; + try { + await until( + async () => { + const held = await store(first.height); + return held.proposed === dead.at(-1)?.height && + held.hash === first.hash.toLowerCase() + ? held + : undefined; + }, + 30_000, + "listener store holding the dead blocks", + ); + } catch (e) { + result.missed = `the listener's block stream store: ${(e as Error).message}`; + return; + } + const before = await broker.endOffsets(blockTopic); + armed = { + lock: stopHold( + await lockRows( + pg, + database, + "SELECT 1 FROM l2_block_stream_hash WHERE block_number = $1 FOR UPDATE", + [first.height], + ), + ), + before, + first, + }; + }, + /** Once the node serves the prune, whose replacing batch starts with `replacing`. */ + fire: async (replacing: BlockId) => { + if (armed === undefined) { + return; + } + const { lock, before, first } = armed; + const deadline = Date.now() + STOP_WAIT_MS; + try { + const waiting = await poll(async () => { + const [write] = await writesWaiting(lock, LISTENER, LISTENER_WRITE); + return write; + }, STOP_WAIT_MS); + if (waiting === undefined) { + result.missed = await missedStop( + lock, + "listener's store", + STOP_WAIT_MS, + ); + return; + } + result.waiting = caughtWrite(waiting); + const atKill = await broker.endOffsets(blockTopic); + result.atKill = { + sent: grown(before, atKill), + store: await store(first.height), + }; + // The batch's one record is on the topic, and the store is still on + // the prune's target, with the dead block at the height it writes. + const expected = { + sent: [1], + store: { proposed: first.height - 1, hash: first.hash.toLowerCase() }, + }; + const seen = { + sent: result.atKill.sent.map((r) => r.to - r.from), + store: result.atKill.store, + }; + if (!isDeepStrictEqual(seen, expected)) { + result.missed = `the state at the stop is not ${JSON.stringify(expected)}`; + return; + } + const refused = await killService(lock, services, LISTENER, deadline); + if (refused !== undefined) { + result.missed = refused; + return; + } + await lock.release(); + const restartedAt = Date.now(); + await services.start(LISTENER); + await until( + async () => + (await store(replacing.height)).hash === + replacing.hash.toLowerCase() + ? true + : undefined, + RECOVERY_WAIT_MS, + "replacing block in the restarted listener's store", + ); + result.recoveryMs = Date.now() - restartedAt; + const sentSince = grown(before, await broker.endOffsets(blockTopic)); + result.records = await Promise.all( + ( + await Promise.all( + sentSince.map(async (range) => + ( + await broker.recordsOf(blockTopic, range.partition, range) + ).map((record) => ({ + record, + beforeKill: + record.offset < (atKill.get(range.partition) ?? 0), + })), + ), + ) + ) + .flat() + .map(({ record, beforeKill }) => blockRecord(record, beforeKill)), + ); + } finally { + await lock.release(); + } + }, + /** Releases the lock `arm` took, if `fire` has not and a kill's cleanup did not keep it. */ + release: async () => { + await armed?.lock.release(); + }, + /** Why the lock stays held, if it does (`stopHold`). */ + kept: () => armed?.lock.kept(), + }; +}; + +type Committed = Record; + +/** The block handler's upsert, held up by the lock, as a stop proved it (see `apiStop`). */ +export type HeldUp = { + waiting: CaughtWrite; + /** The API's upserts the lock held up. */ + writesWaiting: number; + /** The groups of the row's other writers that had not committed a record. */ + othersBehind: string[]; +}; + +export type ApiStop = { + /** Why nothing was crashed; absent once the API was. */ + missed?: string; + held?: HeldUp; + /** + * At the stop: whether the replacing block and the dead blocks are + * canonical in the API's database, what the batch put on the topic, and + * the API groups' committed offsets on the partitions it went to. The kill + * needs all three as expected. + */ + atKill?: { + canonical: { replacing?: boolean; dead: (boolean | undefined)[] }; + sent: OffsetRange[]; + committed: Committed; + }; + /** Why the restarted API was not seen handling the record again; absent once it was. */ + replayMissed?: string; + /** The restarted API's block handler held up at the same upsert, and the committed offsets then. */ + replay?: HeldUp & { committed: Committed }; + /** The same offsets once the lock was released and the restarted API committed past the batch. */ + afterRestart?: { committed: Committed }; + /** From the restart to that commit. */ + recoveryMs?: number; +}; + +/** + * Whether the API's state at its stop is the one its kill needs: the batch's + * one record on the topic, its chain change committed, and the block group, + * the only API group on that partition, still before the record. + */ +export const apiStateAtStop = ( + { canonical, sent, committed }: NonNullable, + deadBlocks: number, +) => + sent.length === 1 && + sent[0].to - sent[0].from === 1 && + isDeepStrictEqual(canonical, { + replacing: true, + dead: Array.from({ length: deadBlocks }, () => false), + }) && + isDeepStrictEqual(committed, { blockHandler: [sent[0].from] }); + +/** + * Kills the API after a block's chain change commits and before its offset + * does. `arm`, once every API group has committed through the topic's end, + * locks the API's rollup-version observation rows, which the block handler + * upserts after the commit; the run's database holds its network's alone. + * `fire`, once the node has pruned, waits for that upsert to be held up by + * the lock, kills the API and starts it again with the lock still held, so + * the restarted API's block handler stops at the same upsert while the + * record is still uncommitted; then it releases the lock. + */ +export const apiStop = ({ + pg, + database, + apiGroupPrefix, + broker, + blockTopic, + services, +}: { + pg: PgAccess; + database: string; + apiGroupPrefix: string; + broker: BrokerReads; + blockTopic: string; + services: Services; +}) => { + const result: ApiStop = {}; + let armed: { lock: StopHold; before: Map } | undefined; + const canonical = async (hash: string) => { + const [row] = await queryRows<{ canonical: boolean }>( + pg, + database, + `SELECT orphan_timestamp IS NULL AS canonical FROM "l2Block" WHERE lower(hash) = lower($1)`, + [hash], + ); + return row?.canonical; + }; + const committedOn = async (partitions: number[]): Promise => + Object.fromEntries( + [...(await broker.apiCommitted(blockTopic)).entries()].map( + ([group, offsets]) => [ + group.slice(apiGroupPrefix.length), + partitions.map((p) => offsets.get(p)), + ], + ), + ); + /** + * The row's other writers (`OTHER_API_WRITERS`) each upsert it while their + * group holds a record it cannot commit until the row is unlocked, and a + * group handles one record at a time: more upserts held up, on the lock or + * queued behind one another, than those groups behind means one is the + * block handler's. They are counted by id, so neither the block group, + * whose member expires while its handler waits, nor an unrelated group + * still rejoining raises the count. Waiters are read before the groups, so + * none of them is missed. + */ + const blockHandlerHeldUp = async ( + lock: Pick, + timeoutMs: number, + ): Promise<{ held?: HeldUp; othersBehind: string[] }> => { + let othersBehind: string[] = []; + const writes = await poll(async () => { + const held = await writesWaiting(lock, API, API_WRITE); + if (held.length === 0) { + return undefined; + } + othersBehind = await broker.groupsBehind( + OTHER_API_WRITERS.map((handler) => apiGroupPrefix + handler), + ); + return held.length > othersBehind.length ? held : undefined; + }, timeoutMs); + return { + held: writes && { + waiting: caughtWrite(writes[0]), + writesWaiting: writes.length, + othersBehind, + }, + othersBehind, + }; + }; + return { + result, + /** Before the prune. */ + arm: async () => { + await broker.apiConsumedThrough(30_000); + const before = await broker.endOffsets(blockTopic); + armed = { + lock: stopHold( + await lockRows( + pg, + database, + "SELECT 1 FROM l2_rollup_version_observation FOR UPDATE", + ), + ), + before, + }; + }, + /** Once the node serves the prune, whose replacing block is `replacing`. */ + fire: async (replacing: BlockId, dead: BlockId[]) => { + if (armed === undefined) { + return; + } + const { lock, before } = armed; + const deadline = Date.now() + STOP_WAIT_MS; + try { + const stopped = await blockHandlerHeldUp(lock, STOP_WAIT_MS); + if (stopped.held === undefined) { + result.missed = await missedStop( + lock, + "API's block handler", + STOP_WAIT_MS, + { othersBehind: stopped.othersBehind }, + ); + return; + } + result.held = stopped.held; + const sent = grown(before, await broker.endOffsets(blockTopic)); + const partitions = sent.map((r) => r.partition); + result.atKill = { + canonical: { + replacing: await canonical(replacing.hash), + dead: await Promise.all(dead.map((b) => canonical(b.hash))), + }, + sent, + committed: await committedOn(partitions), + }; + if (!apiStateAtStop(result.atKill, dead.length)) { + result.missed = + "the state at the stop is not one record sent, committed in the database, and the block group alone before it"; + return; + } + const refused = await killService(lock, services, API, deadline); + if (refused !== undefined) { + result.missed = refused; + return; + } + const restartedAt = Date.now(); + await services.start(API); + const replayed = await blockHandlerHeldUp(lock, RECOVERY_WAIT_MS); + if (replayed.held === undefined) { + result.replayMissed = await missedStop( + lock, + "restarted API's block handler", + RECOVERY_WAIT_MS, + { othersBehind: replayed.othersBehind }, + ); + return; + } + result.replay = { + ...replayed.held, + committed: await committedOn(partitions), + }; + await lock.release(); + result.afterRestart = { + committed: await until( + async () => { + const committed = await committedOn(partitions); + const groups = Object.values(committed); + return groups.length > 0 && + groups.every((offsets) => + offsets.every((o, i) => o !== undefined && o >= sent[i].to), + ) + ? committed + : undefined; + }, + RECOVERY_WAIT_MS, + "commit by the restarted API past the batch", + ), + }; + result.recoveryMs = Date.now() - restartedAt; + } finally { + await lock.release(); + } + }, + /** Releases the lock `arm` took, if `fire` has not and a kill's cleanup did not keep it. */ + release: async () => { + await armed?.lock.release(); + }, + /** Why the lock stays held, if it does (`stopHold`). */ + kept: () => armed?.lock.kept(), + }; +}; diff --git a/services/network-smoke/src/endpoints.ts b/services/network-smoke/src/endpoints.ts index 863f0675..261476b1 100644 --- a/services/network-smoke/src/endpoints.ts +++ b/services/network-smoke/src/endpoints.ts @@ -1,20 +1,61 @@ import { z } from "zod"; +import { brokerAccessSchema } from "./broker.js"; /** The run owner hands this to the Vitest process as one JSON env var. */ export const ENDPOINTS_ENV = "NETWORK_SMOKE_ENDPOINTS"; -export const endpointsSchema = z.object({ +const commonSchema = z.object({ runId: z.string(), logDir: z.string(), - anvilUrl: z.string().url(), aztecNodeUrl: z.string().url(), explorerApiUrl: z.string().url(), - wsUrl: z.string().startsWith("ws://"), /** Log files (without `.log`) of the services that consume Kafka. */ consumerLogs: z.array(z.string()), + /** The listener's block poll interval, as the run set it. */ + listenerPollMs: z.number().int().positive(), + /** The run's broker, with the harness's local credentials. */ + broker: brokerAccessSchema, +}); + +export const endpointsSchema = commonSchema.extend({ + anvilUrl: z.string().url(), + wsUrl: z.string().startsWith("ws://"), +}); + +export const pruneEndpointsSchema = endpointsSchema.extend({ + /** The listener's tip reads, as `rpc-tap.ts` records them. */ + rpcTapFile: z.string(), + /** How long the node holds a read of the block one past its tip. */ + unseenBlockWaitMs: z.number().int().nonnegative(), +}); + +export const scriptedEndpointsSchema = commonSchema.extend({ + /** The scripted node's control port (`script-control.ts`). */ + controlUrl: z.string().url(), + /** The runner's control of its own services (`service-control.ts`). */ + servicesUrl: z.string().url(), + /** The run's Postgres, with the harness's local credentials. */ + postgres: z.object({ + host: z.string(), + port: z.number().int().positive(), + user: z.string(), + password: z.string(), + /** Each service's own database. */ + databases: z.object({ listener: z.string(), api: z.string() }), + }), }); export type Endpoints = z.infer; +export type PruneEndpoints = z.infer; +export type ScriptedEndpoints = z.infer; + +const fromEnv = () => + JSON.parse(process.env[ENDPOINTS_ENV] ?? "null") as unknown; + +export const readEndpoints = (): Endpoints => endpointsSchema.parse(fromEnv()); + +export const readPruneEndpoints = (): PruneEndpoints => + pruneEndpointsSchema.parse(fromEnv()); -export const readEndpoints = (): Endpoints => - endpointsSchema.parse(JSON.parse(process.env[ENDPOINTS_ENV] ?? "null")); +export const readScriptedEndpoints = (): ScriptedEndpoints => + scriptedEndpointsSchema.parse(fromEnv()); diff --git a/services/network-smoke/src/epoch-prune.prune.ts b/services/network-smoke/src/epoch-prune.prune.ts new file mode 100644 index 00000000..6e644edc --- /dev/null +++ b/services/network-smoke/src/epoch-prune.prune.ts @@ -0,0 +1,535 @@ +import { setTimeout as sleep } from "node:timers/promises"; +import { BlockNumber } from "@aztec-labs/aztec.js/fields"; +import { createAztecNodeClient } from "@aztec-labs/aztec.js/node"; +import { TxHash } from "@aztec-labs/aztec.js/tx"; +import { chicmozL2BlockLightSchema } from "@chicmoz-pkg/types"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { brokerReads } from "./broker.js"; +import { readPruneEndpoints } from "./endpoints.js"; +import { + type BlockRef, + type ReorgRecord, + byRoot, + explorerReads, + plusReorg, + served, + settle, +} from "./explorer-reads.js"; +import { + type ChainWatch, + type ForcedPrune, + forceEpochPrune, + readNodeChain, + watchChain, +} from "./force-prune.js"; +import { + longestTipGap, + pruneOrder, + readTipReads, + tipGapBound, +} from "./rpc-tap.js"; +import { type Sender, openSender } from "./send-tx.js"; +import { type WsClient, type WsFrame, connectWs } from "./ws-client.js"; + +const endpoints = readPruneEndpoints(); +const node = createAztecNodeClient(endpoints.aztecNodeUrl); +const api = explorerReads(endpoints.explorerApiUrl); +const broker = brokerReads(endpoints.broker); + +// For the API to reach what a scenario expects once the node's chain is +// final, which a correct pipeline does in a few polls; it bounds the commit +// wait too. +const SETTLE_TIMEOUT_MS = 30_000; +// Longer than the API's 5 s block cache. +const CACHE_MS = 6_000; +// A listener pass that read the node just before the prune may publish +// just after it. +const PREFIX_GRACE_MS = 3_000; +// 15 of the listener's block polls, and longer than its tips cadence (a 5 s +// poll and the 5 s heartbeat set here), so today's tips timer shows. +const PREFIX_WAIT_MS = 15_000; +// A longer gap between the listener's tip reads means it stopped reading. +const LISTENER_READ_GAP_MS = tipGapBound(endpoints); + +const t0 = Date.now(); +const log = (line: string) => + process.stdout.write( + `[prune +${((Date.now() - t0) / 1000).toFixed(1)}s] ${line}\n`, + ); + +type Deployed = { txHash: string; address: string }; +type Receipt = { status: string; blockNumber?: number; blockHash?: string }; + +const range = (from: number, to: number) => + Array.from({ length: Math.max(0, to - from + 1) }, (_, i) => from + i); + +const receiptOf = async (txHash: string): Promise => { + const r = await node.getTxReceipt(TxHash.fromString(txHash)); + return { + status: String(r.status), + blockNumber: + r.blockNumber === undefined ? undefined : Number(r.blockNumber), + blockHash: r.blockHash?.toString().toLowerCase(), + }; +}; + +/** Each tx's receipt once it is in a block of the node's current chain. */ +const minedOnChain = async (txs: Deployed[]) => { + const receipts = new Map(); + await vi.waitFor( + async () => { + const chain = await readNodeChain(node); + for (const { txHash } of txs) { + const r = await receiptOf(txHash); + expect( + r.blockNumber !== undefined && + chain.get(r.blockNumber) === r.blockHash, + `tx ${txHash} in a block of the node's chain: ${JSON.stringify(r)}`, + ).toBe(true); + receipts.set(txHash, r); + } + }, + { timeout: 90_000, interval: 500 }, + ); + return receipts; +}; + +const blockOf = (r: Receipt): BlockRef => ({ + height: r.blockNumber ?? -1, + hash: r.blockHash ?? "", +}); + +const deadOf = (prune: ForcedPrune): BlockRef[] => + prune.removed.map((height) => ({ + height, + hash: prune.before.get(height) ?? "", + })); + +/** Waits until the API serves `hashes` at `heights` as canonical. */ +const apiHolds = (heights: number[], hashes: Map) => + vi.waitFor( + async () => + expect( + await Promise.all(heights.map(api.blockAt)), + `the API at ${heights.join(",")}`, + ).toEqual( + heights.map((height) => + served({ height, hash: hashes.get(height) ?? "" }, false), + ), + ), + { timeout: 60_000, interval: 1_000 }, + ); + +/** + * Each scenario starts from an API that agrees with the node up to the + * proven base, so it judges its own prune, not what an earlier one left. + */ +const baseHeld = (base: Map) => + apiHolds([...base.keys()], base); + +/** The node's block at each height, or a 404 above its tip. */ +const expectedChain = (heights: number[], chain: Map) => + heights.map((height) => { + const hash = chain.get(height); + return hash === undefined + ? { status: 404 } + : served({ height, hash }, false); + }); + +const outcome = async ({ + heights, + txs, + dead, +}: { + heights: number[]; + txs: Deployed[]; + dead: BlockRef[]; +}) => ({ + latestHeight: await api.latestHeight(), + chain: await Promise.all(heights.map(api.blockAt)), + reorgs: byRoot(await api.reorgs()), + txs: await Promise.all( + txs.map(async ({ txHash, address }) => ({ + txHash, + dropped: await api.dropped(txHash), + effect: await api.txEffect(txHash), + contract: await api.contractInstance(address), + })), + ), + dead: await Promise.all(dead.map((b) => api.blockAt(b.hash))), +}); + +type Outcome = Awaited>; + +/** The API once it has consumed what the broker held when `want` was met or its time ran out; a consumer that never catches up fails the scenario. */ +const settled = async ( + args: Parameters[0], + want: Partial, + label: string, +) => { + const { value, met, held } = await settle(() => outcome(args), { + want, + timeoutMs: SETTLE_TIMEOUT_MS, + intervalMs: 1_000, + cacheMs: CACHE_MS, + consumedThrough: broker.apiConsumedThrough, + }); + log( + `${label}: ${met ? "expected state reached" : `expected state not reached in ${SETTLE_TIMEOUT_MS / 1000} s`}; once consumed, ${held ? "as expected" : "not as expected"}`, + ); + return value; +}; + +/** The one reorg a prune adds: rooted at its first removed height, counting every removed block. */ +const reorgOf = (prune: ForcedPrune): ReorgRecord => ({ + height: prune.removed[0], + nbrOfOrphanedBlocks: prune.removed.length, + orphanedBlockHash: prune.before.get(prune.removed[0]) ?? "", +}); + +const summary = (prune: ForcedPrune) => ({ + target: prune.target, + doomed: prune.doomed, + removed: prune.removed, + timings: prune.timings, +}); + +/** What the listener itself read of the prune, from its own node reads. */ +const listenerOrder = (prune: ForcedPrune) => + pruneOrder(readTipReads(endpoints.rpcTapFile), { + since: prune.at.warp, + target: prune.target, + before: prune.before, + }); + +let sender: Sender; +let watch: ChainWatch; +let ws: WsClient; + +beforeAll(async () => { + ws = await connectWs(endpoints.wsUrl); + sender = await openSender(node); + await sender.publishAccountClass(); + log("account class published"); + watch = watchChain(node, log); +}); + +afterAll(async () => { + await watch?.stop(); + await sender?.stop(); + ws?.close(); + await broker.close(); +}); + +describe("a prune of blocks with txs, which the node mines again at once in a replacing block", () => { + let genesisArchive: string; + let firstParent: unknown; + let prune: ForcedPrune; + let txs: Deployed[] = []; + let after: Map; + let chain: Map; + let heights: number[]; + let want: Pick; + let seen: Outcome; + + beforeAll(async () => { + log("replaced at once: start"); + // From the node: the local network's genesis is not the SDK's constant. + const genesis = await node.getBlock(BlockNumber(0)); + if (!genesis) { + throw new Error("the node does not serve block 0"); + } + genesisArchive = genesis.archive.root.toString().toLowerCase(); + let before = new Map(); + prune = await forceEpochPrune({ + node, + nodeUrl: endpoints.aztecNodeUrl, + anvilUrl: endpoints.anvilUrl, + log, + sendTxs: async () => { + txs = [await sender.deploy(), await sender.deploy()]; + before = await minedOnChain(txs); + }, + emptyBlocks: 1, + afterProve: baseHeld, + expectReplacement: true, + // The prune tests something only once the API holds what it removes, + // the account contracts included. + beforeTrigger: async (doomed, hashes) => { + await apiHolds(range(1, Math.max(...doomed)), hashes); + await vi.waitFor( + async () => + expect( + await Promise.all( + txs.map((t) => api.contractInstance(t.address)), + ), + "the account contracts before the prune", + ).toEqual( + txs.map((t) => ({ + hash: before.get(t.txHash)?.blockHash, + orphaned: false, + })), + ), + { timeout: 30_000, interval: 1_000 }, + ); + }, + }); + after = await minedOnChain(txs); + const unmoved = txs.filter( + ({ txHash }) => + after.get(txHash)?.blockHash === before.get(txHash)?.blockHash, + ); + if (unmoved.length > 0) { + throw new Error( + `the node kept ${unmoved.map((t) => t.txHash).join(",")} in its dead block`, + ); + } + heights = range(1, Math.max(...prune.before.keys()) + 1); + // Final: every tx is in a block of the node's chain, and no other comes. + chain = await readNodeChain(node); + want = { + latestHeight: Math.max(...chain.keys()), + chain: expectedChain(heights, chain), + reorgs: [reorgOf(prune)], + txs: txs.map(({ txHash }) => { + const block = served( + blockOf(after.get(txHash) ?? { status: "" }), + false, + ); + return { + txHash, + dropped: { status: 404 }, + effect: block, + contract: { hash: block.hash, orphaned: false }, + }; + }), + dead: deadOf(prune).map((b) => served(b, true)), + }; + seen = await settled( + { heights, txs, dead: deadOf(prune) }, + want, + "replaced at once", + ); + const first = await api.get("/l2/blocks/1"); + firstParent = + first.status === 200 + ? chicmozL2BlockLightSchema + .parse(first.body) + .header.lastArchive.root.toLowerCase() + : { status: first.status }; + const listener = listenerOrder(prune); + log(`replaced at once: listener order: ${listener.order}`); + log( + `replaced at once: end ${JSON.stringify({ + genesis: genesis.hash.toString(), + ...summary(prune), + listener, + receipts: txs.map(({ txHash }) => ({ + txHash, + before: before.get(txHash), + after: after.get(txHash), + })), + nodeChain: Object.fromEntries(chain), + seen, + })}`, + ); + }); + + it("serves the node's chain from its genesis as canonical, and nothing above the node's tip", () => { + expect.soft(seen.latestHeight, "latest height").toBe(want.latestHeight); + expect + .soft(seen.chain, "the canonical block at each height") + .toEqual(want.chain); + expect.soft(firstParent, "block 1's parent archive").toBe(genesisArchive); + }); + + it("lists one reorg: the removed blocks, from the first removed height", () => { + expect(seen.reorgs).toEqual(want.reorgs); + }); + + it("keeps each moved tx mined, not dropped, with its effect and its account contract on the node's block", () => { + for (const [i, tx] of seen.txs.entries()) { + const wanted = want.txs[i]; + expect + .soft(tx.dropped, `${tx.txHash}: dropped-tx lookup`) + .toEqual(wanted.dropped); + expect.soft(tx.effect, `${tx.txHash}: tx effect`).toEqual(wanted.effect); + expect + .soft(tx.contract, `${tx.txHash}: its account contract`) + .toEqual(wanted.contract); + } + }); + + it("serves each dead block by its hash, as orphaned", () => { + expect(seen.dead).toEqual(want.dead); + }); +}); + +/** + * Waits until the websocket publisher has relayed each doomed block and a + * tips frame at the doomed tip sent after `since`, so no frame from before + * the prune can land in the quiet window. + */ +const framesArrived = ( + doomed: number[], + hashes: Map, + since: number, +) => + vi.waitFor( + () => { + const tip = Math.max(...doomed); + expect( + doomed.filter( + (h) => + !ws.frames.some( + (f) => f.kind === "block" && f.hash === hashes.get(h), + ), + ), + "doomed blocks the websocket has not relayed", + ).toEqual([]); + expect( + ws.frames.some( + (f) => + f.kind === "l2Tips" && + f.at >= since && + f.height === tip && + (f.hash === undefined || f.hash === hashes.get(tip)), + ), + `a tips frame at the doomed tip ${tip}`, + ).toBe(true); + }, + { timeout: 30_000, interval: 500 }, + ); + +describe("a prune of empty blocks, which leaves the node on the shorter chain until a tx comes", () => { + let prune: ForcedPrune; + let dead: BlockRef[]; + let quiet: WsFrame[]; + let kept: { start: unknown; end: unknown }; + let baseline: ReorgRecord[]; + let receipt: Receipt; + let chain: Map; + let heights: number[]; + let want: Pick; + let seen: Outcome; + + beforeAll(async () => { + log("shorter chain: start"); + let provedAt = 0; + prune = await forceEpochPrune({ + node, + nodeUrl: endpoints.aztecNodeUrl, + anvilUrl: endpoints.anvilUrl, + log, + sendTxs: () => Promise.resolve(), + emptyBlocks: 2, + afterProve: (base) => { + provedAt = Date.now(); + return baseHeld(base); + }, + expectReplacement: false, + beforeTrigger: async (doomed, hashes) => { + await apiHolds(doomed, hashes); + await framesArrived(doomed, hashes, provedAt); + baseline = await api.reorgList(); + }, + }); + dead = deadOf(prune); + const view = async () => ({ + latestHeight: await api.latestHeight(), + dead: await Promise.all(prune.doomed.map(api.blockAt)), + reorgs: await api.reorgs(), + }); + await sleep(PREFIX_GRACE_MS); + const from = Date.now(); + const start = await view(); + await sleep(PREFIX_WAIT_MS); + const end = await view(); + const to = Date.now(); + const moved = watch.events.filter((e) => e.at >= from); + const tip = Number((await node.getChainTips()).proposed.number); + if (moved.length > 0 || tip !== prune.target) { + throw new Error( + `the node left the shorter chain during the wait: tip ${tip}, ${JSON.stringify(moved)}`, + ); + } + // Silence counts only from an open socket and a listener still reading. + if (ws.closedAt !== undefined && ws.closedAt <= to) { + throw new Error( + `the websocket closed ${ws.closedAt - from} ms into the wait`, + ); + } + const longestGap = longestTipGap( + readTipReads(endpoints.rpcTapFile), + from, + to, + ); + if (longestGap > LISTENER_READ_GAP_MS) { + throw new Error( + `the listener read no tip for ${longestGap} ms of the ${to - from} ms wait`, + ); + } + quiet = ws.frames.filter((f) => f.at >= from && f.at <= to); + kept = { start, end }; + + const tx = await sender.deploy(); + receipt = (await minedOnChain([tx])).get(tx.txHash) ?? { status: "" }; + heights = range(prune.target + 1, Math.max(...prune.before.keys()) + 1); + chain = await readNodeChain(node); + want = { + chain: expectedChain(heights, chain), + reorgs: plusReorg(baseline, reorgOf(prune)), + dead: dead.map((b) => served(b, true)), + }; + seen = await settled({ heights, txs: [tx], dead }, want, "shorter chain"); + const listener = listenerOrder(prune); + log(`shorter chain: listener order: ${listener.order}`); + log( + `shorter chain: end ${JSON.stringify({ + ...summary(prune), + listener, + waitMs: to - from, + quiet, + kept, + receipt, + nodeChain: Object.fromEntries(chain), + seen, + })}`, + ); + }); + + it("publishes no block and no tips while the node sits on the shorter chain", () => { + expect + .soft( + quiet.filter((f) => f.kind === "block"), + "block frames", + ) + .toEqual([]); + expect + .soft( + quiet.filter((f) => f.kind === "l2Tips"), + "tips frames", + ) + .toEqual([]); + }); + + it("keeps the dead blocks canonical while it waits", () => { + expect + .soft(kept.start, "at the start of the wait") + .toMatchObject({ dead: dead.map((b) => served(b, false)) }); + expect.soft(kept.end, "at its end").toEqual(kept.start); + }); + + it("applies the prune once the node builds at the first pruned height", () => { + expect + .soft(receipt.blockNumber, "the new tx's block") + .toBe(prune.removed[0]); + expect + .soft(seen.chain, "the canonical block above the target") + .toEqual(want.chain); + expect + .soft(seen.reorgs, "every reorg: those before the prune, and one") + .toEqual(want.reorgs); + expect.soft(seen.dead, "the dead blocks by hash").toEqual(want.dead); + }); +}); diff --git a/services/network-smoke/src/explorer-reads.test.ts b/services/network-smoke/src/explorer-reads.test.ts new file mode 100644 index 00000000..13f1d2c6 --- /dev/null +++ b/services/network-smoke/src/explorer-reads.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from "vitest"; +import { settle } from "./explorer-reads.js"; + +/** Reads that count up to the expected state 3 and stay there, or never reach it. */ +const steps = (reaches: boolean) => { + const log: string[] = []; + let reads = 0; + const run = settle( + () => { + reads++; + log.push(`read ${reads}`); + return Promise.resolve({ state: reaches ? Math.min(reads, 3) : 0 }); + }, + { + want: { state: 3 }, + timeoutMs: 200, + intervalMs: 20, + cacheMs: 10, + consumedThrough: () => { + log.push("consumed"); + return Promise.resolve(); + }, + }, + ); + return { log, run }; +}; + +describe("settle", () => { + it("waits for the expected state, then for the consumers, then reads once more", async () => { + const { log, run } = steps(true); + expect(await run).toEqual({ value: { state: 3 }, met: true, held: true }); + expect(log).toEqual(["read 1", "read 2", "read 3", "consumed", "read 4"]); + }); + + it("still waits for the consumers and reads once more when the expected state never shows", async () => { + const { log, run } = steps(false); + expect(await run).toEqual({ value: { state: 0 }, met: false, held: false }); + expect(log.length, "reads until the time ran out").toBeGreaterThan(3); + expect(log.slice(-2)).toEqual(["consumed", `read ${log.length - 1}`]); + }); +}); diff --git a/services/network-smoke/src/explorer-reads.ts b/services/network-smoke/src/explorer-reads.ts new file mode 100644 index 00000000..20d06d53 --- /dev/null +++ b/services/network-smoke/src/explorer-reads.ts @@ -0,0 +1,163 @@ +import { setTimeout as sleep } from "node:timers/promises"; +import { isDeepStrictEqual } from "node:util"; +import { + chicmozL2BlockLightSchema, + chicmozL2ContractInstanceDeluxeSchema, + chicmozL2DroppedTxSchema, + chicmozL2TxEffectDeluxeSchema, + chicmozReorgSchema, +} from "@chicmoz-pkg/types"; +import { z } from "zod"; + +export type BlockRef = { height: number; hash: string }; + +export type ReorgRecord = { + height: number; + nbrOfOrphanedBlocks: number; + orphanedBlockHash: string; +}; + +type ReorgList = ReorgRecord[] | { status: number }; + +const sortedByRoot = (records: ReorgRecord[]) => + [...records].sort( + (a, b) => + a.height - b.height || + a.orphanedBlockHash.localeCompare(b.orphanedBlockHash), + ); + +/** Sorted by root, so two lists compare as sets; a failed read stays as it is. */ +export const byRoot = (reorgs: ReorgList): ReorgList => + Array.isArray(reorgs) ? sortedByRoot(reorgs) : reorgs; + +/** `baseline` with `record` added, by root. */ +export const plusReorg = (baseline: ReorgRecord[], record: ReorgRecord) => + sortedByRoot([...baseline, record]); + +/** A block as the scenarios compare it: its id, and whether it is served as orphaned. */ +export const served = ({ height, hash }: BlockRef, orphaned: boolean) => ({ + height, + hash: hash.toLowerCase(), + orphaned, +}); + +/** REST reads of an explorer API: the picked body on 200, `{ status }` on any other status. */ +export const explorerReads = (apiUrl: string) => { + const get = async (path: string) => { + const res = await fetch(new URL(path, apiUrl), { + signal: AbortSignal.timeout(5_000), + }); + const text = await res.text(); + let body: unknown = text; + try { + body = JSON.parse(text); + } catch { + // Not JSON: the text itself is the answer. + } + return { status: res.status, body }; + }; + const read = async (path: string, pick: (body: unknown) => T) => { + const { status, body } = await get(path); + return status === 200 ? pick(body) : { status }; + }; + const reorgs = () => + read("/l2/reorgs", (body) => + z + .array(chicmozReorgSchema) + .parse(body) + .map((r) => ({ + height: Number(r.height), + nbrOfOrphanedBlocks: r.nbrOfOrphanedBlocks, + orphanedBlockHash: r.orphanedBlockHash.toLowerCase(), + })), + ); + return { + get, + latestHeight: () => + read("/l2/latest-height", (body) => z.number().int().parse(body)), + blockAt: (heightOrHash: number | string) => + read(`/l2/blocks/${heightOrHash}`, (body) => { + const block = chicmozL2BlockLightSchema.parse(body); + return { + height: Number(block.height), + hash: block.hash.toLowerCase(), + orphaned: block.orphan !== undefined, + }; + }), + reorgs, + /** The list, or a throw: a baseline that later reads are compared with cannot be a failed read. */ + reorgList: async (): Promise => { + const list = await reorgs(); + if (!Array.isArray(list)) { + throw new Error(`/l2/reorgs answered ${list.status}`); + } + return list; + }, + dropped: (txHash: string) => + read(`/l2/dropped-txs/${txHash}`, (body) => { + const { dropReason } = chicmozL2DroppedTxSchema.parse(body); + return { status: 200, dropReason }; + }), + txEffect: (txHash: string) => + read(`/l2/tx-effects/${txHash}`, (body) => { + const effect = chicmozL2TxEffectDeluxeSchema.parse(body); + return { + height: Number(effect.blockHeight), + hash: effect.blockHash.toLowerCase(), + orphaned: effect.isOrphaned, + }; + }), + contractInstance: (address: string) => + read(`/l2/contract-instances/${address}`, (body) => { + const instance = chicmozL2ContractInstanceDeluxeSchema.parse(body); + return { + hash: instance.blockHash.toLowerCase(), + orphaned: instance.isOrphaned, + }; + }), + }; +}; + +/** Whether `value` holds `want`'s value at each of `want`'s keys. */ +export const holds = (value: T, want: Partial) => + Object.entries(want).every(([key, expected]) => + isDeepStrictEqual(value[key as keyof T], expected), + ); + +/** + * Reads `snapshot` until it `holds` `want` or `timeoutMs` passes, then waits + * until the API has committed through the end offsets of its topics at that + * moment (`consumedThrough`), and reads it once more after `cacheMs`, when + * the API's REST cache holds nothing older: that read is the settled state, + * whether `want` was met or not. Waiting on `want` keeps a fast read from + * settling before the listener publishes; offsets taken once keep records + * that never stop, tips and node liveness, from holding it off. + */ +export const settle = async ( + snapshot: () => Promise, + { + want, + timeoutMs, + intervalMs, + cacheMs, + consumedThrough, + }: { + want: Partial; + timeoutMs: number; + intervalMs: number; + cacheMs: number; + consumedThrough: (timeoutMs: number) => Promise; + }, +) => { + const deadline = Date.now() + timeoutMs; + let value = await snapshot(); + while (!holds(value, want) && Date.now() < deadline) { + await sleep(intervalMs); + value = await snapshot(); + } + const met = holds(value, want); + await consumedThrough(timeoutMs); + await sleep(cacheMs); + const confirmed = await snapshot(); + return { value: confirmed, met, held: holds(confirmed, want) }; +}; diff --git a/services/network-smoke/src/force-prune.ts b/services/network-smoke/src/force-prune.ts new file mode 100644 index 00000000..162b1182 --- /dev/null +++ b/services/network-smoke/src/force-prune.ts @@ -0,0 +1,281 @@ +import { setTimeout as sleep } from "node:timers/promises"; +import { RollupAbi } from "@aztec-foundation/l1-artifacts"; +import { BlockNumber } from "@aztec-labs/aztec.js/fields"; +import { type AztecNode } from "@aztec-labs/aztec.js/node"; +import { RollupCheatCodes } from "@aztec-labs/ethereum/test"; +import { EpochNumber } from "@aztec-labs/foundation/branded-types"; +import { DateProvider } from "@aztec-labs/foundation/timer"; +import { createAztecNodeDebugClient } from "@aztec-labs/stdlib/interfaces/client"; +import { createPublicClient, http } from "viem"; + +// MAX_RPC_BLOCKS_LEN (stdlib interfaces/api_limit.ts). +const NODE_PAGE = 50; + +type NodeTips = Awaited>; + +export type TipsView = { + proposed: number; + checkpointed: number; + proven: number; + finalized: number; +}; + +const tipsView = (t: NodeTips): TipsView => ({ + proposed: Number(t.proposed.number), + checkpointed: Number(t.checkpointed.block.number), + proven: Number(t.proven.block.number), + finalized: Number(t.finalized.block.number), +}); + +/** The hash at each height `from`..`to`, as the node serves them now. */ +export const readHashes = async (node: AztecNode, to: number, from = 1) => { + const hashes = new Map(); + for (let start = from; start <= to; start += NODE_PAGE) { + const blocks = await node.getBlocks( + BlockNumber(start), + Math.min(NODE_PAGE, to - start + 1), + ); + for (const b of blocks) { + hashes.set(Number(b.number), b.hash.toString().toLowerCase()); + } + } + return hashes; +}; + +/** The node's hash at each height up to its proposed tip. */ +export const readNodeChain = async (node: AztecNode) => + readHashes(node, tipsView(await node.getChainTips()).proposed); + +export type ChainEvent = { + at: number; + kind: "tip-back" | "height-removed" | "hash-changed"; + height?: number; + newHash?: string; +}; + +export type ChainWatch = ReturnType; + +/** + * Polls the node's tips and every hash up to its proposed tip, and records + * the tip moving back and any height whose block disappears or changes. + */ +export const watchChain = ( + node: AztecNode, + log: (line: string) => void, + intervalMs = 1_000, +) => { + const events: ChainEvent[] = []; + let hashes = new Map(); + let tip: number | undefined; + let stopped = false; + const record = (event: ChainEvent) => { + events.push(event); + log(`chain ${JSON.stringify(event)}`); + }; + const poll = async () => { + const next = tipsView(await node.getChainTips()).proposed; + const nextHashes = await readHashes(node, next); + // After the reads, so an event is never dated before what it saw. + const at = Date.now(); + if (tip !== undefined && next < tip) { + record({ at, kind: "tip-back" }); + } + for (const [height, hash] of hashes) { + const now = nextHashes.get(height); + if (now === undefined) { + record({ at, kind: "height-removed", height }); + } else if (now !== hash) { + record({ at, kind: "hash-changed", height, newHash: now }); + } + } + hashes = nextHashes; + tip = next; + }; + const loop = (async () => { + while (!stopped) { + const started = Date.now(); + try { + await poll(); + } catch (e) { + log(`chain watch: ${(e as Error).message}`); + } + await sleep(Math.max(0, intervalMs - (Date.now() - started))); + } + })(); + return { + events, + /** Hashes may later change at a height `removed` here: compare with a fresh read. */ + stop: async () => { + stopped = true; + await loop; + }, + }; +}; + +const rollupOf = async (node: AztecNode, anvilUrl: string) => { + const { rollupAddress } = await node.getL1ContractAddresses(); + const address = rollupAddress.toString(); + const l1 = createPublicClient({ + transport: http(anvilUrl, { timeout: 10_000 }), + }); + const read = (functionName: string, args: unknown[] = []) => + l1.readContract({ + address, + abi: RollupAbi, + functionName, + args, + } as never) as Promise; + return { + cheat: RollupCheatCodes.create( + [anvilUrl], + { rollupAddress }, + new DateProvider(), + ), + tips: async () => { + const t = await read<{ pending: bigint; proven: bigint }>("getTips"); + return { pending: Number(t.pending), proven: Number(t.proven) }; + }, + epochOfCheckpoint: async (checkpoint: number) => + Number(await read("getEpochForCheckpoint", [BigInt(checkpoint)])), + proofSubmissionEpochs: async () => + Number(await read("getProofSubmissionEpochs")), + }; +}; + +export type ForcedPrune = { + /** The proven tip the node prunes back to. */ + target: number; + /** Heights built for the prune, all unproven at the warp. */ + doomed: number[]; + /** The node's hashes up to its tip just before the warp. */ + before: Map; + /** Doomed heights the node no longer serves with their old hash. */ + removed: number[]; + /** The node's hashes after the prune, or after the replacement when expected. */ + after: Map; + timings: { triggerToPruneMs: number; pruneToReplacementMs?: number }; + /** Epoch ms: the warp's start, and the first reads, 250 ms apart, that showed the prune and the replacement. */ + at: { warp: number; prune: number; replacement?: number }; +}; + +/** + * Has the local network prune blocks: proves every checkpoint, builds the + * doomed blocks (`sendTxs`, then `emptyBlocks` empty ones), and warps L1 past + * their epoch's proof window, after which the node's archiver removes them. + * Needs the local network with epoch auto-settle off, or nothing stays + * unproven. With txs in the doomed blocks the node builds a replacement at + * once; with none it waits on the shorter chain. + */ +export const forceEpochPrune = async ({ + node, + nodeUrl, + anvilUrl, + sendTxs, + emptyBlocks, + afterProve, + beforeTrigger, + expectReplacement, + log, + timeoutMs = 60_000, +}: { + node: AztecNode; + nodeUrl: string; + anvilUrl: string; + /** Resolves once the node has the txs in blocks. */ + sendTxs: () => Promise; + emptyBlocks: number; + /** Runs once the base is proven, before any doomed block is built. */ + afterProve: (base: Map) => Promise; + /** Runs with the doomed blocks built, before the warp. */ + beforeTrigger: ( + doomed: number[], + hashes: Map, + ) => Promise; + expectReplacement: boolean; + log: (line: string) => void; + timeoutMs?: number; +}): Promise => { + // The local network serves its debug namespace on the public port. With + // auto-settle off, `prove` is the only way the proven tip moves. + const debug = createAztecNodeDebugClient(nodeUrl); + const rollup = await rollupOf(node, anvilUrl); + const provenTo = await debug.prove(); + log(`proved to checkpoint ${provenTo}`); + // One block per checkpoint on the local network. + await afterProve(await readHashes(node, Number(provenTo))); + + await sendTxs(); + for (let i = 0; i < emptyBlocks; i++) { + await debug.mineBlock(); + } + // The automine publishes before it returns; one archiver pass (500 ms) + // then moves the checkpointed tip. + await sleep(1_500); + const tips = tipsView(await node.getChainTips()); + const before = await readHashes(node, tips.proposed); + const doomed = [...before.keys()].filter((h) => h > tips.proven); + const l1 = await rollup.tips(); + if (doomed.length === 0 || l1.pending === l1.proven) { + throw new Error( + `nothing unproven to prune (tips ${JSON.stringify(tips)}, L1 ${JSON.stringify(l1)}): is epoch auto-settle off?`, + ); + } + await beforeTrigger(doomed, before); + + const epoch = await rollup.epochOfCheckpoint(l1.proven + 1); + const targetEpoch = epoch + (await rollup.proofSubmissionEpochs()) + 1; + const warpedAt = Date.now(); + await rollup.cheat.advanceToEpoch(EpochNumber(targetEpoch)); + log( + `doomed ${doomed.join(",")}; warped from epoch ${epoch} to ${targetEpoch}`, + ); + + // Against `before` only: a doomed height is pruned once a read lacks its + // old hash, and replaced once a read shows another block there. + const doomedTip = Math.max(...doomed); + let pruneAt: number | undefined; + let replacedAt: number | undefined; + while (Date.now() < warpedAt + timeoutMs) { + const tip = tipsView(await node.getChainTips()).proposed; + const now = await readHashes(node, Math.min(tip, doomedTip), doomed[0]); + const at = Date.now(); + const moved = doomed.filter((h) => now.get(h) !== before.get(h)); + if (moved.length > 0) { + pruneAt ??= at; + } + if (moved.some((h) => now.has(h))) { + replacedAt ??= at; + } + if ( + pruneAt !== undefined && + (!expectReplacement || replacedAt !== undefined) + ) { + break; + } + await sleep(250); + } + if (pruneAt === undefined) { + throw new Error( + `no prune of ${doomed.join(",")} within ${timeoutMs / 1000} s of the warp`, + ); + } + if (expectReplacement && replacedAt === undefined) { + throw new Error( + `no replacement block within ${timeoutMs / 1000} s of the warp`, + ); + } + const after = await readNodeChain(node); + return { + target: tips.proven, + doomed, + before, + removed: doomed.filter((h) => after.get(h) !== before.get(h)), + after, + timings: { + triggerToPruneMs: pruneAt - warpedAt, + pruneToReplacementMs: + replacedAt === undefined ? undefined : replacedAt - pruneAt, + }, + at: { warp: warpedAt, prune: pruneAt, replacement: replacedAt }, + }; +}; diff --git a/services/network-smoke/src/kafka.ts b/services/network-smoke/src/kafka.ts new file mode 100644 index 00000000..01b31900 --- /dev/null +++ b/services/network-smoke/src/kafka.ts @@ -0,0 +1,45 @@ +import { type Stack } from "@chicmoz/test-harness"; + +const TOPICS = "/opt/kafka/bin/kafka-topics.sh"; +// The broker's own listener and client config inside the harness container. +const CLIENT = [ + "--bootstrap-server", + "localhost:9092", + "--command-config", + "/etc/kafka/secrets/client.properties", +]; + +/** + * Creates `topic` with `partitions` partitions. It must run before any + * client touches the topic: the broker auto-creates topics with one. + */ +export const createTopic = async ( + stack: Stack, + topic: string, + partitions: number, +) => { + await stack.exec("kafka", [ + TOPICS, + ...CLIENT, + "--create", + "--topic", + topic, + "--partitions", + String(partitions), + "--replication-factor", + "1", + ]); + const described = await stack.exec("kafka", [ + TOPICS, + ...CLIENT, + "--describe", + "--topic", + topic, + ]); + const count = /PartitionCount:\s*(\d+)/.exec(described)?.[1]; + if (Number(count) !== partitions) { + throw new Error( + `topic ${topic} has ${count ?? "no"} partitions, not ${partitions}`, + ); + } +}; diff --git a/services/network-smoke/src/network.ts b/services/network-smoke/src/network.ts index ce6d25ca..9787cd44 100644 --- a/services/network-smoke/src/network.ts +++ b/services/network-smoke/src/network.ts @@ -1,11 +1,25 @@ import { randomBytes } from "node:crypto"; +import { copyFileSync, mkdirSync, symlinkSync } from "node:fs"; import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; import { type Ports } from "./ports.js"; import { type ProcessGroups } from "./processes.js"; import { type Toolchain } from "./toolchain.js"; export const L1_CHAIN_ID = 31337; +/** + * How long the node holds a read by number of the block one past its tip, + * waiting for that block: twice the 3 s block duration, the node's default, + * so reads are held as in production. Set rather than left to the default, + * so the prune scenarios can bound the listener's read gap by it. + */ +export const UNSEEN_BLOCK_WAIT_MS = 2 * 3_000; + +const LAUNCHER = fileURLToPath( + new URL("../toolchain/local-network.mjs", import.meta.url), +); + export const startAnvil = ( groups: ProcessGroups, toolchain: Toolchain, @@ -31,6 +45,26 @@ export const startAnvil = ( { cwd: runDir, env: {}, tier: 0 }, ); +const nodeEnv = (toolchain: Toolchain, anvilUrl: string, tmp: string) => ({ + PATH: `${dirname(toolchain.forge)}:${process.env.PATH ?? ""}`, + FORGE_BIN: toolchain.forge, + ANVIL_BIN: toolchain.anvil, + // The local network keeps its stores under TMPDIR, not --data-directory. + TMPDIR: tmp, + ETHEREUM_HOSTS: anvilUrl, + L1_CHAIN_ID: String(L1_CHAIN_ID), + TEST_ACCOUNTS: "true", + LOG_LEVEL: "info", + ARCHIVER_POLLING_INTERVAL_MS: "500", + ARCHIVER_VIEM_POLLING_INTERVAL_MS: "500", + P2P_BLOCK_CHECK_INTERVAL_MS: "500", + SEQ_TX_POLLING_INTERVAL_MS: "500", + WS_BLOCK_CHECK_INTERVAL_MS: "500", + RPC_UNSEEN_BLOCK_BY_NUMBER_WAIT_MS: String(UNSEEN_BLOCK_WAIT_MS), + // The toolchain installs without scripts, so bcrypto has no native build. + NODE_BACKEND: "js", +}); + /** * `aztec start --local-network` through the CLI entry point directly: the * `aztec` shell wrapper's `start` branch launches an anvil of its own. @@ -66,25 +100,44 @@ export const startAztecNode = ( cwd: runDir, tier: 1, env: { - PATH: `${dirname(toolchain.forge)}:${process.env.PATH ?? ""}`, - FORGE_BIN: toolchain.forge, - ANVIL_BIN: toolchain.anvil, - // The local network keeps its stores under TMPDIR, not --data-directory. - TMPDIR: tmp, - ETHEREUM_HOSTS: anvilUrl, - L1_CHAIN_ID: String(L1_CHAIN_ID), - TEST_ACCOUNTS: "true", - LOG_LEVEL: "info", - ARCHIVER_POLLING_INTERVAL_MS: "500", - ARCHIVER_VIEM_POLLING_INTERVAL_MS: "500", - P2P_BLOCK_CHECK_INTERVAL_MS: "500", - SEQ_TX_POLLING_INTERVAL_MS: "500", - WS_BLOCK_CHECK_INTERVAL_MS: "500", - // The toolchain installs without scripts, so bcrypto has no native build. - NODE_BACKEND: "js", + ...nodeEnv(toolchain, anvilUrl, tmp), // Admin auth stays on with a random hash: no key is generated or logged. AZTEC_ADMIN_API_KEY_HASH: randomBytes(32).toString("hex"), }, }, ); }; + +/** + * The local network with epoch auto-settle off (`toolchain/local-network.mjs`). + * The launcher is copied into the run directory, beside a link to the + * toolchain's node_modules: linked, Node would resolve its imports from its + * real path, where those packages are not. + */ +export const startLocalNetwork = ( + groups: ProcessGroups, + toolchain: Toolchain, + ports: Ports, + runDir: string, + tmp: string, +) => { + const anvilUrl = `http://127.0.0.1:${ports.anvil}`; + const dir = join(runDir, "launcher"); + mkdirSync(dir, { recursive: true }); + symlinkSync(toolchain.nodeModules, join(dir, "node_modules"), "dir"); + const entry = join(dir, "local-network.mjs"); + copyFileSync(LAUNCHER, entry); + return groups.start( + "aztec-node", + process.execPath, + [ + "--no-warnings", + entry, + "--port", + String(ports.aztec), + "--l1-rpc-urls", + anvilUrl, + ], + { cwd: runDir, tier: 1, env: nodeEnv(toolchain, anvilUrl, tmp) }, + ); +}; diff --git a/services/network-smoke/src/port-registry-lock.test.ts b/services/network-smoke/src/port-registry-lock.test.ts new file mode 100644 index 00000000..ae591222 --- /dev/null +++ b/services/network-smoke/src/port-registry-lock.test.ts @@ -0,0 +1,36 @@ +import * as fs from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { claimPorts } from "./port-registry.js"; + +// The lock's token is its only writeSync. +vi.mock("node:fs", async (importOriginal) => ({ + ...(await importOriginal()), + writeSync: () => { + throw Object.assign(new Error("no space left on device"), { + code: "ENOSPC", + }); + }, +})); + +describe("port registry lock", () => { + const dir = fs.mkdtempSync(join(tmpdir(), "chicmoz-port-lock-")); + afterEach(() => fs.rmSync(dir, { recursive: true, force: true })); + + it("removes a lock it created when its token cannot be written", async () => { + const file = join(dir, "ports.md"); + await expect( + claimPorts( + { + runId: "ns0000000000", + ports: { anvil: 20_001 }, + ownerPid: process.pid, + worktree: dir, + }, + { file, lockWaitMs: 1_000 }, + ), + ).rejects.toThrow("no space left on device"); + expect(fs.existsSync(`${file}.lock`), "the lock file").toBe(false); + }); +}); diff --git a/services/network-smoke/src/port-registry.test.ts b/services/network-smoke/src/port-registry.test.ts new file mode 100644 index 00000000..b11f493f --- /dev/null +++ b/services/network-smoke/src/port-registry.test.ts @@ -0,0 +1,86 @@ +import { spawnSync } from "node:child_process"; +import { + existsSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { + PortClaimConflict, + claimPorts, + releasePorts, +} from "./port-registry.js"; + +// Another tool's rows and a line no parser expects: both must survive as they are. +const FOREIGN = [ + "# Ports registry — who is RUNNING what, where (atomic-locked)", + "| port | service | owner (run) | worktree | pid-hint | claimed |", + "|---|---|---|---|---|---|", + "| 20248 | other-anvil | other-run | /elsewhere | 1 | 2026-11-26T00:00:00.000Z |", + " a note someone left ", + "", +].join("\n"); + +describe("port registry", () => { + let dir: string; + let file: string; + const claim = ( + runId: string, + ports: Record, + ownerPid = process.pid, + ) => claimPorts({ runId, ports, ownerPid, worktree: "/repo" }, { file }); + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "chicmoz-port-registry-")); + file = join(dir, "ports.md"); + writeFileSync(file, FOREIGN); + }); + + afterEach(() => rmSync(dir, { recursive: true, force: true })); + + it("adds a run's rows, keeps every other line as it was, and releases only that run", async () => { + await claim("ns1", { anvil: 21000, aztec: 21001 }); + await claim("ns2", { anvil: 21002 }); + const lines = readFileSync(file, "utf8").split("\n"); + expect(lines.slice(0, 5)).toEqual(FOREIGN.split("\n").slice(0, 5)); + expect(lines.filter((l) => l.includes("| chicmoz-smoke-"))).toHaveLength(3); + + await releasePorts("ns1", { file }); + await releasePorts("ns2", { file }); + expect(readFileSync(file, "utf8")).toBe(FOREIGN); + expect(existsSync(`${file}.lock`)).toBe(false); + }); + + it("refuses a port any line lists, writing nothing, and frees its own rows once their owner is dead", async () => { + await expect(claim("ns1", { anvil: 20248 })).rejects.toThrow( + PortClaimConflict, + ); + expect(readFileSync(file, "utf8")).toBe(FOREIGN); + + const dead = spawnSync(process.execPath, ["-e", ""]).pid; + await claim("ns1", { anvil: 21000 }, dead); + await expect(claim("ns2", { anvil: 21000 })).resolves.toBeUndefined(); + expect(readFileSync(file, "utf8")).not.toContain("| ns1 |"); + }); + + it("waits for another writer's lock and never breaks it", async () => { + writeFileSync(`${file}.lock`, "held by another tool\n"); + await expect( + claimPorts( + { + runId: "ns1", + ports: { anvil: 21000 }, + ownerPid: process.pid, + worktree: "/repo", + }, + { file, lockWaitMs: 300 }, + ), + ).rejects.toThrow("stayed held"); + expect(readFileSync(`${file}.lock`, "utf8")).toBe("held by another tool\n"); + expect(readFileSync(file, "utf8")).toBe(FOREIGN); + }); +}); diff --git a/services/network-smoke/src/port-registry.ts b/services/network-smoke/src/port-registry.ts new file mode 100644 index 00000000..d800ec4f --- /dev/null +++ b/services/network-smoke/src/port-registry.ts @@ -0,0 +1,267 @@ +import { randomBytes } from "node:crypto"; +import { + chmodSync, + closeSync, + existsSync, + mkdirSync, + openSync, + readFileSync, + realpathSync, + renameSync, + rmSync, + statSync, + unlinkSync, + writeFileSync, + writeSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { setTimeout as sleep } from "node:timers/promises"; + +/** + * Client for the host's port registry, `~/.agents/ports.md`, which every + * agent on the host reads to see which ports another run holds. Other tools + * write the same file, so its format and lock are a contract matched here: + * rows `| port | service | owner (run) | worktree | pid-hint | claimed |`, + * rewritten only while `.lock` exists, created with `open(..., "wx")`. + * Some writers delete a lock older than 15 s; this client never breaks one + * (a breaker can delete a lock taken after it judged the old one stale), and + * fails closed after waiting longer. Only rows with this prefix are parsed + * whole or dropped; every other line is copied byte for byte, and every port + * any line lists counts as taken. + */ +export const SERVICE_PREFIX = "chicmoz-smoke-"; + +const HEADER = [ + "# Ports registry — who is RUNNING what, where (atomic-locked)", + "| port | service | owner (run) | worktree | pid-hint | claimed |", + "|---|---|---|---|---|---|", +]; +// Linux's ceiling for pid_max: a larger hint names no process. +const PID_MAX = 4_194_304; + +export type RegistryOptions = { + /** Defaults to `~/.agents/ports.md`. */ + file?: string; + lockWaitMs?: number; +}; + +const pathOf = ({ file }: RegistryOptions) => + file ?? join(homedir(), ".agents", "ports.md"); + +export class PortClaimConflict extends Error { + constructor(readonly ports: number[]) { + super(`ports already listed in the host registry: ${ports.join(", ")}`); + } +} + +/** The first cell as an integer, as the other writers read it. */ +const portOfLine = (line: string) => { + const port = Number.parseInt(line.split("|")[1]?.trim() ?? "", 10); + return Number.isInteger(port) ? port : undefined; +}; + +/** Every port the registry lists. Read without the lock: a hint for drawing, never the check a claim rests on. */ +export const registeredPorts = (options: RegistryOptions = {}) => { + const ports = new Set(); + let text: string; + try { + text = readFileSync(pathOf(options), "utf8"); + } catch { + return ports; + } + for (const line of text.split("\n")) { + const port = portOfLine(line); + if (port !== undefined) { + ports.add(port); + } + } + return ports; +}; + +type OwnRow = { runId: string; pidHint: string }; + +const ownRow = (line: string): OwnRow | undefined => { + const cells = line.split("|"); + if (cells.length !== 8 || cells[0] !== "" || cells[7] !== "") { + return undefined; + } + const [port, service, runId, , pidHint] = cells + .slice(1, 6) + .map((c) => c.trim()); + return /^\d{1,5}$/.test(port) && service.startsWith(SERVICE_PREFIX) + ? { runId, pidHint } + : undefined; +}; + +/** True only when the kernel says no such process; `kill(pid, 0)` only asks. */ +const ownerIsDead = (pidHint: string) => { + const pid = Number(pidHint); + if (!/^\d+$/.test(pidHint) || pid <= 0 || pid > PID_MAX) { + return false; + } + try { + process.kill(pid, 0); + return false; + } catch (e) { + return (e as NodeJS.ErrnoException).code === "ESRCH"; + } +}; + +const lock = async (file: string, waitMs: number) => { + const path = `${file}.lock`; + const token = `chicmoz-smoke ${process.pid} ${randomBytes(8).toString("hex")}\n`; + const deadline = Date.now() + waitMs; + for (;;) { + let fd: number | undefined; + try { + fd = openSync(path, "wx", 0o600); + } catch (e) { + if ((e as NodeJS.ErrnoException).code !== "EEXIST") { + throw e; + } + } + if (fd !== undefined) { + try { + try { + writeSync(fd, token); + } finally { + closeSync(fd); + } + } catch (e) { + // No unlock could ever match a lock without our token, so it would + // block every writer until removed by hand. + rmSync(path, { force: true }); + throw e; + } + // Unlinked only while it still holds this token. + return () => { + try { + if (readFileSync(path, "utf8") === token) { + unlinkSync(path); + } + } catch { + // Already gone. + } + }; + } + if (Date.now() >= deadline) { + throw new Error( + `${path} stayed held for ${waitMs / 1000} s; if no registry writer is running, remove it by hand`, + ); + } + await sleep(100); + } +}; + +/** + * Rewrites the registry under its lock. `mutate` gets its lines (the last is + * "" when the file ends in a newline) and returns the new ones, or undefined + * to write nothing. The rename means no reader sees a torn file. + */ +const withRegistry = async ( + mutate: (lines: string[] | undefined) => string[] | undefined, + options: RegistryOptions, +) => { + const file = pathOf(options); + mkdirSync(dirname(file), { recursive: true }); + const unlock = await lock(file, options.lockWaitMs ?? 30_000); + try { + const current = existsSync(file) ? readFileSync(file, "utf8") : undefined; + const next = mutate(current?.split("\n")); + if (next === undefined || next.join("\n") === current) { + return; + } + const target = current === undefined ? file : realpathSync(file); + const tmp = `${target}.${SERVICE_PREFIX}${randomBytes(6).toString("hex")}.tmp`; + try { + writeFileSync(tmp, next.join("\n")); + // A rename gives the file the umask's mode instead of its own. + if (current !== undefined) { + chmodSync(tmp, statSync(target).mode & 0o777); + } + renameSync(tmp, target); + } finally { + rmSync(tmp, { force: true }); + } + } finally { + unlock(); + } +}; + +const cell = (value: string) => { + if (value.length === 0 || /[|\r\n]/.test(value)) { + throw new Error( + `registry cell ${JSON.stringify(value)} is empty or holds '|' or a newline`, + ); + } + return value; +}; + +/** + * Under the lock: drops this prefix's rows whose owner is dead, then appends + * one row per service, or throws `PortClaimConflict` and writes nothing when + * any line already lists a wanted port. + */ +export const claimPorts = async ( + { + runId, + ports, + ownerPid, + worktree, + }: { + runId: string; + ports: Record; + /** The process whose life the claim lasts. */ + ownerPid: number; + worktree: string; + }, + options: RegistryOptions = {}, +) => { + const claimed = new Date().toISOString(); + const rows = Object.entries(ports).map( + ([service, port]) => + `| ${port} | ${cell(SERVICE_PREFIX + service)} | ${cell(runId)} | ${cell(worktree)} | ${ownerPid} | ${claimed} |`, + ); + let conflicts: number[] = []; + await withRegistry((lines) => { + const kept = (lines ?? []).filter((line) => { + const row = ownRow(line); + return row === undefined || !ownerIsDead(row.pidHint); + }); + const listed = new Set(kept.map(portOfLine)); + conflicts = Object.values(ports).filter((p) => listed.has(p)); + if (conflicts.length > 0) { + return undefined; + } + const base = kept.every((l) => l.trim() === "") ? [...HEADER, ""] : kept; + const end = base.at(-1) === "" ? base.length - 1 : base.length; + return [...base.slice(0, end), ...rows, ""]; + }, options); + if (conflicts.length > 0) { + throw new PortClaimConflict(conflicts); + } +}; + +/** + * Drops this run's rows. Never throws, so teardown goes on; false, with the + * reason on stderr, when the registry could not be rewritten, and the + * caller's teardown then is not clean. + */ +export const releasePorts = async ( + runId: string, + options: RegistryOptions = {}, +) => { + try { + await withRegistry( + (lines) => lines?.filter((line) => ownRow(line)?.runId !== runId), + options, + ); + return true; + } catch (e) { + process.stderr.write( + `network-smoke: could not release ${runId}'s ports: ${(e as Error).message}\n`, + ); + return false; + } +}; diff --git a/services/network-smoke/src/ports.test.ts b/services/network-smoke/src/ports.test.ts index ea0069be..36324939 100644 --- a/services/network-smoke/src/ports.test.ts +++ b/services/network-smoke/src/ports.test.ts @@ -1,7 +1,44 @@ +import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { createServer } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { parseEphemeralFloor, parsePorts, portBelow } from "./ports.js"; +import { + claimRunPorts, + freePorts, + parseEphemeralFloor, + parsePorts, + portBelow, +} from "./ports.js"; describe("ports", () => { + it("refuses a fixed port that a process outside the registry holds, and claims none", async () => { + const dir = mkdtempSync(join(tmpdir(), "chicmoz-ports-")); + const file = join(dir, "ports.md"); + const fixed = await freePorts(); + const holder = createServer(); + await new Promise((resolve) => holder.listen(fixed.aztec, resolve)); + try { + await expect( + claimRunPorts( + { + runId: "ns0000000000", + ownerPid: process.pid, + worktree: dir, + fixed, + }, + { file }, + ), + ).rejects.toThrow(`fixed port ${fixed.aztec} (aztec) is in use`); + expect(existsSync(file) ? readFileSync(file, "utf8") : "").not.toContain( + "ns0000000000", + ); + } finally { + await new Promise((resolve) => holder.close(resolve)); + rmSync(dir, { recursive: true, force: true }); + } + }); + it("rejects a websocket health port that is not ws + 1", () => { expect(() => parsePorts("20001,20002,20003,20004,20005,20006,20008"), diff --git a/services/network-smoke/src/ports.ts b/services/network-smoke/src/ports.ts index abe49d4e..ecd492f1 100644 --- a/services/network-smoke/src/ports.ts +++ b/services/network-smoke/src/ports.ts @@ -1,5 +1,11 @@ import { readFileSync } from "node:fs"; import { type Server, createServer } from "node:net"; +import { + PortClaimConflict, + type RegistryOptions, + claimPorts, + registeredPorts, +} from "./port-registry.js"; export const PORT_NAMES = [ "anvil", @@ -60,6 +66,35 @@ const portOf = (server: Server) => { return address.port; }; +const closeAll = (servers: Server[]) => + Promise.all( + servers.map( + (s) => new Promise((resolve) => s.close(() => resolve())), + ), + ); + +/** Binds every fixed port, all held until `reserve` has run; one in use fails the claim. */ +const holdFixed = async ( + ports: Ports, + reserve: (ports: Ports) => Promise, +) => { + const held: Server[] = []; + try { + for (const [name, port] of Object.entries(ports)) { + try { + held.push(await listen(port)); + } catch (e) { + throw new Error( + `fixed port ${port} (${name}) is in use: ${(e as NodeJS.ErrnoException).code ?? (e as Error).message}`, + ); + } + } + await reserve(ports); + } finally { + await closeAll(held); + } +}; + const MIN_PORT = 10_000; /** The kernel's ephemeral floor from `ip_local_port_range`'s text, if usable. */ @@ -85,13 +120,23 @@ export const portBelow = (floor: number, span = 1, random = Math.random) => MIN_PORT + Math.floor(random() * (floor - span - MIN_PORT + 1)); /** - * Free ports, all held until every one is chosen. Where the kernel's - * ephemeral range is readable they are random ports below it, which - * outgoing connections never take; elsewhere the OS assigns them. Another - * listener can still take one before our child binds it; the child then dies - * and the run fails naming it. + * Free ports, all held until every one is chosen and `reserve` has run. + * Where the kernel's ephemeral range is readable they are random ports below + * it, which outgoing connections never take; elsewhere the OS assigns them. + * Ports in `skip` are never chosen. A process that ignores the host registry + * can still take one before our child binds it; the child then dies and the + * run fails naming it. */ -export const freePorts = async (floor = ephemeralFloor()): Promise => { +export const freePorts = async ( + floor = ephemeralFloor(), + { + skip = new Set(), + reserve = () => Promise.resolve(), + }: { + skip?: ReadonlySet; + reserve?: (ports: Ports) => Promise; + } = {}, +): Promise => { const held: Server[] = []; const hold = async (port: number) => { const server = await listen(port); @@ -99,18 +144,25 @@ export const freePorts = async (floor = ephemeralFloor()): Promise => { return portOf(server); }; const single = async (span = 1) => { - if (floor === undefined) { - return hold(0); - } for (let attempt = 0; attempt < 50; attempt++) { try { - return await hold(portBelow(floor, span)); + // A skipped port the OS hands out stays held, so it is not handed out again. + const port = await hold( + floor === undefined ? 0 : portBelow(floor, span), + ); + if (!skip.has(port)) { + return port; + } } catch { // In use, or one we already hold: draw again. continue; } } - throw new Error(`no free port between ${MIN_PORT} and ${floor}`); + throw new Error( + floor === undefined + ? "no free port the host registry does not list" + : `no free port between ${MIN_PORT} and ${floor}`, + ); }; try { const [anvil, aztec, aztecAdmin, aztecP2p, explorerApi] = [ @@ -121,26 +173,67 @@ export const freePorts = async (floor = ephemeralFloor()): Promise => { await single(), ]; for (let attempt = 0; attempt < 20; attempt++) { + // A ws whose ws + 1 is taken stays held, so it is not offered again. const ws = await single(2); + if (skip.has(ws + 1)) { + continue; + } try { await hold(ws + 1); - return check({ - anvil, - aztec, - aztecAdmin, - aztecP2p, - explorerApi, - ws, - wsHealth: ws + 1, - }); } catch { - // ws + 1 is taken; keep ws held so it is not offered again. + continue; } + const ports = check({ + anvil, + aztec, + aztecAdmin, + aztecP2p, + explorerApi, + ws, + wsHealth: ws + 1, + }); + await reserve(ports); + return ports; } throw new Error("no free adjacent port pair for the websocket publisher"); } finally { - await Promise.all( - held.map((s) => new Promise((resolve) => s.close(() => resolve()))), - ); + await closeAll(held); + } +}; + +/** + * This run's ports, claimed in the host registry for as long as `ownerPid` + * lives: `fixed` as given, otherwise free ones no registry line lists. Both + * kinds are bound while the claim is made, so a port that a process outside + * the registry still holds, such as a stopped run's surviving child, is + * never claimed. + */ +export const claimRunPorts = async ( + { + runId, + ownerPid, + worktree, + fixed, + }: { runId: string; ownerPid: number; worktree: string; fixed?: Ports }, + options: RegistryOptions = {}, +): Promise => { + const reserve = (ports: Ports) => + claimPorts({ runId, ports, ownerPid, worktree }, options); + if (fixed) { + await holdFixed(fixed, reserve); + return fixed; + } + for (let attempt = 0; ; attempt++) { + try { + return await freePorts(undefined, { + skip: registeredPorts(options), + reserve, + }); + } catch (e) { + // Another agent claimed one between our read and our claim: draw again. + if (!(e instanceof PortClaimConflict) || attempt === 4) { + throw e; + } + } } }; diff --git a/services/network-smoke/src/processes.ts b/services/network-smoke/src/processes.ts index f2e98615..6fde4b9d 100644 --- a/services/network-smoke/src/processes.ts +++ b/services/network-smoke/src/processes.ts @@ -241,5 +241,20 @@ export const createProcessGroups = (runId: string, runDir: string) => { } }; - return { start, stopAll, killAllSync, deaths }; + /** + * SIGKILL, with no grace, for the latest group started as `name`, as a + * crash would end it; not a death. Resolves false if a marked member + * outlives it. + */ + const kill = async (name: string) => { + const entry = started.findLast((s) => s.name === name); + if (entry === undefined) { + throw new Error(`no process ${name} was started`); + } + entry.stopping = true; + signalGroup(entry.pgid, runId, "SIGKILL"); + return goneWithin(entry.pgid, runId, 2_000); + }; + + return { start, stopAll, killAllSync, kill, deaths }; }; diff --git a/services/network-smoke/src/prune.scripted.ts b/services/network-smoke/src/prune.scripted.ts new file mode 100644 index 00000000..5362b060 --- /dev/null +++ b/services/network-smoke/src/prune.scripted.ts @@ -0,0 +1,697 @@ +import { execFile } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { createAztecNodeClient } from "@aztec-labs/aztec.js/node"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { z } from "zod"; +import { brokerReads } from "./broker.js"; +import { + type HeightRange, + checkRanges, + firstMismatch, +} from "./compare-ranges.js"; +import { apiStop, listenerStop } from "./crash-stops.js"; +import { readScriptedEndpoints } from "./endpoints.js"; +import { + type ReorgRecord, + byRoot, + explorerReads, + served, + settle, +} from "./explorer-reads.js"; +import { + type BlockId, + type PruneFacts, + type ScriptStatus, + scriptControl, +} from "./script-control.js"; +import { serviceControl } from "./service-control.js"; +import { + type PruneHooks, + type ShortHold, + type StepTimes, + stepThrough, +} from "./step-through.js"; + +const endpoints = readScriptedEndpoints(); +const control = scriptControl(endpoints.controlUrl); +const api = explorerReads(endpoints.explorerApiUrl); +const broker = brokerReads(endpoints.broker); +const services = serviceControl(endpoints.servicesUrl); +const { databases, ...pgAccess } = endpoints.postgres; + +afterAll(() => broker.close()); + +// Two of the listener's 1 s polls per state. +const STEP_MS = 2_000; +// For the API to reach what a scenario expects after its last step, which a +// correct pipeline does in a few polls; it bounds the commit wait too. +const SETTLE_TIMEOUT_MS = 30_000; +// Longer than the API's 5 s block cache. +const CACHE_MS = 6_000; + +const range = (from: number, to: number) => + Array.from({ length: Math.max(0, to - from + 1) }, (_, i) => from + i); + +/** What the API serves of one prune, from height `from` to one past the node's tip. */ +const snapshot = async ( + prune: PruneFacts, + from: number, + contractAddress?: string, +) => ({ + latestHeight: await api.latestHeight(), + canonical: await Promise.all( + range(from, prune.final.length + 1).map(api.blockAt), + ), + reorgs: byRoot(await api.reorgs()), + dropped: await api.dropped(prune.movedTx.hash), + txEffect: await api.txEffect(prune.movedTx.hash), + contractInstance: + contractAddress === undefined + ? undefined + : await api.contractInstance(contractAddress), + dead: await Promise.all(prune.dead.map((b) => api.blockAt(b.hash))), +}); + +type Snapshot = Awaited>; + +// Scenarios run one after another, each ending on its settled read, so the +// time since the last one is the next one's runtime. +let lastSettledAt = Date.now(); + +/** The API once it has consumed what the broker held when `want` was met or its time ran out; a consumer that never catches up fails the scenario. */ +const settled = async ( + read: () => Promise, + want: Partial, + label: string, +) => { + const { value, met, held } = await settle(read, { + want, + timeoutMs: SETTLE_TIMEOUT_MS, + intervalMs: 1_000, + cacheMs: CACHE_MS, + consumedThrough: broker.apiConsumedThrough, + }); + const took = (Date.now() - lastSettledAt) / 1000; + lastSettledAt = Date.now(); + process.stdout.write( + `${label} (the scenario took ${took.toFixed(1)} s): ${met ? "expected state reached" : `expected state not reached in ${SETTLE_TIMEOUT_MS / 1000} s`}; once consumed, ${held ? "as expected" : "not as expected"}:\n${JSON.stringify(value, null, 2)}\n`, + ); + return value; +}; + +/** Waits until the API serves each of `blocks` at its height, as canonical. */ +const apiHolds = (blocks: BlockId[], label: string) => + vi.waitFor( + async () => + expect( + await Promise.all(blocks.map((b) => api.blockAt(b.height))), + label, + ).toEqual(blocks.map((b) => served(b, false))), + { timeout: 60_000, interval: 1_000 }, + ); + +/** + * Waits until the API holds what `prune` removes, the moved tx on its dead + * block included: on the replacing block alone it would pass as a first + * insert. + */ +const apiHoldsDead = async (prune: PruneFacts, label: string) => { + await apiHolds(prune.dead, label); + const deadHolder = prune.dead.find( + (b) => b.height === prune.movedTx.deadHeight, + ); + await vi.waitFor( + async () => + expect( + await api.txEffect(prune.movedTx.hash), + "the moved tx before the prune", + ).toEqual(deadHolder && served(deadHolder, false)), + { timeout: 30_000, interval: 1_000 }, + ); +}; + +const STEP_TIMES: StepTimes = { + stepMs: STEP_MS, + // Longer than today's 5 s tips poll, so a tips timer would show. + holdMs: 7_000, + // Many passes of the listener's poll: a listener that never handles the + // shorter chain fails the check that needs it, not the whole scenario. + holdLimitMs: 15_000, + pollMs: 250, +}; + +/** The API's state that must not move while the node serves the shorter chain. */ +const apiView = async (prune: PruneFacts) => ({ + latestHeight: await api.latestHeight(), + dead: await Promise.all(prune.dead.map((b) => api.blockAt(b.height))), + reorgs: byRoot(await api.reorgs()), +}); + +type ApiView = Awaited>; + +/** Steps the node through `prune`, as `stepThrough` does, viewing the API. */ +const stepPrune = (prune: PruneFacts, hooks: PruneHooks) => + stepThrough(control, prune, { + ...hooks, + view: () => apiView(prune), + times: STEP_TIMES, + }); + +// Once a stop keeps its lock (`stopHold`), a crash scenario after it would +// only run into its timeouts, so it fails at once. +const stops: { kept: () => string | undefined }[] = []; +const noLockKept = () => { + const kept = stops.map((s) => s.kept()).find((why) => why !== undefined); + if (kept !== undefined) { + throw new Error(`an earlier crash scenario keeps its lock held: ${kept}`); + } +}; + +const COMPARE_CHAIN = fileURLToPath( + new URL("../scripts/compare-chain.ts", import.meta.url), +); + +/** One check of the read-only checker against this run's node and API. */ +const compareChain = (check: "sample" | "window") => + new Promise<{ + code: number; + output: string; + range?: HeightRange; + firstMismatch: unknown; + }>((resolve, reject) => + execFile( + process.execPath, + [COMPARE_CHAIN, check], + { + env: { + ...process.env, + COMPARE_NODE_URL: endpoints.aztecNodeUrl, + COMPARE_API_URL: endpoints.explorerApiUrl, + }, + timeout: 60_000, + }, + (error, stdout, stderr) => { + const code = typeof error?.code === "number" ? error.code : 0; + if (error && code === 0) { + reject(error); + return; + } + let last: unknown; + try { + last = JSON.parse(stdout.trim().split("\n").at(-1) ?? ""); + } catch { + // Not a JSON line: the raw output stands in for the result. + } + const line = z + .object({ + from: z.number(), + to: z.number(), + firstMismatch: z.unknown(), + }) + .safeParse(last); + resolve({ + code, + output: stdout + stderr, + range: line.success + ? { from: line.data.from, to: line.data.to } + : undefined, + firstMismatch: line.success ? line.data.firstMismatch : stdout, + }); + }, + ), + ); + +/** The node's block at each height from `from`, and a 404 one past its tip. */ +const expectedFrom = (prune: PruneFacts, from: number) => [ + ...prune.final.filter((b) => b.height >= from).map((b) => served(b, false)), + { status: 404 }, +]; + +const movedTxBlock = (prune: PruneFacts, height: number) => + served(prune.final[height - 1], false); + +/** The one reorg a prune adds: rooted at its first dead block, counting all of them. */ +const reorgOf = (prune: PruneFacts): ReorgRecord => ({ + height: prune.dead[0].height, + nbrOfOrphanedBlocks: prune.dead.length, + orphanedBlockHash: prune.dead[0].hash.toLowerCase(), +}); + +/** + * What the API must serve once `prune` has settled, read from height `from`, + * with the contract on `contractOn` if given: one reorg per prune the script + * has played by then, never a list read from the API, which would take in a + * record the API added in between. + */ +const wantAfter = ( + script: ScriptStatus, + prune: PruneFacts, + from: number, + contractOn?: BlockId, +): Partial => ({ + latestHeight: prune.final.length, + canonical: expectedFrom(prune, from), + reorgs: byRoot( + script.prunes.filter((p) => p.endAt <= prune.endAt).map(reorgOf), + ), + dropped: { status: 404 }, + txEffect: movedTxBlock(prune, prune.movedTx.finalHeight), + ...(contractOn + ? { + contractInstance: { + hash: contractOn.hash.toLowerCase(), + orphaned: false, + }, + } + : {}), + dead: prune.dead.map((b) => served(b, true)), +}); + +/** The first prune's replacing block, which deploys the script's contract. */ +const contractBlock = ({ prunes: [first] }: ScriptStatus) => + first.final[first.movedTx.finalHeight - 1]; + +const itServesTheScript = ( + read: () => { seen: Snapshot; want: Partial }, + names: { chain: string; reorgs: string; tx: string }, +) => { + it(names.chain, () => { + const { seen, want } = read(); + expect.soft(seen.latestHeight, "latest height").toBe(want.latestHeight); + expect + .soft(seen.canonical, "the canonical block at each height") + .toEqual(want.canonical); + }); + + it(names.reorgs, () => { + const { seen, want } = read(); + expect(seen.reorgs).toEqual(want.reorgs); + }); + + it(names.tx, () => { + const { seen, want } = read(); + expect.soft(seen.dropped, "dropped-tx lookup").toEqual(want.dropped); + expect.soft(seen.txEffect, "tx effect").toEqual(want.txEffect); + if ("contractInstance" in want) { + expect + .soft(seen.contractInstance, "contract instance") + .toEqual(want.contractInstance); + } + }); + + it("serves each dead block by its hash, as orphaned", () => { + const { seen, want } = read(); + expect(seen.dead).toEqual(want.dead); + }); +}; + +describe("a prune of blocks 7-10, replaced by 7'-12' on block 6", () => { + let script: ScriptStatus; + let prune: PruneFacts; + let want: Partial; + let seen: Snapshot; + let checkerBefore: Awaited>; + let checkerAfter: Record< + "sample" | "window", + Awaited> + >; + let nodeTips: { finalized: number; proposed: number }; + + beforeAll(async () => { + script = await control.status(); + [prune] = script.prunes; + await vi.waitFor( + async () => + expect( + (await control.status()).tipReads, + "tip reads by the listener", + ).toBeGreaterThan(1), + { timeout: 60_000, interval: 500 }, + ); + const old = [ + ...prune.final.filter((b) => b.height < prune.dead[0].height), + ...prune.dead, + ]; + const deadHolder = prune.dead.find( + (b) => b.height === prune.movedTx.deadHeight, + ); + const beforePrune = async () => { + // The prune tests something only once the API holds what it removes, + // the moved tx and its contract on their dead block included: on the + // replacing block alone they would pass as a first insert. + await apiHolds(old, "blocks 1-10 before the prune"); + await vi.waitFor( + async () => + expect( + { + txEffect: await api.txEffect(prune.movedTx.hash), + contractInstance: await api.contractInstance( + script.contractAddress, + ), + }, + "the moved tx and its contract before the prune", + ).toEqual({ + txEffect: deadHolder && served(deadHolder, false), + contractInstance: { + hash: deadHolder?.hash.toLowerCase(), + orphaned: false, + }, + }), + { timeout: 30_000, interval: 1_000 }, + ); + checkerBefore = await compareChain("sample"); + }; + await stepPrune(prune, { beforePrune }); + want = wantAfter(script, prune, 1, contractBlock(script)); + seen = await settled( + () => snapshot(prune, 1, script.contractAddress), + want, + "the API after the first prune", + ); + checkerAfter = { + sample: await compareChain("sample"), + window: await compareChain("window"), + }; + const tips = await createAztecNodeClient( + endpoints.aztecNodeUrl, + ).getChainTips(); + nodeTips = { + finalized: Number(tips.finalized.block.number), + proposed: Number(tips.proposed.number), + }; + }); + + it("has compare-chain name the API's first divergence from the node in each check's own range, and never print the endpoints", () => { + const onApi = new Map( + seen.canonical.flatMap((b) => + "hash" in b && !b.orphaned ? [[b.height, b.hash] as const] : [], + ), + ); + const onNode = new Map( + prune.final.map((b) => [b.height, b.hash.toLowerCase()] as const), + ); + const ranges = checkRanges({ + apiLatest: typeof seen.latestHeight === "number" ? seen.latestHeight : 0, + nodeFinalized: nodeTips.finalized, + nodeProposed: nodeTips.proposed, + }); + expect + .soft(checkerBefore, "before the prune") + .toMatchObject({ code: 0, firstMismatch: null }); + for (const check of ["sample", "window"] as const) { + const run = checkerAfter[check]; + const height = firstMismatch(ranges[check], onApi, onNode); + expect.soft(run.range, `${check}: its range`).toEqual(ranges[check]); + expect + .soft(run.code, `${check}: exit code`) + .toBe(height === undefined ? 0 : 1); + expect + .soft(run.firstMismatch, `${check}: first mismatch`) + .toEqual( + height === undefined ? null : expect.objectContaining({ height }), + ); + } + for (const run of [checkerBefore, ...Object.values(checkerAfter)]) { + for (const url of [endpoints.aztecNodeUrl, endpoints.explorerApiUrl]) { + expect.soft(run.output).not.toContain(new URL(url).host); + } + } + }); + + itServesTheScript(() => ({ seen, want }), { + chain: "serves the script's final chain as canonical, and nothing above it", + reorgs: "lists one reorg: the 4 blocks from height 7", + tx: "keeps the moved tx mined, not dropped, and the contract on the replacing block", + }); +}); + +describe("a prune of blocks 13'-16' that serves the shorter chain, tip 12', before 13''-16'", () => { + let script: ScriptStatus; + let prune: PruneFacts; + let short: ShortHold | undefined; + let published: { block: number; tips: number } | undefined; + let want: Partial; + let seen: Snapshot; + + beforeAll(async () => { + script = await control.status(); + prune = script.prunes[1]; + short = await stepPrune(prune, { + beforePrune: () => apiHoldsDead(prune, "blocks 13'-16' before the prune"), + }); + want = wantAfter(script, prune, prune.dead[0].height); + process.stdout.write( + `while the node served the shorter chain:\n${JSON.stringify(short, null, 2)}\n`, + ); + seen = await settled( + () => snapshot(prune, prune.dead[0].height), + want, + "the API after the second prune", + ); + // Read once settled, so a record sent in the window has landed. + const { from, to } = short ?? {}; + if (from !== undefined && to !== undefined) { + published = { + block: await broker.publishedBetween( + endpoints.broker.blockTopic, + from, + to, + ), + tips: await broker.publishedBetween( + endpoints.broker.tipsTopic, + from, + to, + ), + }; + } + }); + + it("publishes no block and no tips record, and keeps its state, while the node serves the shorter chain", () => { + expect + .soft(short?.unhandled, "states of the shorter chain no pass handled") + .toEqual([]); + expect + .soft(published, "records stamped while the node served it") + .toEqual({ block: 0, tips: 0 }); + expect.soft(short?.end, "the API's state").toEqual(short?.start); + }); + + itServesTheScript(() => ({ seen, want }), { + chain: + "serves the node's chain above 12' as canonical, and nothing above it", + reorgs: + "lists two reorgs: the first prune's, and the 4 blocks from height 13", + tx: "keeps the moved tx mined, not dropped, on the replacing block", + }); +}); + +describe("a prune of 17''-18'' replaced by 17''' at once, with the listener killed between sending 17''' and storing it", () => { + let script: ScriptStatus; + let prune: PruneFacts; + let replacing: BlockId; + let stop: ReturnType; + let want: Partial; + let seen: Snapshot; + + beforeAll(async () => { + noLockKept(); + script = await control.status(); + prune = script.prunes[2]; + replacing = prune.final[prune.dead[0].height - 1]; + stop = listenerStop({ + pg: pgAccess, + database: databases.listener, + broker, + blockTopic: endpoints.broker.blockTopic, + services, + }); + stops.push(stop); + await stepPrune(prune, { + beforePrune: async () => { + await apiHoldsDead(prune, "blocks 17''-18'' before the prune"); + await stop.arm(prune.dead); + }, + afterPrune: () => stop.fire(replacing), + onEnd: stop.release, + }); + process.stdout.write( + `the listener's stop:\n${JSON.stringify(stop.result, null, 2)}\n`, + ); + want = wantAfter(script, prune, 1, contractBlock(script)); + seen = await settled( + () => snapshot(prune, 1, script.contractAddress), + want, + "the API after the listener's restart", + ); + }); + + it("kills the listener while the lock holds up its store's write of 17''', with 17''' sent and the store on the prune's tip", () => { + const { missed, waiting, atKill } = stop.result; + expect.soft(missed, "why nothing was killed").toBeUndefined(); + expect.soft(waiting, "the write that waited").toEqual({ + application: "aztec-listener", + database: databases.listener, + statement: 'insert into "l2_block_stream_hash"', + }); + expect + .soft( + atKill?.sent.map((r) => r.to - r.from), + "records the batch had sent, per partition", + ) + .toEqual([1]); + expect.soft(atKill?.store, "the listener's store").toEqual({ + proposed: prune.dead[0].height - 1, + hash: prune.dead[0].hash.toLowerCase(), + }); + }); + + it("sends 17''' again once restarted, under the same key", () => { + const { records = [], recoveryMs } = stop.result; + process.stdout.write( + `from the listener's restart to its store holding 17''': ${recoveryMs} ms\n`, + ); + const copy = { + height: replacing.height, + proposedTip: replacing.height, + hash: replacing.hash.toLowerCase(), + }; + expect + .soft( + records.map(({ height, proposedTip, hash, sentBeforeKill }) => ({ + height, + proposedTip, + hash, + sentBeforeKill, + })), + "block records sent from the prune on", + ) + .toEqual([ + { ...copy, sentBeforeKill: true }, + { ...copy, sentBeforeKill: false }, + ]); + const [first, second] = records; + expect.soft(first?.key, "the first copy's key").toBeTruthy(); + expect.soft(second?.key, "the second copy's key").toBe(first?.key); + }); + + itServesTheScript(() => ({ seen, want }), { + chain: + "serves the node's chain from height 1 as canonical, and nothing above it", + reorgs: + "lists three reorgs: the earlier prunes', and the 2 blocks from height 17", + tx: "keeps the moved tx mined, not dropped, on the replacing block, and the contract on 7'", + }); +}); + +describe("a prune of 20'''-21''' replaced by 20'''' at once, with the API killed between committing 20'''' and committing its offset", () => { + let script: ScriptStatus; + let prune: PruneFacts; + let stop: ReturnType; + let want: Partial; + let seen: Snapshot; + + beforeAll(async () => { + noLockKept(); + script = await control.status(); + prune = script.prunes[3]; + stop = apiStop({ + pg: pgAccess, + database: databases.api, + apiGroupPrefix: endpoints.broker.apiGroupPrefix, + broker, + blockTopic: endpoints.broker.blockTopic, + services, + }); + stops.push(stop); + await stepPrune(prune, { + beforePrune: async () => { + await apiHoldsDead(prune, "blocks 20'''-21''' before the prune"); + await stop.arm(); + }, + afterPrune: () => + stop.fire(prune.final[prune.dead[0].height - 1], prune.dead), + onEnd: stop.release, + }); + process.stdout.write( + `the API's stop:\n${JSON.stringify(stop.result, null, 2)}\n`, + ); + want = wantAfter(script, prune, 1, contractBlock(script)); + seen = await settled( + () => snapshot(prune, 1, script.contractAddress), + want, + "the API after its restart", + ); + }); + + it("kills the API while the lock holds up its block handler's upsert after 20'''', with 20'''' committed and its offset not", () => { + const { missed, held, atKill } = stop.result; + const [sent] = atKill?.sent ?? []; + expect.soft(missed, "why nothing was killed").toBeUndefined(); + expect.soft(held?.waiting, "the write held up").toEqual({ + application: "explorer-api", + database: databases.api, + statement: 'insert into "l2_rollup_version_observation"', + }); + expect + .soft( + atKill?.sent.map((r) => r.to - r.from), + "records the batch put on the topic, per partition", + ) + .toEqual([1]); + expect + .soft( + atKill?.canonical, + "20'''' and the dead blocks in the API's database", + ) + .toEqual({ replacing: true, dead: prune.dead.map(() => false) }); + expect + .soft(atKill?.committed, "the API's committed offsets on that partition") + .toEqual({ blockHandler: [sent?.from] }); + }); + + it("consumes 20'''' again once restarted: its block handler reaches the same upsert with the record uncommitted, and commits past it once the lock goes", () => { + const { atKill, replayMissed, replay, afterRestart, recoveryMs } = + stop.result; + const [sent] = atKill?.sent ?? []; + process.stdout.write( + `from the API's restart to its commit past 20'''': ${recoveryMs} ms\n`, + ); + expect.soft(replayMissed, "why no replay was seen").toBeUndefined(); + expect.soft(replay?.waiting, "the restarted API's write held up").toEqual({ + application: "explorer-api", + database: databases.api, + statement: 'insert into "l2_rollup_version_observation"', + }); + expect + .soft(replay?.committed, "committed offsets while it was held up") + .toEqual({ blockHandler: [sent?.from] }); + expect + .soft(afterRestart?.committed, "committed offsets once the lock went") + .toEqual({ blockHandler: [sent?.to] }); + }); + + // The replayed batch is 20'''' alone, so the replay has no dead block to + // bring back, and no record to write again. + itServesTheScript(() => ({ seen, want }), { + chain: + "serves the node's chain from height 1 as canonical, and nothing above it", + reorgs: + "lists four reorgs, the earlier prunes' and the 2 blocks from height 20: none from the replay", + tx: "keeps the moved tx mined, not dropped, on the replacing block, and the contract on 7'", + }); +}); + +describe("the block topic, after the last prune", () => { + // Spaced steps reach the API in order from any partition, so the scenarios + // cannot show where the block records went; the broker can. + it("holds every block record in one of its partitions", async () => { + const partitions = await broker.recordsPerPartition( + endpoints.broker.blockTopic, + ); + expect(partitions.length, "partitions").toBeGreaterThan(1); + expect( + partitions.filter((p) => p.records > 0), + "partitions holding records", + ).toHaveLength(1); + }); +}); diff --git a/services/network-smoke/src/row-lock.test.ts b/services/network-smoke/src/row-lock.test.ts new file mode 100644 index 00000000..69b13970 --- /dev/null +++ b/services/network-smoke/src/row-lock.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "vitest"; +import { blockedBy } from "./row-lock.js"; + +describe("blockedBy", () => { + it("follows waiters queued behind other waiters, and leaves sessions another lock holds up", () => { + const harness = 1; + expect( + blockedBy(harness, [ + // Queued behind 20's tuple lock, listed before it. + { pid: 30, blockers: [20] }, + { pid: 20, blockers: [harness] }, + { pid: 40, blockers: [99] }, + { pid: 99, blockers: [] }, + ]), + ).toEqual(new Set([20, 30])); + }); +}); diff --git a/services/network-smoke/src/row-lock.ts b/services/network-smoke/src/row-lock.ts new file mode 100644 index 00000000..bcb89f5c --- /dev/null +++ b/services/network-smoke/src/row-lock.ts @@ -0,0 +1,166 @@ +import pg, { type QueryResultRow } from "pg"; + +export type PgAccess = { + host: string; + port: number; + user: string; + password: string; +}; + +/** A session's statement that waits on a lock: one another session holds, or one queued behind such a waiter. */ +export type Waiter = { + pid: number; + /** Its `application_name`: the run gives each service's sessions the service's name. */ + application: string; + database: string; + waitEventType: string | null; + query: string; +}; + +/** + * The sessions `root` holds up, directly or behind another session it holds + * up, from each waiting session's `pg_blocking_pids`. That names direct + * blockers only: a write queued for a row lock that another waiter took + * first names that waiter, not `root`. + */ +export const blockedBy = ( + root: number, + waiting: { pid: number; blockers: number[] }[], +) => { + const chain = new Set([root]); + for (let grew = true; grew; ) { + grew = false; + for (const { pid, blockers } of waiting) { + if (!chain.has(pid) && blockers.some((b) => chain.has(b))) { + chain.add(pid); + grew = true; + } + } + } + chain.delete(root); + return chain; +}; + +// A harness statement or connection that stalls, a lock wait included, fails +// the step it serves instead of holding it until the test's timeout. +const session = (access: PgAccess, database: string) => + new pg.Client({ + ...access, + database, + statement_timeout: 10_000, + connectionTimeoutMillis: 10_000, + }); + +/** Rows of one query in its own session, which ends with it. */ +export const queryRows = async ( + access: PgAccess, + database: string, + text: string, + values: unknown[] = [], +): Promise => { + const client = session(access, database); + await client.connect(); + try { + return (await client.query(text, values)).rows; + } finally { + await client.end(); + } +}; + +/** + * Takes the row locks `lockQuery` (a `SELECT … FOR UPDATE`) takes, in a + * session of the harness's own, and holds them until `release`. Another + * session's write to a locked row then waits, mid-statement and, inside a + * transaction, uncommitted. Throws if the query locks no row. + */ +export const lockRows = async ( + access: PgAccess, + database: string, + lockQuery: string, + values: unknown[] = [], +) => { + const client = session(access, database); + // Inside a transaction, pg_stat_activity shows each session's query as it + // was at the transaction's first read of it, so the waiters are read from + // a session that holds none open. + const watcher = session(access, database); + let pid: number; + try { + await client.connect(); + await watcher.connect(); + pid = ( + await client.query<{ pid: number }>("SELECT pg_backend_pid() AS pid") + ).rows[0].pid; + await client.query("BEGIN"); + const { rowCount } = await client.query(lockQuery, values); + if (!rowCount) { + throw new Error(`no row to lock: ${lockQuery}`); + } + } catch (e) { + await Promise.allSettled([client.end(), watcher.end()]); + throw e; + } + + /** The sessions this one's locks hold up (`blockedBy`), whatever their database. */ + const waiters = async (): Promise => { + const { rows } = await watcher.query<{ + pid: number; + application_name: string; + datname: string; + wait_event_type: string | null; + query: string; + blockers: number[]; + }>( + "SELECT pid, application_name, datname, wait_event_type, query, pg_blocking_pids(pid) AS blockers FROM pg_stat_activity WHERE wait_event_type = 'Lock'", + ); + const chain = blockedBy(pid, rows); + return rows + .filter((r) => chain.has(r.pid)) + .map((r) => ({ + pid: r.pid, + application: r.application_name, + database: r.datname, + waitEventType: r.wait_event_type, + query: r.query, + })); + }; + + const sessionsOf = async (application: string) => + ( + await watcher.query<{ pid: number }>( + "SELECT pid FROM pg_stat_activity WHERE application_name = $1", + [application], + ) + ).rows.map((r) => r.pid); + + let released = false; + return { + waiters, + /** + * Ends every session named `application`, whatever it is doing, so its + * open transaction rolls back and no statement it sent runs once the + * lock goes. Each gets 5 s to end; resolves with the ones left. + */ + endSessions: async (application: string) => { + for (const other of await sessionsOf(application)) { + // False, with a warning, for one that ended on its own meanwhile. + await watcher.query("SELECT pg_terminate_backend($1, 5000)", [other]); + } + return sessionsOf(application); + }, + /** Ends the lock's sessions; a second call does nothing. */ + release: async () => { + if (released) { + return; + } + released = true; + try { + await client.query("ROLLBACK"); + } finally { + await Promise.allSettled([client.end(), watcher.end()]); + } + }, + }; +}; + +export type RowLock = Awaited>; diff --git a/services/network-smoke/src/rpc-tap.test.ts b/services/network-smoke/src/rpc-tap.test.ts new file mode 100644 index 00000000..67855347 --- /dev/null +++ b/services/network-smoke/src/rpc-tap.test.ts @@ -0,0 +1,177 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { type Server, createServer } from "node:http"; +import { type AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { gzipSync } from "node:zlib"; +import { createAztecNodeClient } from "@aztec-labs/aztec.js/node"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + type RpcTap, + type TipRead, + longestTipGap, + pruneOrder, + readTipReads, + startRpcTap, + tipGapBound, +} from "./rpc-tap.js"; + +const HASH = `0x${"ab".repeat(32)}`; +const tip = (number: number) => ({ + block: { number, hash: HASH }, + checkpoint: { number, hash: HASH }, +}); + +type Call = { id: number; method: string; params: unknown[] }; + +const answer = ({ id, method, params }: Call) => { + switch (method) { + case "aztec_getBlockNumber": + return { jsonrpc: "2.0", id, result: params[0] === "proven" ? 5 : 7 }; + case "aztec_getChainTips": + return { + jsonrpc: "2.0", + id, + result: { + proposed: { number: 7, hash: HASH }, + checkpointed: tip(7), + proven: tip(5), + finalized: tip(5), + }, + }; + default: + return { + jsonrpc: "2.0", + id, + error: { code: -32601, message: "Method not found" }, + }; + } +}; + +// Compressed, as the SDK's server compresses large answers. +const fakeNode = () => + createServer((req, res) => { + let body = ""; + req.on("data", (chunk: Buffer) => (body += chunk.toString())); + req.on("end", () => { + const calls = JSON.parse(body) as Call[]; + res.writeHead(200, { + "content-type": "application/json", + "content-encoding": "gzip", + }); + res.end(gzipSync(JSON.stringify(calls.map(answer)))); + }); + }); + +describe("rpc tap", () => { + let dir: string; + let upstream: Server; + let tap: RpcTap; + + beforeAll(async () => { + dir = mkdtempSync(join(tmpdir(), "chicmoz-rpc-tap-")); + upstream = fakeNode(); + await new Promise((resolve) => + upstream.listen(0, "127.0.0.1", resolve), + ); + const { port } = upstream.address() as AddressInfo; + tap = await startRpcTap({ + port: 0, + upstream: `http://127.0.0.1:${port}`, + file: join(dir, "tap.jsonl"), + }); + }); + + afterAll(async () => { + await tap?.close(); + upstream?.closeAllConnections(); + upstream?.close(); + rmSync(dir, { recursive: true, force: true }); + }); + + it("passes the SDK client's batch through and records only its proposed-tip reads", async () => { + const client = createAztecNodeClient(tap.url); + const answers = await Promise.all([ + client.getBlockNumber(), + client.getBlockNumber("proven"), + client.getChainTips().then((t) => Number(t.proposed.number)), + client.getNodeVersion().catch((e: Error) => e.message), + ]); + expect(answers).toEqual([7, 5, 7, "Method not found"]); + expect( + readTipReads(join(dir, "tap.jsonl")).map((r) => ({ + method: r.method, + proposed: r.proposed, + hash: r.hash, + })), + ).toEqual([ + { method: "getBlockNumber", proposed: 7 }, + { method: "getChainTips", proposed: 7, hash: HASH }, + ]); + }); + + describe("the state of a prune that the client read first", () => { + const read = (at: number, proposed: number, hash?: string): TipRead => ({ + at, + method: hash === undefined ? "getBlockNumber" : "getChainTips", + proposed, + ...(hash === undefined ? {} : { hash }), + }); + // Target 6, doomed 7 and 8; the tip also sat at 6 before they were built. + const window = { + since: 100, + target: 6, + before: new Map([ + [6, "0x06"], + [7, "0x07"], + [8, "0x08"], + ]), + }; + const early = [read(50, 6), read(90, 8)]; + + it("goes by the earliest answer that shows the shorter chain or the replacement", () => { + expect( + pruneOrder([...early, read(200, 6), read(400, 7)], window).order, + ).toBe("shorter-chain-first"); + expect(pruneOrder([...early, read(400, 7)], window).order).toBe( + "replacement-first", + ); + expect(pruneOrder(early, window).order).toBe("unseen"); + }); + + it("keeps a replacement read first when a target reply arrives after it", () => { + // The target reply's request went out first, so it is recorded first. + const reads = [...early, read(450, 6), read(300, 7)]; + const order = pruneOrder(reads, window); + expect(order.order).toBe("replacement-first"); + expect(order.decisiveRead).toMatchObject({ + proposed: 7, + afterWarpMs: 200, + }); + }); + + it("reads the old tip as neither state, unless a hash shows another block", () => { + expect( + pruneOrder([read(200, 8), read(250, 8, "0x08")], window).order, + ).toBe("unseen"); + expect( + pruneOrder([read(200, 8), read(250, 8, "0x8f"), read(300, 6)], window) + .order, + ).toBe("replacement-first"); + }); + }); + + it("bounds the gap between tip reads by the node's hold on the height past its tip", () => { + // A correct listener over a shorter chain, tip 6 below its 8, on the + // local network: each pass's walk reads 7, which the node holds 6 s. + const reads: TipRead[] = [ + 1795741859523, 1795741859527, 1795741865554, 1795741866591, 1795741866594, + 1795741872625, 1795741873652, 1795741873657, 1795741879683, + ].map((at) => ({ at, method: "getChainTips", proposed: 6 })); + const gap = longestTipGap(reads, reads[0].at, reads[reads.length - 1].at); + expect(gap).toBe(6031); + expect(gap).toBeLessThanOrEqual( + tipGapBound({ listenerPollMs: 1_000, unseenBlockWaitMs: 6_000 }), + ); + }); +}); diff --git a/services/network-smoke/src/rpc-tap.ts b/services/network-smoke/src/rpc-tap.ts new file mode 100644 index 00000000..c48cadf5 --- /dev/null +++ b/services/network-smoke/src/rpc-tap.ts @@ -0,0 +1,329 @@ +import { appendFileSync, readFileSync, writeFileSync } from "node:fs"; +import { + type IncomingHttpHeaders, + type IncomingMessage, + type ServerResponse, + createServer, + request, +} from "node:http"; +import { brotliDecompressSync, gunzipSync, inflateSync } from "node:zlib"; +import { z } from "zod"; + +const TIP_METHODS = ["getBlockNumber", "getChainTips"] as const; +type TipMethod = (typeof TIP_METHODS)[number]; + +const heightSchema = z.union([ + z.number().int().nonnegative(), + z.string().regex(/^\d+$/).transform(Number), +]); + +export const tipReadSchema = z.object({ + /** When the node's answer reached the tap, in ms since the epoch. */ + at: z.number(), + method: z.enum(TIP_METHODS), + /** The proposed tip the answer named; absent when it named none. */ + proposed: z.number().int().optional(), + /** Only `getChainTips` answers name the hash. */ + hash: z.string().optional(), + error: z.string().optional(), +}); + +export type TipRead = z.infer; + +const callSchema = z.object({ + id: z.union([z.number(), z.string()]), + method: z.string(), + params: z.array(z.unknown()).optional(), +}); + +const replySchema = z.object({ + id: z.union([z.number(), z.string()]).nullable(), + result: z.unknown().optional(), + error: z.object({ message: z.string() }).partial().optional(), +}); + +const chainTipsSchema = z.object({ + proposed: z.object({ number: heightSchema, hash: z.string() }), +}); + +/** Any namespace: `aztec_getBlockNumber`, `node_getChainTips`. */ +const tipMethodOf = (method: string): TipMethod | undefined => { + const name = method.slice(method.lastIndexOf("_") + 1); + return TIP_METHODS.find((m) => m === name); +}; + +const tipOf = (method: TipMethod, result: unknown) => { + if (method === "getChainTips") { + const tips = chainTipsSchema.safeParse(result); + return tips.success + ? { proposed: tips.data.proposed.number, hash: tips.data.proposed.hash } + : undefined; + } + const height = heightSchema.safeParse(result); + return height.success ? { proposed: height.data } : undefined; +}; + +const asList = (body: unknown): unknown[] => + Array.isArray(body) ? body : [body]; + +/** The proposed-tip reads in one JSON-RPC exchange, batched or not. */ +export const tipReadsOf = ( + requestBody: unknown, + replyBody: unknown, + at: number, +): TipRead[] => { + const replies = new Map>(); + for (const item of asList(replyBody)) { + const reply = replySchema.safeParse(item); + if (reply.success && reply.data.id !== null) { + replies.set(reply.data.id, reply.data); + } + } + return asList(requestBody).flatMap((item): TipRead[] => { + const call = callSchema.safeParse(item); + const method = call.success ? tipMethodOf(call.data.method) : undefined; + if (!call.success || method === undefined) { + return []; + } + // `getBlockNumber("proven")` and the other tags read another tip. + const tag = call.data.params?.[0] ?? "proposed"; + if (method === "getBlockNumber" && tag !== "proposed") { + return []; + } + const reply = replies.get(call.data.id); + const tip = reply && tipOf(method, reply.result); + return [ + tip + ? { at, method, ...tip } + : { at, method, error: reply?.error?.message ?? "no readable answer" }, + ]; + }); +}; + +const json = (body: Buffer | undefined): unknown => { + try { + return body === undefined ? undefined : JSON.parse(body.toString("utf8")); + } catch { + return undefined; + } +}; + +const DECODERS: Record Buffer> = { + identity: (body) => body, + gzip: (body) => gunzipSync(body), + deflate: (body) => inflateSync(body), + br: (body) => brotliDecompressSync(body), +}; + +const decoded = (body: Buffer, encoding = "identity") => { + try { + return DECODERS[encoding]?.(body); + } catch { + return undefined; + } +}; + +const HOP_BY_HOP = new Set([ + "connection", + "keep-alive", + "proxy-connection", + "te", + "trailer", + "transfer-encoding", + "upgrade", +]); + +const endToEnd = (headers: IncomingHttpHeaders) => + Object.fromEntries( + Object.entries(headers).filter(([name]) => !HOP_BY_HOP.has(name)), + ); + +const readAll = async (stream: IncomingMessage) => { + const chunks: Buffer[] = []; + for await (const chunk of stream) { + chunks.push(chunk as Buffer); + } + return Buffer.concat(chunks); +}; + +export type RpcTap = { url: string; close: () => Promise }; + +/** + * A pass-through proxy to a node's JSON-RPC that appends each read of the + * proposed tip, with what the node answered, to `file` as one JSON line. It + * records what its client read, whichever of the two methods it reads the + * tip with, without changing what the client gets. + */ +export const startRpcTap = async ({ + port, + upstream, + file, +}: { + port: number; + upstream: string; + file: string; +}): Promise => { + const target = new URL(upstream); + writeFileSync(file, ""); + const handle = async (req: IncomingMessage, res: ServerResponse) => { + const body = await readAll(req); + const reply = await new Promise((resolve, reject) => { + const out = request( + { + host: target.hostname, + port: target.port, + method: req.method, + path: req.url, + headers: { ...endToEnd(req.headers), host: target.host }, + }, + resolve, + ); + out.on("error", reject); + out.end(body); + }); + const replyBody = await readAll(reply); + const at = Date.now(); + res.writeHead(reply.statusCode ?? 502, { + ...endToEnd(reply.headers), + "content-length": replyBody.length, + }); + res.end(replyBody); + return () => { + const reads = tipReadsOf( + json(body), + json(decoded(replyBody, reply.headers["content-encoding"])), + at, + ); + if (reads.length > 0) { + appendFileSync( + file, + reads.map((r) => `${JSON.stringify(r)}\n`).join(""), + ); + } + }; + }; + const server = createServer((req, res) => { + handle(req, res).then( + (record) => { + try { + record(); + } catch (e) { + process.stderr.write( + `network-smoke: the RPC tap lost a record: ${(e as Error).message}\n`, + ); + } + }, + // The client sees a dropped connection, as it would with the node down. + () => res.destroy(), + ); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(port, "127.0.0.1", () => resolve()); + }); + const address = server.address(); + if (address === null || typeof address === "string") { + throw new Error("unexpected tap address"); + } + return { + url: `http://127.0.0.1:${address.port}`, + close: () => + new Promise((resolve) => { + server.close(() => resolve()); + server.closeAllConnections(); + }), + }; +}; + +/** The tap's records so far; a line still being written is left out. */ +export const readTipReads = (file: string): TipRead[] => + readFileSync(file, "utf8") + .split("\n") + .slice(0, -1) + .map((line) => tipReadSchema.parse(JSON.parse(line))); + +/** The longest stretch of [from, to] with no tip answered; its edges count as reads. */ +export const longestTipGap = (reads: TipRead[], from: number, to: number) => { + const instants = [ + from, + ...reads + .filter((r) => r.proposed !== undefined && r.at >= from && r.at <= to) + .map((r) => r.at) + .sort((a, b) => a - b), + to, + ]; + return Math.max(...instants.slice(1).map((t, i) => t - instants[i])); +}; + +/** + * The longest a listener still reading the node goes between tip answers. A + * pass reads the tip and the next starts a poll interval after it ends; over + * a shorter chain, a pass's walk back reads the height one past the node's + * tip, which the node holds for `unseenBlockWaitMs`. Four intervals beyond + * that leave three for the rest of a pass. + */ +export const tipGapBound = ({ + listenerPollMs, + unseenBlockWaitMs, +}: { + listenerPollMs: number; + unseenBlockWaitMs: number; +}) => unseenBlockWaitMs + 4 * listenerPollMs; + +export type PruneOrder = "shorter-chain-first" | "replacement-first" | "unseen"; + +/** + * Which state of a prune to `target` the client read first, by the earliest + * answer that shows one, whatever order the requests went out in. `before` + * is the node's chain just before the warp, `since`; earlier answers are + * left out, since the tip also sat at `target` before the doomed blocks were + * built. The tip at `target` shows the shorter chain. A tip above it shows + * the replacement when its hash is not `before`'s there or, without a hash, + * when it is not the old tip's height; the old tip's height alone shows + * neither. + */ +export const pruneOrder = ( + reads: TipRead[], + { + since, + target, + before, + }: { since: number; target: number; before: Map }, +) => { + const oldTip = Math.max(...before.keys()); + const stateOf = ({ proposed, hash }: TipRead) => { + if (proposed === undefined || proposed < target) { + return undefined; + } + const old = + hash === undefined + ? undefined + : hash.toLowerCase() === before.get(proposed); + if (proposed === target) { + return old === false ? undefined : "shorter-chain-first"; + } + if (old === undefined) { + return proposed === oldTip ? undefined : "replacement-first"; + } + return old ? undefined : "replacement-first"; + }; + const after = reads.filter((r) => r.at >= since).sort((a, b) => a.at - b.at); + const decisive = after.find((r) => stateOf(r) !== undefined); + const order: PruneOrder = (decisive && stateOf(decisive)) ?? "unseen"; + const count = (method: TipMethod) => + after.filter((r) => r.method === method && r.proposed !== undefined).length; + return { + order, + decisiveRead: decisive && { + method: decisive.method, + proposed: decisive.proposed, + hash: decisive.hash, + afterWarpMs: decisive.at - since, + }, + readsAfterWarp: { + getBlockNumber: count("getBlockNumber"), + getChainTips: count("getChainTips"), + }, + errorsAfterWarp: after.filter((r) => r.error !== undefined).length, + }; +}; diff --git a/services/network-smoke/src/run.ts b/services/network-smoke/src/run.ts index 48c749f1..ef989e6b 100644 --- a/services/network-smoke/src/run.ts +++ b/services/network-smoke/src/run.ts @@ -11,26 +11,106 @@ import { createRequire } from "node:module"; import { platform } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; +import { + type L2_MESSAGES, + withKafkaNamespace, +} from "@chicmoz-pkg/message-registry"; import { COMPOSE_FILE, REPO_ROOT, type Stack, up } from "@chicmoz/test-harness"; import { readConfig } from "./config.js"; -import { ENDPOINTS_ENV, type Endpoints } from "./endpoints.js"; -import { L1_CHAIN_ID, startAnvil, startAztecNode } from "./network.js"; -import { freePorts } from "./ports.js"; +import { + ENDPOINTS_ENV, + type Endpoints, + type PruneEndpoints, + type ScriptedEndpoints, +} from "./endpoints.js"; +import { createTopic } from "./kafka.js"; +import { + L1_CHAIN_ID, + UNSEEN_BLOCK_WAIT_MS, + startAnvil, + startAztecNode, + startLocalNetwork, +} from "./network.js"; +import { releasePorts } from "./port-registry.js"; +import { claimRunPorts } from "./ports.js"; import { createProcessGroups, startTimeOf } from "./processes.js"; +import { type RpcTap, startRpcTap } from "./rpc-tap.js"; +import { type ServiceControl, startServiceControl } from "./service-control.js"; import { + LISTENER_POLL_MS, SERVICES, + SMOKE_NETWORK, + type ServiceName, missingBuilds, prepareDatabases, startServices, } from "./services.js"; import { createTmpDir, removeTmpDir, tmpDirs } from "./tmp.js"; -import { prepareToolchain } from "./toolchain.js"; +import { type Toolchain, prepareToolchain } from "./toolchain.js"; import { httpOk, rpc, waitUntil } from "./wait.js"; const PACKAGE_DIR = fileURLToPath(new URL("../", import.meta.url)); +const CLI = fileURLToPath(new URL("./cli.js", import.meta.url)); // Per-test timeouts bound each test; this bounds Vitest itself. const SUITE_TIMEOUT_MS = 15 * 60_000; +export type Mode = "network" | "scripted" | "prune"; + +const ALL_SERVICES = [ + "explorer-api", + "ethereum-listener", + "aztec-listener", + "websocket-event-publisher", +] as const satisfies readonly ServiceName[]; + +// A scenario judges what the blocks alone do to the explorer, so the API's +// repair loop, whose first pass comes 2 min after it starts, stays out. +const NO_REPAIR = { + "explorer-api": { L2_BLOCK_RECONCILIATION_INTERVAL_MS: String(3_600_000) }, +}; + +// Kafka keeps order only within a partition, so a run on several shows +// whether blocks still reach the API in order. +const BLOCK_PARTITIONS = 3; +const BLOCK_TOPIC: keyof L2_MESSAGES = "NEW_BLOCK_EVENT"; +const TIPS_TOPIC: keyof L2_MESSAGES = "L2_TIPS_EVENT"; + +const MODES: Record< + Mode, + { + /** `stock`: `aztec start --local-network`; `launcher`: the same network with epoch auto-settle off. */ + node: "stock" | "launcher" | "scripted"; + services: readonly ServiceName[]; + vitestConfig: string; + extraEnv?: Partial>>; + blockPartitions?: number; + /** The listener reads the node through `rpc-tap.ts`, which records its tip reads. */ + tapListener?: boolean; + } +> = { + network: { + node: "stock", + services: ALL_SERVICES, + vitestConfig: "vitest.smoke.config.ts", + }, + // The scripted node has no L1, and the scenario reads only the REST API. + scripted: { + node: "scripted", + services: ["explorer-api", "aztec-listener"], + vitestConfig: "vitest.scripted.config.ts", + extraEnv: NO_REPAIR, + blockPartitions: BLOCK_PARTITIONS, + }, + prune: { + node: "launcher", + services: ALL_SERVICES, + vitestConfig: "vitest.prune.config.ts", + extraEnv: NO_REPAIR, + blockPartitions: BLOCK_PARTITIONS, + tapListener: true, + }, +}; + export const RUN_ID_PATTERN = /^ns[0-9a-f]{10}$/; export type RunRecord = { @@ -55,18 +135,33 @@ const tail = (file: string, lines = 20) => { /** * The run owner. Vitest only asserts: its CLI exits on SIGINT before its own - * async hooks could tear anything down. + * async hooks could tear anything down. `network` runs a real local network; + * `prune` runs it with epoch auto-settle off, so a scenario can have it + * prune; `scripted` runs the scripted node in its place (`scripted-node.ts`). */ -export const run = async (): Promise => { +export const run = async (mode: Mode): Promise => { if (platform() !== "linux") { throw new Error("the network smoke run needs Linux (/proc)"); } - const missing = missingBuilds(); + const { + node, + services, + vitestConfig, + extraEnv, + blockPartitions, + tapListener, + } = MODES[mode]; + const missing = missingBuilds(services); if (missing.length > 0) { throw new Error(`run \`yarn build\` first; missing ${missing.join(", ")}`); } const config = readConfig(); const runId = `ns${randomBytes(5).toString("hex")}`; + // generateL2TopicName's name, under this run's namespace. + const blockTopic = withKafkaNamespace( + `${SMOKE_NETWORK}__${BLOCK_TOPIC}`, + runId, + ); const runDir = join(config.dir, runId); const logDir = join(runDir, "logs"); mkdirSync(logDir, { recursive: true }); @@ -100,6 +195,8 @@ export const run = async (): Promise => { }; let stack: Stack | undefined; let stackRemoved = false; + let tap: RpcTap | undefined; + let serviceControl: ServiceControl | undefined; process.on("exit", () => { groups.killAllSync(); @@ -139,6 +236,8 @@ export const run = async (): Promise => { let teardown: Promise | undefined; const tearDown = (failed: boolean) => (teardown ??= (async () => { + // First: from here the service control refuses every action and closes, + // so no service starts again behind the stops. abort.abort(); await groups.stopAll(); // Compose up and migrations cannot be cancelled: every started setup @@ -150,9 +249,10 @@ export const run = async (): Promise => { const stuck = await groups.stopAll(); if (stuck.length > 0) { process.stderr.write( - `network-smoke: still running after SIGKILL: ${stuck.join(", ")}\n`, + `network-smoke: still running after SIGKILL: ${stuck.join(", ")}; the run's ports stay claimed until this runner exits, and \`down ${runId}\` stops what is left\n`, ); } + let released = false; try { if (stack) { if (failed) { @@ -164,9 +264,15 @@ export const run = async (): Promise => { } finally { removeTmpDir(tmp.node); removeTmpDir(tmp.wallet); + await tap?.close(); + await serviceControl?.close(); + // Only once every group stopped: a survivor may still bind a port. + if (stuck.length === 0) { + released = await releasePorts(runId); + } } mark("torn down"); - return stuck.length === 0; + return stuck.length === 0 && released; })()); let signalled = false; @@ -195,21 +301,34 @@ export const run = async (): Promise => { try { const nodeTmp = createTmpDir(tmp.node); const walletTmp = createTmpDir(tmp.wallet); - const toolchain = await track( - prepareToolchain({ - toolchainDir: config.toolchainDir, - foundryBinDir: config.foundryBinDir, + let toolchain: Toolchain | undefined; + if (node !== "scripted") { + toolchain = await track( + prepareToolchain({ + toolchainDir: config.toolchainDir, + foundryBinDir: config.foundryBinDir, + runId, + log: join(logDir, "npm-ci.log"), + signal: abort.signal, + }), + ); + mark("toolchain ready"); + abort.signal.throwIfAborted(); + } + + const ports = await track( + claimRunPorts({ runId, - log: join(logDir, "npm-ci.log"), + ownerPid: process.pid, + worktree: REPO_ROOT, + fixed: config.ports, }), ); - mark("toolchain ready"); - abort.signal.throwIfAborted(); - - const ports = config.ports ?? (await freePorts()); const anvilUrl = `http://127.0.0.1:${ports.anvil}`; const aztecNodeUrl = `http://127.0.0.1:${ports.aztec}`; const explorerApiUrl = `http://127.0.0.1:${ports.explorerApi}`; + // The scripted node has no admin API; its control API takes that port. + const controlUrl = `http://127.0.0.1:${ports.aztecAdmin}`; // The first failure aborts the other branch and goes straight to // teardown, which still drains every tracked setup operation. @@ -228,71 +347,178 @@ export const run = async (): Promise => { saveRecord(); mark(`infra up (${started.runId})`); abort.signal.throwIfAborted(); - await prepareDatabases(started, abort.signal); + await prepareDatabases(started, services, abort.signal); mark("migrated"); + if (blockPartitions !== undefined) { + abort.signal.throwIfAborted(); + await createTopic(started, blockTopic, blockPartitions); + mark(`${blockTopic} has ${blockPartitions} partitions`); + } return started; })(), ); + const localNetwork = async (tools: Toolchain) => { + startAnvil(groups, tools, ports, runDir); + await waitUntil( + "anvil", + async () => Number(await rpc(anvilUrl, "eth_chainId")) === L1_CHAIN_ID, + { timeoutMs: 30_000, dead: deathOf("anvil"), signal: abort.signal }, + ); + mark("anvil ready"); + abort.signal.throwIfAborted(); + (node === "launcher" ? startLocalNetwork : startAztecNode)( + groups, + tools, + ports, + runDir, + nodeTmp, + ); + await waitUntil( + "aztec node", + async () => (await rpc(aztecNodeUrl, "node_getBlockNumber")) !== null, + { + timeoutMs: 240_000, + dead: deathOf("aztec-node"), + signal: abort.signal, + }, + ); + mark("aztec node ready"); + }; + const scriptedNode = async () => { + groups.start( + "scripted-node", + process.execPath, + [ + "--enable-source-maps", + CLI, + "scripted-node", + String(ports.aztec), + String(ports.aztecAdmin), + ], + // The SDK's hashing backend puts a Unix socket under TMPDIR. + { cwd: runDir, tier: 1, env: { TMPDIR: nodeTmp } }, + ); + // Not a tip read: the scenario counts those as the listener's polls. + await waitUntil( + "scripted node", + async () => (await rpc(aztecNodeUrl, "node_getNodeInfo")) !== null, + { + timeoutMs: 60_000, + dead: deathOf("scripted-node"), + signal: abort.signal, + }, + ); + mark("scripted node ready"); + }; const chain = failFast( - (async () => { - startAnvil(groups, toolchain, ports, runDir); - await waitUntil( - "anvil", - async () => - Number(await rpc(anvilUrl, "eth_chainId")) === L1_CHAIN_ID, - { timeoutMs: 30_000, dead: deathOf("anvil"), signal: abort.signal }, - ); - mark("anvil ready"); - abort.signal.throwIfAborted(); - startAztecNode(groups, toolchain, ports, runDir, nodeTmp); - await waitUntil( - "aztec node", - async () => (await rpc(aztecNodeUrl, "node_getBlockNumber")) !== null, - { - timeoutMs: 240_000, - dead: deathOf("aztec-node"), - signal: abort.signal, - }, - ); - mark("aztec node ready"); - })(), + toolchain === undefined ? scriptedNode() : localNetwork(toolchain), ); const [infraStack] = await Promise.all([infra, chain]); abort.signal.throwIfAborted(); - startServices(groups, { + const rpcTapFile = join(logDir, "rpc-tap.jsonl"); + if (tapListener) { + // The launcher serves no admin API; the tap takes that port. + tap = await startRpcTap({ + port: ports.aztecAdmin, + upstream: aztecNodeUrl, + file: rpcTapFile, + }); + } + const startService = startServices(groups, services, { stack: infraStack, ports, runId, - anvilUrl, - aztecNodeUrl, + anvilUrl: node === "scripted" ? undefined : anvilUrl, + extraEnv, + aztecNodeUrl: tap?.url ?? aztecNodeUrl, }); - const alive = () => - Object.keys(SERVICES) - .map((name) => deathOf(name)()) - .find(Boolean); + if (node === "scripted") { + const isRunService = (name: string): name is ServiceName => + services.some((s) => s === name); + // The scripted mode runs no anvil; its port takes the runner's control + // of the services, so the groups a scenario restarts stay the run's. + serviceControl = await startServiceControl({ + port: ports.anvil, + names: services, + signal: abort.signal, + actions: { + kill: async (name) => { + if (!(await groups.kill(name))) { + throw new Error(`${name} outlived SIGKILL`); + } + }, + start: (name) => { + if (!isRunService(name)) { + throw new Error(`${name} is not one of this run's services`); + } + startService(name); + return Promise.resolve(); + }, + }, + }); + } + const alive = () => services.map((name) => deathOf(name)()).find(Boolean); await waitUntil("explorer-api", () => httpOk(`${explorerApiUrl}/health`), { timeoutMs: 60_000, dead: alive, signal: abort.signal, }); - await waitUntil( - "websocket-event-publisher", - () => httpOk(`http://127.0.0.1:${ports.wsHealth}/health`), - { timeoutMs: 60_000, dead: alive, signal: abort.signal }, - ); + if (services.includes("websocket-event-publisher")) { + await waitUntil( + "websocket-event-publisher", + () => httpOk(`http://127.0.0.1:${ports.wsHealth}/health`), + { timeoutMs: 60_000, dead: alive, signal: abort.signal }, + ); + } mark("services ready"); abort.signal.throwIfAborted(); - const endpoints: Endpoints = { + const common = { runId, logDir, - anvilUrl, aztecNodeUrl, explorerApiUrl, - wsUrl: `ws://127.0.0.1:${ports.ws}`, - consumerLogs: Object.keys(SERVICES), + consumerLogs: [...services], + listenerPollMs: LISTENER_POLL_MS, + broker: { + brokers: infraStack.env.KAFKA_CONNECTION, + username: infraStack.env.KAFKA_SASL_USERNAME, + password: infraStack.env.KAFKA_SASL_PASSWORD, + blockTopic, + tipsTopic: withKafkaNamespace(`${SMOKE_NETWORK}__${TIPS_TOPIC}`, runId), + // getConsumerGroupId's ids: `__`. + apiGroupPrefix: withKafkaNamespace( + `explorer-api_${SMOKE_NETWORK}_`, + runId, + ), + }, }; + const endpoints: Endpoints | PruneEndpoints | ScriptedEndpoints = + node === "scripted" && serviceControl + ? { + ...common, + controlUrl, + servicesUrl: serviceControl.url, + postgres: { + host: infraStack.env.POSTGRES_IP, + port: Number(infraStack.env.POSTGRES_PORT), + user: infraStack.env.POSTGRES_ADMIN, + password: infraStack.env.POSTGRES_PASSWORD, + databases: { + listener: SERVICES["aztec-listener"].database, + api: SERVICES["explorer-api"].database, + }, + }, + } + : { + ...common, + anvilUrl, + wsUrl: `ws://127.0.0.1:${ports.ws}`, + ...(tap + ? { rpcTapFile, unseenBlockWaitMs: UNSEEN_BLOCK_WAIT_MS } + : {}), + }; const vitestBin = join( dirname(createRequire(import.meta.url).resolve("vitest/package.json")), "vitest.mjs", @@ -300,7 +526,7 @@ export const run = async (): Promise => { const vitest = groups.start( "vitest", process.execPath, - [vitestBin, "run", "--config", "vitest.smoke.config.ts"], + [vitestBin, "run", "--config", vitestConfig], { cwd: PACKAGE_DIR, tier: 3, diff --git a/services/network-smoke/src/script-control.test.ts b/services/network-smoke/src/script-control.test.ts new file mode 100644 index 00000000..04402783 --- /dev/null +++ b/services/network-smoke/src/script-control.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from "vitest"; +import { type StateRead, prefixHandled } from "./script-control.js"; + +describe("the hold on a shorter chain, tip 12", () => { + it("ends at the next pass's walk, never on tip reads alone or on the walking pass's own reread", () => { + const tips: StateRead = { method: "getChainTips", at: 0 }; + const block = (height: number): StateRead => ({ + method: "getBlock", + height, + at: 0, + }); + const walk = [block(16), block(15), block(14), block(13)]; + const handled = (reads: StateRead[]) => prefixHandled(reads, 12); + + expect(handled([tips, tips, tips, tips]), "election probes alone").toBe( + false, + ); + expect( + handled([tips, tips, ...walk, tips]), + "a walk and its pass's reread of the tips", + ).toBe(false); + expect( + handled([tips, block(12), block(6), tips, block(12)]), + "reads at or below the tip", + ).toBe(false); + expect( + handled([tips, tips, ...walk, tips, tips, tips, block(16)]), + "a walk, its pass's reread, then the next pass's walk", + ).toBe(true); + }); +}); diff --git a/services/network-smoke/src/script-control.ts b/services/network-smoke/src/script-control.ts new file mode 100644 index 00000000..2762c35c --- /dev/null +++ b/services/network-smoke/src/script-control.ts @@ -0,0 +1,106 @@ +import { z } from "zod"; + +const blockIdSchema = z.object({ height: z.number().int(), hash: z.string() }); + +const pruneFactsSchema = z.object({ + /** Index of the first state without the dead blocks. */ + pruneAt: z.number().int(), + /** States from `pruneAt` on that serve the shorter chain, whose tip is the prune target, before the replacing block. */ + shorterSteps: z.number().int(), + /** Index of the state where the replacing chain has grown to its end. */ + endAt: z.number().int(), + /** The pruned blocks, as the node served them before the prune. */ + dead: z.array(blockIdSchema), + /** Every block the node serves at `endAt`. */ + final: z.array(blockIdSchema), + /** In a dead block and again in the replacing chain. */ + movedTx: z.object({ + hash: z.string(), + deadHeight: z.number().int(), + finalHeight: z.number().int(), + }), +}); + +/** What the explorer must end up serving, as the scripted node built it. */ +export const scriptFactsSchema = z.object({ + states: z.array(z.string()), + /** A prune whose replacing block is there at once, one that serves the shorter chain first, then two more of the first kind. */ + prunes: z.tuple([ + pruneFactsSchema, + pruneFactsSchema, + pruneFactsSchema, + pruneFactsSchema, + ]), + /** Deployed by the first prune's moved tx. */ + contractAddress: z.string(), +}); + +export type ScriptFacts = z.infer; +export type PruneFacts = z.infer; +export type BlockId = z.infer; + +/** When the node answered or moved, in ms since the epoch, by the host's clock. */ +const atSchema = z.number(); + +const stateReadSchema = z.union([ + /** A read of the proposed tip. */ + z.object({ + method: z.enum(["getChainTips", "getBlockNumber"]), + at: atSchema, + }), + /** A read of a block by its height. */ + z.object({ + method: z.enum(["getBlock", "getBlockData"]), + height: z.number().int(), + at: atSchema, + }), +]); + +export const scriptStatusSchema = scriptFactsSchema.extend({ + current: z.number().int(), + /** `getChainTips` and `getBlockNumber` calls served so far: the listener's polls. */ + tipReads: z.number().int(), + /** The current state's reads, in the order the node answered them. */ + stateReads: z.array(stateReadSchema), +}); + +export type ScriptStatus = z.infer; +export type StateRead = z.infer; + +/** + * Whether a pass of the listener has handled the shorter chain, tip `tip`, and + * ended. Holding a longer chain, the SDK's block stream walks back from its + * own tip, reading heights the node lacks, then rereads the tips in the same + * pass; a walk after a tip read that follows a walk is the next pass's. Tip + * reads alone show neither: an election probes nodes it may not follow. + */ +export const prefixHandled = (reads: StateRead[], tip: number) => { + const walks = (r: StateRead) => "height" in r && r.height > tip; + const first = reads.findIndex(walks); + const reread = reads.findIndex((r, i) => i > first && !("height" in r)); + return first >= 0 && reread >= 0 && reads.slice(reread + 1).some(walks); +}; + +const stepSchema = z.object({ + current: z.number().int(), + label: z.string(), + at: atSchema, +}); + +/** The scripted node's control port: read the script, move to the next state. */ +export const scriptControl = (controlUrl: string) => { + const call = async (path: string, method: "GET" | "POST") => { + const res = await fetch(new URL(path, controlUrl), { + method, + signal: AbortSignal.timeout(5_000), + }); + if (!res.ok) { + throw new Error(`${method} ${path}: ${res.status} ${await res.text()}`); + } + return (await res.json()) as unknown; + }; + return { + status: async () => scriptStatusSchema.parse(await call("/script", "GET")), + step: async () => stepSchema.parse(await call("/script/step", "POST")), + }; +}; diff --git a/services/network-smoke/src/scripted-chain.ts b/services/network-smoke/src/scripted-chain.ts new file mode 100644 index 00000000..78072f2b --- /dev/null +++ b/services/network-smoke/src/scripted-chain.ts @@ -0,0 +1,306 @@ +import { + BlockNumber, + CheckpointNumber, + IndexWithinCheckpoint, + SlotNumber, + TreeLeafIndex, +} from "@aztec-labs/foundation/branded-types"; +import { Fr } from "@aztec-labs/foundation/curves/bn254"; +import { Body, L2Block } from "@aztec-labs/stdlib/block"; +import { CheckpointHeader } from "@aztec-labs/stdlib/rollup"; +import { AppendOnlyTreeSnapshot } from "@aztec-labs/stdlib/trees"; +import { BlockHeader, type TxEffect } from "@aztec-labs/stdlib/tx"; +import { loadFixture } from "@chicmoz/test-harness"; +import { type BlockId, type ScriptFacts } from "./script-control.js"; + +export type ScriptedBlock = { + block: L2Block; + hash: string; + /** Each block is its own checkpoint, as on the local network. */ + checkpointHash: string; +}; + +/** What the node serves at one step: `chain[h]` is the block at height `h`; the last one is the proposed tip. */ +export type NodeState = { + label: string; + chain: readonly ScriptedBlock[]; + checkpointed: number; + proven: number; + finalized: number; +}; + +export type Script = { states: NodeState[]; facts: ScriptFacts }; + +/** The node info a local network served; the blocks carry its chain id and rollup version. */ +export const recordedNodeInfo = () => + loadFixture("local-network", "node-info", "node-info").data.result; + +const recordedBlock = (name: string, source: "local-network" | "testnet") => + loadFixture(source, "l2-block", name).data; + +/** The first tx of a recorded block, as its node served it. */ +const recordedTx = ( + name: string, + source: "local-network" | "testnet" = "local-network", +): TxEffect => { + const { hex } = recordedBlock(name, source); + const [tx] = L2Block.fromBuffer(Buffer.from(hex, "hex")).body.txEffects; + return tx; +}; + +type ChainConstants = { chainId: Fr; version: Fr; genesisTime: bigint }; + +const SLOT_SECONDS = 72n; + +const makeBlock = async ( + parent: ScriptedBlock | undefined, + height: number, + slot: number, + txs: TxEffect[], + { chainId, version, genesisTime }: ChainConstants, +): Promise => { + const body = new Body(txs); + const header = BlockHeader.random({ + lastArchive: parent?.block.archive ?? AppendOnlyTreeSnapshot.empty(), + txEffectsTreeRoot: await body.computeTxEffectsTreeRoot(), + chainId, + version, + blockNumber: BlockNumber(height), + slotNumber: SlotNumber(slot), + timestamp: genesisTime + BigInt(slot) * SLOT_SECONDS, + }); + // Only the links matter downstream: a child's hash covers its lastArchive, + // and nothing recomputes a root from the archive tree, so a random root, as + // L2Block.random draws, is enough. + const archive = new AppendOnlyTreeSnapshot( + Fr.random(), + TreeLeafIndex(height + 1), + ); + const block = new L2Block( + archive, + header, + body, + CheckpointNumber(height), + IndexWithinCheckpoint(0), + ); + const { globalVariables } = header; + const checkpoint = CheckpointHeader.random({ + lastArchiveRoot: header.lastArchive.root, + slotNumber: globalVariables.slotNumber, + timestamp: globalVariables.timestamp, + coinbase: globalVariables.coinbase, + feeRecipient: globalVariables.feeRecipient, + gasFees: globalVariables.gasFees, + totalManaUsed: header.totalManaUsed, + }); + return { + block, + hash: (await block.hash()).toString(), + checkpointHash: checkpoint.hash().toString(), + }; +}; + +const idOf = ({ block, hash }: ScriptedBlock): BlockId => ({ + height: block.number, + hash, +}); + +/** + * Blocks 1–10 grow one per step and 1–6 become proven and finalized; then + * the node prunes 7–10 and grows 7′–12′ on 6. The tips move as the local + * network's did across an epoch prune: the shorter chain is never served + * (the replacing block is already there), the checkpointed tip reaches 7′ one + * step later, and the proven and finalized tips stay at the prune target. + * Then 7′–12′ become proven and finalized, 13′–16′ grow, and the node + * prunes them the other way: it serves the shorter chain, tip 12′, for one + * step before it proposes 13″ and grows 13″–16″. Last, two more prunes + * replaced at once, for the crash scenarios: 17″–18″ by 17‴–19‴, then + * 20‴–21‴ by 20⁗–22⁗, each moving one tx. + */ +export const buildScript = async (): Promise