Integration Testing
This document describes APM’s integration testing strategy to ensure runtime setup scripts work correctly and the golden scenario from the README functions as expected.
Testing Strategy
Section titled “Testing Strategy”APM uses a tiered approach to integration testing:
1. Smoke Tests (merge queue, runtime changes, and releases)
Section titled “1. Smoke Tests (merge queue, runtime changes, and releases)”- Location:
tests/integration/test_runtime_smoke.py - Purpose: Fast verification that runtime setup scripts work
- Scope:
- Runtime installation (codex, llm)
- Binary functionality (
--version,--help) - APM runtime detection
- Workflow compilation without execution
- Duration: ~2-3 minutes per platform
- Trigger: merge queue integration workflow, runtime-code pushes, scheduled/manual runs, and release validation
2. End-to-End Golden Scenario Tests (merge queue and promotion runs)
Section titled “2. End-to-End Golden Scenario Tests (merge queue and promotion runs)”- Location:
tests/integration/test_golden_scenario_e2e.py - Purpose: Complete verification of the README golden scenario
- Scope:
- Full runtime setup and configuration
- Project initialization (
apm init) - Dependency installation (
apm install) - Real API calls to GitHub Models
- Copilot, Codex, LLM, and Gemini runtime execution
- Duration: ~10-15 minutes per platform (with 20-minute timeout)
- Trigger: merge queue integration workflow, plus tag, schedule, and manual promotion runs
3. Lifecycle Smoke (PR-time required check)
Section titled “3. Lifecycle Smoke (PR-time required check)”- Location: selected declaratively via
lifecycle_smoke and not lifecycle_merge_group. Tests markedlifecycle_merge_groupremain outside the bounded required set. - Purpose: Promote a stable, hermetic slice of Consume/Produce/Govern lifecycle contracts onto the PR-time critical path, so regressions in install, lock, deployment ownership, compile, pack, prune, uninstall, audit, and repair fail the PR.
- Scope: the family contains a static authority guard plus content-hash, policy, hook, virtual-package, audit, auth, and installed-console rows. Real subprocess cases use the uv-installed
apmcommand and local Git. This is not frozen PyInstaller coverage. - Prerequisites: the pytest step sets
APM_E2E_TESTS=1so subprocess rows execute.APM_RUN_INTEGRATION_TESTSremains unset, the socket guard denies network sockets, and the job binds no credentials. - Duration: five shards each have a hard 20-minute timeout, including setup and cleanup; a balanced shard is expected to use under 60 percent of it, with four
loadgroupworkers. Hosted job results are authoritative; a printed pytest summary does not override a job timeout. - Trigger: every pull request and merge queue run. The required
Lifecycle Smoke (Linux)aggregate checks every shard result independently and fails if any is missing, skipped, cancelled, or failed. - Selection mechanism:
pytest --strict-markers -m 'lifecycle_smoke and not lifecycle_merge_group' tests/integration— declarative, not a file/node-id list. No central count or membership list is maintained. - Sharding:
scripts.ci_shardingbalances the shards by the measured lifecycle smoke durations in.github/ci-durations/lifecycle-smoke.jsonwhile keeping each module and compositexdist_groupintact. The shards are disjoint and their union is the unchanged required selection. - Full-coverage path: merge-group workflow
ci-integration.yml, jobintegration-tests-shard, stepRun integration tests (sharded + parallelized), callsuv run ./scripts/test-integration.shovertests/integration/. The hermetic shards and the network lane together run every non-livetest, so the complete lifecycle family remains exercised. - Drift guard:
tests/quality/test_ci_topology.pyindependently collects the full, merge-group-only, required, and every sharded selection. It verifies their set relationships, each shard’s timeout and worker bounds, the aggregate’s failure behavior, the full-integration execution path, step-levelAPM_E2E_TESTS: "1"binding, network/credential prohibitions, and required-check membership. - Fixture controls: lifecycle helpers set
APM_TEST_LOOPBACK_PORTSfor a port-scoped local registry andAPM_TEST_FAIL_LOCK_REPLACE=1for atomic-write fault injection, andAPM_TEST_LOCK_COMMIT(hold:<marker>orkill) to stop a command at its lockfile commit point. These are internal test controls, not user-facing APM settings. - Source and ownership fixtures: downloader stubs must return real
PackageInfoandResolvedReferencevalues and materialize each package at the requested path, including staging directories. Native MCP cleanup tests must generate managed baselines through the real writer, then prove both authorized removal and unchanged bytes on unverifiable or foreign entries. Keep successful transitive-service, frozen replay, and exact-byte assertions; a mock-error exit is not success. - Learning ledger:
tests/fixtures/lifecycle_bug_ledger/(one JSON file per row, such asbugs/<issue>.json, so concurrent PRs do not conflict) maps representative escaped defects to generalized laws, oracle tiers, phases, and executable regression node IDs, including coverage of already-correct behavior. Use same-workspace transitions to prove survivor ownership and scoped cleanup. It is not a bug-count census;tests/quality/test_lifecycle_bug_ledger.pyvalidates its taxonomy and links. - Spine state machine:
tests/lifecycle/machines/test_m_spine.pyuses Hypothesis to generate guarded install, dry-run, audit, tamper, repair, declaration, prune, update, lock, compile and frozen sequences through the lifecycle driver (python -m apm_cli.clion PR, the packaged binary on the nightly). The model tracks declaration, materialization, integrity, and lock state independently of the product lockfile. Its mandatory and generated project, global-canonical, and global-aliased replays verify that ordinary reinstall preserves edited skill bytes and their original deployment hashes. After prune removes ownership, ordinary install must refuse the retained user file without changing its bytes or durable state. Deliberate repair uses existinginstall --forceconsent, then checks exact source bytes, installed lock state, and a clean audit. Every command, including those the shared helpers run, is followed bycheck_cross_cutting, so each step keeps I1-I9 and earns receipts; per-rule write-set snapshots stay as before. The mandatory spine replays once per world; later examples restore that post-spine world in place. PR shards run 4 derandomized examples per variant; the nightly explores 25 (APM_SPINE_MAX_EXAMPLES=25). - GATE state machine:
tests/lifecycle/machines/test_m_gate.pydrives the lifecycle driver (python -m apm_cli.clion PR, the packaged binary on the nightly) through declare, approve, deny, revoke, org-policy tightening, install,install --frozen, update, uninstall, prune andaudit --cifor hook, LSP and native-plugin content, at project scope and at user scope withAPM_HOMEoutsideHOME. After every stepcheck_cross_cutting(tests/lifecycle/oracles.py) checks lock/deployed agreement, idempotence, frozen/audit agreement, gate monotonicity (relative to the model: after each successful mutating step nothing is deployed that current approvals and policy do not allow), write sets, ASCII output, failure atomicity, exit codes and duplicated output. A cell that fails onmainis a strict expected failure naming its tracking issue. Every step emits acell:event; the mandatory spine must covertests/quality/gate_cell_obligations.json, and a recorded mutant that skips the approval check must fail the machine. PR shards run 4 derandomized examples per scope;.github/workflows/gate-machine-nightly.ymlbuilds the binary and explores 25 fresh examples per scope (APM_LIFECYCLE_DRIVER=binary,APM_GATE_MAX_EXAMPLES=25). - Lifecycle family core:
tests/lifecycle/holds the shared pieces: a pure reference model (model/state.py,model/expected.py), a driver (driver.py,APM_LIFECYCLE_DRIVER=engine|binary), the cross-cutting oracle (oracles.py) and receipts (receipts.py). Each oracle law that applies to a step and passes writes one receipt; only the oracle module may write receipts.tests/quality/promise_obligations.jsonlists every obligation asrequired, with the witness test that must earn its receipt (checked inside the lifecycle shards), or in thebaselinewith the lane that will cover it. A new obligation must be in one of the two lists, and the 0.37 release needs an empty baseline. - Docs journeys:
tests/lifecycle/journeys/test_journeys.pyreplays the 25 journeys ofindex.yaml(one YAML file per journey; the schema is the module docstring) through the driver and applies output oracles O1-O13 pluscheck_cross_cutting. Golden journeys carrylifecycle_smoke;.github/workflows/lifecycle-journeys.ymlruns all of them nightly on Linux, Windows and macOS, plus the fulltests/lifecyclesuite on Linux (PR and push CI run only the smoke subset), and on dispatch for a release-candidateref, which must be a commit onmainor arelease/*branch (a firstresolve-refjob refuses anything else before any checkout). Regenerate goldens withpython tests/lifecycle/journeys/regen_goldens.py. - Frozen under-recording: the required smoke scenario and the generated model’s mandatory project replay add a local skill without refreshing the lockfile, require frozen refusal with unchanged lockfile bytes, repair with ordinary install, and verify two byte-stable frozen replays. The scenario uses
ApmLifecycleRunnerin an isolated environment. It does not promise filesystem rollback: the new skill is deployed before refusal. - Frozen local dependencies:
test_frozen_local_path_lifecycle.pyuses the selected installed CLI to check direct and transitive source changes before deployment, including portable identities for packages inside the consumer project. It covers a fresh consumer with a separate empty cache, unchanged lock and managed bytes on refusal, preserved unrelated cache content, and recovery by restoring the source or explicitly accepting it with a normal install. This is separate from the root project’s under-recording scenario above. - Known gap: a late lockfile replacement failure can leave target files on the newly declared target while retaining the prior lockfile. The required lifecycle suite bounds that blast radius and proves the next install converges; expanding the install transaction is a separate design decision recorded in the ledger.
- Run it locally (repeat with shards
2and3to cover the full required selection):Terminal window APM_E2E_TESTS=1 uv run --extra dev python -m pytest -p no:cacheprovider -q --strict-markers \-p scripts.ci_sharding --shard-count 3 --shard-index 1 \--shard-durations .github/ci-durations/linux-x86_64.json \-n 4 --dist loadgroup --durations=20 \-m 'lifecycle_smoke and not lifecycle_merge_group' tests/integration
3b. Owner Surface Check (required on every PR)
Section titled “3b. Owner Surface Check (required on every PR)”- Location:
.github/workflows/owner-surface.yml, selection inscripts/owner_surface.py. - Purpose: run, on every pull request, the slice of the merge-time integration suite that an owner or install-path change can break. Owner-guard and install regressions then show on the PR, not on
main. - Trigger: a change to
src/apm_cli/install/*,src/apm_cli/deps/lockfile*,.apm/architecture/*,scripts/architecture_linter/*,tests/integration/test_architecture_*.py,tests/integration/test_install_*.py, or any file an owner registry selector names. - Slice: owner-rule mutation cases and
test_architecture_*.pyfiles that name a changed file or an affected owner, guard or rule; plus everytest_install_*.pyfile for install-path changes. It runs hermetic tests in 3 duration-balanced shards (target under 10 min). - Result:
Owner Surface Checkalways reports and is required bygatein every context. It passes when no owner surface changed (the slice steps are skipped) and on merge_group and merge trains (as theownertier), where the full suite runs. - Run it locally:
Terminal window python3 -m scripts.owner_surface plan --base origin/main --out /tmp/changed.txtAPM_E2E_TESTS=1 uv run --extra dev python -m scripts.owner_surface run \--base origin/main --changed /tmp/changed.txt -- -n 4 --dist loadgroup
4. Live Guardrailing Hero (scheduled/manual)
Section titled “4. Live Guardrailing Hero (scheduled/manual)”- Location:
tests/integration/test_guardrailing_hero_e2e.py - Purpose: Preserve the real remote, token-gated packaged CLI hero without multiplying it across the default packaged platform matrix
- Scope: project initialization, two GitHub-backed installs, compile/deploy, and prompt startup through the built Linux x64 binary
- Trigger: one
ci-runtime.ymlinvocation on schedule or manual dispatch that fails the workflow on error (continue-on-erroris not set); never pull requests or the generic integration script - Selection mechanism: the explicit test node with
-m live; collection gates remain owned bytests/integration/conftest.py
5. Real Harness (nightly, manual, native-plugin PRs; not required)
Section titled “5. Real Harness (nightly, manual, native-plugin PRs; not required)”- Location:
scripts/real_harness/probe.py,.github/workflows/real-harness.yml; harness pins are npm lockfiles underscripts/real_harness/npm/ - Purpose: Prove that pinned Claude Code and Copilot CLI releases actually load a plugin APM installs natively, not only that the files exist
- Cells: harness x environment (TUI in tmux, git worktree,
-p) x scope (user, project), plus Claude diagnostic cells (second session, absolute path, no folder trust, nativeclaude plugin install, worktree branches), and two #1120 cells: two packages whose native plugins ship the same skill name, and the same plugin name from two packages (refused) - Evidence: the plugin’s SessionStart hook marker, its stdio MCP server’s JSON-RPC log, the skill in the
claude -pinit event orcopilot skill list. Claude never reaches a model; Copilot sessions need thereal-harnessenvironment token, available only to schedule and dispatch runs on main, so those cells report BLOCKED elsewhere - Verdicts:
scripts/real_harness/expected.jsonrecords each cell’s expected verdict, known bugs included.probe.py checkfails on any divergence except BLOCKED; a fix flips its cells
Running Tests Locally
Section titled “Running Tests Locally”Exact-head HOME-alias lifecycle qualification
Section titled “Exact-head HOME-alias lifecycle qualification”The #2867 contract uses real CLI subprocesses in isolated project, canonical-home and aliased-home fixtures. Its eight required/generated/replay witnesses retain the mandatory lifecycle inside Hypothesis execution; an additional project scenario checks semver transport refusal and recovery. Ownership snapshot tests also enforce one lockfile read per used root and integration phase, zero unused reads, and at most 15x record visits when fixture size grows from N to 10N. These counts do not claim a wall-clock speedup.
For fully native Claude fixtures, global compile verifies the installed revision
in rules/revision.md, absence of redundant CLAUDE.md, and unchanged complete
snapshots. Separate lifecycle cases retain unmatched fallback, policy refusal,
and protected explicit-cleanup coverage. Mixed Claude/Hermes fixtures additionally
check the Hermes revision and permit only its AGENTS.md compilation write.
Use a clean committed checkout. Set BASE_SHA to the full 40-hex commit SHA
of a locally available, distinct ancestor of the checked-out HEAD.
Set REPORT_PATH and COMPLETION_PATH to distinct, new paths outside the checkout:
uv run --frozen --extra dev python scripts/check_lifecycle_evidence.py \ --base "$BASE_SHA" --head "$(git rev-parse HEAD)" --lane full \ --report "$REPORT_PATH" --completion-output "$COMPLETION_PATH"The command emits the schema-validated native completion sidecar only after fresh success. It verifies source/interpreter identity and freshly executes the authored contract; a skipped witness or disconnected sequence is not acceptance. It is source-Python coverage, not packaged-binary parity. Ordinary hosted platform checks remain separate.
For independent acceptance, use another clean checkout with the same base/head,
its own interpreter and disposable environment. Replace --completion-output
with --completion "$DRIVER_COMPLETION_PATH", pointing to the driver’s native
sidecar, and use a new external --report path. Keep the driver’s report available
at the path recorded in that sidecar. Completion mode verifies its digest and
reruns the contract; it does not reuse the report as execution. Keep this native
sidecar separate from the unchanged merge-worker completion JSON.
Selecting integration tests
Section titled “Selecting integration tests”Integration tests live under tests/integration/ and run via pytest
directly. Each test module declares the preconditions it needs as
standard pytest markers; the registry in
tests/integration/conftest.py (_MARKER_CHECKS) automatically skips
tests whose precondition is not met, so you only have to install/set
what the test family you want actually requires.
The marker registry
Section titled “The marker registry”| Marker | Precondition | How to satisfy it |
|---|---|---|
requires_e2e_mode | Opt-in for the heavyweight golden-scenario suite | export APM_E2E_TESTS=1 |
requires_network_integration | Opt-in for tests that hit live registries | export APM_RUN_INTEGRATION_TESTS=1 |
requires_windows | A Windows-only process or filesystem boundary | Run on Windows |
requires_windows_native_standard_user | Verified standard-user token without symlink privilege | The disposable Windows native-symlink CI job; do not enable manually |
requires_inference | Opt-in for tests that call inference APIs | export APM_RUN_INFERENCE_TESTS=1 |
requires_github_token | A token usable against github.com / GitHub Models | export GITHUB_APM_PAT=... (or GITHUB_TOKEN) |
requires_ado_pat | Azure DevOps PAT for ADO host tests | export ADO_APM_PAT=... |
requires_ado_bearer | Azure CLI signed in + opt-in flag | az login and export APM_TEST_ADO_BEARER=1 |
requires_apm_binary | A built apm binary on disk or PATH | scripts/build-binary.sh (or set APM_BINARY_PATH) |
requires_runtime_codex | The codex runtime on PATH or under ~/.apm/runtimes/; optional min_version="0.163.0" requires a stable release at or above that version on PATH | apm runtime setup codex |
requires_runtime_copilot | The GitHub Copilot CLI runtime installed under ~/.apm/runtimes/ | apm runtime setup copilot |
requires_runtime_llm | The llm runtime installed under ~/.apm/runtimes/ | apm runtime setup llm |
live | Tests that hit real third-party repositories; deselected by default | Override the deselect: pytest -m live tests/integration -v |
Without any of those env vars or runtimes a pytest tests/integration
invocation is silent rather than red: every test is collected and
reported as SKIPPED with a one-line reason, so you can see exactly
what is missing and why.
Three marker axes
Section titled “Three marker axes”Pytest markers compose across independent axes:
| Axis | Question | Markers |
|---|---|---|
| Behavioral | What boundary does the test cross? | unit, component, e2e |
| Scheduling | When is the test selected? | integration, slow, benchmark, live |
| Prerequisite | What environment must exist? | requires_* |
| CI-selection | Is this test part of a named required CI gate? | lifecycle_smoke |
live is both an opt-in scheduling marker and an external-service
prerequisite. Behavioral markers do not replace prerequisite markers.
lifecycle_smoke is orthogonal to all three: it does not describe a
test’s boundary, scheduling, or precondition, only that
ci.yml selects it for lifecycle coverage. The required smoke shards use
-m 'lifecycle_smoke and not lifecycle_merge_group'; the full integration
path also retains the merge-group-only cases (see Tier 3 above).
The behavioral definitions are:
| Marker | Definition |
|---|---|
unit | Pure logic with no filesystem and no CLI |
component | In-process behavior that touches a filesystem or one command boundary |
e2e | A real installed CLI crossing at least one command boundary |
pyproject.toml owns these definitions.
Module-level pytestmark is the sole behavioral classification authority.
This is a marker-only behavioral taxonomy.
Every classified module declares exactly one behavioral marker, and every
collected node in that module must inherit the same classification. Function-
or class-level behavioral markers are rejected because they would split the
module’s authority.
There is no central module whitelist or exact classified-module count. New modules opt in by adding one module-level marker. The trade-off is deliberate: APM gives up the old closed-set/count ratchet in exchange for distributed ownership and removal of a central merge hotspot. Repository-wide collection still rejects empty, mixed, and multiple classifications deterministically.
Directory names and _e2e.py suffixes are not proof of behavior.
test_policy_pinned_constraint_e2e.py is component because it uses Click
in-process; test_core_smoke.py is e2e because it invokes an installed
binary through subprocess boundaries.
To classify a module:
- Confirm the whole module has one behavioral boundary.
- Add exactly one module-level behavioral
pytestmark, preserving scheduling and prerequisite markers. - Document why behavior wins if the filename suggests another boundary.
- Run the contracts:
uv run --extra dev pytest -p no:cacheprovider -q tests/qualityuv run --frozen python scripts/check_test_assertions.pyuv run --frozen python scripts/check_exact_test_duplicates.pyThe assertion and exact-duplicate baseline updaters only accept reductions.
uv run --frozen python scripts/check_test_assertions.py --update-baselineuv run --frozen python scripts/check_exact_test_duplicates.py --update-baselineProvisional mode is CI-only and allowed only on draft pull requests.
Contributor commands, ready pull requests, merge queue runs, and final
validation are strict. Do not pass the internal provisional flag manually;
remove provisional metadata after remeasurement and review.
Test corpus ratchets
Section titled “Test corpus ratchets”Three no-growth ratchets keep the test corpus from getting worse. Each
records today’s debt in a baseline and fails only on new debt. A baseline
entry whose test or module is gone or fixed is reported as stale ([i]) and
never fails, so parallel cleanups do not conflict. Baselines are sorted JSON
with one entry per line; entries may only be removed.
- Duplicate tests (
scripts/check_exact_test_duplicates.py, baselinetests/quality/exact_test_duplicates.json). Each test body is hashed as a normalized AST (ast-body-v1: docstrings, comments and formatting ignored, literals kept). A test whose body equals another test’s body, or whoseClass::namealso exists in another file, fails unless the baseline lists it. Fix: delete the copy, parametrize it, or rename it after the distinct contract it checks. - Classification and placement (
tests/quality/test_test_taxonomy.py, baselinetests/quality/test_taxonomy_baseline.json). A module with no behavioral marker, aunitmodule undertests/integration, or atests/unitmodule that spawns processes fails unless listed. Fix: add the marker, or move the module. - Promise links (same contract and baseline). Every new test module
names the promises it protects in its module-level
pytestmark, using ids fromtests/quality/promise-catalog.json: OpenAPMreq-*ids,P-OWN-<owner id>architecture owners,P-INV-I1..P-INV-I9lifecycle invariants,P-LAW-<id>lifecycle laws andP-DOC-<id>documented-surface promises. Add a missing promise to the catalog in the same pull request. A new id family (P-<FAMILY>-<id>) must first be declared in the catalog’sfamilies; undeclared families fail.
pytestmark = [pytest.mark.unit, pytest.mark.promise("P-OWN-accepted-target-vocabulary")]scripts/check_test_assertions.py (baseline
tests/quality/assertion_quality_baseline.json) ratchets per-file counts the
same way: AQ001 constant assertions, AQ002 pytest.raises(Exception), AQ003
component or e2e tests that assert no user-visible output, exit code or durable
state, AQ004 tests that patch a symbol defined in an owner module they import,
and AQ006 e2e modules that do not drive the real CLI (they use CliRunner,
patch an owner module, or never run apm through ApmLifecycleRunner, the
apm_binary_path or apm_engine_command fixtures, or the lifecycle driver).
For consolidation, uv run --frozen python scripts/check_exact_test_duplicates.py --report-equal-copies lists equal copies that are safe to delete. A copy
qualifies only if body, decorators, fixtures, class context, module bindings and
CI lane all match its kept twin. The report never fails and never edits files.
Moving a listed test or module to another directory under the same name keeps
its allowance and is reported as moved. Prune stale or moved duplicate entries
with --update-baseline; edit stale or moved taxonomy entries by hand.
Keeping fixtures portable
Section titled “Keeping fixtures portable”Keep transport selection and authentication owners real in download tests; mock the Git/HTTP I/O instead. To exercise GitLab REST fallback, first simulate a typed Git transport failure on the same-origin HTTPS route. An empty mock transport plan does not authorize REST.
Home-directory fixtures must align HOME and USERPROFILE so Path.home()
and Path("~").expanduser() refer to the same directory on Windows. Assert
serialized dependency paths with Path.as_posix(). For deployed_file_hashes,
use compute_file_hash, which canonicalizes text CRLF; package-tree integrity
continues to hash raw bytes.
Concurrent fixtures must await every worker before inspecting shared results or
cleaning up resources. Submit both consumers before collecting their futures;
Thread.join(timeout=...) can return while a worker is still running. Keep real
parallel materialization and content assertions in cache regression tests.
Installation snapshots must allow only the three local identity paths
(.apm-local, .apm-local/.gitignore, .apm-local/installation) at the
appropriate project or user root, not the whole subtree. Changing ownership
metadata in a fixture invalidates its bound local receipt. For project installs,
derive the exact user-state receipt path through DeploymentMaterializationSession
under the fixture home; do not allow arbitrary sibling receipts. Pair conservative
preservation checks with an unchanged, trusted-receipt recovery control.
When adding a registered architecture-owner guard, add its surgical mutation
to test_architecture_owner_rule_mutations.py in the same change. The matrix
requires exactly one mutation for every registered guard.
Common invocations
Section titled “Common invocations”# Run everything you currently have the prerequisites foruv run pytest tests/integration -v
# Run a single suite (the marker registry still applies)uv run pytest tests/integration/test_golden_scenario_e2e.py -v
# Run only a marker familyuv run pytest tests/integration -m requires_github_token -v
# Run the spine state machine (python -m apm_cli.cli; no binary needed)uv run --extra dev pytest -q tests/lifecycle/machines/test_m_spine.py
# Run the GATE state machine (python -m apm_cli.cli; no binary needed)uv run --extra dev pytest -q tests/lifecycle/machines/test_m_gate.py
# Run the lifecycle family core and its obligation ratchetuv run --extra dev pytest -q tests/lifecycle tests/quality/test_promise_obligations.pyHermetic lifecycle fixtures
Section titled “Hermetic lifecycle fixtures”tests/integration/test_hermetic_lifecycle_foundation.py is the cross-module
contract. Complete the development setup first.
| Utility | Owns | Contract test |
|---|---|---|
isolated_apm_environment.py | Child roots, environment, Python socket tripwire | test_isolated_apm_environment_contract.py |
local_git_repository.py | Deterministic local Git origins | test_local_git_repository_factory_contract.py |
local_package.py | Source-only package inputs | test_local_package_factory_contract.py |
apm_lifecycle_runner.py | Bounded process execution and evidence | test_apm_lifecycle_runner_contract.py |
lifecycle_state.py | Exact bytes and semantic durable-state receipts | test_lifecycle_state_snapshot_contract.py |
artifact_snapshot.py | Read-only filesystem observations | test_artifact_snapshot_contract.py |
scenario_rows.py | Immutable scenario data | test_scenario_rows_contract.py |
Source fixtures author only source inputs; the real APM CLI creates lockfiles, deployed trees, compiled output, bundles, hashes, cache state, and audit reports.
Use ArtifactSnapshot for one complete filesystem root and
ArtifactSnapshotSet when an operation can affect multiple isolated roots.
These open-world captures complement LifecycleStateSnapshot: the latter
explains semantic lock and deployment state, while the former catches stray
files even when the lockfile fails to record them.
Hypothesis failures print a minimized transition program that can be replayed
by running the failing test with the reported example. Keep the generated model
bounded and deterministic in CI (database=None, derandomize=True), and turn
every confirmed product defect into a named regression before extending the
ledger. The static scenario rows remain valuable for exact reproductions; the
generated model searches valid orderings that authored rows may miss.
IsolatedApmEnvironment builds deterministic child environments for
APM/Git/GitHub/ADO/GitLab/SSH flows with a best-effort Python socket guard.
The guard preserves native optional socket API availability: it defines
sendmsg only when the native socket supports it, keeping feature detection
platform-correct. It isolates APM, Git, GH, Azure, home, cache, and temporary
roots, not arbitrary variables; it is not a general credential scrubber.
For deeply nested fixtures that populate real sparse Git caches, use short
pytest-owned roots such as tmp_path_factory.mktemp("r") instead of
test-named tmp_path roots to avoid Git for Windows metadata path limits.
Retain worker-equivalent directory depth in focused gates so they still
exercise the paths used by the sharded suite.
It is also not an OS/native-code sandbox: executables found through PATH
remain trusted, reflective access to CPython internals or native extensions can
bypass Python monkey-patches, file:// access is not confined by the OS, and
hostile post-creation filesystem races are outside the contract.
GIT_ALLOW_PROTOCOL=file and local url.*.insteadOf rewriting separately
restrict Git transport in reviewed scenarios.
Keep modules flat. Inside a pytest test with tmp_path and
apm_binary_path, compose them directly:
import os
from tests.utils.apm_lifecycle_runner import ApmLifecycleRunnerfrom tests.utils.artifact_snapshot import ArtifactSnapshotfrom tests.utils.isolated_apm_environment import IsolatedApmEnvironmentfrom tests.utils.local_package import LocalPackageFactory
isolated = IsolatedApmEnvironment.create(tmp_path / "scenario", base_env=os.environ)environment = isolated.subprocess_env()sources = LocalPackageFactory(isolated.package_root)project = sources.create("consumer", targets=("copilot",))sources.add_skill( project, "example", "---\nname: example\ndescription: Fixture\n---\n# Example\n",)result = ApmLifecycleRunner((str(apm_binary_path),)).run( ("install", "--target", "copilot"), cwd=project.root, env=environment,)snapshot = ArtifactSnapshot.capture(project.root)assert result.returncode == 0assert "apm.lock.yaml" in snapshot.pathsFor auth-bearing remote-package scenarios, create a local origin with
LocalGitRepositoryFactory and pass the complete environment returned by
url_rewrite_subprocess_env() to ApmLifecycleRunner. That process-scoped Git
rewrite survives the production auth environment builder; do not hand-merge
GIT_CONFIG_* slots or rely on the older global-config-only rewrite.
ApmLifecycleRunner((str(apm_binary_path),)) invokes the fixture-selected
console script. Packaged-binary tests belong to the separate platform lane.
test_packaged_virtual_file_lifecycle_e2e.py,
test_deployed_files_e2e.py, and
test_silent_adopt_existing_files_e2e.py are narrow hermetic packaged
counterparts to the live hero. They run the real binary against a local bare
Git origin through process-scoped URL rewriting, then check package
installation, deployment lifecycle, and exact lock provenance without
credentials or live HTTP.
# The three hermetic packaged counterparts (real binary, local file:// origin, no creds):uv run pytest tests/integration/test_packaged_virtual_file_lifecycle_e2e.py -vuv run pytest tests/integration/test_deployed_files_e2e.py -vuv run pytest tests/integration/test_silent_adopt_existing_files_e2e.py -v
# Supporting hermetic foundation + contract suites:uv run pytest tests/integration/test_local_package_factory_contract.py -vuv run pytest tests/integration/test_hermetic_lifecycle_foundation.py -vuv run pytest -n auto tests/integration/test_hermetic_lifecycle_foundation.py -vThese suites need no PAT and make no live HTTP calls: the packaged binary reaches
the dependency through a process-scoped file:// URL rewrite. If one fails with a
network or authentication error, the rewrite did not apply — confirm the test uses
the hermetic_packaged_sample fixture (which sets GIT_CONFIG_COUNT and
GIT_ALLOW_PROTOCOL=file) rather than invoking apm against the raw GitHub URL.
Apm binary resolution
Section titled “Apm binary resolution”Tests that need to shell out to a real apm binary use the
apm_binary_path fixture and the requires_apm_binary marker. The
binary is resolved in this order, so a local build is preferred over a
system install:
APM_BINARY_PATHenv var./dist/apm-<os>-<arch>/apm(the layout produced byscripts/build-binary.sh)shutil.which("apm")
apm_engine_command is the canonical fixture for narrowly scoped Python
filesystem-boundary fault injection: it returns (sys.executable, "-m", "apm_cli.cli") so ApmLifecycleRunner executes the installed Python engine.
This is an explicit engine contract, not packaged-binary coverage, and it is
independent of APM_BINARY_PATH so frozen CI cannot bypass the instrumentation.
Packaged executable tests must continue to use apm_binary_path.
Adding an integration test that needs a precondition
Section titled “Adding an integration test that needs a precondition”- Apply the marker at module or test level:
import pytestpytestmark = pytest.mark.requires_github_token
- If you need a brand-new precondition, add an entry to
_MARKER_CHECKSintests/integration/conftest.py(predicate + skip reason) and declare the marker inpyproject.toml. That is the only place the precondition needs to live.
CI orchestrator: scripts/test-integration.sh
Section titled “CI orchestrator: scripts/test-integration.sh”scripts/test-integration.sh is the thin orchestrator the CI
integration job invokes. Its sole responsibilities are: resolve
GitHub / ADO tokens, detect platform, locate or build the apm
PyInstaller binary, install runtimes (codex / copilot / llm),
install python test dependencies, and run
pytest tests/integration/ once. All per-test gating lives in the
marker registry described above. New integration tests dropped into
tests/integration/ are picked up automatically; add the right
requires_* marker and the registry will skip the test when its
precondition is missing.
Release promotion sets PYTEST_MARK_EXPR="not live", so an expiring
third-party credential cannot block publication. Live ADO PAT coverage is
owned by the Auth Acceptance Tests workflow: dispatch it with
ado_pat_e2e: true and an ado_repo acceptance fixture. That workflow
selects live and requires_ado_pat, requires
AUTH_TEST_ADO_APM_PAT, and fails with the normal actionable auth
diagnostic when the PAT is rejected.
Run the same focused acceptance locally with:
APM_TEST_ADO_REPO=dev.azure.com/org/project/_git/repo \ADO_APM_PAT=... \uv run pytest tests/integration/ -m "live and requires_ado_pat" -vThe orchestrator is mainly intended for reproducing the full CI
environment end-to-end; for local iteration prefer the direct
pytest invocations earlier on this page.
CI/CD Integration
Section titled “CI/CD Integration”GitHub Actions Workflow
Section titled “GitHub Actions Workflow”On PR and merge queue:
- PR-time unit checks and the hermetic Lifecycle Smoke gate run first; merge queue adds the global coverage floor (
Coverage Combine (Linux)) and Linux smoke, integration, and release-validation gates. Integration runs in up to 16 shards planned like the release pipeline’s, in about 16-18 minutes.
Architecture ratchet contracts and the real architecture-scaling test run in
separate Linux jobs, each with the same five-minute setup-to-cleanup limit.
Their test selections, scaling threshold and environment opt-ins are unchanged.
The required Test Architecture Ratchets aggregate gates only the contracts
job; failure, cancellation, skipping or a missing result fails it.
merge-gate.yml requires it at PR time and on merge_group, because it runs the
tests/quality guards, including the merge-time topology checks. The
wall-clock scaling ratio stays a separate, non-required Architecture Scaling (Linux) check, since timing asserts flake. A passing test summary does not
override a cancelled job.
gate also requires Spec conformance gate and its three Spec tests (N/3)
shards on every pull request and merge group. spec-conformance.yml has no
paths: filter, so these checks always run.
The required Windows compatibility gate runs the full Windows unit suite through
scripts/ci_selections.py, the same selection main push runs, then the
windows_compat tests in tests/integration with APM_E2E_TESTS=1 for marked
real-CLI contracts. It runs only that integration marker subset, not the full
integration suite. Its collection guard requires a non-empty subset, not a fixed
test count. Every module under those roots must import on Windows before marker deselection.
Import Unix-only modules such as pwd or fcntl inside the helpers that need
them, not at module scope. The collection guard checks this with Unix-only
standard modules unavailable, even on Linux and macOS.
The nested collection subprocess has a 300-second hard timeout: pytest must
import and collect the whole root before applying the marker, including on release
runners sharing CPU with other test workers. Plugin autoload remains disabled,
and a collection timeout fails the check rather than skipping it.
Collection proves a test is selected; a successful Windows job provides
Windows execution evidence. The existing job timeout bounds runtime.
The trusted_executable scheduling marker selects Git/GitHub CLI discovery
contracts and real install/reinstall/update scenarios for an additional Windows
Python 3.11 job. That version needs explicit PATHEXT candidates
for directory-qualified executable lookup. The same tests also carry
windows_compat, so the existing Python 3.12 gate checks compatibility.
Run the focused contracts locally with
uv run --frozen --extra dev pytest -m trusted_executable tests/unit/cache/test_git_env.py tests/integration/test_trusted_executable_discovery.py.
The legacy job collects only these files so unrelated tests requiring newer
interpreters cannot prevent collection. They select the same discovery cases
as the marker across both test roots. Production imports on this path remain
compatible with Python 3.11, the minimum supported version.
Python 3.12 and later use the standard-library lookup without the legacy
fallback; a candidate-count regression checks linear extension scanning.
Only a native Windows run demonstrates Windows behavior; passing mocks or
collection alone do not.
The Windows Native Symlink Acceptance job checks out the exact PR head and
uses a temporary standard account on a disposable hosted runner. It requires
successful ordinary file I/O, no administrator or symlink privilege, and actual
Windows error 1314 before running the Git/APM link regression. APM must
install a package with links as their target content, with the POSIX
content_hash, and apm install --frozen must replay that lock.
The job requires a passing native case, failure after disabling the
Git-object link writer in memory, and a restored pass. Empty or skipped runs
fail.
Account, profile, scratch and any changed Developer Mode value are cleaned up
independently, with an always() cleanup fallback. A restoration failure fails
the job. This is link-materialization evidence, not archive-symlink support, and
the job does not change repository protection or replace required SDL scanning.
Plugin sequential-install coverage checks deployed-file removal and lockfile ownership after uninstall, plus unchanged files and ownership for the retained skill. The local fixture covers both an independent skill and a separately installed skill from the plugin; the network-backed case uses the same assertions. Cleanup wording is not the lifecycle contract.
Linux Lifecycle Smoke runs the required marker subset with four bounded workers (-n 4 --dist loadgroup) on the public Ubuntu runner. Grouped tests stay on one worker. The 20-minute whole-job limit includes setup and cleanup; --durations=20 reports slow cases without changing selection or assertions.
Its lifecycle_smoke and not lifecycle_merge_group selection is not all
lifecycle coverage: also run affected generated state machines, deployment
ledger, and failure/retry contracts when changing those behaviors.
Releasing: push a v* tag, as before. scripts/release_plan.py picks how
much the run validates:
- push (push to
main): unit tests and Linux/Windows binaries. The Windows installer runs alongside two duration-balanced unit shards. All three must succeed before the Windows binary is built or uploaded. - full (nightly schedule or
repository_dispatch): every lane. A green full run is promotion evidence for its SHA. - promoted (tag whose SHA already has a green full run on
main): builds, binary smoke tests and release validation only, then publishes (about 5 min). - tag without evidence: full validation in the tag run, then publishes.
For the fast path, dispatch manual-build-release on the main commit, wait
for it to finish green, then tag that commit. Nothing publishes without a
green full validation of the exact SHA.
The tag must point at a commit on main or a release/* branch. Any other
tag fails the plan before anything builds or publishes; if the plan cannot
reach the GitHub compare API, it fails too, and you re-run the job.
If a published stable release never reached PyPI, re-publish it from its tag without re-running validation:
gh api repos/microsoft/apm/dispatches -f event_type=publish-existing-tag \ -F 'client_payload[tag]=vX.Y.Z'The run refuses a tag that is not a published stable GitHub release, or whose version is already on PyPI.
On qualifying PRs and merge groups, Spec conformance gate requires three
serial pytest shards on isolated runners plus the statement check. Only the
statement job’s full collection is used to regenerate CONFORMANCE.{json,md}.
On every PR, Windows Compatibility Gate requires three shards on parallel
Windows runners (units with four xdist workers, then serial windows_compat
integration); Lifecycle Smoke (Linux) and the two
Build & Test shards are split the same way. The seeds in
.github/ci-durations/ (windows-unit, windows-compat, linux-unit,
spec-conformance, and linux-x86_64 for lifecycle smoke) weight the current
pytest collection; they are not lists of tests to run.
Full-run lanes:
- Linux x86_64 and arm64: hermetic integration (
not live and not requires_github_token and not requires_network_integration) split across runners byscripts/ci_sharding.py. Shards are balanced by measured durations and keep xdist groups and heavy modules whole. The nightly run publishes durations;.github/ci-durations/holds the fallback seeds. Architecture-linter contracts (architecture_contract) run on x86_64 only. - Network lane (Linux x86_64):
requires_github_token or requires_network_integration, re-running only failed tests up to twice. - Windows:
scripts/windows/test-integration.ps1. - macOS: Intel is one job running
windows_compat or platform_sensitive. Apple Silicon runs the unit suite in its own job, in parallel with the build job that runslifecycle_smoke or windows_compat or platform_sensitive. Mark OS-, filesystem- or shell-sensitive integration testsplatform_sensitive.
create-release requires a pushed tag and every release-bound lane. Only a
promoted tag may skip integration and the Apple Silicon unit job.
The existing unprivileged PR Binary Smoke (Linux) job also runs
tests/integration/test_audit_workspace_identity_lifecycle.py against its built
binary with a five-minute limit. The fixture isolates HOME, credentials, cache,
and local Git repositories; captured audit output and full failure tracebacks
remain visible in the job log. This focused witness does not replace the full
release qualification or change required checks.
Daily scheduled release smoke:
- Runs the same promotion validation path once per day.
- Failing scheduled runs update one
ci/daily-smoketracking issue; a later recovered run closes it. - This signal is advisory and is not a required PR check.
Manual workflow dispatch:
- Test builds (uploads as workflow artifacts)
- Allows testing the full build pipeline without creating a release, even when dispatched from a tag ref
- Useful for validating changes before tagging
Tier 1 and Tier 2 on every push to main
Section titled “Tier 1 and Tier 2 on every push to main”main-push-gate.yml runs the whole PR gate suite (ci.yml, including every
Lifecycle Smoke shard), the full integration suite (ci-integration.yml,
every shard) and the lifecycle security cells (lifecycle-security.yml) on
each push to main. Its main-push-gate job fails the run when any tier job
fails, so a red main shows on the commit. It is not a required check and
never saves caches to the main scope.
lifecycle-security.yml runs tests/lifecycle/security on Linux and then
requires a receipt from every security witness. Pull requests run it when they
touch src/apm_cli/, tests/lifecycle/, the receipt ratchet, pyproject.toml
or uv.lock; it is not a required check. The security cells run on Linux
only; Windows and macOS run only the nightly journeys.
Merge-train proof
Section titled “Merge-train proof”merge-train.yml proves one exact merge result before it lands. Push the
merged tree (main plus the queued PRs) to a queue/* branch and read the
single train-gate check at that SHA:
| Ref | Runs | Time |
|---|---|---|
queue/t<id>/p<k>-guard | scope, guard, train-gate | about 5-10 min |
queue/t<id>/p<k>-full | the guard plus tier1 (ci.yml), tier2 (ci-integration.yml), spec (spec-conformance.yml) and owner (owner-surface.yml) | about 30-35 min |
queue/b<sha12>/p0-full | a full proof of a main SHA | about 30-35 min |
guard runs the Lint chain (.github/actions/lint-chain, shared with the
Lint job), the architecture ratchet contracts, every other tests/quality
module and the NOTICE check. The ratchets compare against the merge base with
main; a Queue-Base: <sha> trailer must name exactly that commit. A full
train runs every check the merge_group gate requires. train-gate passes only
when every job is green, or when every failure is inherited: gate.py collects the
failing pytest node ids from the failed jobs’ logs and subtracts the
train-failures.json of the newest base probe (queue/b<sha12>/p0-full). It then
publishes the run’s own train-failures.json. A cancelled job, or a failure
without node ids, is never excused.
Strict known cells must cite open issues. Pull requests check the committed
snapshot (tests/quality/known_cell_issue_states.json) only. A train’s guard
checks the live GitHub state, fail-closed. Every main push and a daily run
check it in .github/workflows/known-cells-live.yml, outside the main push gate:
a failure there is a ledger-state red (an issue changed state), not a code red,
and opens one tracking issue. An API outage or a closed issue never reds open
pull requests.
Queue refs are real branches: only write-access users can push them, and every
job tests the triggering commit. Train jobs restore caches (including main’s)
read-only and never save one. After train-gate reports, the cleanup job
deletes the train branch, so push it again to re-run (a manual dispatch with
--ref <queue branch> works only while the branch exists).
A green train-gate found by SHA alone is not a full proof: the same SHA can
also carry a guard-only run. A full proof is a successful merge-train run on the
-full branch (queue/t<id>/p<k>-full or queue/b<sha12>/p0-full) at that
exact SHA:
git push origin HEAD:refs/heads/queue/t0001/p1-fullgh run list --workflow merge-train.yml --branch queue/t0001/p1-full \ --commit "$(git rev-parse HEAD)" --json conclusion,urlThe run must show "conclusion": "success"; cite its url as the proof.
scripts/merge_queue/ composes these trains automatically (shadow mode: it
builds and proves trains but never merges). It reads PRs labeled queue:ready
with an apm-queue-ticket marker comment, builds queue-build/t<id> through
the merges API, publishes the prefix refs, and logs would-land events:
python -m scripts.merge_queue.runner tick # one pass; state in ~/.apm-queuepython -m scripts.merge_queue.runner metrics # shadow summary from events.jsonlA red train is classified by scripts/merge_queue/classify.py:
- the earliest red guard prefix ejects its PR;
- an infra failure is rerun once, and a second infra failure halts launches;
- a failure attributable to one member’s files ejects that member;
- any other failure is rerun once (a flake lands), then bisected by halves.
An ejected PR re-enters only with a new head.
Landing is off by default. --land (scripts/merge_queue/landing.py) also
admin-merges proven trains in launch order with
gh pr merge --merge --admin --match-head-commit. It does so only when main’s
tree is the tree the member was proven on, and the merge commit must carry the
proven tree. Any drift, or a merge to main that the runner did not make, HALTs
landing and records the reason in landing.json; trains keep testing. Two
failed admin probes in a row pause landing until elevation returns.
Before merging, closure.py requires the issues GitHub will close
(closingIssuesReferences plus closing keywords in commit messages) to equal the
ticket’s fixes; a mismatch ejects the train unmerged. After the merge it closes
any fix GitHub left open and retargets stacked PRs.
Windows unit hang diagnostics
Section titled “Windows unit hang diagnostics”The Windows unit steps in .github/workflows/build-release.yml and the PR
Windows Compatibility Gate run the selection owned by scripts/ci_selections.py:
uv run --frozen python -m scripts.ci_selections windows-unit [--shard-count N --shard-index I]which runs pytest tests/unit tests/test_console.py -n 4 --dist worksteal -vv --tb=short --show-capture=no --no-showlocals.
PYTHONUNBUFFERED=1 keeps named test starts and outcomes visible while the suite runs. Captured test output and local-variable dumps remain disabled. These diagnostics identify candidate unfinished tests, not stack frames or the exact blocked phase; an outcome can appear before fixture teardown completes.
The 60-minute step limit fails closed on a hang; it is not proof that tests pass or a root-cause fix. The PR-time gate exercises live name visibility during setup, call, and teardown after a failed call.
GitHub Actions Authentication
Section titled “GitHub Actions Authentication”E2E tests require proper GitHub Models API access:
Required Permissions:
contents: read- for repository accessmodels: read- Required for GitHub Models API access
Environment Variables:
GITHUB_TOKEN- user-scoped token for GitHub Models runtime callsGITHUB_APM_PAT- package access token; used as fallback by runtime setup
Runtime setup prefers GITHUB_TOKEN for GitHub Models and falls back to GITHUB_APM_PAT when no user-scoped token is present.
Release Pipeline Sequencing
Section titled “Release Pipeline Sequencing”The workflow ensures quality gates at each step:
- release-plan job - Chooses push, full or promoted mode
- build-linux-x86, build-linux-arm, build-windows jobs - Unit tests plus binary builds
- integration-tests job (
Integration Tests Summary) - Requires every sharded integration lane - release-validation jobs - Final shipped-binary validation
- create-release job - GitHub release creation
- publish-pypi job - PyPI package publication
Each publication stage must succeed before proceeding to the next. Live third-party credential acceptance remains a failing gate in the opt-in Auth Acceptance workflow rather than a dependency of release publication.
The microsoft/homebrew-apm tap updates independently: it polls the latest APM release and commits formula updates with its own repository-scoped GITHUB_TOKEN. The release pipeline does not hold a cross-repository Homebrew credential.
Test Matrix
Section titled “Test Matrix”Promotion integration tests run on:
- Linux: ubuntu-24.04 (x86_64), ubuntu-24.04-arm (arm64)
- Windows: windows-latest (x86_64)
- macOS Intel: macos-15-intel (x86_64), with the
windows_compat or platform_sensitivesubset, native binary startup, and isolated release validation - macOS Apple Silicon: macos-latest (arm64), with unit tests and the
lifecycle_smoke or windows_compat or platform_sensitivesubset
Python Version: 3.12 (standardized across all environments) Package Manager: uv (for fast dependency management and virtual environments)
What the Tests Verify
Section titled “What the Tests Verify”Smoke Tests Verify:
Section titled “Smoke Tests Verify:”- [+] Runtime setup scripts execute successfully
- [+] Binaries are downloaded and installed correctly
- [+] Binaries respond to basic commands
- [+] APM can detect installed runtimes
- [+] Configuration files are created properly
- [+] Workflow compilation works (without execution)
E2E Tests Verify:
Section titled “E2E Tests Verify:”- [+] Complete golden scenario from README works
- [+]
apm runtime setup copilotinstalls and configures GitHub Copilot CLI - [+]
apm runtime setup codexinstalls and configures Codex - [+]
apm runtime setup llminstalls and configures LLM - [+]
apm init my-hello-worldcreates project correctly - [+]
apm installhandles dependencies - [+]
apm run start --param name="Tester"executes successfully - [+] Real API calls to GitHub Models work
- [+] Parameter substitution works correctly
- [+] MCP integration functions (GitHub tools)
- [+] Binary artifacts work across platforms
- [+] Release pipeline integrity (GitHub Release -> PyPI)
Lifecycle Smoke Verifies:
Section titled “Lifecycle Smoke Verifies:”- Install content-hash roundtrip (Consume contract)
- Virtual-skill lock convergence (Produce contract, adjacent to the #2226 ADO lock-coordinate fix)
- Policy pinned-constraint enforcement (Govern contract)
- The virtual/manifestless lifecycle matrix: install, lock, frozen-install, update, and audit stay consistent (the direct #2240 regression)
- The ADO lock-coordinate single-owner guard (the direct #2226 regression)
- Prune’s merged-hook and ownership-sidecar reconciliation for the
claudetarget (the direct #2249 regression — an orphaned package’s merged hook entries and sidecar markers must be cleaned up, not left pointing at deleted scripts) - No network, no credentials, no built binary required for any of the above
Benefits
Section titled “Benefits”Speed vs Confidence Balance
Section titled “Speed vs Confidence Balance”- Smoke tests: Fast feedback (2-3 min) in the merge queue and on runtime changes
- E2E tests: High confidence (15 min) in the merge queue and promotion runs
Cost Efficiency
Section titled “Cost Efficiency”- Smoke tests use no API credits
- E2E tests run in the merge queue and promotion runs, not on every PR push (minimizing API usage)
- Manual workflow dispatch for test builds without publishing
Platform Coverage
Section titled “Platform Coverage”- Tests run on all supported platforms
- Catches platform-specific runtime issues
Release Confidence
Section titled “Release Confidence”- E2E tests must pass before any publishing steps
- Multi-stage release pipeline ensures quality gates
- Guarantees shipped releases work end-to-end
- Users can trust the README golden scenario
- Cross-platform binary verification
Debugging Test Failures
Section titled “Debugging Test Failures”Smoke Test Failures
Section titled “Smoke Test Failures”- Check runtime setup script output
- Verify platform compatibility
- Check network connectivity for downloads
E2E Test Failures
Section titled “E2E Test Failures”- Use the unified integration script first: Run
./scripts/test-integration.shto reproduce the exact CI environment locally - Verify
GITHUB_TOKENhas required permissions (models:read) - Ensure both
GITHUB_TOKENandGITHUB_MODELS_KEYenvironment variables are set - Check GitHub Models API availability
- Review actual vs expected output
- Test locally with same environment
Lifecycle Smoke Failures
Section titled “Lifecycle Smoke Failures”- These tests are hermetic — no credentials, no built binary, no network (a real socket attempt raises
OSError, it does not hang or retry). A failure is a genuine regression, not an environment issue. - Run the exact CI command from the “Run it locally” block under Tier 3 above to reproduce.
- If the failure is about the CI job’s shape (marker not registered, wrong
-m/--strict-markersinvocation, unbounded root, timeout, empty marker family, or required-check wiring) rather than test logic, checktests/quality/test_ci_topology.py— that guard pins the job’s contract and its own failure message will point at what drifted. - For hanging issues: Check command transformation in script runner (codex expects prompt content, not file paths)
Adding New Tests
Section titled “Adding New Tests”For New Runtime Support:
Section titled “For New Runtime Support:”- Add a smoke test for runtime setup, marked
@pytest.mark.requires_runtime_<name>(and add the marker entry to_MARKER_CHECKSintests/integration/conftest.pyif the runtime is brand new). - Add an E2E test for the golden scenario with the new runtime,
marked
@pytest.mark.requires_e2e_modeand any token markers it needs. - Update the CI matrix if the runtime introduces new platform support.
Lifecycle family: add a row or a machine rule
Section titled “Lifecycle family: add a row or a machine rule”- Name the promise ids, for example
P-INV-I4orP-LAW-<property>. Every id must resolve intests/quality/promise-catalog.json; the row loader rejects any other id. - For a fixed command sequence, add a row to
tests/lifecycle/replay/rows/(copycore_gate_row.yaml) withpromises,world,given,whenandthen(exit,deployed: expected,announce).RowReplay(tests/lifecycle/rows.py) runs every step through the driver andcheck_cross_cutting, and compares the final world withexpected_deployed. - For a transition that must hold from many states, add a rule to the matching state machine. Each rule builds an
Operation(oracles.operation_for(args)) and callscheck_cross_cutting; never write receipts yourself. - If a step fails on
main, open a neutral tracking issue and add aknown_cellsentry (law, tracking issue, step,match). It is a strict expected failure; never skip the step. - Run the row red first: use a recorded mutant (
entry_point=), or remove the oracle call and check that its obligations show up uncovered. Then move the obligations it covers frombaselinetorequiredintests/quality/promise_obligations.json, with the row’s test as witness.
For New Features:
Section titled “For New Features:”- Add a smoke test for compilation/validation.
- Add an E2E test if the feature requires API calls — pick the
smallest set of markers that captures its real preconditions
(
requires_github_token,requires_network_integration, etc.) so contributors without those credentials still get a cleanSKIPPEDrather than a hard failure. - Keep tests focused and fast.
Copyright (c) Microsoft Corporation. General documentation: CC-BY-4.0. Software, code examples and OpenAPM: Apache-2.0. See scope and exclusions.