Testing

The runtime has a layered testing strategy that covers unit tests, conformance fixtures, and a separate integration test crate that exercises the full gRPC boundary. This page explains each layer, how to run the tests, and how they fit into CI/CD.

Unit tests and conformance

The core test suite runs with standard Cargo commands:

cargo test --all-targets          # Unit tests + Rust integration tests
make test-conformance             # JSON fixture-driven conformance suite
make test-all                     # fmt -> clippy -> test -> integration -> conformance

Unit tests live inside src/ modules under #[cfg(test)] and cover mode state machines, policy evaluation algorithms, storage backends (including compaction, legacy-format migration, and crash-recovery paths), replay logic, metrics rendering, the extension registry, JWT auth including remote-JWKS fetch/caching/rotation, the auth resolver chain, and error handling. The conformance fixtures in tests/conformance/ -- a byte-identical vendored copy of the spec repo's schemas/conformance/ at SPEC_REV (see tests/conformance/SOURCE.md for provenance and the re-vendor command) -- define mode lifecycles as JSON files and verify that each mode's happy path and reject paths produce the expected results.

Parity contract

tests/parity_contract.rs asserts every macp-runtime-relevant section of the spec repo's schemas/parity/contract.json -- a small, non-normative manifest pinning cross-implementation-agreed values (protocol version, mode-id sets, defaults, error codes, commitment-hash format, Contribute payload encoding, Proposal mode's disposition domain) shared with macp-sdk-python and macp-sdk-typescript -- against this runtime's real, live code: macp_core::MACP_VERSION, the mode-registry constants, is_canonical_commitment_hash/parse_contribute_value, MacpError::error_code(), PolicyRegistry::register, and macp_modes::mode::proposal::ProposalDisposition.

cargo test --test parity_contract

It reads tests/parity/contract.json (a byte-identical vendored copy; see tests/parity/SOURCE.md for provenance and the re-vendor command) by default, or the file named by MACP_PARITY_CONTRACT when set -- CI's conformance-oracle job points this at the spec-repo checkout directly, proving the runtime matches canonical, not merely the vendored copy.

Integration test suite

A separate Rust crate at integration_tests/ tests the runtime through the real gRPC transport boundary. It is not part of the main Cargo build -- cargo build --release ignores it entirely.

The crate starts the runtime binary as a subprocess on a free port, connects as a gRPC client, and runs test scenarios against the live server. This ensures that the transport layer, authentication, serialization, and kernel logic all work together correctly.

Lockfile

Being a separate workspace, integration_tests/ has its own checked-in integration_tests/Cargo.lock, and that lock records the full dependency edges of the seven macp-* path crates. So adding or removing a dependency, or changing a requirement the existing pin no longer satisfies, in any workspace crate — crates/macp-*/Cargo.toml or the root Cargo.toml, not only integration_tests/Cargo.toml — leaves it stale, and the Integration (tier 1 + 2, real gRPC boundary) CI job fails with cargo metadata --locked. Regenerate it in the same PR:

cargo metadata --manifest-path integration_tests/Cargo.toml --format-version 1 > /dev/null

See CONTRIBUTING.md for the full rule, including how release PRs keep this lock in step automatically.

Test architecture

integration_tests/
  src/
    config.rs             -- Test target configuration (local / CI / hosted)
    server_manager.rs     -- Start/stop runtime as subprocess on free port
    helpers.rs            -- Envelope builders, payload helpers, gRPC wrappers
    macp_tools/           -- Rig Tool implementations for MACP operations
  tests/
    tier1.rs -> tier1_protocol/    -- Scripted gRPC protocol tests
    tier2.rs -> tier2_agents/      -- Rig agent tool tests
    tier3.rs -> tier3_e2e/         -- Real LLM agent tests

Three tiers

