diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 93dd6f97129..977e2ec5722 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -79,10 +79,12 @@ So is recovery from the ledger and snapshots of 7.x, in the `long` runs of the s The Virtual A, B, and C jobs target `gha-vmss-d16av7-ci`, `gha-vmss-d16av7-ci-b`, and `gha-vmss-d16av7-ci-c`, respectively, to distribute demand across the regional pools. End to end tests record each network's trace events, of every tag, and upload the capture with their logs. +The Virtual B and C jobs also run with `CCF_CONSISTENCY_TRACE=1`, record consistency traces for each traced network, and upload them with their logs. The SNP Genoa job also runs with `CCF_RECOVERY_TRACE=1`, records a recovery trace manifest for each recovery decision protocol scenario, and uploads the manifests with its node logs. The `Replay e2e traces` job runs after the Virtual and SNP Genoa jobs complete (unless the workflow is cancelled), builds or restores the cached Lean replayers, and invokes `tests/trace_replay.py` to validate both sets of logs. It replays the `ccf.cft` events of every capture from the Virtual logs against the consensus model with `tests/cft_trace_validation.py`. A capture may be incomplete, for example if a test killed a node, so consensus replay runs with `--lenient` and fails if the model disagrees with a capture, if replay consumes less than 90% of the events of one of a capture's nodes, or if there is no capture. +It replays the consistency traces from the Virtual logs against the consistency model with `tests/consistency_trace_replay.py`, failing if replay rejects a trace or if no trace is found. It replays the recovery decision protocol node logs referenced by each manifest in the SNP Genoa logs against the disaster recovery model with `tests/recovery_trace_validation.py`, failing if any manifest is invalid, if replay rejects a scenario, or if no manifest is found. File: `ci.yml` diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7d24f16ca5d..5b073db768c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -167,6 +167,7 @@ jobs: rm -rf /github/home/.cache mkdir -p /github/home/.cache + export CCF_CONSISTENCY_TRACE=1 ./tests.sh --timeout 360 --output-on-failure -L bucket_b shell: bash @@ -182,6 +183,7 @@ jobs: build/workspace/*/*.ledger.*/* build/workspace/*/stack_trace build/workspace/*_trace/*.msgpack + build/workspace/*_consistency_trace/*.ndjson build/workspace/**/openapi_coverage.json if-no-files-found: ignore if: success() || failure() @@ -215,13 +217,6 @@ jobs: - name: "Install Lean" uses: ./.github/actions/install-lean - - name: "Build Lean consistency trace replayer" - run: | - set -euo pipefail - cd lean/consistency - lake build consistency-replay - shell: bash - - name: "Build Debug" run: | set -ex @@ -240,7 +235,7 @@ jobs: rm -rf /github/home/.cache mkdir -p /github/home/.cache - export CCF_LEAN_CONSISTENCY_REPLAYER="$GITHUB_WORKSPACE/lean/consistency/.lake/build/bin/consistency-replay" + export CCF_CONSISTENCY_TRACE=1 ./tests.sh --timeout 360 --output-on-failure -L bucket_c shell: bash @@ -248,7 +243,7 @@ jobs: run: | set -ex cd build - export CCF_LEAN_CONSISTENCY_REPLAYER="$GITHUB_WORKSPACE/lean/consistency/.lake/build/bin/consistency-replay" + export CCF_CONSISTENCY_TRACE=1 ./tests.sh --timeout 360 --output-on-failure -L partitions -C partitions shell: bash @@ -264,8 +259,8 @@ jobs: build/workspace/*/*.ledger.*/* build/workspace/*/stack_trace build/workspace/*_trace/*.msgpack + build/workspace/*_consistency_trace/*.ndjson build/workspace/**/openapi_coverage.json - build/workspace/*_consistency_trace.ndjson if-no-files-found: ignore if: success() || failure() @@ -378,6 +373,16 @@ jobs: hashFiles('lean/lean-toolchain', 'lean/common/**', 'lean/consensus/**') }} + - name: Cache consistency replay + id: consistency_replay_cache + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: lean/consistency/.lake/build/bin/consistency-replay + key: >- + consistency-replay-${{ runner.os }}-${{ runner.arch }}-${{ + hashFiles('lean/lean-toolchain', 'lean/common/**', 'lean/consistency/**') + }} + - name: Cache disaster recovery replay id: recovery_replay_cache uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 @@ -391,6 +396,7 @@ jobs: - name: Install Lean if: >- steps.consensus_replay_cache.outputs.cache-hit != 'true' || + steps.consistency_replay_cache.outputs.cache-hit != 'true' || steps.recovery_replay_cache.outputs.cache-hit != 'true' uses: ./.github/actions/install-lean @@ -401,6 +407,13 @@ jobs: set -euo pipefail lake build --wfail consensus-replay + - name: Build consistency replay + if: steps.consistency_replay_cache.outputs.cache-hit != 'true' + working-directory: lean/consistency + run: | + set -euo pipefail + lake build --wfail consistency-replay + - name: Build disaster recovery replay if: steps.recovery_replay_cache.outputs.cache-hit != 'true' working-directory: lean/disaster-recovery diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 4c9ce7de40b..7e8b55d2c7e 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -203,27 +203,35 @@ jobs: --no-summary \ --json "${out_dir}/consensus.json.gz" - # 2. consistency: consistency_trace_validation + e2e_logging + - # recorder-backed partitions groups (excluding untraced - # ledger/restart groups). + # 2. consistency: consistency_trace_validation + traced virtual e2e + # tests + recorder-backed partitions groups (only nodes started inside + # consistency_trace.recording(), excluding untraced recovery, + # lifecycle, and ledger/restart processes). shopt -s nullglob - consistency_profraws=(consistency_trace_validation-*.profraw) - logging_profraws=(e2e_logging-*.profraw) - partition_profraws=(partitions_consistency_tests-*.profraw) - if [[ ${#consistency_profraws[@]} -eq 0 ]]; then - echo "::error::No consistency_trace_validation-*.profraw files found" - exit 1 - fi - if [[ ${#logging_profraws[@]} -eq 0 ]]; then - echo "::error::No e2e_logging-*.profraw files found" - exit 1 - fi - if [[ ${#partition_profraws[@]} -eq 0 ]]; then - echo "::error::No partitions_consistency_tests-*.profraw files found" - exit 1 - fi - echo "consistency: selected ${#consistency_profraws[@]} consistency_trace_validation, ${#logging_profraws[@]} e2e_logging and ${#partition_profraws[@]} partitions_consistency_tests .profraw file(s)" - printf '%s\n' "${consistency_profraws[@]}" "${logging_profraws[@]}" "${partition_profraws[@]}" | + consistency_test_prefixes=( + consistency_trace_validation + e2e_forwarding_smoke + e2e_limits + e2e_logging + governance_test + js_batched_stress_test + partitions_consistency_tests + schema_test + tls_stress_test + ) + all_consistency_profraws=() + summary_parts=() + for prefix in "${consistency_test_prefixes[@]}"; do + matched=("consistency-${prefix}"-*.profraw) + if [[ ${#matched[@]} -eq 0 ]]; then + echo "::error::No consistency-${prefix}-*.profraw files found" + exit 1 + fi + all_consistency_profraws+=("${matched[@]}") + summary_parts+=("${#matched[@]} ${prefix}") + done + echo "consistency: selected $(IFS=', '; echo "${summary_parts[*]}") .profraw file(s)" + printf '%s\n' "${all_consistency_profraws[@]}" | ../scripts/coverage.sh \ --profiles-file - \ -o "${tmp_dir}/consistency.profdata" \ diff --git a/.github/workflows/lean.yml b/.github/workflows/lean.yml index 894f97c5c20..fd7d4801bcd 100644 --- a/.github/workflows/lean.yml +++ b/.github/workflows/lean.yml @@ -228,7 +228,7 @@ jobs: uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: consistency-traces - path: build/workspace/*_consistency_trace.ndjson + path: build/workspace/*_consistency_trace/*.ndjson if-no-files-found: error retention-days: 1 overwrite: true diff --git a/doc/architecture/verification.rst b/doc/architecture/verification.rst index 5850c40f8c4..0f27abebae7 100644 --- a/doc/architecture/verification.rst +++ b/doc/architecture/verification.rst @@ -69,7 +69,7 @@ Each replayer consumes traces produced by existing C++ tests: Tracing is disabled in normal builds. * **Consistency**: nodes export consensus events as Fluentd records with the ``ccf.cft`` tag, which :ccf_repo:`tests/infra/consistency_trace.py` collects, joins with the transaction statuses given to clients, and replays through ``consistency-replay``. The ``consistency_trace_validation`` e2e test (:ccf_repo:`tests/consistency_trace_validation.py`) starts a three-node network running the :ccf_repo:`basic_tv ` JavaScript application, runs :ccf_repo:`tests/tvc.py` against it, and suspends the primary to cause an election. - The ``e2e_logging`` (:ccf_repo:`tests/e2e_logging.py`) and partitions (:ccf_repo:`tests/partitions_test.py`) e2e tests also record and replay a trace for each of their traced networks. + The ``e2e_forwarding_smoke`` (:ccf_repo:`tests/forwarding.py`), ``e2e_limits`` (:ccf_repo:`tests/limits.py`), ``e2e_logging`` (:ccf_repo:`tests/e2e_logging.py`), ``governance_test`` (:ccf_repo:`tests/governance.py`), ``js_batched_stress_test`` (:ccf_repo:`tests/e2e_batched.py`), ``schema_test`` (:ccf_repo:`tests/schema.py` and :ccf_repo:`tests/e2e_operations.py`), ``tls_stress_test`` (:ccf_repo:`tests/connections.py`), and partitions (:ccf_repo:`tests/partitions_test.py`) e2e tests also record and replay a trace for each of their traced networks. * **Disaster recovery**: nodes started with the ``CCF_RECOVERY_TRACE`` environment variable set log each step of the recovery decision protocol as an ``RDP_TRACE`` record. These scenarios only run in the SNP Genoa CI job, where :ccf_repo:`tests/infra/recovery_trace.py` records a manifest for the quorum, failover and multiple-timeout scenarios in :ccf_repo:`tests/e2e_operations.py` and the follow-up ``Replay e2e traces`` job replays those node logs through ``disaster-recovery-replay`` via :ccf_repo:`tests/recovery_trace_validation.py`. @@ -87,7 +87,7 @@ The :ccf_repo:`Lean workflow <.github/workflows/lean.yml>` runs on pull requests * A final ``Lean models and proofs`` job succeeds only if all of the above succeed. The disaster recovery traces are captured by the SNP Genoa job in the main CI workflow and replayed by its follow-up ``Replay e2e traces`` job, since that is where the recovery scenarios run. -The ``e2e_logging`` and partitions tests replay their consistency traces in the main CI workflow for the same reason. +The remaining consistency-traced e2e tests and partitions tests replay their consistency traces in the main CI workflow for the same reason. A separate ``Lean Mathlib equivalence`` workflow proves that the replacements for Mathlib definitions in ``lean/common`` are equivalent to the Mathlib originals, and runs only when those definitions change; see :ccf_repo:`lean/mathlib-equivalence/README.md`. diff --git a/lean/consistency/README.md b/lean/consistency/README.md index 02d799e0d96..751ffcc2167 100644 --- a/lean/consistency/README.md +++ b/lean/consistency/README.md @@ -77,12 +77,13 @@ Nothing is reconstructed: a trace missing an election or a ledger entry is rejec Client reads are not traced, so this does not validate the model's read observations. Empty traces, malformed records, and disabled transitions fail with a line-numbered diagnostic and nonzero exit code. -[`tests/infra/consistency_trace.py`](../../tests/infra/consistency_trace.py) records such a trace for the nodes of a test and replays it, when `CCF_LEAN_CONSISTENCY_REPLAYER` names the replayer. -The trace is written to the test workspace, named after the test, such as `basic_partitions_consistency_trace.ndjson`. -Three e2e tests use it (they require the [CCF build prerequisites](../../doc/contribute/build_setup.rst)): +[`tests/infra/consistency_trace.py`](../../tests/infra/consistency_trace.py) records such a trace for the nodes of a test when `CCF_CONSISTENCY_TRACE` is set or `CCF_LEAN_CONSISTENCY_REPLAYER` names the replayer, and replays it inline when `CCF_LEAN_CONSISTENCY_REPLAYER` is set. +Each trace is written to the test workspace under a directory named after the test, such as `basic_partitions_consistency_trace/0.ndjson`. +Nine e2e tests use it (they require the [CCF build prerequisites](../../doc/contribute/build_setup.rst)): - [`tests/consistency_trace_validation.py`](../../tests/consistency_trace_validation.py) suspends the primary to cause an election while [`tests/tvc.py`](../../tests/tvc.py) writes, and reports the final status of each write. - [`tests/e2e_logging.py`](../../tests/e2e_logging.py) traces each of its networks (including the common-endpoints groups in [`tests/e2e_common_endpoints.py`](../../tests/e2e_common_endpoints.py)), and records client-observed statuses from `wait_for_commit`. +- [`tests/forwarding.py`](../../tests/forwarding.py), [`tests/limits.py`](../../tests/limits.py), [`tests/e2e_batched.py`](../../tests/e2e_batched.py), [`tests/connections.py`](../../tests/connections.py) (including [`tests/fuzzing.py`](../../tests/fuzzing.py)), [`tests/governance.py`](../../tests/governance.py) (and its helper modules, excluding disaster-recovery networks), and [`tests/schema.py`](../../tests/schema.py) (including [`tests/e2e_tutorial.py`](../../tests/e2e_tutorial.py) and non-recovery networks in [`tests/e2e_operations.py`](../../tests/e2e_operations.py)) trace their networks and record client-observed statuses from `wait_for_commit`. - [`tests/partitions_test.py`](../../tests/partitions_test.py) traces each of its networks, and reports the `Invalid` statuses that it checks. From the repository root: @@ -91,11 +92,10 @@ From the repository root: (cd lean/consistency && lake build --wfail consistency-replay) export CCF_LEAN_CONSISTENCY_REPLAYER="$PWD/lean/consistency/.lake/build/bin/consistency-replay" cmake -S . -B build -GNinja -DCMAKE_BUILD_TYPE=Debug -DLONG_TESTS=ON -cmake --build build --target consistency_trace_validation e2e_logging partitions -(cd build && ./tests.sh -VV -R '^consistency_trace_validation$' --no-tests=error) -(cd build && ./tests.sh -VV -R '^e2e_logging$' --no-tests=error) +cmake --build build --target consistency_trace_validation e2e_forwarding_smoke e2e_limits e2e_logging governance_test js_batched_stress_test partitions schema_test tls_stress_test +(cd build && ./tests.sh -VV -R '^(consistency_trace_validation|e2e_forwarding_smoke|e2e_limits|e2e_logging|governance_test|js_batched_stress_test|schema_test|tls_stress_test)$' --no-tests=error) (cd build && ./tests.sh -VV -C partitions -R '^partitions$' --no-tests=error) ``` -The [Lean workflow](../../.github/workflows/lean.yml) runs `consistency_trace_validation` with the replayer, and the [CI workflow](../../.github/workflows/ci.yml) does the same for `e2e_logging` and the partitions tests. +The [Lean workflow](../../.github/workflows/lean.yml) runs `consistency_trace_validation` with the replayer, and the [CI workflow](../../.github/workflows/ci.yml) records traces for the remaining consistency-traced e2e tests and the partitions tests with `CCF_CONSISTENCY_TRACE=1` and replays them in `Replay e2e traces` via [`tests/consistency_trace_replay.py`](../../tests/consistency_trace_replay.py). The [replay fixtures](replayer/fixtures/README.md) check that the replayer accepts valid traces and rejects invalid ones. diff --git a/scripts/coverage_cft_profiles.py b/scripts/coverage_cft_profiles.py index 7bfcfdca5a1..5777832c135 100755 --- a/scripts/coverage_cft_profiles.py +++ b/scripts/coverage_cft_profiles.py @@ -6,9 +6,9 @@ Outputs one profile path per line: - All cft_scenario-*.profraw files (validated by lean/consensus in lean.yml). -- Every virtual e2e -.profraw whose OS PID emitted ccf.cft - events in workspace/*_trace/*.msgpack with a trace directory label matching - (matching tests/cft_trace_validation.py in ci.yml). +- Every virtual e2e [consistency-]-.profraw whose OS PID + emitted ccf.cft events in workspace/*_trace/*.msgpack with a trace directory + label matching (matching tests/cft_trace_validation.py in ci.yml). """ import argparse @@ -62,6 +62,7 @@ def select_profiles(build_dir: pathlib.Path) -> tuple[list[pathlib.Path], int, i if "-" not in stem_pid: continue test_name, pid = stem_pid.rsplit("-", 1) + test_name = test_name.removeprefix("consistency-") if test_name == "cft_scenario" or not pid.isdigit(): continue labels = pid_to_labels.get(pid) diff --git a/tests/ci-buckets.txt b/tests/ci-buckets.txt index 373ad5d28e4..fb3b8367b74 100644 --- a/tests/ci-buckets.txt +++ b/tests/ci-buckets.txt @@ -33,6 +33,7 @@ bucket_c: trace_replay: cft_trace_validation + consistency_trace_replay recovery_trace_validation no_bucket: diff --git a/tests/connections.py b/tests/connections.py index 944cab7f70c..57c2ef2caaf 100644 --- a/tests/connections.py +++ b/tests/connections.py @@ -14,6 +14,7 @@ import fuzzing import httpx import infra.checker +import infra.consistency_trace import infra.e2e_args import infra.interfaces import infra.network @@ -71,7 +72,7 @@ def run_unsecured_connection_cap_test(args): accepted_endpoints=["/node/version"], ) - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb ) as network: network.start_and_open(args) @@ -132,7 +133,7 @@ def run_removed_quic_tests(args): app_protocol="QUIC", ) - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb ) as network: network.start_and_open(args) @@ -171,7 +172,7 @@ def run_connection_caps_tests(args): ) args.ubsan_options = "suppressions=" + str(supp_file) - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb ) as network: check = infra.checker.Checker() @@ -387,7 +388,7 @@ def verbose_sleep(sleep_time): timeout = test_case.get("timeout") args.idle_connection_timeout_s = timeout - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb ) as network: network.start_and_open(args) @@ -444,7 +445,7 @@ def node_tcp_socket(node): # NB: This does rudimentary smoke testing. See fuzzing.py for more thorough test def run_node_socket_robustness_tests(args): - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb ) as network: network.start_and_open(args) diff --git a/tests/consistency_trace_replay.py b/tests/consistency_trace_replay.py new file mode 100755 index 00000000000..8cee321bf4d --- /dev/null +++ b/tests/consistency_trace_replay.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache 2.0 License. +"""Replay recorded consistency traces against the Lean model. + +usage: consistency_trace_replay.py CONSISTENCY_REPLAY DIRECTORY... +""" + +import concurrent.futures +import functools +import os +import pathlib +import subprocess +import sys + + +def replay(replayer, path): + result = subprocess.run( + [replayer, str(path)], + capture_output=True, + text=True, + check=False, + ) + output = ((result.stdout or "") + (result.stderr or "")).strip() + return result.returncode == 0, output + + +def main(replayer, *directories): + paths = sorted( + path + for directory in directories + for path in pathlib.Path(directory).rglob("*_consistency_trace/*.ndjson") + ) + with concurrent.futures.ThreadPoolExecutor(os.cpu_count()) as pool: + results = list(pool.map(functools.partial(replay, replayer), paths)) + rejected = 0 + for path, (accepted, output) in zip(paths, results, strict=True): + rejected += not accepted + print(f"{'OK ' if accepted else 'FAIL'} {path}: {output}") + print(f"{len(paths) - rejected} accepted, {rejected} rejected") + return 0 if paths and not rejected else 1 + + +if __name__ == "__main__": + if len(sys.argv) < 3: + sys.exit(__doc__) + sys.exit(main(*sys.argv[1:])) diff --git a/tests/e2e_batched.py b/tests/e2e_batched.py index aaf266e5c28..b5664be9e43 100644 --- a/tests/e2e_batched.py +++ b/tests/e2e_batched.py @@ -9,6 +9,7 @@ from hashlib import sha256 import infra.checker +import infra.consistency_trace import infra.e2e_args import infra.net import infra.network @@ -154,7 +155,7 @@ def test( def run(args): - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb ) as network: network.start_and_open(args) @@ -189,7 +190,7 @@ def run(args): def run_to_transaction_limit(args): - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb ) as network: network.start_and_open(args) diff --git a/tests/e2e_operations.py b/tests/e2e_operations.py index 792f944c5bf..f5c7959424a 100644 --- a/tests/e2e_operations.py +++ b/tests/e2e_operations.py @@ -32,6 +32,7 @@ import ccf.split_ledger import infra.commit import infra.concurrency +import infra.consistency_trace import infra.crypto import infra.e2e_args import infra.interfaces @@ -634,13 +635,16 @@ def run_manual_snapshot_tests(const_args): ) args.snapshot_time_interval = "0s" - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - txs=app.LoggingTxs("user0"), - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + txs=app.LoggingTxs("user0"), + ) as network, + ): network.start_and_open(args) # These bounded, read-only checks must keep the explicitly requested @@ -658,12 +662,15 @@ def run_forced_snapshot_while_opening(const_args): args.label = f"{args.label}_opening_snapshot" args.snapshot_tx_interval = 10000 - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + ) as network, + ): # Note: start() rather than start_and_open() intentionally leaves # the service in the Opening state for test_forced_snapshot_while_opening network.start(args) @@ -1955,13 +1962,16 @@ def run_file_operations(args): with tempfile.TemporaryDirectory() as tmp_dir: txs = app.LoggingTxs("user0") - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - txs=txs, - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + txs=txs, + ) as network, + ): args.common_read_only_ledger_dir = tmp_dir network.start_and_open(args, service_data_json_file=ntf.name) @@ -1988,14 +1998,17 @@ def run_file_operations(args): def run_ledger_chunk_download(args): - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - txs=app.LoggingTxs("user0"), - check_file_invariants=False, - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + txs=app.LoggingTxs("user0"), + check_file_invariants=False, + ) as network, + ): network.start_and_open(args) # Issue enough transactions to create multiple ledger chunks network.txs.issue(network, number_txs=10) @@ -2006,13 +2019,16 @@ def run_ledger_chunk_download(args): def run_committed_ledger_prefix_download(args): - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - txs=app.LoggingTxs("user0"), - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + txs=app.LoggingTxs("user0"), + ) as network, + ): network.start_and_open(args) test_committed_ledger_prefix_access(network, args) @@ -2020,12 +2036,15 @@ def run_committed_ledger_prefix_download(args): def run_tls_san_checks(const_args): args = copy.deepcopy(const_args) args.label += "_tls_san" - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + ) as network, + ): network.start_and_open(args) network.verify_service_certificate_validity_period( args.initial_service_cert_validity_days @@ -2095,12 +2114,15 @@ def run_tls_san_join_mismatch(const_args): target_spec.get_file_serving_interface().host = file_serving_host args.subject_alt_names = [f"iPAddress:{primary_host}"] - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + ) as network, + ): network.start_and_open(args) LOG.info( @@ -2140,12 +2162,15 @@ def run_config_timeout_check(const_args): args = copy.deepcopy(const_args) args.nodes = infra.e2e_args.nodes(args, 1) args.label += "_config_timeout" - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + ) as network, + ): network.start_and_open(args) # This is relatively direct test to make sure the config timeout feature # works as intended. It is difficult to do with the existing framework @@ -2212,12 +2237,15 @@ def run_sighup_check(const_args): args = copy.deepcopy(const_args) args.nodes = infra.e2e_args.nodes(args, 1) args.label += "_sighup_check" - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + ) as network, + ): network.start_and_open(args) network.nodes[0].remote.remote.hangup() time.sleep(5) @@ -2250,9 +2278,12 @@ def assert_log_order(output, *messages): "cleanup iteration(s)", ) - with infra.network.network( - args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb + ) as network, + ): network.start_and_open(args) node = network.nodes[0] node.stop() @@ -2625,12 +2656,15 @@ def run_limit_config_checks(args): def run_preopen_readiness_check(args): - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + ) as network, + ): network.start(args) primary, _ = network.find_primary() with primary.client() as c: @@ -2647,12 +2681,15 @@ def run_preopen_readiness_check(args): def run_pid_file_check(args): - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + ) as network, + ): network.start_and_open(args) LOG.info("Check that pid file exists") node = network.nodes[0] @@ -2681,12 +2718,15 @@ def run_max_uncommitted_tx_count(const_args): args = copy.deepcopy(const_args) args.nodes = infra.e2e_args.nodes(args, 2) args.label += "_max_uncommitted_tx" - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + ) as network, + ): uncommitted_cap = 20 network.per_node_args_override[0] = { "max_uncommitted_tx_count": uncommitted_cap @@ -2742,12 +2782,15 @@ def service_subject(network): assert node_cert.subject == cert.subject, (node_cert.subject, cert.subject) return cert.subject - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + ) as network, + ): network.start_and_open( args, service_subject_name="CN=https://this.test.service,O=CCF User", @@ -2883,13 +2926,16 @@ def replace_nodes(network, old_nodes, new_package): nargs = copy.deepcopy(args) nargs.nodes = infra.e2e_args.max_nodes(nargs, f=0) - with infra.network.network( - nargs.nodes, - nargs.binary_dir, - nargs.debug_nodes, - pdb=nargs.pdb, - txs=app.LoggingTxs("user0"), - ) as network: + with ( + infra.consistency_trace.recording(nargs), + infra.network.network( + nargs.nodes, + nargs.binary_dir, + nargs.debug_nodes, + pdb=nargs.pdb, + txs=app.LoggingTxs("user0"), + ) as network, + ): network.start_and_open(nargs) primary, _ = network.find_nodes() @@ -3002,12 +3048,15 @@ def run_cose_signatures_config_check(args): nargs = copy.deepcopy(args) nargs.nodes = infra.e2e_args.max_nodes(nargs, f=0) - with infra.network.network( - nargs.nodes, - nargs.binary_dir, - nargs.debug_nodes, - pdb=nargs.pdb, - ) as network: + with ( + infra.consistency_trace.recording(nargs), + infra.network.network( + nargs.nodes, + nargs.binary_dir, + nargs.debug_nodes, + pdb=nargs.pdb, + ) as network, + ): network.start_and_open( nargs, cose_signatures_issuer="test.issuer.example.com", @@ -3063,12 +3112,15 @@ def run_late_mounted_ledger_check(args): nargs = copy.deepcopy(args) nargs.nodes = infra.e2e_args.min_nodes(nargs, f=0) - with infra.network.network( - nargs.nodes, - nargs.binary_dir, - nargs.debug_nodes, - pdb=nargs.pdb, - ) as network: + with ( + infra.consistency_trace.recording(nargs), + infra.network.network( + nargs.nodes, + nargs.binary_dir, + nargs.debug_nodes, + pdb=nargs.pdb, + ) as network, + ): network.start_and_open( nargs, ) @@ -3197,13 +3249,16 @@ def try_historical_fetch(node, timeout=1): def run_empty_ledger_dir_check(args): - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - check_file_invariants=False, - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + check_file_invariants=False, + ) as network, + ): LOG.info("Check that empty ledger directory is handled correctly") with tempfile.TemporaryDirectory() as tmp_dir: LOG.debug(f"Using {tmp_dir} as ledger directory") @@ -4612,13 +4667,16 @@ def _run_backup_snapshot_download( args.label += label_suffix args.snapshot_tx_interval = snapshot_tx_interval args.nodes = infra.e2e_args.max_nodes(args, f=0) - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - txs=app.LoggingTxs("user0"), - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + txs=app.LoggingTxs("user0"), + ) as network, + ): network.start_and_open(args, backup_snapshot_fetch_enabled=True) for test in tests: test(network, args) @@ -4675,12 +4733,15 @@ def run_propose_request_vote(const_args): # use a high timeout to hedge against flaky nodes which pause for seconds # In most cases this should not matter as the propose_request_vote will cause the election quickly args.election_timeout_ms = 20000 - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + ) as network, + ): LOG.info("Start a network") network.start_and_open(args, ignore_first_sigterm=True) network.wait_for_node_commit_sync(timeout=16) @@ -4726,13 +4787,16 @@ def net_with_min_tx(label, min_tx_interval): inner_args = copy.deepcopy(args) inner_args.snapshot_min_tx_interval = min_tx_interval inner_args.label += label - with infra.network.network( - inner_args.nodes, - inner_args.binary_dir, - inner_args.debug_nodes, - pdb=inner_args.pdb, - txs=app.LoggingTxs("user0"), - ) as net: + with ( + infra.consistency_trace.recording(inner_args), + infra.network.network( + inner_args.nodes, + inner_args.binary_dir, + inner_args.debug_nodes, + pdb=inner_args.pdb, + txs=app.LoggingTxs("user0"), + ) as net, + ): net.start_and_open(inner_args) yield net @@ -4839,13 +4903,16 @@ def run_snapshot_persistence_across_primary_failure(const_args): args.snapshot_time_interval = f"{snapshot_interval_ms}ms" args.snapshot_min_tx_interval = 0 - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - txs=app.LoggingTxs("user0"), - ) as net: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + txs=app.LoggingTxs("user0"), + ) as net, + ): net.start_and_open(args) start_time = time.time() @@ -5055,13 +5122,16 @@ def run_max_retained_snapshot_files(const_args): args.files_cleanup_max_snapshots = 3 args.files_cleanup_interval = "1s" - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - txs=app.LoggingTxs("user0"), - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + txs=app.LoggingTxs("user0"), + ) as network, + ): network.start_and_open(args) test_max_retained_snapshot_files(network, args) @@ -5131,13 +5201,16 @@ def run_backup_snapshot_cleanup(const_args): args.files_cleanup_interval = "1s" args.nodes = infra.e2e_args.max_nodes(args, f=0) - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - txs=app.LoggingTxs("user0"), - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + txs=app.LoggingTxs("user0"), + ) as network, + ): network.start_and_open(args, backup_snapshot_fetch_enabled=True) test_backup_snapshot_cleanup(network, args) @@ -5253,13 +5326,16 @@ def run_max_committed_ledger_chunk_files(const_args): with tempfile.TemporaryDirectory() as tmp_dir: args.common_read_only_ledger_dir = tmp_dir - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - txs=app.LoggingTxs("user0"), - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + txs=app.LoggingTxs("user0"), + ) as network, + ): network.start_and_open(args) # Copy all existing committed chunks to read-only dir so they can be pruned @@ -5586,13 +5662,16 @@ def run_post_snapshot_chunk_retention(const_args): with tempfile.TemporaryDirectory() as tmp_dir: args.common_read_only_ledger_dir = tmp_dir - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - txs=app.LoggingTxs("user0"), - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + txs=app.LoggingTxs("user0"), + ) as network, + ): network.start_and_open(args) primary, _ = network.find_primary() @@ -5665,14 +5744,17 @@ def run_ledger_chunk_cleanup_tests(const_args): with tempfile.TemporaryDirectory() as tmp_dir: args.common_read_only_ledger_dir = tmp_dir - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - txs=app.LoggingTxs("user0"), - check_file_invariants=False, - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + txs=app.LoggingTxs("user0"), + check_file_invariants=False, + ) as network, + ): network.start_and_open(args) # These tests intentionally produce [fail] log lines when chunks # are kept because no matching read-only copy exists, or because @@ -5729,13 +5811,16 @@ def run_pending_node_expiration(const_args): args.nodes = infra.e2e_args.min_nodes(args, f=1) args.pending_node_timeout = "10s" - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - pdb=args.pdb, - txs=app.LoggingTxs("user0"), - ) as network: + with ( + infra.consistency_trace.recording(args), + infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + pdb=args.pdb, + txs=app.LoggingTxs("user0"), + ) as network, + ): network.start_and_open(args) test_pending_node_expiration(network, args) diff --git a/tests/e2e_tutorial.py b/tests/e2e_tutorial.py index ec38544cf5d..02dc7868761 100644 --- a/tests/e2e_tutorial.py +++ b/tests/e2e_tutorial.py @@ -3,13 +3,14 @@ import os import infra.clients +import infra.consistency_trace import infra.e2e_args import infra.network import infra.proc def run(args): - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb ) as network: for node in network.nodes: diff --git a/tests/forwarding.py b/tests/forwarding.py index b411f14655f..b5f7e8801f4 100644 --- a/tests/forwarding.py +++ b/tests/forwarding.py @@ -5,6 +5,7 @@ import http +import infra.consistency_trace import infra.e2e_args import infra.interfaces import infra.network @@ -20,7 +21,7 @@ def run(args): interface ) - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb ) as network: network.start_and_open(args) diff --git a/tests/fuzzing.py b/tests/fuzzing.py index 1705ba60278..0e7823ea02d 100644 --- a/tests/fuzzing.py +++ b/tests/fuzzing.py @@ -4,6 +4,7 @@ import struct import boofuzz +import infra.consistency_trace import infra.e2e_args import infra.network from loguru import logger as LOG @@ -198,7 +199,7 @@ def fuzz_node_to_node(network, args): def run(args): - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb ) as network: network.start_and_open(args) diff --git a/tests/governance.py b/tests/governance.py index 319fd2072c8..33e4f91cc60 100644 --- a/tests/governance.py +++ b/tests/governance.py @@ -16,6 +16,7 @@ import governance_history import governance_js import infra.clients +import infra.consistency_trace import infra.crypto import infra.e2e_args import infra.interfaces @@ -268,75 +269,48 @@ def test_member_data(network, args): @reqs.description("Check /gov/service/members endpoint") -def test_all_members(network, args): - def run_test_all_members(network): - primary, _ = network.find_primary() - with primary.api_versioned_client(api_version=args.gov_api_version) as c: - r = c.get("/gov/service/members") - assert r.status_code == http.HTTPStatus.OK.value - m_body = r.body.json()["value"] - response_members = {m["memberId"]: m for m in m_body} - - network_members = network.get_members() - assert len(network_members) == len(response_members) - - for member in network_members: - assert member.service_id in response_members - response_member = response_members[member.service_id] - - response_cert = response_member["certificate"] - assert response_cert == member.cert +def check_all_members(network, args): + primary, _ = network.find_primary() + with primary.api_versioned_client(api_version=args.gov_api_version) as c: + r = c.get("/gov/service/members") + assert r.status_code == http.HTTPStatus.OK.value + m_body = r.body.json()["value"] + response_members = {m["memberId"]: m for m in m_body} - response_status = infra.member.MemberStatus(response_member["status"]) - assert response_status == member.status + network_members = network.get_members() + assert len(network_members) == len(response_members) - response_data = response_member.get("memberData") - assert response_data == member.member_data + for member in network_members: + assert member.service_id in response_members + response_member = response_members[member.service_id] - response_pub_enc_key = response_member.get("publicEncryptionKey") - if member.recovery_role != infra.member.RecoveryRole.NonParticipant: - enc_pub_key_file = os.path.join( - primary.common_dir, member.member_info["encryption_public_key_file"] - ) - with open(enc_pub_key_file, encoding="utf-8") as enc_pub_key: - recovery_enc_key = enc_pub_key.read() - assert response_pub_enc_key == recovery_enc_key - else: - assert response_pub_enc_key is None + response_cert = response_member["certificate"] + assert response_cert == member.cert - response_recovery_role = response_member.get("recoveryRole") - if member.recovery_role == infra.member.RecoveryRole.Owner: - assert response_recovery_role == "Owner" - elif member.recovery_role == infra.member.RecoveryRole.Participant: - assert response_recovery_role == "Participant" - else: - assert response_recovery_role == "NonParticipant" + response_status = infra.member.MemberStatus(response_member["status"]) + assert response_status == member.status - # Test on current network - run_test_all_members(network) + response_data = response_member.get("memberData") + assert response_data == member.member_data - # Test on mid-recovery network - network.save_service_identity(args) - primary, _ = network.find_primary() - network.stop_all_nodes() - current_ledger_dir, committed_ledger_dirs = primary.get_ledger() - # NB: Don't try to get snapshots, since there may not be any committed, - # and we cannot wait for commit now that the node is stopped - recovered_network = infra.network.Network( - args.nodes, - args.binary_dir, - args.debug_nodes, - existing_network=network, - ) - recovered_network.start_in_recovery( - args, - ledger_dir=current_ledger_dir, - committed_ledger_dirs=committed_ledger_dirs, - ) - run_test_all_members(recovered_network) - recovered_network.recover(args) + response_pub_enc_key = response_member.get("publicEncryptionKey") + if member.recovery_role != infra.member.RecoveryRole.NonParticipant: + enc_pub_key_file = os.path.join( + primary.common_dir, member.member_info["encryption_public_key_file"] + ) + with open(enc_pub_key_file, encoding="utf-8") as enc_pub_key: + recovery_enc_key = enc_pub_key.read() + assert response_pub_enc_key == recovery_enc_key + else: + assert response_pub_enc_key is None - return recovered_network + response_recovery_role = response_member.get("recoveryRole") + if member.recovery_role == infra.member.RecoveryRole.Owner: + assert response_recovery_role == "Owner" + elif member.recovery_role == infra.member.RecoveryRole.Participant: + assert response_recovery_role == "Participant" + else: + assert response_recovery_role == "NonParticipant" @reqs.description("Test ack state digest updates") @@ -696,7 +670,7 @@ def gov(args): for node in args.nodes: node.rpc_interfaces.update(infra.interfaces.make_secondary_interface()) - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb ) as network: network.start_and_open(args) @@ -705,28 +679,45 @@ def gov(args): test_consensus_status(network, args) test_member_data(network, args) test_ack_state_digest_update(network, args) + check_all_members(network, args) + network.save_service_identity(args) + primary, _ = network.find_primary() + network.stop_all_nodes() + current_ledger_dir, committed_ledger_dirs = primary.get_ledger() - # test_all_members stops this network and recovers into a new one, which - # the enclosing context manager does not own: it still holds the - # original. Stop the recovered network here, or its nodes outlive the - # test. That includes the deliberately untrusted nodes added by - # test_no_quote and test_node_data, which then sit in a join retry loop - # for the rest of the CI job. - recovered_network = test_all_members(network, args) - try: - test_user(recovered_network, args) - test_jinja_templates(recovered_network, args) - test_no_quote(recovered_network, args) - test_node_data(recovered_network, args) - test_each_node_cert_renewal(recovered_network, args) - test_binding_proposal_to_service_identity(recovered_network, args) - test_all_nodes_cert_renewal(recovered_network, args) - test_service_cert_renewal(recovered_network, args) - test_service_cert_renewal_extended(recovered_network, args) - test_pq_service_cert_renewal(recovered_network, args) - test_pq_service_cert_renewal_rejected(recovered_network, args) - finally: - recovered_network.stop_all_nodes(skip_verification=True) + # Disaster recovery is outside the consistency model, so the recovered + # network runs outside consistency_trace.recording(). Stop it explicitly so + # its nodes (including deliberately untrusted nodes from test_no_quote and + # test_node_data) do not outlive the test. + # NB: Don't try to get snapshots, since there may not be any committed, + # and we cannot wait for commit now that the node is stopped. + recovered_network = infra.network.Network( + args.nodes, + args.binary_dir, + args.debug_nodes, + existing_network=network, + ) + try: + recovered_network.start_in_recovery( + args, + ledger_dir=current_ledger_dir, + committed_ledger_dirs=committed_ledger_dirs, + ) + check_all_members(recovered_network, args) + recovered_network.recover(args) + test_user(recovered_network, args) + test_jinja_templates(recovered_network, args) + test_no_quote(recovered_network, args) + test_node_data(recovered_network, args) + test_each_node_cert_renewal(recovered_network, args) + test_binding_proposal_to_service_identity(recovered_network, args) + test_all_nodes_cert_renewal(recovered_network, args) + test_service_cert_renewal(recovered_network, args) + test_service_cert_renewal_extended(recovered_network, args) + test_pq_service_cert_renewal(recovered_network, args) + test_pq_service_cert_renewal_rejected(recovered_network, args) + finally: + recovered_network.stop_all_nodes(skip_verification=True) # These tests requiring starting up + shutting down a node with specific @@ -741,7 +732,7 @@ def test_desc(s): json.dump(start_node_data, ntf) ntf.flush() - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, @@ -898,7 +889,7 @@ def rand_hex(): def js_gov(args): - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb ) as network: network.start_and_open(args) @@ -926,7 +917,7 @@ def js_gov(args): def gov_replay(args): - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb ) as network: network.start_and_open(args) @@ -936,7 +927,7 @@ def gov_replay(args): def did_key_identities(args): - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, pdb=args.pdb ) as network: initial_format = getattr(args, "identity_id_format", "sha256") @@ -1254,40 +1245,40 @@ def did_key_identities(args): network.save_service_identity(args) network.stop_all_nodes() ledger_dir, committed_ledger_dirs = primary.get_ledger() - recovery_args = copy.deepcopy(args) - recovery_args.label = f"{args.label}_disk_recovery" - with infra.network.network( - args.nodes, - args.binary_dir, - args.debug_nodes, - ) as recovered: - recovered.start_in_recovery( - recovery_args, - ledger_dir=ledger_dir, - committed_ledger_dirs=committed_ledger_dirs, - snapshots_dir=snapshots_dir, - common_dir=network.common_dir, - node_id_format="did:key", + + # Disaster recovery is outside the consistency model. + recovery_args = copy.deepcopy(args) + recovery_args.label = f"{args.label}_disk_recovery" + with infra.network.network( + args.nodes, + args.binary_dir, + args.debug_nodes, + ) as recovered: + recovered.start_in_recovery( + recovery_args, + ledger_dir=ledger_dir, + committed_ledger_dirs=committed_ledger_dirs, + snapshots_dir=snapshots_dir, + common_dir=network.common_dir, + node_id_format="did:key", + ) + for original in network.consortium.members: + restored = recovered.consortium.get_member_by_local_id(original.local_id) + assert restored is not None, original.local_id + assert restored.service_id == original.service_id + assert restored.id_format == original.id_format + assert restored.recovery_role == original.recovery_role + assert ( + restored.member_data + == members_before_recovery[original.service_id]["memberData"] ) - for original in network.consortium.members: - restored = recovered.consortium.get_member_by_local_id( - original.local_id - ) - assert restored is not None, original.local_id - assert restored.service_id == original.service_id - assert restored.id_format == original.id_format - assert restored.recovery_role == original.recovery_role - assert ( - restored.member_data - == members_before_recovery[original.service_id]["memberData"] - ) - assert restored.status == original.status - recovered.recover(recovery_args, via_recovery_owner=True) - recovered_primary, _ = recovered.find_primary() - assert recovered_primary.node_id.startswith("did:key:z") - with recovered_primary.client(replacement_identity) as c: - r = c.get("/app/log/private?id=1") - assert r.status_code == http.HTTPStatus.UNAUTHORIZED, r + assert restored.status == original.status + recovered.recover(recovery_args, via_recovery_owner=True) + recovered_primary, _ = recovered.find_primary() + assert recovered_primary.node_id.startswith("did:key:z") + with recovered_primary.client(replacement_identity) as c: + r = c.get("/app/log/private?id=1") + assert r.status_code == http.HTTPStatus.UNAUTHORIZED, r if __name__ == "__main__": diff --git a/tests/governance_api.py b/tests/governance_api.py index 45f2f5bede8..5d7b39667a2 100644 --- a/tests/governance_api.py +++ b/tests/governance_api.py @@ -1,6 +1,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the Apache 2.0 License. import infra.clients +import infra.consistency_trace import infra.network import suite.test_requirements as reqs from loguru import logger as LOG # type: ignore @@ -164,7 +165,7 @@ def test_api_transactions(network, args): def run(args): - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, diff --git a/tests/governance_history.py b/tests/governance_history.py index d9595995ef8..50b5eb42de3 100644 --- a/tests/governance_history.py +++ b/tests/governance_history.py @@ -10,6 +10,7 @@ import ccf.read_ledger import ccf.signatures import cwt +import infra.consistency_trace import infra.crypto import infra.doc import infra.logging_app as app @@ -348,7 +349,7 @@ def run(args): governance_operations = set() txs = app.LoggingTxs("user0") - with infra.network.network( + with infra.consistency_trace.recording(args), infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, diff --git a/tests/infra/consistency_trace.py b/tests/infra/consistency_trace.py index a9c388e9d60..640588fabc2 100644 --- a/tests/infra/consistency_trace.py +++ b/tests/infra/consistency_trace.py @@ -8,8 +8,10 @@ """ import contextlib +import itertools import json import os +import shutil import struct import subprocess import threading @@ -29,6 +31,9 @@ # (nanoseconds since the epoch, per-process sequence number, record). _recording = threading.local() +_trace_lock = threading.Lock() +_cleared_trace_folders = set() + def tx_status(body, ts=None): """Record a transaction status given to a client: the body of a /tx response.""" @@ -44,47 +49,105 @@ def tx_status(body, ts=None): events[("client", len(events))] = (ts or time.time_ns(), 0, {"msg": msg}) -@contextlib.contextmanager -def recording(args): - """Trace the nodes started with args, then replay the trace. +def _consistency_profile_file(): + profile_file = os.environ.get("LLVM_PROFILE_FILE") + if not profile_file: + return None + directory, filename = os.path.split(profile_file) + return os.path.join(directory, f"consistency-{filename}") - Does nothing unless CCF_LEAN_CONSISTENCY_REPLAYER names the replayer. The - body must stop its nodes. The trace is not replayed if the body raises. - """ - replayer = os.getenv("CCF_LEAN_CONSISTENCY_REPLAYER") - if not replayer: + +@contextlib.contextmanager +def _profile_for_consistency(args): + profile_file = _consistency_profile_file() + if not profile_file: yield return - events = {} - - def node_event(tag, timestamp, record): - if tag == "ccf.cft" and record["msg"]["fn"] in FUNCTIONS: - seconds, nanos = struct.unpack(">II", timestamp.data) - # Keyed by origin, as delivery retries can duplicate records. - events[(record["pid"], record["m_ts"])] = ( - seconds * 10**9 + nanos, - record["m_ts"], - record, - ) - - path = os.path.join(args.workspace, f"{args.label}_consistency_trace.ndjson") + had_profile = hasattr(args, "llvm_profile_file") + prev_profile = getattr(args, "llvm_profile_file", None) + args.llvm_profile_file = profile_file try: - with infra.fluentd.Collector(MAX_NODES, node_event) as collector: - endpoint = {**collector.endpoint, "tag-prefix-allow-list": ["ccf.cft"]} - args.observability = {"fluentd": [endpoint]} - _recording.events = events - yield + yield finally: - _recording.events = None + if had_profile: + args.llvm_profile_file = prev_profile + elif hasattr(args, "llvm_profile_file"): + delattr(args, "llvm_profile_file") + + +def _write_trace(workspace, label, ordered): + folder = os.path.join(workspace, f"{label}_consistency_trace") + with _trace_lock: + if folder not in _cleared_trace_folders: + _cleared_trace_folders.add(folder) + shutil.rmtree(folder, ignore_errors=True) + os.makedirs(folder, exist_ok=True) + for index in itertools.count(): + path = os.path.join(folder, f"{index}.ndjson") + try: + f = open(path, "x", encoding="ascii") # noqa: SIM115 + break + except FileExistsError: + pass + with f: + f.writelines( + json.dumps({"ts": ts, **record}) + "\n" for ts, _, record in ordered + ) + return path + + +@contextlib.contextmanager +def recording(args): + """Trace the nodes started with args, and replay inline if requested. + + Records when CCF_CONSISTENCY_TRACE is set or CCF_LEAN_CONSISTENCY_REPLAYER + names the replayer, writing /