Tier 1: Protocol tests exercise every mode through scripted gRPC calls. These tests cover the full protocol surface: Initialize negotiation, happy-path flows for all five standard modes plus multi-round (consolidated in test_mode_happy_paths.rs), signals, deduplication, version binding, cancellation authorization, session suspend/resume including the RFC-MACP-0006 §3.2 ordinal/no-delivery invariant for SessionSuspend/SessionResume/SessionCancel (test_suspend_resume.rs's subscribe_never_delivers_lifecycle_annotations, mirrored in-process by tests/stream_integration.rs and tests/integration_mode_lifecycle.rs in the root crate), session lifecycle, StreamSession including RFC-MACP-0006-A1 passive subscribe (test_passive_subscribe.rs -- history replay with after_sequence offsets, unknown-session and non-participant rejection, late-joiner replay-then-live delivery), mode registry operations including PromoteMode and the WatchModeRegistry/WatchPolicies/WatchRoots observation streams, the policy registry including the reserved policy.std. namespace (non-canonical and unassigned identifiers rejected with INVALID_POLICY_DEFINITION, pre-registered profiles refusing unregistration) and the RFC-MACP-0012 §5.2 outcome table driven end to end, JWT bearer auth, TLS transport (self-signed round-trip plus a no-plaintext-fallback check), persistence and restart-replay against a real data directory, payload-size and per-sender rate limits, ListSessions keyset pagination (page-size default and clamp, continuation-token traversal, and malformed-token rejection), true concurrent senders racing into one session, and discovery RPCs. Most tests share one dev-mode server; tests that need special server configuration (TLS, limits, persistence, promotion) spawn their own on dynamic ports. They run in a few seconds with no external dependencies.

Tier 2: Rig agent tools (5 tests) validate the MACP operations implemented as Rig Tool trait objects. These are called through ToolSet::call(), the same interface an LLM agent would use. They cover all five standard modes and verify that the tool abstraction correctly maps to gRPC operations.

Tier 3: End-to-end with real LLM (3 tests, marked #[ignore]) use real OpenAI GPT-4o-mini agents coordinating through the runtime. The architecture follows the protocol's design: orchestrator operations are deterministic plain code, while specialist reasoning uses real LLM inference. Agents run in parallel and the runtime serializes their contributions by acceptance order. These tests demonstrate both the coordination plane and the ambient plane (signals) working simultaneously.

Running integration tests

# Build the runtime first
cargo build

# Tier 1 + 2 (no API keys needed)
cd integration_tests
MACP_TEST_BINARY=../target/debug/macp-runtime cargo test -- --test-threads=1

# Individual tiers
MACP_TEST_BINARY=../target/debug/macp-runtime cargo test --test tier1 -- --test-threads=1
MACP_TEST_BINARY=../target/debug/macp-runtime cargo test --test tier2 -- --test-threads=1

# Tier 3 (requires OpenAI API key; Doppler macp-runtime/dev holds it, see CONTRIBUTING.md)
doppler run -- env MACP_TEST_BINARY=../target/debug/macp-runtime \
  cargo test --test tier3 -- --ignored --test-threads=1
# or, without Doppler: OPENAI_API_KEY=sk-... MACP_TEST_BINARY=... cargo test ...

# Against a hosted runtime (no local server started)
MACP_TEST_ENDPOINT=host:50051 cargo test -- --test-threads=1

Or use the Makefile targets from the project root:

make test-integration-grpc      # Tier 1
make test-integration-agents    # Tier 2
make test-integration-e2e       # Tier 3 (doppler run -- make test-integration-e2e, or a root .env)
make test-integration-hosted    # All tiers against MACP_TEST_ENDPOINT

Or run it in a container via docker-compose.yml, which builds the runtime binary from this checkout and drives it through the real gRPC boundary (integration_tests/Dockerfile), passing through OPENAI_API_KEY (from a gitignored root .env or the host) and RUST_LOG (default warn):

docker compose build integration-tests
docker compose run --rm integration-tests                                                          # tier 1 + 2 (default CMD)
docker compose run --rm integration-tests --test tier3 -- --ignored --test-threads=1    # tier 3, real LLM (ENTRYPOINT is already `cargo test`)

CI does not use this -- the integration job in ci.yml runs the suite directly on the runner. docker-compose.yml is a contributor convenience for a reproducible local environment, not the canonical test path.

Configuration

VariablePurposeDefault
MACP_TEST_BINARYPath to the runtime binaryBuilds from parent crate
MACP_TEST_ENDPOINTHosted runtime to test against (skips local server)Starts local server
MACP_TEST_TLSUse TLS for hosted connection0
MACP_TEST_AUTH_TOKENBearer token for hosted runtimeDev headers
MACP_TEST_BACKENDRun the storage-backend smoke test on rocksdb/redis/file (binary must be built with the matching feature)Test skips if unset
MACP_TEST_REDIS_URLRedis endpoint for the redis backend smoke testredis://127.0.0.1:6379
OPENAI_API_KEYRequired for Tier 3 tests. Doppler macp-runtime/dev holds it (doppler run -- ...); a root .env is the fallbackTier 3 tests skip if unset
MACP_CONFORMANCE_FIXTURES_DIRRun tests/conformance_loader.rs's suite against an external fixtures directory instead of the vendored tests/conformance/ copy (also set by ci.yml's conformance-oracle job)Uses the vendored copy

Policy tests

The policy engine has dedicated coverage across multiple test layers:

Unit tests in crates/macp-policy/ include approximately 170 tests covering all six voting algorithms, quorum threshold calculations, veto logic, evaluation confidence requirements, registry CRUD operations, the registration-time rule checks (value domains, conditional constraints, and the reserved policy.std. namespace -- not a JSON-Schema evaluator; see Policy), default policy behavior, and rule deserialization.

Mode unit tests in crates/macp-modes/src/mode/*.rs exercise policy denial paths in all five standard modes, verifying that governance policies correctly block commitment when rules are not satisfied.

Conformance fixtures exercise mode lifecycles with policy version binding to ensure policies are resolved and applied correctly during replay.

Integration tests perform gRPC round-trips for all five policy RPCs (RegisterPolicy, GetPolicy, ListPolicies, UnregisterPolicy, WatchPolicies) and test end-to-end policy enforcement: registering a policy, starting a session bound to it, and verifying that commitment is blocked when rules are not met.

CI/CD

Every pull request runs the full gate in .github/workflows/ci.yml: MSRV check (1.89.0), fmt, clippy, rustdoc (-D warnings), unit + conformance + policy tests, release build, crate dependency-isolation checks, a blocking cargo audit (ignore list in .cargo/audit.toml), feature-gated builds and tests for the rocksdb/redis/otel features (including backend smoke tests through the real gRPC binary against rocksdb and a live redis service), the Tier 1 + Tier 2 integration suites, the conformance oracle against the spec repo's canonical fixtures, macp-conform over gRPC and HTTP, and a Docker gate that builds the image and smoke-tests the HTTP listener off and on. Coverage uploads to Codecov as advisory. All jobs run on the toolchain pinned in rust-toolchain.toml; a weekly scheduled audit (scheduled-audit.yml) catches new RUSTSEC advisories between PRs.

The features job runs cargo test -p macp-runtime --features otel as well as clippy, so the otel feature is tested, not only compiled. The vendored OpenTelemetry semantic conventions (tests/otel/macp-semconv.json, see tests/otel/SOURCE.md) are drift-checked by the conformance oracle and pinned to the runtime's span and metric set by cargo test --test otel_semconv.

OpenTelemetry tests

The otel feature is tested in the root crate, not in integration_tests/. Run cargo test -p macp-runtime --features otel; the features job's "Test otel feature" step runs exactly that on every PR, after its "Clippy (otel feature)" step. Spans are captured in-process with the SDK's in-memory exporter, and OTLP export with tests/support/fake_collector.rs, a local OTLP/gRPC collector. No test needs network access or a real collector.

FileCovers
tests/otel_semconv.rsThe vendored tests/otel/macp-semconv.json is macp-semconv/0.1, and its span and metric groups equal the runtime's set (runs without the feature too)
tests/otel_bootstrap.rsA wrong protocol, an unreadable certificate or a non-URI endpoint logs one error and the runtime still serves; the feature-off warning; bounded shutdown against a dead collector; TLS with the configured CA; log lines unchanged, even when RUST_LOG names the telemetry target
tests/otel_grpc.rsThe gRPC SERVER span: W3C traceparent from metadata, health checks unspanned, _OTHER naming, codes from headers and trailers, stream span lifetime
tests/otel_process.rsprocess spans on Send and StreamSession, parents, rejection codes, privacy (no payload or reason), storage failure and panic as ERROR, and the macp_envelope_* metrics
tests/otel_transitions.rsTransition spans, their parents and anchor links, expire as a root on every path, the commitment hash on resolve, the anchor cache's bound, and the macp_session_* metrics
tests/otel_anchor_restart.rsThe stored anchor across a restart (FileBackend), including the whole chain for a StreamSession Commitment after a restart (client traceparent → SERVER → process → resolve, both linked to the pre-restart anchor), corrupt records, memory-only storage, disk GC, store ordering, and anchor storage failures that never fail a message
tests/otel_replay_equivalence.rsTelemetry on and off produce the same session state and replay, with and without compaction
tests/otel_binary.rsThe real binary: export to the fake collector, zero egress on the default OTLP ports with no OTEL_* set, and the SIGINT flush bound

Activation, resource, endpoint/protocol/certificate resolution, label folding and the anchor record format are unit tests in src/telemetry/.

The macp-storage anchor contract (store_trace_anchor/load_trace_anchor/sweep_orphan_trace_anchors) is unit-tested per backend in crates/macp-storage/src/storage/; the RocksDB tests need cargo test -p macp-storage --features rocksdb-backend.

HTTP/JSON binding tests

The http-listener feature is tested in the root crate. cargo test -p macp-runtime --features http-listener runs the unit tests in src/http/ and the files below; the features job's "Test http-listener feature" step runs exactly that, and "Test http-listener with otel" adds the dispatch-table pin and tests/otel_http.rs (cargo test -p macp-runtime --features otel,http-listener --test otel_http).

FileCovers
tests/http_json.rsThe canonical JSON codec (RFC-MACP-0001 §10): the vendored examples round-trip, canonical bytes, number rules
tests/http_binary.rsThe real binary: no extra socket and a byte-identical GetManifest without MACP_HTTP_BIND_ADDR, configuration errors, TLS, shared shutdown
tests/http_unary.rsUnary RPCs and Send's in-band Ack, status mapping, golden parity with gRPC, the vendored send.json/errors.json exchanges
tests/http_sse.rsSSE streams: Last-Event-ID resume, framing, keepalive, how each stream ends, lag, the vendored subscribe/WatchSignals exchanges
tests/http_cors_discovery.rsCORS preflight and actual-response headers; /.well-known/macp.json
tests/otel_http.rsThe HTTP SERVER span and http.server.request.duration (otel,http-listener)
tests/conformance_http.rsThe conformance fixtures through macp-conform's HttpTarget, with outcomes equal to the gRPC target's

Two more checks run in CI against built artifacts. The conform-cli job runs macp-conform --transport http against a local binary, and then scripts/check-http-examples.sh, which executes every marked curl example in Examples against that binary and fails on any unexpected status or output (run it locally after cargo build -p macp-runtime --features http-listener). The docker-build job runs the image it builds twice: without MACP_HTTP_* it must listen on 50051 only, and with MACP_HTTP_BIND_ADDR=0.0.0.0:8080 GetManifest over HTTP must answer 200.

The HTTP/JSON binding artifacts in tests/http/ (the spec's examples/http/*.json, macp-http-error.schema.json and its invalid-http-errors/ negative fixtures, see tests/http/SOURCE.md) are vendored byte-identically and drift-checked by the conformance oracle (check_dir for the two directories, check_file for the schema).

The conformance oracle reads the spec repo at a pinned revision (SPEC_REV in ci.yml), not at its default branch, so the check stays reproducible regardless of upstream merge timing. A separate scheduled workflow, spec-drift.yml, watches that pin daily and files a tracked spec-drift-labelled issue — but only when the upstream change is one the oracle's gates can actually act on. A change it can prove inert (a file outside the oracle's scope, or a policy-schema edit that is provably annotation-only once description/$comment/title are stripped) is reported on the workflow run's step summary instead of escalated, so the label stays a reliable signal rather than routine noise.

Tier 3 runs only via manual GitHub Actions dispatch:

Actions -> "Integration Tests" -> Run workflow -> check "Run Tier 3 E2E"

Tier 3 reads OPENAI_API_KEY from Doppler macp-runtime/ci, using the read-only service token in the DOPPLER_TOKEN repository secret; the job fails if the key is missing rather than skipping. Tiers 1 and 2 run without any secrets.